Code

Cleaned faiManagement from role strings
[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   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     $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(!$this->cpHandler->entries_queued()){
186       $this->cpPastingStarted = FALSE;
187     }
188     return("");
189   }
192   /*! \brief  A new FAI object was requested, let the user specify a name theis object now. 
193    */
194   function newEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
195   {
196     $types = array( 
197         "new_partition"     =>  "FAIpartitionTable",
198         "new_script"        =>  "FAIscript",
199         "new_hook"          =>  "FAIhook",
200         "new_variable"      =>  "FAIvariable",
201         "new_template"      =>  "FAItemplate",
202         "new_package"       =>  "FAIpackageList");
203     $types_i18n = array( 
204         "new_partition"     =>  _("partition table"),
205         "new_script"        =>  _("script"),
206         "new_hook"          =>  _("hook"),
207         "new_variable"      =>  _("variable"),
208         "new_template"      =>  _("template"),
209         "new_package"       =>  _("package list"));
211     if(isset($types[$action])){
212       $type_acl_mapping = array(
213           "FAIpartitionTable"  => "faiPartitionTable",
214           "FAIpackageList"     => "faiPackage",
215           "FAIscript"          => "faiScript",
216           "FAIvariable"        => "faiVariable",
217           "FAIhook"            => "faiHook",
218           "FAIprofile"         => "faiProfile",
219           "FAItemplate"        => "faiTemplate");
221       $acl = $this->ui->get_permissions($this->acl_base,"fai/".$type_acl_mapping[$types[$action]]);
222       if(preg_match("/c/",$acl)){
223         $this->dialogObject = new askClassName($this->config,$this->dn,$this->ui,$types[$action]);
224         $this->dialogObject->parent = &$this;
225       }else{
226         msg_dialog::display(_("Permission error"), 
227             sprintf(_("You have no permission to create a new %s!"), $types_i18n[$action]),      ERROR_DIALOG);
228       }
229     }
230     if($action == "new_profile"){
231       $this->dn = "new" ;
233       $acl = $this->ui->get_permissions($this->acl_base,"fai/faiProfile");
234       if(preg_match("/c/",$acl)){
235         $type= $this->get_type(array("objectClass"=>array("FAIprofile")));
236         $str= management::newEntry('newEntry',array(),array(),$type[0],$type[2],$type[1]);
237         if($str) return($str);
238         $this->tabObject->set_acl_base($this->acl_base);
239         $this->tabObject->by_object[$type[1]]->cn = $name;
240       }else{
241         msg_dialog::display(_("Permission error"), sprintf(_("You have no permission to create a new %s!"), _("profile")), ERROR_DIALOG);
242       }
243     }
244   }
247   /*! \brief   A new FAI class was requested and the user had a specify a name for it.
248    *           Here we check if this name is useable and then open the edit dialogs.
249    */
250   function newClassNameSelected()
251   {
252     $this->dialogObject->save_object();
253     if(count($this->dialogObject->check())!=0){
254       foreach($this->dialogObject->check() as $msg){
255         msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
256       }
257     }elseif(isset($this->dialogObject->objectClass)){
258       $this->dn = "new" ;
259       $type= $this->get_type(array("objectClass"=>array($this->dialogObject->objectClass)));
260       $name = $this->dialogObject->save();
262       if(class_exists($type[0])){
263         $this->closeDialogs();
264         $str = management::newEntry('newEntry',array(),array(),$type[0],$type[2],$type[1]);
265         if($str) return($str);
266         $this->tabObject->set_acl_base($this->acl_base);
267         $this->tabObject->by_object[$type[1]]->cn = $name;
268       }
269     }
270   }
273   /*! \brief   Edit the selected entry.
274    *           If there was a FAI group clicked, display a dialog with all members of the group.
275    */
276   function editEntry($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
277   {
278     $headpage = $this->getHeadpage();
279     if(count($target) == 1){
280       $entry = $headpage->getEntry($target[0]);
281       if($entry){
283         // Edit Opsi objects here 
284         if(in_array("opsi_local", $entry['TYPES']) || in_array("opsi_netboot", $entry['TYPES'])){ 
285           $name = $entry['cn'];
286           $cfg = $this->opsi->get_product_properties($name);
288           $str = management::editEntry('editEntry',array($name),array(),'tabs_opsiProdConfig','OPSIPRODCONFIG','opsi');
289           if($str) return($str);
290           if(isset($this->tabObject->by_object['opsiProperties'])){
291             $this->tabObject->by_object['opsiProperties']->set_cfg($cfg);
292             $this->tabObject->by_object['opsiProperties']->set_product($name);
293             $this->skipFooter = TRUE;
294           }else{
295             trigger_error("Unknown tab, please check config.");
296           }
298         }else{
300           // Edit FAI objects here 
301           if(count($entry['GROUPS']) == 1){
302             $data = array_pop($entry['GROUPS']);
303             $type = $this->get_type($data);
304             $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]);
305             if($str) return($str);
306             $this->tabObject->by_object[$type[1]]->FAIstate = $data['FAIstate'];
307             $this->tabObject->read_only = preg_match("/freeze/i", $data['FAIstate']);
309           }else{
310             $this->dialogObject = new faiGroupHandle($entry['GROUPS'],"edit");
311           }
312         }
313       }
314     }
315   }
318   /*! \brief   Save changes made in opsi dialogs.
319    */
320   function saveOpsiProperties()
321   {
322     if($this->tabObject instanceof tabs_opsiProdConfig && isset($_POST['save_properties'])){
323       $this->tabObject->save_object();
324       $op    = $this->tabObject->by_object['opsiProperties'];
325       $name  = $op->get_product();
326       $cfg   = $op->get_cfg();
327       $this->opsi->set_product_properties($name,$cfg);
328       if($this->opsi->is_error()){
329         msg_dialog::display(_("Error"),msgPool::siError($this->opsi->get_error()),ERROR_DIALOG);
330       }else{
331         $this->remove_lock();
332         $this->closeDialogs();
333       }
334     }
335   }
338   /*! \brief   Someone wants to remove some object(s)
339    *            ask for a confirmation now.
340    */
341   function removeEntryRequested($action="",$target=array(),$all=array(), $altTabClass ="", $altTabType = "", $altAclCategory="")
342   {
343     $this->closeDialogs();
344     if($action == "remove_multiple"){
346       // Collect objects to delete
347       $headpage = $this->getHeadpage();
348       $to_delete = array();
349       foreach($target as $id){
350         $object = $headpage->getEntry($id);
351         if(in_array("FAKE_OC_FAI", $object['objectClass'])){
352           foreach($object['GROUPS']  as $entry){
353             array_push($to_delete, $entry);
354           }
355         }
356       }
357       return($this->removeFAIObjects($to_delete));
358     }else{
360       // Try to remove a single object, only FAI objects can be removed!
361       $headpage = $this->getHeadpage();
362       if(count($target) == 1){
363         $entry = $headpage->getEntry($target[0]);
364         if($entry && in_array("FAKE_OC_FAI",$entry['objectClass'])){
365           $this->dialogObject = new faiGroupHandle($entry['GROUPS'],"remove");
366         }
367       }
368     }
369   }
372   /*! \brief   Someone wants to remove some object(s)
373    *            ask for a confirmation now.
374    */
375   function removeFAIObjects($to_delete)
376   {
377     // Do not allow to remove objects with state freeezed
378     $errors = $disallowed = array();
379   
380     foreach($to_delete as $obj){
381       $type = $this->get_type($obj);
382       $acl  = $this->ui->get_permissions($obj['dn'],"fai/".$type[1]);
383       if(!preg_match("/d/",$acl)){
384         $disallowed[] = $obj['dn'];
385       }elseif(isset($obj['FAIstate']) && preg_match('/^freeze/', $obj['FAIstate'])){
386         $errors[] = $obj['dn'];
387       }else{
388         $this->dns[] = $obj['dn'];
389       }
390     }
391     if(count($errors)){
392       msg_dialog::display(_("Branch locked"),
393           sprintf(_("The following entries are locked, you can't remove them %s."),msgPool::buildList($errors)),INFO_DIALOG);
394     }
395     if(count($disallowed)){ 
396       msg_dialog::display(_("Permission error"), msgPool::permDelete($disallowed), ERROR_DIALOG);
397     }
399     // Check entry locking
400     if(count($this->dns)){
401       if ($user= get_multiple_locks($this->dns)){
402         return(gen_locked_message($user,$this->dns));
403       }
404       if(count($this->dns)){
405         $smarty = get_smarty();
406         $dns_names = array();
407         foreach($this->dns as $dn){
408           add_lock ($dn, $this->ui->dn);
409           $dns_names[] = LDAP::fix($dn);
410         }
411         $smarty->assign("info",msgPool::deleteInfo($dns_names,_("FAI object")));
412         $smarty->assign("multiple", true);
413         return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
414       }
415     }
416   }
419   /*! \brief   Entry removal is confirmed, now remove objects
420    */
421   function removeEntryConfirmed($action="",$target=array(),$all=array(),
422       $altTabClass="",$altTabType="",$altAclCategory="")
423   {
424     $ldap = $this->config->get_ldap_link();
425     $ldap->cd($this->config->current['BASE']); 
427     $disallowed = array();
428     foreach($this->dns as $key => $dn){
429       $ldap->cat($dn);
430       if($ldap->count()){
431         $attrs = $ldap->fetch();
432         $type= $this->get_type($attrs);
434         $acl  = $this->ui->get_permissions($dn,"fai/".$type[1]);
435         if(preg_match("/d/",$acl)){
437           // Now save changes
438           management::removeEntryConfirmed($action,array($dn),$all,$type[0],$type[2],$type[1]);
439           FAI::save_release_changes_now();
440           $to_del = FAI::clean_up_releases($dn);
441           foreach($to_del as $dn){
442             $ldap->rmdir_recursive($dn);
443           }
445         } else {
446           $disallowed[] = $dn;
447           new log("security","fai/".get_class($this),$dn,array(),"Tried to trick deletion.");
448         }
449       }
450     }
452     /* Normally this shouldn't be reached, send some extra
453        logs to notify the administrator */
454     if(count($disallowed)){ 
455       msg_dialog::display(_("Permission error"), msgPool::permDelete($disallowed), ERROR_DIALOG);
456     }
457   }
460   /*! \brief   Someone clicked on edit/remove for a grouped FAI object.
461    *           We are now going to display a dialog to let the user select the entry 
462    *            he wants to perform the action on.
463    */
464   function editByGroup()
465   {
466     if($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "edit"){
467       $this->dialogObject->save_object();
468       $entry = $this->dialogObject->get_selected();
469       $this->closeDialogs();
470       $data = array_pop($entry);
471       $type = $this->get_type($data);
472       $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]);
473       if($str) return($str);
474       $this->tabObject->by_object[$type[1]]->FAIstate = $data['FAIstate'];
475       $this->tabObject->read_only = preg_match("/freeze/i", $data['FAIstate']);
476     }elseif($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "remove"){
477       $this->dialogObject->save_object();
478       $to_delete = $entry = $this->dialogObject->get_selected();
479       if(count($to_delete)) $this->closeDialogs();
480       return($this->removeFAIObjects($to_delete));
481     }elseif($this->dialogObject instanceOf faiGroupHandle && $this->dialogObject->get_mode() == "copy"){
482       $this->dialogObject->save_object();
483       $entries = $entry = $this->dialogObject->get_selected();
484       if(count($entries)){
485         foreach($entries as $entry){
486           $type = $this->get_type($entry);
487           $this->cpHandler->add_to_queue($entry['dn'],"copy",$type[0],$type[2],'fai',$this);
488           @DEBUG (DEBUG_TRACE, __LINE__, __FUNCTION__, __FILE__,$entry['dn'],"Entry copied!");
489         }
490         $this->closeDialogs();
491       }
492     }
493   }
496   /*! \brief   Save dialog/object modifications
497    */
498   protected function saveChanges()
499   {
500     $str = management::saveChanges();
501     if($str) return($str);
503     // Now save changes
504     FAI::save_release_changes_now();
505     $to_del = FAI::clean_up_releases($this->last_dn);
506     foreach($to_del as $dn){
507       $ldap->rmdir_recursive($dn);
508     }
509   }
512   /*! \brief   Save dialog/object modifications but keep the dialogs opened
513    */
514   protected function applyChanges()
515   {
516     $str = management::applyChanges();
517     if($str) return($str);
519     // Now save changes
520     FAI::save_release_changes_now();
521     $to_del = FAI::clean_up_releases($this->last_dn);
522     foreach($to_del as $dn){
523       $ldap->rmdir_recursive($dn);
524     }
525   }
528   /*! \brief   Initiates release removal
529    */
530   function removeBranch()
531   {
532     /* Check if we have a post remove method configured
533      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
534      */
535     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
536       /* Load permissions for selected 'dn' and check if
537          we're allowed to remove this 'dn' */
538       if(preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
539         $smarty=get_smarty();
540         $smarty->assign("release_hidden",base64_encode($this->fai_release));
541         $smarty->assign("info", msgPool::deleteInfo(LDAP::fix($this->fai_release),_("FAI branch/freeze")));
542         return($smarty->fetch(get_template_path('remove_branch.tpl',TRUE)));
543       } else {
544         msg_dialog::display(_("Permission error"), _("You have no permission to delete this release!"), ERROR_DIALOG);
545       }
546     }
547   }
550   /*! \brief   Remove a release after removal was confirmed
551    */
552   function removeBranchConfirmed()
553   {
554     /* Check if we have a post remove method configured
555      *  else skip this operation. (Skip:Button in the ui should be disabled in this case too)
556      */
557     if("" != $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'))){
559       if(!isset($_POST['release_hidden']) || base64_decode($_POST['release_hidden']) != $this->fai_release){
560         msg_dialog::display(_("Warning"),_("Release remove aborted because the release name check failed!"));
561       }else{
563         $bb =  $this->fai_release;
564         $ldap = $this->config->get_ldap_link();
566         $br = $this->getBranches();
568         if(isset($br[$bb]) && preg_match("/d/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
569           $name = $br[$bb];
571           $ldap->cd($bb);
572           $ldap->recursive_remove();
573           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('applicationRDN'), $bb));
574           $ldap->recursive_remove();
575           $ldap->cd(preg_replace('/,'.preg_quote(get_ou('faiBaseRDN'), '/').'/i', ','.get_ou('mimetypeRDN'), $bb));
576           $ldap->recursive_remove();
578           /* Search for all groups with configured application menus.
579              - First search all groups, to ensure that we only remove entries form whithin groups.
580              - The search für menu configuration for the specified release and collect all those dns.
581              - Remove entries
582            */
583           $release_ou = preg_replace("/".preg_quote(get_ou("faiBaseRDN"), '/').".*$/i","",$bb);
584           $ldap->cd($this->config->current['BASE']);
585           $ldap->search("(objectClass=posixGroup)",array("dn"));
587           /* Collect all group dns
588            */
589           $groups = array();
590           while($attrs = $ldap->fetch()){
591             $groups[] = $attrs['dn'];
592           }
595           /* Collect all group menu release dns that match the release we have removed
596            */
597           $dns = array();
598           foreach($groups as $dn){
599             $ldap->cd($dn);
600             $ldap->search("(objectClass=FAIbranch)",array("dn"));
601             while($attrs = $ldap->fetch()){
602               if(preg_match("/^".preg_quote($release_ou, '/')."/",$attrs['dn'])){
603                 $dns[] = $attrs['dn'];
604               }
605             }
606           }
608           /* Finally remove collected release dns
609            */
610           foreach($dns as $dn){
611             $ldap->cd($dn);
612             $ldap->recursive_remove();
613           }
615           /* Post remove */
616           $this->fai_release = $this->fai_base;
617           $this->lock_name   = $name;
618           $this->lock_dn     = $bb;
619           $this->postremove();
621           $fai_filter = session::get("fai_filter");
622           $fai_filter['fai_release'] = $this->fai_release;
623           session::set("fai_filter",$fai_filter);
625           new log("remove","fai/".get_class($this),$br[$bb],array(),"Release removed");
626         }
627       }
628     }
629   }
632   /*! \brief   Initiates release creation 
633    */
634   function createBranch()
635   { 
636     if($this->config->search("faiManagement", "POSTCREATE",array('menu','tabs')) == ""){ 
637       msg_dialog::display(_("Configuration"), msgPool::cmdnotfound(_("POSTCREATE"), get_class()), ERROR_DIALOG);
638     }elseif(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
639       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
640     }else{
641       $smarty = get_smarty();
642       $this->dispNewBranch=true;
643       $this->dispNewFreeze=false;
644       $smarty->assign("iframe",false);
645       if(isset($_POST['BranchName'])){
646         $smarty->assign("BranchName", $_POST['BranchName']);
647       }else{
648         $smarty->assign("BranchName","");
649       }
650       return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
651     }
652   }
655   /*! \brief   Initiates release creation 
656    */
657   function createFreeze()
658   {
659     if($this->config->search("faiManagement", "POSTCREATE",array('menu','tabs')) == ""){ 
660       msg_dialog::display(_("Configuration"), msgPool::cmdnotfound(_("POSTCREATE"), get_class()), ERROR_DIALOG);
661     }elseif(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
662       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
663     }else{
664       $smarty = get_smarty();
665       $this->dispNewFreeze=true;
666       $this->dispNewBranch=false;
667       $smarty->assign("iframe",false);
668       if(isset($_POST['BranchName'])){
669         $smarty->assign("BranchName", $_POST['BranchName']);
670       }else{
671         $smarty->assign("BranchName","");
672       }
673       return($smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__))));
674     }
675   }
678   /*! \brief   Creates a new branch
679    */
680   function PerformBranch()
681   {
682     if(!preg_match("/c/",$this->ui->get_permissions($this->acl_base,"fai/faiManagement"))){
683       msg_dialog::display(_("Permission error"), msgPool::permCreate(_("Branch")), ERROR_DIALOG);
684     }else{
686       /* In order to see error messages we have to reset the error handler.
687          Due to the exit();
688        */
689       restore_error_handler();
691       $this->dispNewBranch = false;
692       $this->dispNewFreeze = false;
694       $LASTPOST = session::get('LASTPOST');
695       $base = $LASTPOST['base'];
696       $_POST  = session::get('LASTPOST');
697       $name = $_POST['BranchName'];
699       $type = $LASTPOST['type'];
700       $ldap = $this->config->get_ldap_link();
702       $baseToUse = $base;
703       if($this->fai_release !=  $this->fai_base){
704         $baseToUse = $this->fai_release;
705       }
707       /* Create new Release name to be able to set faidebianRelease for FAIpackageList */
709       $CurrentReleases  = $this->getBranches();
710       $NewReleaseName   = $name;
711       if(isset($CurrentReleases[$this->fai_release])) {
712         if($this->fai_release != $this->fai_base){
713           $NewReleaseName = $CurrentReleases[$this->fai_release]."/".$name;
714           $NewReleaseName = preg_replace("#\/#","/",$NewReleaseName);
715         }else{
716           $NewReleaseName   = $name;
717         }
718       }
719       $appsrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),$baseToUse);
720       $appdst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('applicationRDN'),"ou=".$name.",".$baseToUse) ;
722       $mimesrc = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),$baseToUse);
723       $mimedst = preg_replace("/".preg_quote(get_ou('faiBaseRDN'), '/')."/i",get_ou('mimetypeRDN'),"ou=".$name.",".$baseToUse) ;
725       /* Check if source depeartments exist */
726       foreach(array($baseToUse,$appsrc,$mimesrc) as $dep){
727         $ldap->cd($this->config->current['BASE']);
728         $ldap->cat($dep);
729         if(!$ldap->count()){
730           $ldap->create_missing_trees($dep);
731         }
732       }
734       /* Print header to have styles included */
735       echo '  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
736         <html>
737         <head>
738         <title></title>
739         <style type="text/css">@import url("themes/default/style.css");</style>
740         <script language="javascript" src="include/focus.js" type="text/javascript"></script>
741         </head>
742         <body style="background: none;margin:3px;color:black">
743         ';
745       new log("create","fai/".get_class($this),$NewReleaseName,array(),"New $type created");
747       /* Duplicate group application releases
748        */
749       FAI::copy_FAI_group_releases($CurrentReleases[$this->fai_release],$name,$type);
751       /* Duplicate applications
752        */
753       $ldap->cat($appsrc,array("dn")) ;
754       if($ldap->count()){
755         $ldap->cd ($appdst);
756         $ldap->recursive_remove();
757         FAI::copy_FAI_resource_recursive($appsrc,$appdst,$NewReleaseName,$type,true);
758       }
760       /* Duplicate mime types
761        */
762       $ldap->cat($mimesrc,array("dn")) ;
763       if($ldap->count()){
764         $ldap->cd ($mimedst);
765         $ldap->recursive_remove();
766         FAI::copy_FAI_resource_recursive($mimesrc,$mimedst,$NewReleaseName,$type,true);
767       }
769       $attr = array();
770       $attr['objectClass'] = array("organizationalUnit","FAIbranch");
771       $attr['ou']       = $name;
772       $attr['FAIstate'] = $type;
773       $ldap->cd($this->config->current['BASE']);
774       $ldap->cd("ou=".$name.",".$baseToUse);
775       $ldap->cat("ou=".$name.",".$baseToUse);
776       if($ldap->count()){
777         $ldap->modify($attr);
778       }else{
779         $ldap->add($attr);
780       }
782       /* Duplicate fai objects
783        */
784       //      $ldap->cd ("ou=".$name.",".$baseToUse);
785       //      $ldap->recursive_remove();
786       //      FAI::copy_FAI_resource_recursive($baseToUse,"ou=".$name.",".$baseToUse,$NewReleaseName,$type,true);
788       echo "<div style='width:100%;text-align:right;'><form name='form' method='post' action='?plug=".$_GET['plug']."' target='_parent'>
789         <br><input type='submit' name='CloseIFrame' value='"._("Continue")."'>
790         <input type='hidden' name='php_c_check' value='1'>
791         </form></div>";
793       echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
795       /* Print footer to have valid html */
796       echo "</body></html>";
798       $this->dispNewFreeze = false;
800       /* Postcreate */
802       /* Assign possible attributes */
803       $this->lock_type  = $type;
804       $this->lock_name  = $name;
805       $this->lock_dn    = $baseToUse;
806       $this->postcreate();
808       /* Send daemon event to reload the fai release database
809        */
810       if(class_available("DaemonEvent") && class_available("gosaSupportDaemon")){
811         $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);
812         if(isset($events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'])){
813           $evt = $events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'];
814           $tmp = new $evt['CLASS_NAME']($this->config);
815           $tmp->set_type(TRIGGERED_EVENT);
816           $tmp->add_targets(array("GOSA"));
817           $o_queue = new gosaSupportDaemon();
818           if(!$o_queue->append($tmp)){
819             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
820           }
821         }
822       }else{
823         trigger_error("Unknown class DaemonEvent / gosaSupportDaemon");
824         msg_dialog::display(_("Fatal error"),
825             "Daemon events called but classes where not accessible, DaemonEvent gosaSupportDaemon",
826             FATAL_ERROR_DIALOG);
827       }
828       exit();
829     }
830   }
833   /*! \brief   Creates a new branch, after a useable name was specified.
834    */
835   function saveBranch()
836   {
837     if($this->dispNewBranch){
838       $type = "branch";
839     }else{
840       $type = "freeze";
841     }
843     /* Check branch name */
844     $name = $_POST['BranchName'];
845     $is_ok = true;
846     $smarty = get_smarty();
847     $smarty->assign("BranchName",$name);
848     $base= $this->fai_base;
850     /* Check used characters */
851     if(!preg_match("/^[0-9a-z\.]*$/",$name)){
852       msg_dialog::display(_("Error"), msgPool::invalid(_("Name"),$name,"/[0-9a-z\.]/"), ERROR_DIALOG);
853       $is_ok = false;
854     }
856     // Check if this name is already in use 
857     if(!$this->CheckNewBranchName($_POST['BranchName'],$this->fai_release)){
858       msg_dialog::display(_("Error"), msgPool::duplicated(_("Name")), ERROR_DIALOG);
859       $is_ok = false;
860     }
862     // Handle errors
863     if(!$is_ok && $this->dispNewFreeze){
864       return($this->createFreeze());
865     }elseif(!$is_ok && $this->dispNewBranch){
866       return($this->createBranch());
867     }
869     // Now create new release
871     if(session::is_set('LASTPOST')){
872       $LASTPOST = session::get('LASTPOST');
873     }else{
874       $LASTPOST = array();
875     }
876     $LASTPOST['base'] = $base;
877     $LASTPOST['type'] = $type;
878     $LASTPOST['BranchName'] = $name;
879     session::set('LASTPOST',$LASTPOST);
880     $smarty->assign("iframe", true);
881     $smarty->assign("plugID", $_GET['plug']);
882     $display  = $smarty->fetch(get_template_path('faiNewBranch.tpl', TRUE, dirname(__FILE__)));
883     return($display);
885   }
889   /*! \brief   Returns a list of all releases for useable for drop down boxes.
890    *                      ou=fai... /
891    *              ou=siga,ou=fai... &nbsp; siga
892    *         ou=1,ou=siga,ou=fai... &nbsp;&nbsp; 1
893    */
894   function getReleaseList($base = "", $prefix ="")
895   {
896     $list = array();
897     if(empty($base)){
898       $base = $this->fai_base;
899       $list[$base] = "/";
900     }
902     $ldap = $this->config->get_ldap_link();
903     $ldap->ls("(objectClass=FAIbranch)",$base,array("ou","FAIstate"));
905     while($release = $ldap->fetch()){
906       $list[$release['dn']] = $prefix.$release['ou'][0];
907       $list = array_merge($list,$this->getReleaseList($release['dn'],$prefix."&nbsp; "));
908     }
909     return($list);
910   }
913   /*! \brief   Returns a list of all releases with full release names
914    *                      ou=fai... /
915    *              ou=siga,ou=fai... siga
916    *         ou=1,ou=siga,ou=fai... siga/1
917    */
918   function getBranches($base = false,$prefix = "")
919   {
920     $ret = array("/"=>$this->fai_base);
921     $ldap = $this->config->get_ldap_link();
922     if(!$base){
923       $base = $this->fai_base;
924     }
925     $tmp = FAI::get_all_releases_from_base($base,true);
926     foreach($tmp as $dn => $name){
927       $ret[$name]=$dn;
928     }
929     ksort($ret);
930     $ret = array_flip($ret);
932     return ($ret);
933   }
936   /*! \brief   Detects object info like corresponding  tab,class,acl 
937    *    e.g.    [0]   =  tabsPartition
938    *            [1]   =  faiPartitionTable
939    *            [2]   =  FAIPARTITIONTABS
940    */
941   function get_type($array)
942   {
943     if(!isset($array['objectClass'])) return(array());
944     if(in_array("FAIpartitionTable",$array['objectClass'])){
945       return(array("tabsPartition","faiPartitionTable","FAIPARTITIONTABS"));
946     }
947     if(in_array("FAIscript",$array['objectClass'])){
948       return(array("tabsScript","faiScript","FAISCRIPTTABS"));
949     }
950     if(in_array("FAItemplate",$array['objectClass'])){
951       return(array("tabsTemplate","faiTemplate","FAITEMPLATETABS"));
952     }
953     if(in_array("FAIhook",$array['objectClass'])){
954       return(array("tabsHook","faiHook","FAIHOOKTABS"));
955     }
956     if(in_array("FAIvariable",$array['objectClass'])){
957       return(array("tabsVariable","faiVariable","FAIVARIABLETABS"));
958     }
959     if(in_array("FAIprofile",$array['objectClass'])){
960       return(array("tabsProfile","faiProfile","FAIPROFILETABS"));
961     }
962     if(in_array("FAIpackageList",$array['objectClass'])){
963       return(array("tabsPackage","faiPackage","FAIPACKAGETABS"));
964     }
965     return(array());
966   }
969   /*! \brief   Checks if the given string can be used as class name
970    */
971   static function check_class_name($oc,$name,$dn)
972   {
973     $base = FAI::get_release_dn($dn);
975     if($oc == "FAIprofile"){
976       $f = "";
977       $ocs = array("FAIprofile","FAItemplate","FAIhook","FAIpartitionTable","FAIpackageList","FAIscript","FAIvariable");
978       foreach($ocs as $oc){
979         $f .= "(objectClass=".$oc.")";
980       }
981       $res  = FAI::get_all_objects_for_given_base($base,"(|".$f.")",TRUE);
982     }else{
983       $res  = FAI::get_all_objects_for_given_base($base,"(objectClass=".$oc.")",TRUE);
984     }
985     $delete = array();
986     $used   = array();
987     foreach($res as $object){
988       $used[$object['cn'][0]]= $object['cn'][0];
989     }
990     return($used);
991   }
994   /*! \brief   Checks if the given string can be used for a new release
995    */
996   function CheckNewBranchName($name,$base)
997   {
998     $f = $this->fai_release;
999     if($name == ""){
1000       return(false);
1001     }elseif(in_array($name,$this->getBranches($f))) {
1002       return(false);
1003     }elseif(tests::is_department_name_reserved($name,$base)){
1004       return(false);
1005     }
1006     return(true);
1007   }
1010   /*! \brief   This filter is used to display small icons for each listed object 
1011    *            instead of their typ names
1012    */
1013   static function filterProperties($row, $classes)
1014   {
1015     $objects = array(
1016         "FAIpartitionTable"  => array("IMG"=> "plugins/fai/images/fai_partitionTable.png",
1017           "NAME"=>_("Partition table"),"KZL"=> "PT", "VAR"=>"ShowPartitions"),
1018         "FAIpackageList"     => array("IMG"=> "plugins/fai/images/fai_packages.png",
1019           "NAME"=>_("Package list") ,  "KZL"=> "PL", "VAR"=>"ShowPackages"),
1020         "FAIscript"          => array("IMG"=> "plugins/fai/images/fai_script.png",
1021           "NAME"=>_("Scripts") ,       "KZL"=> "S",  "VAR"=>"ShowScripts"),
1022         "FAIvariable"        => array("IMG"=> "plugins/fai/images/fai_variable.png",
1023           "NAME"=>_("Variables") ,     "KZL"=> "V",  "VAR"=>"ShowVariables"),
1024         "FAIhook"            => array("IMG"=> "plugins/fai/images/fai_hook.png",
1025           "NAME"=>_("Hooks"),          "KZL"=> "H",  "VAR"=>"ShowHooks"),
1026         "FAIprofile"         => array("IMG"=> "plugins/fai/images/fai_profile.png",
1027           "NAME"=>_("Profile") ,       "KZL"=> "P",  "VAR"=>"ShowProfiles"),
1028         "FAItemplate"        => array("IMG"=> "plugins/fai/images/fai_template.png",
1029           "NAME"=>_("Templates") ,     "KZL"=> "T",  "VAR"=>"ShowTemplates"),
1030         "opsi_netboot"       => array("IMG"=> "plugins/opsi/images/netboot_package.png",
1031           "NAME"=>_("OPSI netboot product") ,     "KZL"=> "ON",  "VAR"=>"ShowOpsiNetboot"),
1032         "opsi_local"         => array("IMG"=> "plugins/opsi/images/local_package.png",
1033           "NAME"=>_("OPSI localboot product")   ,     "KZL"=> "OL",  "VAR"=>"ShowOpsiLocal"));
1035     $icon_list = "";
1036     foreach($objects as $type => $type_data){
1037       if(in_array($type, $classes)){
1038         $icon_list .= "<input type='image' src='".$type_data['IMG']."' title='".$type_data['NAME']."'
1039           alt='".$type_data['KZL']."' class='center' name='edit_".$row."_".$type."'>\n";
1040       }else{
1041         $icon_list .= "<img src='images/empty.png' alt=' ' class='center'>\n";
1042       }
1043     }
1045     return $icon_list;
1046   }
1049   /*! \brief   Overridden render method of class mangement. 
1050    *            this allows us to add a release selection box.
1051    */
1052   function renderList()
1053   {
1054     $filter = $this->getFilter();
1055     $headpage = $this->getHeadpage();
1056     $filter->setComboBoxOptions("RELEASE",$this->getReleaseList());
1058     if(isset($_POST['RELEASE'])){
1059       $this->fai_release = get_post('RELEASE');
1060     }
1061     $headpage->setBase($this->fai_release);
1062     $headpage->update();
1063     $smarty = get_smarty();
1064     $smarty->assign("fai_release", $this->fai_release);
1065     $smarty->assign("opsi_available", (is_object($this->opsi) && $this->opsi->enabled()));
1066     $smarty->assign("fai_base", $this->fai_base);
1067     $r = $this->config->search("faiManagement", "POSTREMOVE",array('menu','tabs'));
1068     $c = $this->config->search("faiManagement", "POSTCREATE",array('menu','tabs'));
1069     $smarty->assign("allow_create", $c);
1070     $smarty->assign("allow_remove", $r);
1071     $display = $headpage->render();
1072     return($this->getHeader().$display);
1073   }
1076   /*! \brief   Convert POST and GET variables into actions.
1077    */
1078   function detectPostActions()
1079   {
1080     $action = management::detectPostActions();
1081     if(isset($_POST['remove_multiple'])) $action['action'] = "remove";
1082     if(isset($_POST['new_profile'])) $action['action'] = "new_profile";
1083     if(isset($_POST['new_template'])) $action['action'] = "new_template";
1084     if(isset($_POST['new_script'])) $action['action'] = "new_script";
1085     if(isset($_POST['new_hook'])) $action['action'] = "new_hook";
1086     if(isset($_POST['new_variable'])) $action['action'] = "new_variable";
1087     if(isset($_POST['new_package'])) $action['action'] = "new_package";
1088     if(isset($_POST['new_partition'])) $action['action'] = "new_partition";
1090     if(isset($_POST['save_properties'])) $action['action'] = "saveOpsiProperties";
1091     if(isset($_POST['cancel_properties'])) $action['action'] = "cancel";
1093     if(isset($_POST['edit_continue'])) $action['action'] = "newClassNameSelected";
1094     if(isset($_POST['edit_cancel'])) $action['action'] = "cancel";
1096     if(isset($_POST['faiGroupHandle_cancel'])) $action['action'] = "cancel";
1097     if(isset($_POST['CancelBranchName'])) $action['action'] = "cancel";
1098     if(isset($_POST['delete_branch_confirm'])) $action['action'] = "removeBranchConfirmed";
1099     if(isset($_GET['PerformBranch'])) $action['action'] = "PerformBranch";
1100     if(isset($_POST['UseBranchName'])) $action['action'] = "saveBranch";
1101     if(isset($_POST['faiGroupHandle_apply']))  $action['action'] = "editByGroup";
1102     if(isset($_GET['act']) && $_GET['act'] == "branch_branch")  $action['action'] = "createBranch";
1103     if(isset($_GET['act']) && $_GET['act'] == "freeze_branch")  $action['action'] = "createFreeze";
1104     if(isset($_GET['act']) && $_GET['act'] == "remove_branch")  $action['action'] = "removeBranch";
1106     foreach($_POST as $name => $value){
1107       if(preg_match("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i", $name)){
1108         $id = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\1", $name);
1109         $tab = preg_replace("/^edit_([0-9]*)_([a-z_]*)_(x|y)/i","\\2", $name);
1111         $headpage = $this->getHeadpage();
1112         $entry = $headpage->entries[$id];
1114         if(in_array('FAKE_OC_FAI', $entry['objectClass'])){
1115           if(isset($headpage->entries[$id]['GROUPS'][$tab])){
1116             $data =$headpage->entries[$id]['GROUPS'][$tab];
1117             $type = $this->get_type($data);
1118             $str = management::editEntry('editEntry',array($data['dn']),array(),$type[0],$type[2],$type[1]); 
1119             if($str) return($str);
1120           } 
1121         }else{
1122           $str = $this->editEntry('editEntry',array($entry['dn'])); 
1123           if($str) return($str);
1124         }
1125         break;
1126       }
1127     }
1128     return($action);
1129   }
1132   static function plInfo()
1133   {
1134     return (array(
1135           "plShortName"   => _("FAI releases"),
1136           "plDescription" => _("FAI release management"),
1137           "plSelfModify"  => FALSE,
1138           "plDepends"     => array(),
1139           "plPriority"    => 0,
1140           "plSection"     => array("administration"),
1141           "plCategory"    => array("fai"=> array("description" => _("FAI"),
1142               "objectClass" => "FAIclass")),
1143           "plProvidedAcls"=> array()));
1144   }
1145
1146 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1147 ?>