Code

Updated listing table summary
[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     // Close dialogs and remove locks for currently handled dns
378     $this->cancelEdit();
380     // Do not allow to remove objects with state freeezed
381     $errors = $disallowed = array();
382   
383     foreach($to_delete as $obj){
384       $type = $this->get_type($obj);
385       $acl  = $this->ui->get_permissions($obj['dn'],"fai/".$type[1]);
386       if(!preg_match("/d/",$acl)){
387         $disallowed[] = $obj['dn'];
388       }elseif(isset($obj['FAIstate']) && preg_match('/^freeze/', $obj['FAIstate'])){
389         $errors[] = $obj['dn'];
390       }else{
391         $this->dns[] = $obj['dn'];
392       }
393     }
394     if(count($errors)){
395       msg_dialog::display(_("Branch locked"),
396           sprintf(_("The following entries are locked, you can't remove them %s."),msgPool::buildList($errors)),INFO_DIALOG);
397     }
398     if(count($disallowed)){ 
399       msg_dialog::display(_("Permission error"), msgPool::permDelete($disallowed), ERROR_DIALOG);
400     }
402     // Check entry locking
403     $smarty = get_smarty();
404     if(count($this->dns)){
405       if ($user= get_multiple_locks($this->dns)){
406         return(gen_locked_message($user,$this->dns));
407       }
408       if(count($this->dns)){
410         // Add locks
411         $dns_names = array();
412         $types = array();
413         $h = $this->getHeadpage();
415         // Build list of object -labels
416         foreach($h->objectTypes as $type){
417           $map[$type['objectClass']]= $type['label'];
418         }
420         foreach($this->dns as $dn){
421           $tmp = $h->getType($dn);
422           if(isset($map[$tmp])){
423             $dns_names[] = '('._($map[$tmp]).')&nbsp;-&nbsp;'.LDAP::fix($dn);
424           }else{
425             $dns_names[] =LDAP::fix($dn);
426           }
427         }
428         add_lock ($this->dns, $this->ui->dn);
430         $smarty->assign("info",msgPool::deleteInfo($dns_names));
431         return($smarty->fetch(get_template_path('removeEntries.tpl', TRUE)));
432       }
433     }
434   }
437   /*! \brief   Entry removal is confirmed, now remove objects
438    */
439   function removeEntryConfirmed($action="",$target=array(),$all=array(),
440       $altTabClass="",$altTabType="",$altAclCategory="")
441   {
442     $ldap = $this->config->get_ldap_link();
443     $ldap->cd($this->config->current['BASE']); 
445     $disallowed = array();
446     foreach($this->dns as $key => $dn){
447       $ldap->cat($dn);
448       if($ldap->count()){
449         $attrs = $ldap->fetch();
450         $type= $this->get_type($attrs);
452         $acl  = $this->ui->get_permissions($dn,"fai/".$type[1]);
453         if(preg_match("/d/",$acl)){
455           // Now save changes
456           $str = management::removeEntryConfirmed($action,array($dn),$all,$type[0],$type[2],$type[1]);
457           if(!empty($str)) return($str);
458           FAI::save_release_changes_now();
459           $to_del = FAI::clean_up_releases($dn);
460           foreach($to_del as $dn){
461             $ldap->rmdir_recursive($dn);
462           }
464         } else {
465           $disallowed[] = $dn;
466           new log("security","fai/".get_class($this),$dn,array(),"Tried to trick deletion.");
467         }
468       }
469     }
471     /* Normally this shouldn't be reached, send some extra
472        logs to notify the administrator */
473     if(count($disallowed)){ 
474       msg_dialog::display(_("Permission error"), msgPool::permDelete($disallowed), ERROR_DIALOG);
475     }
476   }
479   /*! \brief   Someone clicked on edit/remove for a grouped FAI object.
480    *           We are now going to display a dialog to let the user select the entry 
481    *            he wants to perform the action on.
482    */
483   function editByGroup()
484   {
485     if($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "edit"){
486       $this->dialogObject->save_object();
487       $entry = $this->dialogObject->get_selected();
488       $this->closeDialogs();
489       $data = array_pop($entry);
490       $type = $this->get_type($data);
491       $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]);
492       if($str) return($str);
493       $this->tabObject->by_object[$type[1]]->FAIstate = $data['FAIstate'];
494       $this->tabObject->read_only = preg_match("/freeze/i", $data['FAIstate']);
495     }elseif($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "remove"){
496       $this->dialogObject->save_object();
497       $to_delete = $entry = $this->dialogObject->get_selected();
498       if(count($to_delete)) $this->closeDialogs();
499       return($this->removeFAIObjects($to_delete));
500     }elseif($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "copy"){
501       $this->dialogObject->save_object();
502       $entries = $entry = $this->dialogObject->get_selected();
503       if(count($entries)){
504         foreach($entries as $entry){
505           $type = $this->get_type($entry);
506           $this->cpHandler->add_to_queue($entry['dn'],"copy",$type[0],$type[2],'fai',$this);
507           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,$entry['dn'],"Entry copied!");
508         }
509         $this->closeDialogs();
510       }
511     }
512   }
515   /*! \brief   Save dialog/object modifications
516    */
517   protected function saveChanges()
518   {
519     $str = management::saveChanges();
520     if($str) return($str);
522     // Now save changes
523     FAI::save_release_changes_now();
524     $to_del = FAI::clean_up_releases($this->last_dn);
525     $ldap= $this->config->get_ldap_link();
526     foreach($to_del as $dn){
527       $ldap->rmdir_recursive($dn);
528     }
529   }
532   /*! \brief   Save dialog/object modifications but keep the dialogs opened
533    */
534   protected function applyChanges()
535   {
536     $str = management::applyChanges();
537     if($str) return($str);
539     // Now save changes
540     FAI::save_release_changes_now();
541     $to_del = FAI::clean_up_releases($this->last_dn);
542     foreach($to_del as $dn){
543       $ldap->rmdir_recursive($dn);
544     }
545   }
548   /*! \brief   Initiates release removal
549    */
550   function removeBranch()
551   {
552     /* Check if we have a post remove method configured
553      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
554      */
555     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
556       /* Load permissions for selected 'dn' and check if
557          we're allowed to remove this 'dn' */
558       if(preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
559         $smarty=get_smarty();
560         $smarty->assign("release_hidden",base64_encode($this->fai_release));
561         $smarty->assign("info", msgPool::deleteInfo(LDAP::fix($this->fai_release),_("FAI branch/freeze")));
562         return($smarty->fetch(get_template_path('remove_branch.tpl',TRUE)));
563       } else {
564         msg_dialog::display(_("Permission error"), _("You have no permission to delete this release!"), ERROR_DIALOG);
565       }
566     }
567   }
570   /*! \brief   Remove a release after removal was confirmed
571    */
572   function removeBranchConfirmed()
573   {
574     /* Check if we have a post remove method configured
575      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
576      */
577     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
579       if(!isset($_POST['release_hidden']) || base64_decode($_POST['release_hidden']) != $this->fai_release){
580         msg_dialog::display(_("Warning"),_("Release remove aborted because the release name check failed!"));
581       }else{
583         $bb =  $this->fai_release;
584         $ldap = $this->config->get_ldap_link();
586         $br = $this->getBranches();
588         if(isset($br[$bb]) && preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
589           $name = $br[$bb];
591           $ldap->cd($bb);
592           $ldap->recursive_remove();
593           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('applicationRDN'), $bb));
594           $ldap->recursive_remove();
595           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('mimetypeRDN'), $bb));
596           $ldap->recursive_remove();
598           /* Search for all groups with configured application menus.
599              - First search all groups, to ensure that we only remove entries form whithin groups.
600              - The search für menu configuration for the specified release and collect all those dns.
601              - Remove entries
602            */
603           $release_ou = preg_replace("/".preg_quote(get_ou("faiBaseRDN"), '/').".*$/i","",$bb);
604           $ldap->cd($this->config->current['BASE']);
605           $ldap->search("(objectClass=posixGroup)",array("dn"));
607           /* Collect all group dns
608            */
609           $groups = array();
610           while($attrs = $ldap->fetch()){
611             $groups[] = $attrs['dn'];
612           }
615           /* Collect all group menu release dns that match the release we have removed
616            */
617           $dns = array();
618           foreach($groups as $dn){
619             $ldap->cd($dn);
620             $ldap->search("(objectClass=FAIbranch)",array("dn"));
621             while($attrs = $ldap->fetch()){
622               if(preg_match("/^".preg_quote($release_ou, '/')."/",$attrs['dn'])){
623                 $dns[] = $attrs['dn'];
624               }
625             }
626           }
628           /* Finally remove collected release dns
629            */
630           foreach($dns as $dn){
631             $ldap->cd($dn);
632             $ldap->recursive_remove();
633           }
635           /* Post remove */
636           $this->fai_release = $this->fai_base;
637           $this->lock_name   = $name;
638           $this->lock_dn     = $bb;
639           $this->handle_post_events('remove');
641           $fai_filter = session::get("fai_filter");
642           $fai_filter['fai_release'] = $this->fai_release;
643           session::set("fai_filter",$fai_filter);
645           new log("remove","fai/".get_class($this),$br[$bb],array(),"Release removed");
646         }
647       }
648     }
649   }
652   /*! \brief   Initiates release creation 
653    */
654   function createBranch()
655   { 
656     if($this->config->search("faiManagement", "POSTCREATE",array('menu','tabs')) == ""){ 
657       msg_dialog::display(_("Configuration"), msgPool::cmdnotfound("POSTCREATE", get_class()), ERROR_DIALOG);
658     }elseif(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
659       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
660     }else{
661       $smarty = get_smarty();
662       $this->dispNewBranch=true;
663       $this->dispNewFreeze=false;
664       $smarty->assign("iframe",false);
665       if(isset($_POST['BranchName'])){
666         $smarty->assign("BranchName", $_POST['BranchName']);
667       }else{
668         $smarty->assign("BranchName","");
669       }
670       return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
671     }
672   }
675   /*! \brief   Initiates release creation 
676    */
677   function createFreeze()
678   {
679     if($this->config->search("faiManagement", "POSTCREATE",array('menu','tabs')) == ""){ 
680       msg_dialog::display(_("Configuration"), msgPool::cmdnotfound("POSTCREATE", get_class()), ERROR_DIALOG);
681     }elseif(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
682       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
683     }else{
684       $smarty = get_smarty();
685       $this->dispNewFreeze=true;
686       $this->dispNewBranch=false;
687       $smarty->assign("iframe",false);
688       if(isset($_POST['BranchName'])){
689         $smarty->assign("BranchName", $_POST['BranchName']);
690       }else{
691         $smarty->assign("BranchName","");
692       }
693       return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
694     }
695   }
698   /*! \brief   Creates a new branch
699    */
700   function PerformBranch()
701   {
702     if(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
703       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
704     }else{
706       /* In order to see error messages we have to reset the error handler.
707          Due to the exit();
708        */
709       restore_error_handler();
711       $this->dispNewBranch = false;
712       $this->dispNewFreeze = false;
714       $LASTPOST = session::get('LASTPOST');
715       $base = $LASTPOST['base'];
716       $_POST  = session::get('LASTPOST');
717       $name = $_POST['BranchName'];
719       $type = $LASTPOST['type'];
720       $ldap = $this->config->get_ldap_link();
722       $baseToUse = $base;
723       if($this->fai_release !=  $this->fai_base){
724         $baseToUse = $this->fai_release;
725       }
727       /* Create new Release name to be able to set faidebianRelease for FAIpackageList */
729       $CurrentReleases  = $this->getBranches();
730       $NewReleaseName   = $name;
731       if(isset($CurrentReleases[$this->fai_release])) {
732         if($this->fai_release != $this->fai_base){
733           $NewReleaseName = $CurrentReleases[$this->fai_release]."/".$name;
734           $NewReleaseName = preg_replace("#\/#","/",$NewReleaseName);
735         }else{
736           $NewReleaseName   = $name;
737         }
738       }
739       $appsrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),$baseToUse);
740       $appdst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),"ou=".$name.",".$baseToUse) ;
742       $mimesrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),$baseToUse);
743       $mimedst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),"ou=".$name.",".$baseToUse) ;
745       /* Check if source depeartments exist */
746       foreach(array($baseToUse,$appsrc,$mimesrc) as $dep){
747         $ldap->cd($this->config->current['BASE']);
748         $ldap->cat($dep);
749         if(!$ldap->count()){
750           $ldap->create_missing_trees($dep);
751         }
752       }
754       /* Print header to have styles included */
755       echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
756         <html>
757         <head>
758         <title></title>
759         <style type="text/css">@import url("themes/default/style.css");</style>
760         <script language="javascript" src="include/focus.js" type="text/javascript"></script>
761         </head>
762         <body style="background: none;margin:3px;color:black">
763         ';
765       new log("create","fai/".get_class($this),$NewReleaseName,array(),"New $type created");
767       /* Duplicate group application releases
768        */
769       FAI::copy_FAI_group_releases($CurrentReleases[$this->fai_release],$name,$type);
771       /* Duplicate applications
772        */
773       $ldap->cat($appsrc,array("dn")) ;
774       if($ldap->count()){
775         $ldap->cd ($appdst);
776         $ldap->recursive_remove();
777         FAI::copy_FAI_resource_recursive($appsrc,$appdst,$NewReleaseName,$type,true);
778       }
780       /* Duplicate mime types
781        */
782       $ldap->cat($mimesrc,array("dn")) ;
783       if($ldap->count()){
784         $ldap->cd ($mimedst);
785         $ldap->recursive_remove();
786         FAI::copy_FAI_resource_recursive($mimesrc,$mimedst,$NewReleaseName,$type,true);
787       }
789       $attr = array();
790       $attr['objectClass'] = array("organizationalUnit","FAIbranch");
791       $attr['ou']       = $name;
792       $attr['FAIstate'] = $type;
793       $ldap->cd($this->config->current['BASE']);
794       $ldap->cd("ou=".$name.",".$baseToUse);
795       $ldap->cat("ou=".$name.",".$baseToUse);
796       if($ldap->count()){
797         $ldap->modify($attr);
798       }else{
799         $ldap->add($attr);
800       }
802       /* Duplicate fai objects
803        */
804       //      $ldap->cd ("ou=".$name.",".$baseToUse);
805       //      $ldap->recursive_remove();
806       //      FAI::copy_FAI_resource_recursive($baseToUse,"ou=".$name.",".$baseToUse,$NewReleaseName,$type,true);
808       echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
809         <br><input type='submit' name='CloseIFrame' value='"._("Continue")."'>
810         <input type='hidden' name='php_c_check' value='1'>
811         </form></div>";
813       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
815       /* Print footer to have valid html */
816       echo "</body></html>";
818       $this->dispNewFreeze = false;
820       /* Assign possible attributes */
821       $this->lock_type  = $type;
822       $this->lock_name  = $name;
823       $this->lock_dn    = $baseToUse;
824       $this->handle_post_events('add');
826       /* Send daemon event to reload the fai release database
827        */
828       if(class_available("DaemonEvent") && class_available("gosaSupportDaemon")){
829         $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);
830         if(isset($events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'])){
831           $evt = $events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'];
832           $tmp = new $evt['CLASS_NAME']($this->config);
833           $tmp->set_type(TRIGGERED_EVENT);
834           $tmp->add_targets(array("GOSA"));
835           $o_queue = new gosaSupportDaemon();
836           if(!$o_queue->append($tmp)){
837             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
838           }
839         }
840       }else{
841         trigger_error("Unknown class DaemonEvent / gosaSupportDaemon");
842         msg_dialog::display(_("Fatal error"),
843             "Daemon events called but classes where not accessible, DaemonEvent gosaSupportDaemon",
844             FATAL_ERROR_DIALOG);
845       }
846       exit();
847     }
848   }
851   /*! \brief   Creates a new branch, after a useable name was specified.
852    */
853   function saveBranch()
854   {
855     if($this->dispNewBranch){
856       $type = "branch";
857     }else{
858       $type = "freeze";
859     }
861     /* Check branch name */
862     $name = $_POST['BranchName'];
863     $is_ok = true;
864     $smarty = get_smarty();
865     $smarty->assign("BranchName",$name);
866     $base= $this->fai_base;
868     /* Check used characters */
869     if(!preg_match("/^[0-9a-z\.]*$/",$name)){
870       msg_dialog::display(_("Error"), msgPool::invalid(_("Name"),$name,"/[0-9a-z\.]/"), ERROR_DIALOG);
871       $is_ok = false;
872     }
874     // Check if this name is already in use 
875     if(!$this->CheckNewBranchName($_POST['BranchName'],$this->fai_release)){
876       msg_dialog::display(_("Error"), msgPool::duplicated(_("Name")), ERROR_DIALOG);
877       $is_ok = false;
878     }
880     // Handle errors
881     if(!$is_ok && $this->dispNewFreeze){
882       return($this->createFreeze());
883     }elseif(!$is_ok && $this->dispNewBranch){
884       return($this->createBranch());
885     }
887     // Now create new release
889     if(session::is_set('LASTPOST')){
890       $LASTPOST = session::get('LASTPOST');
891     }else{
892       $LASTPOST = array();
893     }
894     $LASTPOST['base'] = $base;
895     $LASTPOST['type'] = $type;
896     $LASTPOST['BranchName'] = $name;
897     session::set('LASTPOST',$LASTPOST);
898     $smarty->assign("iframe", true);
899     $smarty->assign("plugID", $_GET['plug']);
900     $display  = $smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__)));
901     return($display);
903   }
907   /*! \brief   Returns a list of all releases for useable for drop down boxes.
908    *                      ou=fai... /
909    *              ou=siga,ou=fai... &nbsp; siga
910    *         ou=1,ou=siga,ou=fai... &nbsp;&nbsp; 1
911    */
912   function getReleaseList($base = "", $prefix ="")
913   {
914     $list = array();
915     if(empty($base)){
916       $base = $this->fai_base;
917       $list[$base] = "/";
918     }
920     $ldap = $this->config->get_ldap_link();
921     $ldap->ls("(objectClass=FAIbranch)",$base,array("ou","FAIstate"));
923     while($release = $ldap->fetch()){
924       $list[$release['dn']] = $prefix.$release['ou'][0];
925       $list = array_merge($list,$this->getReleaseList($release['dn'],$prefix."&nbsp; "));
926     }
927     return($list);
928   }
931   /*! \brief   Returns a list of all releases with full release names
932    *                      ou=fai... /
933    *              ou=siga,ou=fai... siga
934    *         ou=1,ou=siga,ou=fai... siga/1
935    */
936   function getBranches($base = false,$prefix = "")
937   {
938     $ret = array("/"=>$this->fai_base);
939     $ldap = $this->config->get_ldap_link();
940     if(!$base){
941       $base = $this->fai_base;
942     }
943     $tmp = FAI::get_all_releases_from_base($base,true);
944     foreach($tmp as $dn => $name){
945       $ret[$name]=$dn;
946     }
947     ksort($ret);
948     $ret = array_flip($ret);
950     return ($ret);
951   }
954   /*! \brief   Detects object info like corresponding  tab,class,acl 
955    *    e.g.    [0]   =  tabsPartition
956    *            [1]   =  faiPartitionTable
957    *            [2]   =  FAIPARTITIONTABS
958    */
959   function get_type($array)
960   {
961     if(!isset($array['objectClass'])) return(array());
962     if(in_array("FAIpartitionTable",$array['objectClass'])){
963       return(array("tabsPartition","faiPartitionTable","FAIPARTITIONTABS"));
964     }
965     if(in_array("FAIscript",$array['objectClass'])){
966       return(array("tabsScript","faiScript","FAISCRIPTTABS"));
967     }
968     if(in_array("FAItemplate",$array['objectClass'])){
969       return(array("tabsTemplate","faiTemplate","FAITEMPLATETABS"));
970     }
971     if(in_array("FAIhook",$array['objectClass'])){
972       return(array("tabsHook","faiHook","FAIHOOKTABS"));
973     }
974     if(in_array("FAIvariable",$array['objectClass'])){
975       return(array("tabsVariable","faiVariable","FAIVARIABLETABS"));
976     }
977     if(in_array("FAIprofile",$array['objectClass'])){
978       return(array("tabsProfile","faiProfile","FAIPROFILETABS"));
979     }
980     if(in_array("FAIpackageList",$array['objectClass'])){
981       return(array("tabsPackage","faiPackage","FAIPACKAGETABS"));
982     }
983     return(array());
984   }
987   /*! \brief   Checks if the given string can be used as class name
988    */
989   static function check_class_name($oc,$name,$dn)
990   {
991     $base = FAI::get_release_dn($dn);
993     if($oc == "FAIprofile"){
994       $f = "";
995       $ocs = array("FAIprofile","FAItemplate","FAIhook","FAIpartitionTable","FAIpackageList","FAIscript","FAIvariable");
996       foreach($ocs as $oc){
997         $f .= "(objectClass=".$oc.")";
998       }
999       $res  = FAI::get_all_objects_for_given_base($base,"(|".$f.")",TRUE);
1000     }else{
1001       $res  = FAI::get_all_objects_for_given_base($base,"(objectClass=".$oc.")",TRUE);
1002     }
1003     $delete = array();
1004     $used   = array();
1005     foreach($res as $object){
1006       $used[$object['cn'][0]]= $object['cn'][0];
1007     }
1008     return($used);
1009   }
1012   /*! \brief   Checks if the given string can be used for a new release
1013    */
1014   function CheckNewBranchName($name,$base)
1015   {
1016     $f = $this->fai_release;
1017     if($name == ""){
1018       return(false);
1019     }elseif(in_array($name,$this->getBranches($f))) {
1020       return(false);
1021     }elseif(tests::is_department_name_reserved($name,$base)){
1022       return(false);
1023     }
1024     return(true);
1025   }
1028   /*! \brief   This filter is used to display small icons for each listed object 
1029    *            instead of their typ names
1030    */
1031   static function filterProperties($row, $classes)
1032   {
1033     $objects = array(
1034         "FAIpartitionTable"  => array("IMG"=> "plugins/fai/images/fai_partitionTable.png",
1035           "NAME"=>_("Partition table"),"KZL"=> "PT", "VAR"=>"ShowPartitions"),
1036         "FAIpackageList"     => array("IMG"=> "plugins/fai/images/fai_packages.png",
1037           "NAME"=>_("Package list") ,  "KZL"=> "PL", "VAR"=>"ShowPackages"),
1038         "FAIscript"          => array("IMG"=> "plugins/fai/images/fai_script.png",
1039           "NAME"=>_("Scripts") ,       "KZL"=> "S",  "VAR"=>"ShowScripts"),
1040         "FAIvariable"        => array("IMG"=> "plugins/fai/images/fai_variable.png",
1041           "NAME"=>_("Variables") ,     "KZL"=> "V",  "VAR"=>"ShowVariables"),
1042         "FAIhook"            => array("IMG"=> "plugins/fai/images/fai_hook.png",
1043           "NAME"=>_("Hooks"),          "KZL"=> "H",  "VAR"=>"ShowHooks"),
1044         "FAIprofile"         => array("IMG"=> "plugins/fai/images/fai_profile.png",
1045           "NAME"=>_("Profile") ,       "KZL"=> "P",  "VAR"=>"ShowProfiles"),
1046         "FAItemplate"        => array("IMG"=> "plugins/fai/images/fai_template.png",
1047           "NAME"=>_("Templates") ,     "KZL"=> "T",  "VAR"=>"ShowTemplates"),
1048         "opsi_netboot"       => array("IMG"=> "plugins/opsi/images/netboot_package.png",
1049           "NAME"=>_("OPSI netboot product") ,     "KZL"=> "ON",  "VAR"=>"ShowOpsiNetboot"),
1050         "opsi_local"         => array("IMG"=> "plugins/opsi/images/local_package.png",
1051           "NAME"=>_("OPSI localboot product")   ,     "KZL"=> "OL",  "VAR"=>"ShowOpsiLocal"));
1053     $icon_list = "";
1054     foreach($objects as $type => $type_data){
1055       if(in_array($type, $classes)){
1056         $icon_list .= "<input type='image' src='".$type_data['IMG']."' title='".$type_data['NAME']."'
1057           alt='".$type_data['KZL']."' class='center' name='edit_".$row."_".$type."'>\n";
1058       }else{
1059         $icon_list .= "<img src='images/empty.png' alt=' ' class='center'>\n";
1060       }
1061     }
1063     return $icon_list;
1064   }
1067   /*! \brief   Overridden render method of class mangement. 
1068    *            this allows us to add a release selection box.
1069    */
1070   function renderList()
1071   {
1072     $filter = $this->getFilter();
1073     $headpage = $this->getHeadpage();
1074     $filter->setComboBoxOptions("RELEASE",$this->getReleaseList());
1076     if(isset($_POST['RELEASE'])){
1077       $this->fai_release = get_post('RELEASE');
1078     }
1079     $headpage->setBase($this->fai_release);
1080     $headpage->update();
1081     $smarty = get_smarty();
1082     $smarty->assign("fai_release", $this->fai_release);
1083     $smarty->assign("opsi_available", (is_object($this->opsi) && $this->opsi->enabled()));
1084     $smarty->assign("fai_base", $this->fai_base);
1085     $r = $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'));
1086     $c = $this->config->search("faiManagement", "POSTCREATE",array('menu','tabs'));
1087     $smarty->assign("allow_create", $c);
1088     $smarty->assign("allow_remove", $r);
1089     $display = $headpage->render();
1090     return($this->getHeader().$display);
1091   }
1094   /*! \brief   Convert POST and GET variables into actions.
1095    */
1096   function detectPostActions()
1097   {
1098     $action = management::detectPostActions();
1099     if(isset($_POST['remove_multiple'])) $action['action'] = "remove";
1100     if(isset($_POST['new_profile'])) $action['action'] = "new_profile";
1101     if(isset($_POST['new_template'])) $action['action'] = "new_template";
1102     if(isset($_POST['new_script'])) $action['action'] = "new_script";
1103     if(isset($_POST['new_hook'])) $action['action'] = "new_hook";
1104     if(isset($_POST['new_variable'])) $action['action'] = "new_variable";
1105     if(isset($_POST['new_package'])) $action['action'] = "new_package";
1106     if(isset($_POST['new_partition'])) $action['action'] = "new_partition";
1108     if(isset($_POST['save_properties'])) $action['action'] = "saveOpsiProperties";
1109     if(isset($_POST['cancel_properties'])) $action['action'] = "cancel";
1111     if(isset($_POST['edit_continue'])) $action['action'] = "newClassNameSelected";
1112     if(isset($_POST['edit_cancel'])) $action['action'] = "cancel";
1114     if(isset($_POST['faiGroupHandle_cancel'])) $action['action'] = "cancel";
1115     if(isset($_POST['CancelBranchName'])) $action['action'] = "cancel";
1116     if(isset($_POST['delete_branch_confirm'])) $action['action'] = "removeBranchConfirmed";
1117     if(isset($_GET['PerformBranch'])) $action['action'] = "PerformBranch";
1118     if(isset($_POST['UseBranchName'])) $action['action'] = "saveBranch";
1119     if(isset($_POST['faiGroupHandle_apply']))  $action['action'] = "editByGroup";
1120     if(isset($_GET['act']) && $_GET['act'] == "branch_branch")  $action['action'] = "createBranch";
1121     if(isset($_GET['act']) && $_GET['act'] == "freeze_branch")  $action['action'] = "createFreeze";
1122     if(isset($_GET['act']) && $_GET['act'] == "remove_branch")  $action['action'] = "removeBranch";
1124     foreach($_POST as $name => $value){
1125       if(preg_match("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i", $name)){
1126         $id = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\1", $name);
1127         $tab = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\2", $name);
1129         $headpage = $this->getHeadpage();
1130         $entry = $headpage->entries[$id];
1132         if(in_array('FAKE_OC_FAI', $entry['objectClass'])){
1133           if(isset($headpage->entries[$id]['GROUPS'][$tab])){
1134             $data =$headpage->entries[$id]['GROUPS'][$tab];
1135             $type = $this->get_type($data);
1136             $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]); 
1137             if($str) return($str);
1138           } 
1139         }else{
1140           $str = $this->editEntry('editEntry',array($entry['dn'])); 
1141           if($str) return($str);
1142         }
1143         break;
1144       }
1145     }
1146     return($action);
1147   }
1150   static function plInfo()
1151   {
1152     return (array(
1153           "plShortName"   => _("FAI releases"),
1154           "plDescription" => _("FAI release management"),
1155           "plSelfModify"  => FALSE,
1156           "plDepends"     => array(),
1157           "plPriority"    => 0,
1158           "plSection"     => array("administration"),
1159           "plCategory"    => array("fai"=> array("description" => _("FAI"),
1160               "objectClass" => "FAIclass")),
1161           "plProvidedAcls"=> array()));
1162   }
1163
1164 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1165 ?>