Code

Added missing permission check to faiManagement::remove
[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     $disallowed = array();
396     foreach($this->dns as $key => $dn){
397       $ldap->cat($dn);
398       if($ldap->count()){
399         $attrs = $ldap->fetch();
400         $type= $this->get_type($attrs);
402         $acl  = $this->ui->get_permissions($dn,"fai/".$type[1]);
403         if(preg_match("/d/",$acl)){
405           // Now save changes
406           management::removeEntryConfirmed($action,array($dn),$all,$type[0],$type[2],$type[1]);
407           FAI::save_release_changes_now();
408           $to_del = FAI::clean_up_releases($dn);
409           foreach($to_del as $dn){
410             $ldap->rmdir_recursive($dn);
411           }
413         } else {
414           $disallowed[] = $dn;
415           new log("security","fai/".get_class($this),$dn,array(),"Tried to trick deletion.");
416         }
417       }
418     }
420     /* Normally this shouldn't be reached, send some extra
421        logs to notify the administrator */
422     if(count($disallowed)){ 
423       msg_dialog::display(_("Permission error"), msgPool::permDelete($disallowed), ERROR_DIALOG);
424     }
425   }
428   /*! \brief   Someone clicked on edit/remove for a grouped FAI object.
429    *           We are now going to display a dialog to let the user select the entry 
430    *            he wants to perform the action on.
431    */
432   function editByGroup()
433   {
434     if($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "edit"){
435       $this->dialogObject->save_object();
436       $entry = $this->dialogObject->get_selected();
437       $this->closeDialogs();
438       $data = array_pop($entry);
439       $type = $this->get_type($data);
440       $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]);
441       if($str) return($str);
442       $this->tabObject->by_object[$type[1]]->FAIstate = $data['FAIstate'];
443       $this->tabObject->read_only = preg_match("/freeze/i", $data['FAIstate']);
444     }elseif($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "remove"){
445       $this->dialogObject->save_object();
446       $to_delete = $entry = $this->dialogObject->get_selected();
447       return($this->removeFAIObjects($to_delete));
448     }
449   }
452   /*! \brief   Save dialog/object modifications
453    */
454   protected function saveChanges()
455   {
456     $str = management::saveChanges();
457     if($str) return($str);
459     // Now save changes
460     FAI::save_release_changes_now();
461     $to_del = FAI::clean_up_releases($this->last_dn);
462     foreach($to_del as $dn){
463       $ldap->rmdir_recursive($dn);
464     }
465   }
468   /*! \brief   Save dialog/object modifications but keep the dialogs opened
469    */
470   protected function applyChanges()
471   {
472     $str = management::applyChanges();
473     if($str) return($str);
475     // Now save changes
476     FAI::save_release_changes_now();
477     $to_del = FAI::clean_up_releases($this->last_dn);
478     foreach($to_del as $dn){
479       $ldap->rmdir_recursive($dn);
480     }
481   }
484   /*! \brief   Initiates release removal
485    */
486   function removeBranch()
487   {
488     /* Check if we have a post remove method configured
489      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
490      */
491     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
492       /* Load permissions for selected 'dn' and check if
493          we're allowed to remove this 'dn' */
494       if(preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
495         $smarty=get_smarty();
496         $smarty->assign("release_hidden",base64_encode($this->fai_release));
497         $smarty->assign("info", msgPool::deleteInfo(LDAP::fix($this->fai_release),_("FAI branch/freeze")));
498         return($smarty->fetch(get_template_path('remove_branch.tpl',TRUE)));
499       } else {
500         msg_dialog::display(_("Permission error"), _("You have no permission to delete this release!"), ERROR_DIALOG);
501       }
502     }
503   }
506   /*! \brief   Remove a release after removal was confirmed
507    */
508   function removeBranchConfirmed()
509   {
510     /* Check if we have a post remove method configured
511      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
512      */
513     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
515       if(!isset($_POST['release_hidden']) || base64_decode($_POST['release_hidden']) != $this->fai_release){
516         msg_dialog::display(_("Warning"),_("Release remove aborted because the release name check failed!"));
517       }else{
519         $bb =  $this->fai_release;
520         $ldap = $this->config->get_ldap_link();
522         $br = $this->getBranches();
524         if(isset($br[$bb]) && preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
525           $name = $br[$bb];
527           $ldap->cd($bb);
528           $ldap->recursive_remove();
529           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('applicationRDN'), $bb));
530           $ldap->recursive_remove();
531           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('mimetypeRDN'), $bb));
532           $ldap->recursive_remove();
534           /* Search for all groups with configured application menus.
535              - First search all groups, to ensure that we only remove entries form whithin groups.
536              - The search für menu configuration for the specified release and collect all those dns.
537              - Remove entries
538            */
539           $release_ou = preg_replace("/".preg_quote(get_ou("faiBaseRDN"), '/').".*$/i","",$bb);
540           $ldap->cd($this->config->current['BASE']);
541           $ldap->search("(objectClass=posixGroup)",array("dn"));
543           /* Collect all group dns
544            */
545           $groups = array();
546           while($attrs = $ldap->fetch()){
547             $groups[] = $attrs['dn'];
548           }
551           /* Collect all group menu release dns that match the release we have removed
552            */
553           $dns = array();
554           foreach($groups as $dn){
555             $ldap->cd($dn);
556             $ldap->search("(objectClass=FAIbranch)",array("dn"));
557             while($attrs = $ldap->fetch()){
558               if(preg_match("/^".preg_quote($release_ou, '/')."/",$attrs['dn'])){
559                 $dns[] = $attrs['dn'];
560               }
561             }
562           }
564           /* Finally remove collected release dns
565            */
566           foreach($dns as $dn){
567             $ldap->cd($dn);
568             $ldap->recursive_remove();
569           }
571           /* Post remove */
572           $this->fai_release = $this->fai_base;
573           $this->lock_name   = $name;
574           $this->lock_dn     = $bb;
575           $this->postremove();
577           $fai_filter = session::get("fai_filter");
578           $fai_filter['fai_release'] = $this->fai_release;
579           session::set("fai_filter",$fai_filter);
581           new log("remove","fai/".get_class($this),$br[$bb],array(),"Release removed");
582         }
583       }
584     }
585   }
588   /*! \brief   Initiates release creation 
589    */
590   function createBranch()
591   { 
592     $smarty = get_smarty();
593     $this->dispNewBranch=true;
594     $this->dispNewFreeze=false;
595     $smarty->assign("iframe",false);
596     if(isset($_POST['BranchName'])){
597       $smarty->assign("BranchName", $_POST['BranchName']);
598     }else{
599       $smarty->assign("BranchName","");
600     }
601     return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
602   }
605   /*! \brief   Initiates release creation 
606    */
607   function createFreeze()
608   { 
609     $smarty = get_smarty();
610     $this->dispNewFreeze=true;
611     $this->dispNewBranch=false;
612     $smarty->assign("iframe",false);
613     if(isset($_POST['BranchName'])){
614       $smarty->assign("BranchName", $_POST['BranchName']);
615     }else{
616       $smarty->assign("BranchName","");
617     }
618     return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
619   }
622   /*! \brief   Creates a new branch
623    */
624   function PerformBranch()
625   {
626     if(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
627       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
628     }else{
630       /* In order to see error messages we have to reset the error handler.
631          Due to the exit();
632        */
633       restore_error_handler();
635       $this->dispNewBranch = false;
636       $this->dispNewFreeze = false;
638       $LASTPOST = session::get('LASTPOST');
639       $base = $LASTPOST['base'];
640       $_POST  = session::get('LASTPOST');
641       $name = $_POST['BranchName'];
643       $type = $LASTPOST['type'];
644       $ldap = $this->config->get_ldap_link();
646       $baseToUse = $base;
647       if($this->fai_release !=  $this->fai_base){
648         $baseToUse = $this->fai_release;
649       }
651       /* Create new Release name to be able to set faidebianRelease for FAIpackageList */
653       $CurrentReleases  = $this->getBranches();
654       $NewReleaseName   = $name;
655       if(isset($CurrentReleases[$this->fai_release])) {
656         if($this->fai_release != $this->fai_base){
657           $NewReleaseName = $CurrentReleases[$this->fai_release]."/".$name;
658           $NewReleaseName = preg_replace("#\/#","/",$NewReleaseName);
659         }else{
660           $NewReleaseName   = $name;
661         }
662       }
663       $appsrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),$baseToUse);
664       $appdst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),"ou=".$name.",".$baseToUse) ;
666       $mimesrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),$baseToUse);
667       $mimedst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),"ou=".$name.",".$baseToUse) ;
669       /* Check if source depeartments exist */
670       foreach(array($baseToUse,$appsrc,$mimesrc) as $dep){
671         $ldap->cd($this->config->current['BASE']);
672         $ldap->cat($dep);
673         if(!$ldap->count()){
674           $ldap->create_missing_trees($dep);
675         }
676       }
678       /* Print header to have styles included */
679       echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
680         <html>
681         <head>
682         <title></title>
683         <style type="text/css">@import url("themes/default/style.css");</style>
684         <script language="javascript" src="include/focus.js" type="text/javascript"></script>
685         </head>
686         <body style="background: none;margin:3px;color:black">
687         ';
689       new log("create","fai/".get_class($this),$NewReleaseName,array(),"New $type created");
691       /* Duplicate group application releases
692        */
693       FAI::copy_FAI_group_releases($CurrentReleases[$this->fai_release],$name,$type);
695       /* Duplicate applications
696        */
697       $ldap->cat($appsrc,array("dn")) ;
698       if($ldap->count()){
699         $ldap->cd ($appdst);
700         $ldap->recursive_remove();
701         FAI::copy_FAI_resource_recursive($appsrc,$appdst,$NewReleaseName,$type,true);
702       }
704       /* Duplicate mime types
705        */
706       $ldap->cat($mimesrc,array("dn")) ;
707       if($ldap->count()){
708         $ldap->cd ($mimedst);
709         $ldap->recursive_remove();
710         FAI::copy_FAI_resource_recursive($mimesrc,$mimedst,$NewReleaseName,$type,true);
711       }
713       $attr = array();
714       $attr['objectClass'] = array("organizationalUnit","FAIbranch");
715       $attr['ou']       = $name;
716       $attr['FAIstate'] = $type;
717       $ldap->cd($this->config->current['BASE']);
718       $ldap->cd("ou=".$name.",".$baseToUse);
719       $ldap->cat("ou=".$name.",".$baseToUse);
720       if($ldap->count()){
721         $ldap->modify($attr);
722       }else{
723         $ldap->add($attr);
724       }
726       /* Duplicate fai objects
727        */
728       //      $ldap->cd ("ou=".$name.",".$baseToUse);
729       //      $ldap->recursive_remove();
730       //      FAI::copy_FAI_resource_recursive($baseToUse,"ou=".$name.",".$baseToUse,$NewReleaseName,$type,true);
732       echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
733         <br><input type='submit' name='CloseIFrame' value='"._("Continue")."'>
734         <input type='hidden' name='php_c_check' value='1'>
735         </form></div>";
737       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
739       /* Print footer to have valid html */
740       echo "</body></html>";
742       $this->dispNewFreeze = false;
744       /* Postcreate */
746       /* Assign possible attributes */
747       $this->lock_type  = $type;
748       $this->lock_name  = $name;
749       $this->lock_dn    = $baseToUse;
750       $this->postcreate();
752       /* Send daemon event to reload the fai release database
753        */
754       if(class_available("DaemonEvent") && class_available("gosaSupportDaemon")){
755         $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);
756         if(isset($events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'])){
757           $evt = $events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'];
758           $tmp = new $evt['CLASS_NAME']($this->config);
759           $tmp->set_type(TRIGGERED_EVENT);
760           $tmp->add_targets(array("GOSA"));
761           $o_queue = new gosaSupportDaemon();
762           if(!$o_queue->append($tmp)){
763             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
764           }
765         }
766       }else{
767         trigger_error("Unknown class DaemonEvent / gosaSupportDaemon");
768         msg_dialog::display(_("Fatal error"),
769             "Daemon events called but classes where not accessible, DaemonEvent gosaSupportDaemon",
770             FATAL_ERROR_DIALOG);
771       }
772       exit();
773     }
774   }
777   /*! \brief   Creates a new branch, after a useable name was specified.
778    */
779   function saveBranch()
780   {
781     if($this->dispNewBranch){
782       $type = "branch";
783     }else{
784       $type = "freeze";
785     }
787     /* Check branch name */
788     $name = $_POST['BranchName'];
789     $is_ok = true;
790     $smarty = get_smarty();
791     $smarty->assign("BranchName",$name);
792     $base= $this->fai_base;
794     /* Check used characters */
795     if(!preg_match("/^[0-9a-z\.]*$/",$name)){
796       msg_dialog::display(_("Error"), msgPool::invalid(_("Name"),$name,"/[0-9a-z\.]/"), ERROR_DIALOG);
797       $is_ok = false;
798     }
800     // Check if this name is already in use 
801     if(!$this->CheckNewBranchName($_POST['BranchName'],$this->fai_release)){
802       msg_dialog::display(_("Error"), msgPool::duplicated(_("Name")), ERROR_DIALOG);
803       $is_ok = false;
804     }
806     // Handle errors
807     if(!$is_ok && $this->dispNewFreeze){
808       return($this->createFreeze());
809     }elseif(!$is_ok && $this->dispNewBranch){
810       return($this->createBranch());
811     }
813     // Now create new release
815     if(session::is_set('LASTPOST')){
816       $LASTPOST = session::get('LASTPOST');
817     }else{
818       $LASTPOST = array();
819     }
820     $LASTPOST['base'] = $base;
821     $LASTPOST['type'] = $type;
822     $LASTPOST['BranchName'] = $name;
823     session::set('LASTPOST',$LASTPOST);
824     $smarty->assign("iframe", true);
825     $smarty->assign("plugID", $_GET['plug']);
826     $display  = $smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__)));
827     return($display);
829   }
833   /*! \brief   Returns a list of all releases for useable for drop down boxes.
834    *                      ou=fai... /
835    *              ou=siga,ou=fai... &nbsp; siga
836    *         ou=1,ou=siga,ou=fai... &nbsp;&nbsp; 1
837    */
838   function getReleaseList($base = "", $prefix ="")
839   {
840     $list = array();
841     if(empty($base)){
842       $base = $this->fai_base;
843       $list[$base] = "/";
844     }
846     $ldap = $this->config->get_ldap_link();
847     $ldap->ls("(objectClass=FAIbranch)",$base,array("ou","FAIstate"));
849     while($release = $ldap->fetch()){
850       $list[$release['dn']] = $prefix.$release['ou'][0];
851       $list = array_merge($list,$this->getReleaseList($release['dn'],$prefix."&nbsp; "));
852     }
853     return($list);
854   }
857   /*! \brief   Returns a list of all releases with full release names
858    *                      ou=fai... /
859    *              ou=siga,ou=fai... siga
860    *         ou=1,ou=siga,ou=fai... siga/1
861    */
862   function getBranches($base = false,$prefix = "")
863   {
864     $ret = array("/"=>$this->fai_base);
865     $ldap = $this->config->get_ldap_link();
866     if(!$base){
867       $base = $this->fai_base;
868     }
869     $tmp = FAI::get_all_releases_from_base($base,true);
870     foreach($tmp as $dn => $name){
871       $ret[$name]=$dn;
872     }
873     ksort($ret);
874     $ret = array_flip($ret);
876     return ($ret);
877   }
880   /*! \brief   Detects object info like corresponding  tab,class,acl 
881    *    e.g.    [0]   =  tabsPartition
882    *            [1]   =  faiPartitionTable
883    *            [2]   =  FAIPARTITIONTABS
884    */
885   function get_type($array)
886   {
887     if(!isset($array['objectClass'])) return(array());
888     if(in_array("FAIpartitionTable",$array['objectClass'])){
889       return(array("tabsPartition","faiPartitionTable","FAIPARTITIONTABS"));
890     }
891     if(in_array("FAIscript",$array['objectClass'])){
892       return(array("tabsScript","faiScript","FAISCRIPTTABS"));
893     }
894     if(in_array("FAItemplate",$array['objectClass'])){
895       return(array("tabsTemplate","faiTemplate","FAITEMPLATETABS"));
896     }
897     if(in_array("FAIhook",$array['objectClass'])){
898       return(array("tabsHook","faiHook","FAIHOOKTABS"));
899     }
900     if(in_array("FAIvariable",$array['objectClass'])){
901       return(array("tabsVariable","faiVariable","FAIVARIABLETABS"));
902     }
903     if(in_array("FAIprofile",$array['objectClass'])){
904       return(array("tabsProfile","faiProfile","FAIPROFILETABS"));
905     }
906     if(in_array("FAIpackageList",$array['objectClass'])){
907       return(array("tabsPackage","faiPackage","FAIPACKAGETABS"));
908     }
909     return(array());
910   }
913   /*! \brief   Checks if the given string can be used as class name
914    */
915   static function check_class_name($oc,$name,$dn)
916   {
917     $base = FAI::get_release_dn($dn);
919     if($oc == "FAIprofile"){
920       $f = "";
921       $ocs = array("FAIprofile","FAItemplate","FAIhook","FAIpartitionTable","FAIpackageList","FAIscript","FAIvariable");
922       foreach($ocs as $oc){
923         $f .= "(objectClass=".$oc.")";
924       }
925       $res  = FAI::get_all_objects_for_given_base($base,"(|".$f.")",TRUE);
926     }else{
927       $res  = FAI::get_all_objects_for_given_base($base,"(objectClass=".$oc.")",TRUE);
928     }
929     $delete = array();
930     $used   = array();
931     foreach($res as $object){
932       $used[$object['cn'][0]]= $object['cn'][0];
933     }
934     return($used);
935   }
938   /*! \brief   Checks if the given string can be used for a new release
939    */
940   function CheckNewBranchName($name,$base)
941   {
942     $f = $this->fai_release;
943     if($name == ""){
944       return(false);
945     }elseif(in_array($name,$this->getBranches($f))) {
946       return(false);
947     }elseif(tests::is_department_name_reserved($name,$base)){
948       return(false);
949     }
950     return(true);
951   }
954   /*! \brief   This filter is used to display small icons for each listed object 
955    *            instead of their typ names
956    */
957   static function filterProperties($row, $classes)
958   {
959     $objects = array(
960         "FAIpartitionTable"  => array("IMG"=> "plugins/fai/images/fai_partitionTable.png",
961           "NAME"=>_("Partition table"),"KZL"=> "PT", "VAR"=>"ShowPartitions"),
962         "FAIpackageList"     => array("IMG"=> "plugins/fai/images/fai_packages.png",
963           "NAME"=>_("Package list") ,  "KZL"=> "PL", "VAR"=>"ShowPackages"),
964         "FAIscript"          => array("IMG"=> "plugins/fai/images/fai_script.png",
965           "NAME"=>_("Scripts") ,       "KZL"=> "S",  "VAR"=>"ShowScripts"),
966         "FAIvariable"        => array("IMG"=> "plugins/fai/images/fai_variable.png",
967           "NAME"=>_("Variables") ,     "KZL"=> "V",  "VAR"=>"ShowVariables"),
968         "FAIhook"            => array("IMG"=> "plugins/fai/images/fai_hook.png",
969           "NAME"=>_("Hooks"),          "KZL"=> "H",  "VAR"=>"ShowHooks"),
970         "FAIprofile"         => array("IMG"=> "plugins/fai/images/fai_profile.png",
971           "NAME"=>_("Profile") ,       "KZL"=> "P",  "VAR"=>"ShowProfiles"),
972         "FAItemplate"        => array("IMG"=> "plugins/fai/images/fai_template.png",
973           "NAME"=>_("Templates") ,     "KZL"=> "T",  "VAR"=>"ShowTemplates"),
974         "opsi_netboot"       => array("IMG"=> "plugins/opsi/images/netboot_package.png",
975           "NAME"=>_("OPSI netboot product") ,     "KZL"=> "ON",  "VAR"=>"ShowOpsiNetboot"),
976         "opsi_local"         => array("IMG"=> "plugins/opsi/images/local_package.png",
977           "NAME"=>_("OPSI localboot product")   ,     "KZL"=> "OL",  "VAR"=>"ShowOpsiLocal"));
979     $icon_list = "";
980     foreach($objects as $type => $type_data){
981       if(in_array($type, $classes)){
982         $icon_list .= "<input type='image' src='".$type_data['IMG']."' title='".$type_data['NAME']."'
983           alt='".$type_data['KZL']."' class='center' name='edit_".$row."_".$type."'>\n";
984       }else{
985         $icon_list .= "<img src='images/empty.png' alt=' ' class='center'>\n";
986       }
987     }
989     return $icon_list;
990   }
993   /*! \brief   Overridden render method of class mangement. 
994    *            this allows us to add a release selection box.
995    */
996   function renderList()
997   {
998     $filter = $this->getFilter();
999     $headpage = $this->getHeadpage();
1000     $filter->setComboBoxOptions("RELEASE",$this->getReleaseList());
1002     if(isset($_POST['RELEASE'])){
1003       $this->fai_release = get_post('RELEASE');
1004     }
1005     $headpage->setBase($this->fai_release);
1006     $headpage->update();
1007     $smarty = get_smarty();
1008     $smarty->assign("fai_release", $this->fai_release);
1009     $smarty->assign("opsi_available", is_object($this->opsi));
1010     $smarty->assign("fai_base", $this->fai_base);
1011     $r = $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'));
1012     $c = $this->config->search("faiManagement", "POSTCREATE",array('menu','tabs'));
1013     $smarty->assign("allow_create", $c);
1014     $smarty->assign("allow_remove", $r);
1015     $display = $headpage->render();
1016     return($this->getHeader().$display);
1017   }
1020   /*! \brief   Convert POST and GET variables into actions.
1021    */
1022   function detectPostActions()
1023   {
1024     $action = management::detectPostActions();
1025     if(isset($_POST['remove_multiple'])) $action['action'] = "remove";
1026     if(isset($_POST['new_profile'])) $action['action'] = "new_profile";
1027     if(isset($_POST['new_template'])) $action['action'] = "new_template";
1028     if(isset($_POST['new_script'])) $action['action'] = "new_script";
1029     if(isset($_POST['new_hook'])) $action['action'] = "new_hook";
1030     if(isset($_POST['new_variable'])) $action['action'] = "new_variable";
1031     if(isset($_POST['new_package'])) $action['action'] = "new_package";
1032     if(isset($_POST['new_partition'])) $action['action'] = "new_partition";
1034     if(isset($_POST['save_properties'])) $action['action'] = "saveOpsiProperties";
1035     if(isset($_POST['cancel_properties'])) $action['action'] = "cancel";
1037     if(isset($_POST['edit_continue'])) $action['action'] = "newClassNameSelected";
1038     if(isset($_POST['edit_cancel'])) $action['action'] = "cancel";
1040     if(isset($_POST['faiGroupHandle_cancel'])) $action['action'] = "cancel";
1041     if(isset($_POST['CancelBranchName'])) $action['action'] = "cancel";
1042     if(isset($_POST['delete_branch_confirm'])) $action['action'] = "removeBranchConfirmed";
1043     if(isset($_GET['PerformBranch'])) $action['action'] = "PerformBranch";
1044     if(isset($_POST['UseBranchName'])) $action['action'] = "saveBranch";
1045     if(isset($_POST['faiGroupHandle_apply']))  $action['action'] = "editByGroup";
1046     if(isset($_GET['act']) && $_GET['act'] == "branch_branch")  $action['action'] = "createBranch";
1047     if(isset($_GET['act']) && $_GET['act'] == "freeze_branch")  $action['action'] = "createFreeze";
1048     if(isset($_GET['act']) && $_GET['act'] == "remove_branch")  $action['action'] = "removeBranch";
1050     foreach($_POST as $name => $value){
1051       if(preg_match("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i", $name)){
1052         $id = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\1", $name);
1053         $tab = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\2", $name);
1055         $headpage = $this->getHeadpage();
1056         $entry = $headpage->entries[$id];
1058         if(in_array('FAKE_OC_FAI', $entry['objectClass'])){
1059           if(isset($headpage->entries[$id]['GROUPS'][$tab])){
1060             $data =$headpage->entries[$id]['GROUPS'][$tab];
1061             $type = $this->get_type($data);
1062             $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]); 
1063             if($str) return($str);
1064           } 
1065         }else{
1066           $str = $this->editEntry('editEntry',array($entry['dn'])); 
1067           if($str) return($str);
1068         }
1069         break;
1070       }
1071     }
1072     return($action);
1073   }
1076   static function plInfo()
1077   {
1078     return (array(
1079           "plShortName"   => _("FAI releases"),
1080           "plDescription" => _("FAI release management"),
1081           "plSelfModify"  => FALSE,
1082           "plDepends"     => array(),
1083           "plPriority"    => 0,
1084           "plSection"     => array("administration"),
1085           "plCategory"    => array("fai"=> array("description" => _("FAI"),
1086               "objectClass" => "FAIclass")),
1087           "plProvidedAcls"=> array()));
1088   }
1089
1090 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1091 ?>