Code

Allow to save item changes again
[gosa.git] / gosa-plugins / goto-ng / admin / newConfigManagement / class_newConfigManagement.inc
1 <?php
3 /*! \brief  This class allows to manage backend config items and packages.
4  */
5 class newConfigManagement extends plugin
6 {
7     var $initTime;
8     var $plHeadline = "Config management";
9     var $plDescription = "Config management";
11     var $selectedContainer;
13     var $dataModel = NULL;
14     var $listing = NULL;
16     var $cfgTypeMap = NULL;
17     var $cfgItemMap = NULL;
19     var $addableContainerItems = array();
20     var $currentObject = NULL;
23     /*! \brief  Initialize the plugin and finally update the data model.
24      */
25     function __construct($config, $dn)
26     {
27         $this->config = &$config;
28         $this->listing = new ConfigManagementListing($this->config, get_userinfo(), $this);
30         // Load the template engine and tell her what template
31         //  to use for the HTML it produces.
32         $this->TemplateEngine = new TemplateEngine($config);
34         // Request an update of the data model
35         $this->loadInstallationMethods();
36         $this->updateDataModel();
37         $this->listing->setListingTypes($this->getListingTypes());
38     }
41     /*! \brief  Sets the installation method to the given method.
42      *          Updates the template engine and adds the initial root
43      *           object for the selected method.
44      *  @param  The method to use.
45      *  @return TRUE on success else FALSE.
46      */
47     function setInstallMethod($str)
48     {
49         if(!isset($this->installationMethods[$str])){
50             $this->itemConfig = array();
51             $this->invalidInstallMethod =TRUE;
52             $this->errorMessage = sprintf(_("Invalid installation method %s selected!"), bold($str));
53             msg_dialog::display(_("Setup"), $this->errorMessage, ERROR_DIALOG);
54             return(FALSE);
55         }else{
56     
57             $this->TemplateEngine->setTemplate($str.".tpl");
58             $this->itemConfig = $this->installationMethods[$str]['items'];
59             $this->invalidInstallMethod =FALSE;
60             $this->TemplateEngine->load($this->itemConfig);
62             // Detect root item, its name is /
63             $root = NULL;
64             foreach($this->itemConfig as $key => $item){
65                 if($item['name'] == '/') {
66                     $root = $key;
67                     break;
68                 }
69             }
70             if(!$root){
71                 $this->errorMessage = sprintf(_("Installation method %s is invalid: no root object found!"), bold($str));
72                 msg_dialog::display(_("Setup"), $this->errorMessage , ERROR_DIALOG);
73                 $this->initFailed = TRUE;
74                 $this->itemConfig = array();
75                 return(FALSE);
76             }
77         }
78     }
81     /*! \brief  Updates all distributions, releases, packages and items in the dataModel
82      *          Load information from the backend.
83      */
84     function updateDataModel()
85     {
86         // Recreate the data model, to have a clean and fresh instance.
87         $this->dataModel = new ConfigManagementDataModel();
89         // Load distributions 
90         $rpc = $this->config->getRpcHandle();
91         $res = $rpc->getDistributions();
93         if(!$rpc->success()){
94             msg_dialog::display(_("Error"), sprintf(_("Failed to load distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
95             return(NULL);
96         }else{
97             $this->cfgTypeMap = array();
98             foreach($res as $dist){
99                 $dist['__removeable'] = TRUE;
100                 $this->dataModel->addItem('Distribution','/root', $dist['name'], $dist);
101                 $this->cfgTypeMap['/root/'.$dist['name']] = $dist['installation_method'];
102                 foreach($dist['releases'] as $release){
103                     $distPath = "/root/{$dist['name']}";
104                     $release['__removeable'] = TRUE;
105                     $this->dataModel->addItem('Release',$distPath, $release['name'], $release);
106                 }
107             }
108         }
109     }
112     /*! \brief  Keep track of posted values and populate those 
113      *           which are interesting for us.
114      *          Inspects the _POST and _GET values.
115      */
116     function save_object()
117     {
118         // Update the listing class, this is necessary to get post
119         //  actions from it.
120         $this->listing->save_object();
122         // Get the selected distribution and release from the listing widget.
123         $cont = $this->listing->getSelectedContainer();
124         if(isset($_POST['ROOT'])){
125             $this->setCurrentContainer('/root');
126         }elseif(isset($_POST['BACK'])){
128             $path = $this->selectedContainer;
129             if($this->dataModel->itemExistsByPath($path)){
130                 $data = $this->dataModel->getItemByPath($path);
131                 if($data['parentPath']){
132                     $this->setCurrentContainer($data['parentPath']);
133                 }
134             }
135         }else{
136             $this->setCurrentContainer($cont);
137         }
138     }
141     /*! \brief  Load extended sub-objecte like 'config items' or 'packages'
142      *           for the given release path.
143      *  @param  String  The release path to load sub-objects for.
144      *  @return NULL 
145      */
146     function updateItemList($path)
147     {
148         // Fist get Item and check if it is an release 
149         if($this->dataModel->itemExistsByPath($path)){
150             $data = $this->dataModel->getItemByPath($path);
152             // Only releases can contain config-items.
153             if($data['type'] == 'Release' && $data['status'] != "fetched"){
155                 $rpc = $this->config->getRpcHandle();
156                 $res = $rpc->listConfigItems($data['name']);
157                 if(!$rpc->success()){
158                     msg_dialog::display(_("Error"), 
159                             sprintf(_("Failed to load distributions: %s"), 
160                                 $rpc->get_error()),ERROR_DIALOG);
161                 }else{
163                     // Sort entries by path length 
164                     $sLen = array();
165                     foreach($res as $itemPath => $type){
166                         $sLen[strlen($itemPath)."_".$itemPath] = $itemPath;
167                     }
168                     uksort($sLen, "strnatcasecmp");   
170                     // Walk through each entry and then try to add it to the model
171                     foreach($sLen as $unused => $itemPath){
173                         $type = $res[$itemPath];
174                 
175                         // Root installation objects do not have a name, so we use 'root' here.
176                         $targetPath = trim($path."/root/".$itemPath);
178                         // Remove trailing and duplicated slashes
179                         $targetPath = rtrim($targetPath, '/');
180                         $targetPath = preg_replace("/\/\/*/","/", $targetPath);
182                         // Extract the items name
183                         $name = preg_replace("/^.*\//","", $targetPath);
184     
185                         // Cleanup the path and then add the item.
186                         $targetPath = preg_replace("/[^\/]*$/","", $targetPath);
187                         $targetPath = rtrim($targetPath,'/');
188                         $this->dataModel->addItem($type, $targetPath, $name, 
189                                 array(    
190                                         '__editable' => TRUE,
191                                         '__removeable' => TRUE,
192                                         '__path' => $itemPath,
193                                         '__release' => $path
194                                     ),'-' ); 
195                     }
196                     $this->dataModel->setItemStatus($path, 'fetched');
197                 }
198             }
199         }
200     }
203     /*! \brief  Sets the currently selected container and item path. 
204      *  @param  String  The path of the container to set.
205      *  @param  String  The path of the item to set.
206      *  @return 
207      */
208     function setCurrentContainer($cont)
209     {
211         $this->selectedContainer = $cont;
213         // Update list of items within the selected container. 
214         $this->updateItemList($this->selectedContainer);
216         // Transfer checked values back to the listing class.
217         $this->listing->setContainers($this->getContainerList());
218         $this->listing->setContainer($cont);
220         // Set the correct installation method for the selected item
221         if(isset($this->cfgTypeMap[$cont])){
222             $method = $this->cfgTypeMap[$cont];
223             $this->setInstallMethod($method);
224         }
226         // Update the list of addable sub objects
227         $item = $this->dataModel->getItemByPath($cont);
228         if(isset($this->itemConfig[$item['type']]['container'])){
229             $this->addableContainerItems = $this->itemConfig[$item['type']]['container'];
230         }else{
231             $this->addableContainerItems = array();
232         }
233     }
236     /*! \brief  Generate the HTML content for this plugin.
237      *          Actually renders the listing widget..
238      */
239     function execute()
240     {
241         // Get the selected release and store it in a session variable
242         //  to allow the configFilter to access it and display the
243         //  packages and items.
244         $res = $this->listing->execute();
245         $this->listing->setListingTypes($this->getListingTypes());
246         return($res);
247     }
250     /*! \brief      Returns a list of items which will then be displayed 
251      *               in the management-list. 
252      *              (The management class calls this method from its execute())
253      *  @return     Array   A list of items/objects for the listing. 
254      */
255     function getItemsToBeDisplayed()
256     {
258         $path = $this->selectedContainer;
259         $item = $this->dataModel->getItemByPath($path);
260         return($item);
261     }
264     /*! \brief  Returns a simply list of all distributions.
265      *          This list will then be used to generate the entries of the 
266      *           ItemSelectors in the listing class.
267      */
268     function getContainerList()
269     {
270         $data = $this->dataModel->getItemByPath('/root');
271         $res = array();
272         $res["/root"] = array("name" => "/", "desc" => "");
273         $res = array_merge($res,$this->__recurseItem($data, array('Distribution','Release')));
274         return($res);
275     }
278     /*! \brief  Recursivly walks through an item and collects all path and name info.
279      *          The reult can then be used to fill the ItemSelector.
280      *  @param  Array   The Item to recurse. 
281      *  @param  Array   The type of of objects to collect. 
282      *  @param  String  The parent path prefix which should be removed.
283      *  @return Array   An array containing Array[path] = name
284      */
285     function __recurseItem($item, $types, $parent = "")
286     {
287         $res = array();
288         if(1 ||  in_array($item['type'], $types)){
289             $path = preg_replace("/".preg_quote($parent,'/')."/","",$item['path']);
290             $res[$path] = array('name' => $item['name'],'desc'=>$item['type']);
291         }
292         if(count($item['children'])){
293             foreach($item['children'] as $child){
294                 $res = array_merge($res, $this->__recurseItem($child, $types, $parent));
295             }
296         }
297         return($res);
298     }
301     /*! \brief  Intializes this plugin
302      *          All available installation methods will be loaded
303      */
304     function loadInstallationMethods()
305     {
306         // Reset erros
307         $this->rpcError = $this->initFailed = FALSE;
309         // Load configuration via rpc.
310         $rpc = $this->config->getRpcHandle();
312         // Populate install methods on success.
313         $res = $rpc->getSupportedInstallMethods();
314         if(!$rpc->success()){
315             $this->rpcError = TRUE;
316             $this->errorMessage = $rpc->get_error();;
317             return;
318         }
319         $this->installationMethods = $res;
320         if(!count($this->installationMethods)){
321             $this->errorMessage = _("No selectable install methods returned!");
322             msg_dialog::display(_("Setup"), $this->errorMessage , ERROR_DIALOG);
323             $this->initFailed = TRUE;
324             return;
325         }else{
326             $this->cfgItemMap = array();
327             foreach($this->installationMethods as $method => $items){
328                 foreach($items['items'] as $itemName => $item){
329                     $this->cfgItemMap[$itemName] = $method;
330                 }
331             }
332         }
333     }
336     /*! \brief   Returns a info list about all items we can manage,
337      *            this used to fill the listings <objectType> settings.
338      *  @return Array   An array with item info.
339      */
340     function getListingTypes()
341     {
342         $types= array();
343         $types['Distribution']['objectClass'] = 'Distribution';
344         $types['Distribution']['label'] = _('Distribution');
345         $types['Distribution']['image'] = 'images/lists/edit.png';
346         $types['Distribution']['category'] = 'Device';
347         $types['Distribution']['class'] = 'Device';
349         $types['Release']['objectClass'] = 'Release';
350         $types['Release']['label'] = _('Release');
351         $types['Release']['image'] = 'images/lists/delete.png';
352         $types['Release']['category'] = 'Device';
353         $types['Release']['class'] = 'Device';
355         $types['Component']['objectClass'] = 'Component';
356         $types['Component']['label'] = _('Component');
357         $types['Component']['image'] = 'plugins/users/images/select_user.png';
358         $types['Component']['category'] = 'Device';
359         $types['Component']['class'] = 'Device';
361         foreach($this->installationMethods as $method => $items){
362             foreach($items['items'] as $itemName => $item){
363                 $types[$itemName]['objectClass'] = $itemName;
364                 $types[$itemName]['label'] = $item['name'];
365                 $types[$itemName]['image'] = 'plugins/fai/images/fai_script.png';
366                 $types[$itemName]['category'] = 'Device';
367                 $types[$itemName]['class'] = 'Device';
368             }
369         }
371         return($types);
372     }
375     /*! \brief      The plugins ACL and plugin-property definition. 
376      *  @return 
377      */
378     public static function plInfo()
379     {
380         return (array(
381                     "plShortName"   => _("Config management"),
382                     "plDescription" => _("Config management"),
383                     "plSelfModify"  => FALSE,
384                     "plDepends"     => array(),
385                     "plPriority"    => 0,
386                     "plSection"     => array("administration"),
387                     "plCategory"    => array(
388                         "newConfigManagement" => array("description"  => _("Config management"),
389                             "objectClass"  => "FAKE_OC_newConfigManagement")),
390                     "plProvidedAcls"=> array()
391                     ));
392     }
395     /*! \brief  Acts on open requests.
396      *          (This action is received from the ConfigManagementListing class.)
397      *  @param  Array   The items ids. (May contain multiple ids)
398      *  @return
399      */
400     function openEntry($ids)
401     {
402         $id = $ids[0];
403         $item = $this->dataModel->getItemById($id);
404         $this->setCurrentContainer($item['path']);
405         return;
406     }
410     /*! \brief   
411      *  @param  
412      *  @return 
413      */
414     function remove_lock()
415     {
416     }
419     function editEntry($ids)
420     {
421         // Update the template engine to use another type of item and
422         //  some other values.
423         $item = $this->dataModel->getItemById($ids[0]);
425         if(isset($this->cfgItemMap[$item['type']])){
426             $release = preg_replace("/^.*\//","",$item['values']['__release']);
427             $path = $item['values']['__path'];
428             $method = $this->cfgItemMap[$item['type']];
430             // Load item values on demand
431             if($item['status'] == '-'){
432                 $rpc = $this->config->getRpcHandle();
433                 $item['values']['itemValues'] = $rpc->getConfigItem($release, $path);
434                 $this->dataModel->setItemStatus($item['path'], 'fetched');
435                 $this->dataModel->setItemValues($item['path'], $item['values']);
436             }
438             $this->setInstallMethod($method);
439             $this->TemplateEngine->setValues($item['type'],$item['values']['itemValues']);
440             $this->listing->setDialogObject($this->TemplateEngine);
441             $this->currentObject = $item;
442         }
443     }
445     function saveItemChanges()
446     {
447         $this->listing->clearDialogObject();
448         $item = $this->currentObject;
449         $this->TemplateEngine->save_object();
450         foreach($this->TemplateEngine->getWidgets() as $w){
451             $item['values']['itemValues'][$w->getName()] = $w->getValue();
452         }
453         $this->dataModel->setItemValues($item['path'], $item['values']);
454     }
456 ?>