Code

1719e82c3c599acca4263b48117057f5aa8afb50
[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_roleManagement.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 = "roletabs";
31   protected $tabType = "ROLETABS";
32   protected $aclCategory = "roles";
33   protected $aclPlugin   = "role";
34   protected $objectName   = "role";
36   //  Attributes Managed by this plugin can be used in post events
37   protected $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     $this->acl_base = $this->config->current['BASE'];
72     $this->ui = $ui;
73     $this->storagePoints = array(
74         get_ou('faiPartitionRDN'),
75         get_ou('faiPackageRDN'),
76         get_ou('faiScriptRDN'),
77         get_ou('faiVariableRDN'),
78         get_ou('faiHookRDN'),
79         get_ou('faiProfileRDN'),
80         get_ou('faiTemplateRDN'));
82     // Build filter
83     if (session::global_is_set(get_class($this)."_filter")){
84       $filter= session::global_get(get_class($this)."_filter");
85     } else {
86       $filter = new filter(get_template_path("fai-filter.xml", true));
87       $filter->setObjectStorage($this->storagePoints);
88     }
89     $this->setFilter($filter);
91     // Build headpage
92     $headpage = new listing(get_template_path("fai-list.xml", true));
93     $headpage->setFilter($filter);
94     $headpage->setBase($this->fai_release);
95     $headpage->registerElementFilter("filterProperties", "faiManagement::filterProperties");
97     // Add copy&paste and snapshot handler.
98     if ($this->config->boolValueIsTrue("main", "copyPaste")){
99       $this->cpHandler = new CopyPasteHandler($this->config);
100     }
102     $this->registerAction("remove_multiple","removeEntryRequested");
103     $this->registerAction("new_profile","newEntry");
104     $this->registerAction("new_template","newEntry");
105     $this->registerAction("new_script","newEntry");
106     $this->registerAction("new_hook","newEntry");
107     $this->registerAction("new_variable","newEntry");
108     $this->registerAction("new_package","newEntry");
109     $this->registerAction("new_partition","newEntry");
110     $this->registerAction("newClassNameSelected","newClassNameSelected");
111     $this->registerAction("saveOpsiProperties","saveOpsiProperties");
112     $this->registerAction("editByGroup","editByGroup");
113     $this->registerAction("createBranch","createBranch");
114     $this->registerAction("createFreeze","createFreeze");
115     $this->registerAction("removeBranch","removeBranch");
116     $this->registerAction("removeBranchConfirmed","removeBranchConfirmed");
117     $this->registerAction("saveBranch","saveBranch");
118     $this->registerAction("PerformBranch","PerformBranch");
120     parent::__construct($config, $ui, "roles", $headpage);
121   }
124   /*! \brief  Act on copy & paste actions here.
125    */
126   function copyPasteHandler($action="",$target=array(),$all=array(),$altTabClass ="",$altTabType="",$altAclCategory="",$altAclPlugin="")
127   {
128     // Collect real dns, the listed objects are grouped by their cn
129     $headpage = $this->getHeadpage();
130     if($action == "copy"){
131       foreach($target as $t){
132         $entry = $headpage->getEntry($t);
134         // Check for valid FAI objects
135         if(in_array('FAKE_OC_FAI', $entry['objectClass'])){
136           foreach($entry['GROUPS'] as $g){
137             $type = $this->get_type($g);
138             $this->cpHandler->add_to_queue($g['dn'],"copy",$type[0],$type[2],'fai',$this);
139             @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,$dn,"Entry copied!");
140           }
141         }
142       }
143     }
145     // Initiate pasting
146     if($action == "paste"){
147       $this->cpPastingStarted = TRUE;
148     }
150     // Display any c&p dialogs, eg. object modifications required before pasting.
151     if($this->cpPastingStarted && $this->cpHandler->entries_queued()){
152       $this->cpHandler->SetVar("base",$headpage->getBase());
153       $data = $this->cpHandler->execute();
154       FAI::save_release_changes_now();
155       if(!empty($data)){
156         return($data);
157       }
158     }
160     // Automatically disable pasting process since there is no entry left to paste.
161     if(!$this->cpHandler->entries_queued()){
162       $this->cpPastingStarted = FALSE;
163     }
164     return("");
165   }
168   /*! \brief  A new FAI object was requested, let the user specify a name theis object now. 
169    */
170   function newEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
171   {
172     $types = array( 
173         "new_partition"     =>  "FAIpartitionTable",
174         "new_script"        =>  "FAIscript",
175         "new_hook"          =>  "FAIhook",
176         "new_variable"      =>  "FAIvariable",
177         "new_template"      =>  "FAItemplate",
178         "new_package"       =>  "FAIpackageList");
179     $types_i18n = array( 
180         "new_partition"     =>  _("partition table"),
181         "new_script"        =>  _("script"),
182         "new_hook"          =>  _("hook"),
183         "new_variable"      =>  _("variable"),
184         "new_template"      =>  _("template"),
185         "new_package"       =>  _("package list"));
187     if(isset($types[$action])){
188       $type_acl_mapping = array(
189           "FAIpartitionTable"  => "faiPartitionTable",
190           "FAIpackageList"     => "faiPackage",
191           "FAIscript"          => "faiScript",
192           "FAIvariable"        => "faiVariable",
193           "FAIhook"            => "faiHook",
194           "FAIprofile"         => "faiProfile",
195           "FAItemplate"        => "faiTemplate");
197       $acl = $this->ui->get_permissions($this->acl_base,"fai/".$type_acl_mapping[$types[$action]]);
198       if(preg_match("/c/",$acl)){
199         $this->dialogObject = new askClassName($this->config,$this->dn,$this->ui,$types[$action]);
200         $this->dialogObject->parent = &$this;
201       }else{
202         msg_dialog::display(_("Permission error"), 
203             sprintf(_("You have no permission to create a new %s!"), $types_i18n[$action]),      ERROR_DIALOG);
204       }
205     }
206     if($action == "new_profile"){
207       $this->dn = "new" ;
209       $acl = $this->ui->get_permissions($this->acl_base,"fai/faiProfile");
210       if(preg_match("/c/",$acl)){
211         $type= $this->get_type(array("objectClass"=>array("FAIprofile")));
212         $str= management::newEntry('newEntry',array(),array(),$type[0],$type[2],$type[1]);
213         if($str) return($str);
214         $this->tabObject->set_acl_base($this->acl_base);
215         $this->tabObject->by_object[$type[1]]->cn = $name;
216       }else{
217         msg_dialog::display(_("Permission error"), sprintf(_("You have no permission to create a new %s!"), _("profile")), ERROR_DIALOG);
218       }
219     }
220   }
223   /*! \brief   A new FAI class was requested and the user had a specify a name for it.
224    *           Here we check if this name is useable and then open the edit dialogs.
225    */
226   function newClassNameSelected()
227   {
228     $this->dialogObject->save_object();
229     if(count($this->dialogObject->check())!=0){
230       foreach($this->dialogObject->check() as $msg){
231         msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
232       }
233     }elseif(isset($this->dialogObject->objectClass)){
234       $this->dn = "new" ;
235       $type= $this->get_type(array("objectClass"=>array($this->dialogObject->objectClass)));
236       $name = $this->dialogObject->save();
238       if(class_exists($type[0])){
239         $this->closeDialogs();
240         $str = management::newEntry('newEntry',array(),array(),$type[0],$type[2],$type[1]);
241         if($str) return($str);
242         $this->tabObject->set_acl_base($this->acl_base);
243         $this->tabObject->by_object[$type[1]]->cn = $name;
244       }
245     }
246   }
249   /*! \brief   Edit the selected entry.
250    *           If there was a FAI group clicked, display a dialog with all members of the group.
251    */
252   function editEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
253   {
254     $headpage = $this->getHeadpage();
255     if(count($target) == 1){
256       $entry = $headpage->getEntry($target[0]);
257       if($entry){
259         // Edit Opsi objects here 
260         if(in_array("opsi_local", $entry['TYPES']) || in_array("opsi_netboot", $entry['TYPES'])){ 
261           $name = $entry['cn'];
262           $cfg = $this->opsi->get_product_properties($name);
264           $str = management::editEntry('editEntry',array($name),array(),'tabs_opsiProdConfig','OPSIPRODCONFIG','opsi');
265           if($str) return($str);
266           if(isset($this->tabObject->by_object['opsiProperties'])){
267             $this->tabObject->by_object['opsiProperties']->set_cfg($cfg);
268             $this->tabObject->by_object['opsiProperties']->set_product($name);
269             $this->skipFooter = TRUE;
270           }else{
271             trigger_error("Unknown tab, please check config.");
272           }
274         }else{
276           // Edit FAI objects here 
277           if(count($entry['GROUPS']) == 1){
278             $data = array_pop($entry['GROUPS']);
279             $type = $this->get_type($data);
280             $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]);
281             if($str) return($str);
282             $this->tabObject->by_object[$type[1]]->FAIstate = $data['FAIstate'];
283             $this->tabObject->read_only = preg_match("/freeze/i", $data['FAIstate']);
285           }else{
286             $this->dialogObject = new faiGroupHandle($entry['GROUPS'],"edit");
287           }
288         }
289       }
290     }
291   }
294   /*! \brief   Save changes made in opsi dialogs.
295    */
296   function saveOpsiProperties()
297   {
298     if($this->tabObject instanceof tabs_opsiProdConfig && isset($_POST['save_properties'])){
299       $this->tabObject->save_object();
300       $op    = $this->tabObject->by_object['opsiProperties'];
301       $name  = $op->get_product();
302       $cfg   = $op->get_cfg();
303       $this->opsi->set_product_properties($name,$cfg);
304       if($this->opsi->is_error()){
305         msg_dialog::display(_("Error"),msgPool::siError($this->opsi->get_error()),ERROR_DIALOG);
306       }else{
307         $this->remove_lock();
308         $this->closeDialogs();
309       }
310     }
311   }
314   /*! \brief   Someone wants to remove some object(s)
315    *            ask for a confirmation now.
316    */
317   function removeEntryRequested($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
318   {
319     $this->closeDialogs();
320     if($action == "remove_multiple"){
322       // Collect objects to delete
323       $headpage = $this->getHeadpage();
324       $to_delete = array();
325       foreach($target as $id){
326         $object = $headpage->getEntry($id);
327         if(in_array("FAKE_OC_FAI", $object['objectClass'])){
328           foreach($object['GROUPS']  as $entry){
329             array_push($to_delete, $entry);
330           }
331         }
332       }
333       return($this->removeFAIObjects($to_delete));
334     }else{
336       // Try to remove a single object, only FAI objects can be removed!
337       $headpage = $this->getHeadpage();
338       if(count($target) == 1){
339         $entry = $headpage->getEntry($target[0]);
340         if($entry && in_array("FAKE_OC_FAI",$entry['objectClass'])){
341           $this->dialogObject = new faiGroupHandle($entry['GROUPS'],"remove");
342         }
343       }
344     }
345   }
348   /*! \brief   Someone wants to remove some object(s)
349    *            ask for a confirmation now.
350    */
351   function removeFAIObjects($to_delete)
352   {
353     // Do not allow to remove objects with state freeezed
354     $errors=array();
355     foreach($to_delete as $obj){
356       if(isset($obj['FAIstate']) && preg_match('/^freeze/', $obj['FAIstate'])){
357         $errors[] = $obj['dn'];
358       }else{
359         $this->dns[] = $obj['dn'];
360       }
361     }
362     if(count($errors)){
363       msg_dialog::display(_("Branch locked"),
364           sprintf(_("The following entries are locked, you can't remove them %s."),msgPool::buildList($errors)),INFO_DIALOG);
365     }
367     // Check entry locking
368     if(count($this->dns)){
369       if ($user= get_multiple_locks($this->dns)){
370         return(gen_locked_message($user,$this->dns));
371       }
372       if(count($this->dns)){
373         $smarty = get_smarty();
374         $dns_names = array();
375         foreach($this->dns as $dn){
376           add_lock ($dn, $this->ui->dn);
377           $dns_names[] = LDAP::fix($dn);
378         }
379         $smarty->assign("info",msgPool::deleteInfo($dns_names,_("FAI object")));
380         $smarty->assign("multiple", true);
381         return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
382       }
383     }
384   }
387   /*! \brief   Entry removal is confirmed, now remove objects
388    */
389   function removeEntryConfirmed($action="",$target=array(),$all=array(),
390       $altTabClass="",$altTabType="",$altAclCategory="")
391   {
392     $ldap = $this->config->get_ldap_link();
393     $ldap->cd($this->config->current['BASE']); 
395     foreach($this->dns as $key => $dn){
396       $ldap->cat($dn);
397       if($ldap->count()){
398         $attrs = $ldap->fetch();
399         $type= $this->get_type($attrs);
400         $str = management::removeEntryConfirmed($action,array($dn),$all,$type[0],$type[2],$type[1]);
401         if($str) return($str);
403         // Now save changes
404         FAI::save_release_changes_now();
405         $to_del = FAI::clean_up_releases($dn);
406         foreach($to_del as $dn){
407           $ldap->rmdir_recursive($dn);
408         }
409       }
410     }
411   }
414   /*! \brief   Someone clicked on edit/remove for a grouped FAI object.
415    *           We are now going to display a dialog to let the user select the entry 
416    *            he wants to perform the action on.
417    */
418   function editByGroup()
419   {
420     if($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "edit"){
421       $this->dialogObject->save_object();
422       $entry = $this->dialogObject->get_selected();
423       $this->closeDialogs();
424       $data = array_pop($entry);
425       $type = $this->get_type($data);
426       $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]);
427       if($str) return($str);
428       $this->tabObject->by_object[$type[1]]->FAIstate = $data['FAIstate'];
429       $this->tabObject->read_only = preg_match("/freeze/i", $data['FAIstate']);
430     }elseif($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "remove"){
431       $this->dialogObject->save_object();
432       $to_delete = $entry = $this->dialogObject->get_selected();
433       return($this->removeFAIObjects($to_delete));
434     }
435   }
438   /*! \brief   Save dialog/object modifications
439    */
440   protected function saveChanges()
441   {
442     $str = management::saveChanges();
443     if($str) return($str);
445     // Now save changes
446     FAI::save_release_changes_now();
447     $to_del = FAI::clean_up_releases($this->last_dn);
448     foreach($to_del as $dn){
449       $ldap->rmdir_recursive($dn);
450     }
451   }
454   /*! \brief   Save dialog/object modifications but keep the dialogs opened
455    */
456   protected function applyChanges()
457   {
458     $str = management::applyChanges();
459     if($str) return($str);
461     // Now save changes
462     FAI::save_release_changes_now();
463     $to_del = FAI::clean_up_releases($this->last_dn);
464     foreach($to_del as $dn){
465       $ldap->rmdir_recursive($dn);
466     }
467   }
470   /*! \brief   Initiates release removal
471    */
472   function removeBranch()
473   {
474     /* Check if we have a post remove method configured
475      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
476      */
477     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
478       /* Load permissions for selected 'dn' and check if
479          we're allowed to remove this 'dn' */
480       if(preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
481         $smarty=get_smarty();
482         $smarty->assign("release_hidden",base64_encode($this->fai_release));
483         $smarty->assign("info", msgPool::deleteInfo(LDAP::fix($this->fai_release),_("FAI branch/freeze")));
484         return($smarty->fetch(get_template_path('remove_branch.tpl',TRUE)));
485       } else {
486         msg_dialog::display(_("Permission error"), _("You have no permission to delete this release!"), ERROR_DIALOG);
487       }
488     }
489   }
492   /*! \brief   Remove a release after removal was confirmed
493    */
494   function removeBranchConfirmed()
495   {
496     /* Check if we have a post remove method configured
497      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
498      */
499     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
501       if(!isset($_POST['release_hidden']) || base64_decode($_POST['release_hidden']) != $this->fai_release){
502         msg_dialog::display(_("Warning"),_("Release remove aborted because the release name check failed!"));
503       }else{
505         $bb =  $this->fai_release;
506         $ldap = $this->config->get_ldap_link();
508         $br = $this->getBranches();
510         if(isset($br[$bb]) && preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
511           $name = $br[$bb];
513           $ldap->cd($bb);
514           $ldap->recursive_remove();
515           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('applicationRDN'), $bb));
516           $ldap->recursive_remove();
517           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('mimetypeRDN'), $bb));
518           $ldap->recursive_remove();
520           /* Search for all groups with configured application menus.
521              - First search all groups, to ensure that we only remove entries form whithin groups.
522              - The search für menu configuration for the specified release and collect all those dns.
523              - Remove entries
524            */
525           $release_ou = preg_replace("/".preg_quote(get_ou("faiBaseRDN"), '/').".*$/i","",$bb);
526           $ldap->cd($this->config->current['BASE']);
527           $ldap->search("(objectClass=posixGroup)",array("dn"));
529           /* Collect all group dns
530            */
531           $groups = array();
532           while($attrs = $ldap->fetch()){
533             $groups[] = $attrs['dn'];
534           }
537           /* Collect all group menu release dns that match the release we have removed
538            */
539           $dns = array();
540           foreach($groups as $dn){
541             $ldap->cd($dn);
542             $ldap->search("(objectClass=FAIbranch)",array("dn"));
543             while($attrs = $ldap->fetch()){
544               if(preg_match("/^".preg_quote($release_ou, '/')."/",$attrs['dn'])){
545                 $dns[] = $attrs['dn'];
546               }
547             }
548           }
550           /* Finally remove collected release dns
551            */
552           foreach($dns as $dn){
553             $ldap->cd($dn);
554             $ldap->recursive_remove();
555           }
557           /* Post remove */
558           $this->fai_release = $this->fai_base;
559           $this->lock_name   = $name;
560           $this->lock_dn     = $bb;
561           $this->postremove();
563           $fai_filter = session::get("fai_filter");
564           $fai_filter['fai_release'] = $this->fai_release;
565           session::set("fai_filter",$fai_filter);
567           new log("remove","fai/".get_class($this),$br[$bb],array(),"Release removed");
568         }
569       }
570     }
571   }
574   /*! \brief   Initiates release creation 
575    */
576   function createBranch()
577   { 
578     $smarty = get_smarty();
579     $this->dispNewBranch=true;
580     $this->dispNewFreeze=false;
581     $smarty->assign("iframe",false);
582     if(isset($_POST['BranchName'])){
583       $smarty->assign("BranchName", $_POST['BranchName']);
584     }else{
585       $smarty->assign("BranchName","");
586     }
587     return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
588   }
591   /*! \brief   Initiates release creation 
592    */
593   function createFreeze()
594   { 
595     $smarty = get_smarty();
596     $this->dispNewFreeze=true;
597     $this->dispNewBranch=false;
598     $smarty->assign("iframe",false);
599     if(isset($_POST['BranchName'])){
600       $smarty->assign("BranchName", $_POST['BranchName']);
601     }else{
602       $smarty->assign("BranchName","");
603     }
604     return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
605   }
608   /*! \brief   Creates a new branch
609    */
610   function PerformBranch()
611   {
612     if(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
613       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
614     }else{
616       /* In order to see error messages we have to reset the error handler.
617          Due to the exit();
618        */
619       restore_error_handler();
621       $this->dispNewBranch = false;
622       $this->dispNewFreeze = false;
624       $LASTPOST = session::get('LASTPOST');
625       $base = $LASTPOST['base'];
626       $_POST  = session::get('LASTPOST');
627       $name = $_POST['BranchName'];
629       $type = $LASTPOST['type'];
630       $ldap = $this->config->get_ldap_link();
632       $baseToUse = $base;
633       if($this->fai_release !=  $this->fai_base){
634         $baseToUse = $this->fai_release;
635       }
637       /* Create new Release name to be able to set faidebianRelease for FAIpackageList */
639       $CurrentReleases  = $this->getBranches();
640       $NewReleaseName   = $name;
641       if(isset($CurrentReleases[$this->fai_release])) {
642         if($this->fai_release != $this->fai_base){
643           $NewReleaseName = $CurrentReleases[$this->fai_release]."/".$name;
644           $NewReleaseName = preg_replace("#\/#","/",$NewReleaseName);
645         }else{
646           $NewReleaseName   = $name;
647         }
648       }
649       $appsrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),$baseToUse);
650       $appdst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),"ou=".$name.",".$baseToUse) ;
652       $mimesrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),$baseToUse);
653       $mimedst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),"ou=".$name.",".$baseToUse) ;
655       /* Check if source depeartments exist */
656       foreach(array($baseToUse,$appsrc,$mimesrc) as $dep){
657         $ldap->cd($this->config->current['BASE']);
658         $ldap->cat($dep);
659         if(!$ldap->count()){
660           $ldap->create_missing_trees($dep);
661         }
662       }
664       /* Print header to have styles included */
665       echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
666         <html>
667         <head>
668         <title></title>
669         <style type="text/css">@import url("themes/default/style.css");</style>
670         <script language="javascript" src="include/focus.js" type="text/javascript"></script>
671         </head>
672         <body style="background: none;margin:3px;color:black">
673         ';
675       new log("create","fai/".get_class($this),$NewReleaseName,array(),"New $type created");
677       /* Duplicate group application releases
678        */
679       FAI::copy_FAI_group_releases($CurrentReleases[$this->fai_release],$name,$type);
681       /* Duplicate applications
682        */
683       $ldap->cat($appsrc,array("dn")) ;
684       if($ldap->count()){
685         $ldap->cd ($appdst);
686         $ldap->recursive_remove();
687         FAI::copy_FAI_resource_recursive($appsrc,$appdst,$NewReleaseName,$type,true);
688       }
690       /* Duplicate mime types
691        */
692       $ldap->cat($mimesrc,array("dn")) ;
693       if($ldap->count()){
694         $ldap->cd ($mimedst);
695         $ldap->recursive_remove();
696         FAI::copy_FAI_resource_recursive($mimesrc,$mimedst,$NewReleaseName,$type,true);
697       }
699       $attr = array();
700       $attr['objectClass'] = array("organizationalUnit","FAIbranch");
701       $attr['ou']       = $name;
702       $attr['FAIstate'] = $type;
703       $ldap->cd($this->config->current['BASE']);
704       $ldap->cd("ou=".$name.",".$baseToUse);
705       $ldap->cat("ou=".$name.",".$baseToUse);
706       if($ldap->count()){
707         $ldap->modify($attr);
708       }else{
709         $ldap->add($attr);
710       }
712       /* Duplicate fai objects
713        */
714       //      $ldap->cd ("ou=".$name.",".$baseToUse);
715       //      $ldap->recursive_remove();
716       //      FAI::copy_FAI_resource_recursive($baseToUse,"ou=".$name.",".$baseToUse,$NewReleaseName,$type,true);
718       echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
719         <br><input type='submit' name='CloseIFrame' value='"._("Continue")."'>
720         <input type='hidden' name='php_c_check' value='1'>
721         </form></div>";
723       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
725       /* Print footer to have valid html */
726       echo "</body></html>";
728       $this->dispNewFreeze = false;
730       /* Postcreate */
732       /* Assign possible attributes */
733       $this->lock_type  = $type;
734       $this->lock_name  = $name;
735       $this->lock_dn    = $baseToUse;
736       $this->postcreate();
738       /* Send daemon event to reload the fai release database
739        */
740       if(class_available("DaemonEvent") && class_available("gosaSupportDaemon")){
741         $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);
742         if(isset($events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'])){
743           $evt = $events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'];
744           $tmp = new $evt['CLASS_NAME']($this->config);
745           $tmp->set_type(TRIGGERED_EVENT);
746           $tmp->add_targets(array("GOSA"));
747           $o_queue = new gosaSupportDaemon();
748           if(!$o_queue->append($tmp)){
749             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
750           }
751         }
752       }else{
753         trigger_error("Unknown class DaemonEvent / gosaSupportDaemon");
754         msg_dialog::display(_("Fatal error"),
755             "Daemon events called but classes where not accessible, DaemonEvent gosaSupportDaemon",
756             FATAL_ERROR_DIALOG);
757       }
758       exit();
759     }
760   }
763   /*! \brief   Creates a new branch, after a useable name was specified.
764    */
765   function saveBranch()
766   {
767     if($this->dispNewBranch){
768       $type = "branch";
769     }else{
770       $type = "freeze";
771     }
773     /* Check branch name */
774     $name = $_POST['BranchName'];
775     $is_ok = true;
776     $smarty = get_smarty();
777     $smarty->assign("BranchName",$name);
778     $base= $this->fai_base;
780     /* Check used characters */
781     if(!preg_match("/^[0-9a-z\.]*$/",$name)){
782       msg_dialog::display(_("Error"), msgPool::invalid(_("Name"),$name,"/[0-9a-z\.]/"), ERROR_DIALOG);
783       $is_ok = false;
784     }
786     // Check if this name is already in use 
787     if(!$this->CheckNewBranchName($_POST['BranchName'],$this->fai_release)){
788       msg_dialog::display(_("Error"), msgPool::duplicated(_("Name")), ERROR_DIALOG);
789       $is_ok = false;
790     }
792     // Handle errors
793     if(!$is_ok && $this->dispNewFreeze){
794       return($this->createFreeze());
795     }elseif(!$is_ok && $this->dispNewBranch){
796       return($this->createBranch());
797     }
799     // Now create new release
801     if(session::is_set('LASTPOST')){
802       $LASTPOST = session::get('LASTPOST');
803     }else{
804       $LASTPOST = array();
805     }
806     $LASTPOST['base'] = $base;
807     $LASTPOST['type'] = $type;
808     $LASTPOST['BranchName'] = $name;
809     session::set('LASTPOST',$LASTPOST);
810     $smarty->assign("iframe", true);
811     $smarty->assign("plugID", $_GET['plug']);
812     $display  = $smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__)));
813     return($display);
815   }
819   /*! \brief   Returns a list of all releases for useable for drop down boxes.
820    *                      ou=fai... /
821    *              ou=siga,ou=fai... &nbsp; siga
822    *         ou=1,ou=siga,ou=fai... &nbsp;&nbsp; 1
823    */
824   function getReleaseList($base = "", $prefix ="")
825   {
826     $list = array();
827     if(empty($base)){
828       $base = $this->fai_base;
829       $list[$base] = "/";
830     }
832     $ldap = $this->config->get_ldap_link();
833     $ldap->ls("(objectClass=FAIbranch)",$base,array("ou","FAIstate"));
835     while($release = $ldap->fetch()){
836       $list[$release['dn']] = $prefix.$release['ou'][0];
837       $list = array_merge($list,$this->getReleaseList($release['dn'],$prefix."&nbsp; "));
838     }
839     return($list);
840   }
843   /*! \brief   Returns a list of all releases with full release names
844    *                      ou=fai... /
845    *              ou=siga,ou=fai... siga
846    *         ou=1,ou=siga,ou=fai... siga/1
847    */
848   function getBranches($base = false,$prefix = "")
849   {
850     $ret = array("/"=>$this->fai_base);
851     $ldap = $this->config->get_ldap_link();
852     if(!$base){
853       $base = $this->fai_base;
854     }
855     $tmp = FAI::get_all_releases_from_base($base,true);
856     foreach($tmp as $dn => $name){
857       $ret[$name]=$dn;
858     }
859     ksort($ret);
860     $ret = array_flip($ret);
862     return ($ret);
863   }
866   /*! \brief   Detects object info like corresponding  tab,class,acl 
867    *    e.g.    [0]   =  tabsPartition
868    *            [1]   =  faiPartitionTable
869    *            [2]   =  FAIPARTITIONTABS
870    */
871   function get_type($array)
872   {
873     if(!isset($array['objectClass'])) return(array());
874     if(in_array("FAIpartitionTable",$array['objectClass'])){
875       return(array("tabsPartition","faiPartitionTable","FAIPARTITIONTABS"));
876     }
877     if(in_array("FAIscript",$array['objectClass'])){
878       return(array("tabsScript","faiScript","FAISCRIPTTABS"));
879     }
880     if(in_array("FAItemplate",$array['objectClass'])){
881       return(array("tabsTemplate","faiTemplate","FAITEMPLATETABS"));
882     }
883     if(in_array("FAIhook",$array['objectClass'])){
884       return(array("tabsHook","faiHook","FAIHOOKTABS"));
885     }
886     if(in_array("FAIvariable",$array['objectClass'])){
887       return(array("tabsVariable","faiVariable","FAIVARIABLETABS"));
888     }
889     if(in_array("FAIprofile",$array['objectClass'])){
890       return(array("tabsProfile","faiProfile","FAIPROFILETABS"));
891     }
892     if(in_array("FAIpackageList",$array['objectClass'])){
893       return(array("tabsPackage","faiPackage","FAIPACKAGETABS"));
894     }
895     return(array());
896   }
899   /*! \brief   Checks if the given string can be used as class name
900    */
901   static function check_class_name($oc,$name,$dn)
902   {
903     $base = FAI::get_release_dn($dn);
905     if($oc == "FAIprofile"){
906       $f = "";
907       $ocs = array("FAIprofile","FAItemplate","FAIhook","FAIpartitionTable","FAIpackageList","FAIscript","FAIvariable");
908       foreach($ocs as $oc){
909         $f .= "(objectClass=".$oc.")";
910       }
911       $res  = FAI::get_all_objects_for_given_base($base,"(|".$f.")",TRUE);
912     }else{
913       $res  = FAI::get_all_objects_for_given_base($base,"(objectClass=".$oc.")",TRUE);
914     }
915     $delete = array();
916     $used   = array();
917     foreach($res as $object){
918       $used[$object['cn'][0]]= $object['cn'][0];
919     }
920     return($used);
921   }
924   /*! \brief   Checks if the given string can be used for a new release
925    */
926   function CheckNewBranchName($name,$base)
927   {
928     $f = $this->fai_release;
929     if($name == ""){
930       return(false);
931     }elseif(in_array($name,$this->getBranches($f))) {
932       return(false);
933     }elseif(tests::is_department_name_reserved($name,$base)){
934       return(false);
935     }
936     return(true);
937   }
940   /*! \brief   This filter is used to display small icons for each listed object 
941    *            instead of their typ names
942    */
943   static function filterProperties($row, $classes)
944   {
945     $objects = array(
946         "FAIpartitionTable"  => array("IMG"=> "plugins/fai/images/fai_partitionTable.png",
947           "NAME"=>_("Partition table"),"KZL"=> "PT", "VAR"=>"ShowPartitions"),
948         "FAIpackageList"     => array("IMG"=> "plugins/fai/images/fai_packages.png",
949           "NAME"=>_("Package list") ,  "KZL"=> "PL", "VAR"=>"ShowPackages"),
950         "FAIscript"          => array("IMG"=> "plugins/fai/images/fai_script.png",
951           "NAME"=>_("Scripts") ,       "KZL"=> "S",  "VAR"=>"ShowScripts"),
952         "FAIvariable"        => array("IMG"=> "plugins/fai/images/fai_variable.png",
953           "NAME"=>_("Variables") ,     "KZL"=> "V",  "VAR"=>"ShowVariables"),
954         "FAIhook"            => array("IMG"=> "plugins/fai/images/fai_hook.png",
955           "NAME"=>_("Hooks"),          "KZL"=> "H",  "VAR"=>"ShowHooks"),
956         "FAIprofile"         => array("IMG"=> "plugins/fai/images/fai_profile.png",
957           "NAME"=>_("Profile") ,       "KZL"=> "P",  "VAR"=>"ShowProfiles"),
958         "FAItemplate"        => array("IMG"=> "plugins/fai/images/fai_template.png",
959           "NAME"=>_("Templates") ,     "KZL"=> "T",  "VAR"=>"ShowTemplates"),
960         "opsi_netboot"       => array("IMG"=> "plugins/opsi/images/netboot_package.png",
961           "NAME"=>_("OPSI netboot product") ,     "KZL"=> "ON",  "VAR"=>"ShowOpsiNetboot"),
962         "opsi_local"         => array("IMG"=> "plugins/opsi/images/local_package.png",
963           "NAME"=>_("OPSI localboot product")   ,     "KZL"=> "OL",  "VAR"=>"ShowOpsiLocal"));
965     $icon_list = "";
966     foreach($objects as $type => $type_data){
967       if(in_array($type, $classes)){
968         $icon_list .= "<input type='image' src='".$type_data['IMG']."' title='".$type_data['NAME']."'
969           alt='".$type_data['KZL']."' class='center' name='edit_".$row."_".$type."'>\n";
970       }else{
971         $icon_list .= "<img src='images/empty.png' alt=' ' class='center'>\n";
972       }
973     }
975     return $icon_list;
976   }
979   /*! \brief   Overridden render method of class mangement. 
980    *            this allows us to add a release selection box.
981    */
982   function renderList()
983   {
984     $filter = $this->getFilter();
985     $headpage = $this->getHeadpage();
986     $filter->setComboBoxOptions("RELEASE",$this->getReleaseList());
988     if(isset($_POST['RELEASE'])){
989       $this->fai_release = get_post('RELEASE');
990     }
991     $headpage->setBase($this->fai_release);
992     $headpage->update();
993     $smarty = get_smarty();
994     $smarty->assign("fai_release", $this->fai_release);
995     $smarty->assign("opsi_available", is_object($this->opsi));
996     $smarty->assign("fai_base", $this->fai_base);
997     $r = $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'));
998     $c = $this->config->search("faiManagement", "POSTCREATE",array('menu','tabs'));
999     $smarty->assign("allow_create", $c);
1000     $smarty->assign("allow_remove", $r);
1001     $display = $headpage->render();
1002     return($this->getHeader().$display);
1003   }
1006   /*! \brief   Convert POST and GET variables into actions.
1007    */
1008   function detectPostActions()
1009   {
1010     $action = management::detectPostActions();
1011     if(isset($_POST['remove_multiple'])) $action['action'] = "remove";
1012     if(isset($_POST['new_profile'])) $action['action'] = "new_profile";
1013     if(isset($_POST['new_template'])) $action['action'] = "new_template";
1014     if(isset($_POST['new_script'])) $action['action'] = "new_script";
1015     if(isset($_POST['new_hook'])) $action['action'] = "new_hook";
1016     if(isset($_POST['new_variable'])) $action['action'] = "new_variable";
1017     if(isset($_POST['new_package'])) $action['action'] = "new_package";
1018     if(isset($_POST['new_partition'])) $action['action'] = "new_partition";
1020     if(isset($_POST['save_properties'])) $action['action'] = "saveOpsiProperties";
1021     if(isset($_POST['cancel_properties'])) $action['action'] = "cancel";
1023     if(isset($_POST['edit_continue'])) $action['action'] = "newClassNameSelected";
1024     if(isset($_POST['edit_cancel'])) $action['action'] = "cancel";
1026     if(isset($_POST['faiGroupHandle_cancel'])) $action['action'] = "cancel";
1027     if(isset($_POST['CancelBranchName'])) $action['action'] = "cancel";
1028     if(isset($_POST['delete_branch_confirm'])) $action['action'] = "removeBranchConfirmed";
1029     if(isset($_GET['PerformBranch'])) $action['action'] = "PerformBranch";
1030     if(isset($_POST['UseBranchName'])) $action['action'] = "saveBranch";
1031     if(isset($_POST['faiGroupHandle_apply']))  $action['action'] = "editByGroup";
1032     if(isset($_GET['act']) && $_GET['act'] == "branch_branch")  $action['action'] = "createBranch";
1033     if(isset($_GET['act']) && $_GET['act'] == "freeze_branch")  $action['action'] = "createFreeze";
1034     if(isset($_GET['act']) && $_GET['act'] == "remove_branch")  $action['action'] = "removeBranch";
1036     foreach($_POST as $name => $value){
1037       if(preg_match("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i", $name)){
1038         $id = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\1", $name);
1039         $tab = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\2", $name);
1041         $headpage = $this->getHeadpage();
1042         $entry = $headpage->entries[$id];
1044         if(in_array('FAKE_OC_FAI', $entry['objectClass'])){
1045           if(isset($headpage->entries[$id]['GROUPS'][$tab])){
1046             $data =$headpage->entries[$id]['GROUPS'][$tab];
1047             $type = $this->get_type($data);
1048             $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]); 
1049             if($str) return($str);
1050           } 
1051         }else{
1052           $str = $this->editEntry('editEntry',array($entry['dn'])); 
1053           if($str) return($str);
1054         }
1055         break;
1056       }
1057     }
1058     return($action);
1059   }
1062   static function plInfo()
1063   {
1064     return (array(
1065           "plShortName"   => _("FAI releases"),
1066           "plDescription" => _("FAI release management"),
1067           "plSelfModify"  => FALSE,
1068           "plDepends"     => array(),
1069           "plPriority"    => 0,
1070           "plSection"     => array("administration"),
1071           "plCategory"    => array("fai"=> array("description" => _("FAI"),
1072               "objectClass" => "FAIclass")),
1073           "plProvidedAcls"=> array()));
1074   }
1075
1076 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1077 ?>