Code

Fixed template engine problems
[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 $cfgItemMap = NULL;
18     var $addableContainerItems = array();
19     var $currentObject = NULL;
20     var $itemsPerMethod = NULL;
22     /*! \brief  Initialize the plugin and finally update the data model.
23      */
24     function __construct($config, $dn)
25     {
26         $this->config = &$config;
27         $this->listing = new ConfigManagementListing($this->config, get_userinfo(), $this);
29         // Load the template engine and tell her what template
30         //  to use for the HTML it produces.
31         $this->TemplateEngine = new TemplateEngine($config);
33         // Preset item config - with Distribution and Release objects.
34         $items = array();
35         $items['root']['container'] = array('Distribution');
36         $items['root']['name'] = '/';
37         $items['root']['description'] = _('Root');
39         $items['Distribution']['container'] = array('Release');
40         $items['Distribution']['name'] = 'Distribution';
41         $items['Distribution']['description'] = _('Distribution');
42         $items['Distribution']['options']['name']['description'] = _("Name");
43         $items['Distribution']['options']['name']['default'] = "";
44         $items['Distribution']['options']['name']['value'] = "";
45         $items['Distribution']['options']['name']['required'] = true;
46         $items['Distribution']['options']['name']['type'] = 'string';
47         $items['Distribution']['options']['name']['display'] = _('Name');
48         $items['Distribution']['options']['type']['description'] = _("Distribution type");
49         $items['Distribution']['options']['type']['default'] = "deb";
50         $items['Distribution']['options']['type']['value'] = "deb";
51         $items['Distribution']['options']['type']['values'] = array("deb" => 'deb', "rpm" => 'rpm');
52         $items['Distribution']['options']['type']['required'] = true;
53         $items['Distribution']['options']['type']['type'] = 'combobox';
54         $items['Distribution']['options']['type']['display'] = _('Distribution type');
56         $items['Release']['container'] = array('Release', '__CFG_ITEMS__');
57         $items['Release']['name'] = 'Release';
58         $items['Release']['description'] = _('Release');
59         $items['Release']['options']['name']['description'] = _("Name");
60         $items['Release']['options']['name']['default'] = "";
61         $items['Release']['options']['name']['value'] = "";
62         $items['Release']['options']['name']['required'] = true;
63         $items['Release']['options']['name']['type'] = 'string';
64         $items['Release']['options']['name']['display'] = _('Name');
66         $this->installationMethods = array();
67         $this->installationMethods['root']['description'] = _('root');
68         $this->installationMethods['root']['name'] = 'root';
69         $this->installationMethods['root']['title'] = _('root');
70         $this->installationMethods['root']['items']['Distribution'] = &$items['Distribution'];
71         $this->installationMethods['root']['items']['Release'] = &$items['Release'];
72         $this->installationMethods['root']['items']['root'] = &$items['root'];
74         // Request an update of the data model
75         $this->loadInstallationMethods();
76         $this->updateDataModel();
77         $this->listing->setListingTypes($this->getListingTypes());
78     }
81     /*! \brief  Intializes this plugin
82      *          All available installation methods will be loaded
83      */
84     function loadInstallationMethods()
85     {
86         // Reset erros
87         $this->rpcError = $this->initFailed = FALSE;
89         // Load configuration via rpc.
90         $rpc = $this->config->getRpcHandle();
91         $res = $rpc->getSupportedInstallMethods();
92         if(!$rpc->success()){
93             $this->rpcError = TRUE;
94             $this->errorMessage = $rpc->get_error();;
95             return;
96         }
98         // Populate install methods on success.
99         if(!count($res)){
100             $this->errorMessage = _("No selectable install methods returned!");
101             msg_dialog::display(_("Setup"), $this->errorMessage , ERROR_DIALOG);
102             $this->initFailed = TRUE;
103             return;
104         }else{
106             // Merge result with hard coded methods
107             $this->installationMethods = array_merge($this->installationMethods, $res);
109             // Walk through entries and create useful mappings.
110             $this->cfgItemMap = array();
111             $this->itemConfig = array();
112             $this->itemsPerMethod = array();
113             $rootElements = array();
114             foreach($this->installationMethods as $method => $items){
115                 foreach($items['items'] as $itemName => $item){
116                     $this->itemsPerMethod[$method][] = $itemName;
117                     $this->cfgItemMap[$itemName] = $method;
118                     $this->itemConfig[$itemName] = &$this->installationMethods[$method]['items'][$itemName];
119  
120                     // This enables us to create the first level of config items when 
121                     //  a release is selected.
122                     if($item['name'] == "/" && $itemName != 'root'){
123                         $rootElements = array_merge($rootElements, $item['container']);
124                     }
125                 }
126             }
128             // Merge in root elements to releases.
129             foreach($this->itemConfig as $item => $data){
130                 if(in_array('__CFG_ITEMS__', $data['container'])){
131                     $this->itemConfig[$item]['container'] = array_merge($this->itemConfig[$item]['container'], $rootElements );
132                 }
133             }
134         }
135     }
138     /*! \brief  Updates all distributions, releases, packages and items in the dataModel
139      *          Load information from the backend.
140      */
141     function updateDataModel()
142     {
143         // Recreate the data model, to have a clean and fresh instance.
144         $this->dataModel = new ConfigManagementDataModel();
146         // Load distributions 
147         $rpc = $this->config->getRpcHandle();
148         $res = $rpc->getDistributions();
149         if(!$rpc->success()){
150             msg_dialog::display(_("Error"), sprintf(_("Failed to load distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
151             return(NULL);
152         }else{
153             foreach($res as $dist){
154                 $dist['__removeable'] = TRUE;
155                 $this->dataModel->addItem('Distribution','/root', $dist['name'], $dist);
156                 if(isset($dist['releases'])){
157                     foreach($dist['releases'] as $release){
158                         $distPath = "/root/{$dist['name']}";
159                         $release['__removeable'] = TRUE;
160                         $this->dataModel->addItem('Release',$distPath, $release['name'], $release);
161                     }
162                 }
163             }
164         }
165     }
168     /*! \brief  Keep track of posted values and populate those 
169      *           which are interesting for us.
170      *          Inspects the _POST and _GET values.
171      */
172     function save_object()
173     {
174         // Update the listing class, this is necessary to get post
175         //  actions from it.
176         $this->listing->save_object();
178         // Get the selected distribution and release from the listing widget.
179         $cont = $this->listing->getSelectedContainer();
180         if(isset($_POST['ROOT'])){
181             $this->setCurrentContainer('/root');
182         }elseif(isset($_POST['BACK'])){
183             $path = $this->selectedContainer;
184             if($this->dataModel->itemExistsByPath($path)){
185                 $data = $this->dataModel->getItemByPath($path);
186                 if($data['parentPath']){
187                     $this->setCurrentContainer($data['parentPath']);
188                 }
189             }
190         }else{
191             $this->setCurrentContainer($cont);
192         }
193     }
196     /*! \brief  Load extended sub-objecte like 'config items' or 'packages'
197      *           for the given release path.
198      *  @param  String  The release path to load sub-objects for.
199      *  @return NULL 
200      */
201     function updateItemList($path)
202     {
203         // Fist get Item and check if it is an release 
204         if($this->dataModel->itemExistsByPath($path)){
205             $data = $this->dataModel->getItemByPath($path);
207             // Only releases can contain config-items.
208             if($data['type'] == 'Release' && $data['status'] != "fetched"){
211                 // Request all config items for the selected release via rpc.
212                 $rpc = $this->config->getRpcHandle();
213                 $res = $rpc->listConfigItems($data['name']);
214                 if(!$rpc->success()){
215                     msg_dialog::display(_("Error"),sprintf(_("Failed to load distributions: %s"),$rpc->get_error()),ERROR_DIALOG);
216                 }else{
218                     // Sort entries by path length 
219                     $sLen = array();
220                     foreach($res as $itemPath => $type){
221                         $sLen[strlen($itemPath)."_".$itemPath] = $itemPath;
222                     }
223                     uksort($sLen, "strnatcasecmp");   
225                     // Walk through each entry and then try to add it to the model
226                     foreach($sLen as $unused => $itemPath){
228                         // Do not add the root element '/'
229                         if($itemPath == "/") continue;
231                         $type = $res[$itemPath];
232                 
233                         // Append the items-path to the current path to create the 
234                         //  effective item path in the data model.
235                         $targetPath = trim($path."/".$itemPath);
237                         // Remove trailing and duplicated slashes
238                         $targetPath = rtrim($targetPath, '/');
239                         $targetPath = preg_replace("/\/\/*/","/", $targetPath);
241                         // Extract the items name
242                         $name = preg_replace("/^.*\//","", $targetPath);
243     
244                         // Cleanup the path and then add the item.
245                         $targetPath = preg_replace("/[^\/]*$/","", $targetPath);
246                         $targetPath = rtrim($targetPath,'/');
247                         $this->dataModel->addItem($type, $targetPath, $name, 
248                                 array(    
249                                         '__editable' => TRUE,
250                                         '__removeable' => TRUE,
251                                         '__path' => $itemPath,
252                                         '__release' => $path
253                                     ),'-' ); 
254                     }
255                     $this->dataModel->setItemStatus($path, 'fetched');
256                 }
257             }
258         }
259     }
262     /*! \brief  Sets the currently selected container and item path. 
263      *  @param  String  The path of the container to set.
264      *  @param  String  The path of the item to set.
265      *  @return 
266      */
267     function setCurrentContainer($cont)
268     {
269         $this->selectedContainer = $cont;
271         // Update list of items within the selected container. 
272         $this->updateItemList($this->selectedContainer);
274         // Transfer checked values back to the listing class.
275         $this->listing->setContainers($this->getContainerList());
276         $this->listing->setContainer($cont);
278         // Update the list of addable sub objects
279         $this->addableContainerItems = $this->getAddableContainersPerPath($cont);
280     }
283     function getAddableContainersPerPath($path)
284     {
285         $currentItem = $this->dataModel->getItemByPath($path);
286         $method = $this->getInstallationMethodPerPath($path);
288         // Get allowed items for the currently selected method 
289         //  merge in root elements, they are allowed everywhere.
290         $allowedItems = $this->itemsPerMethod[$method];
291         $allowedItems = array_merge($allowedItems, $this->itemsPerMethod['root']);
293         // Get addable items
294         $possibleItems = $this->itemConfig[$currentItem['type']]['container'];
295         return(array_unique(array_intersect($allowedItems, $possibleItems)));
296     }
298     
299     function getInstallationMethodPerPath($path)
300     {
301         $path .= '/';
302         while(preg_match("/\//", $path)){
303             $path = preg_replace("/\/[^\/]*$/","",$path);
304             $item = $this->dataModel->getItemByPath($path);
305             if(isset($item['values']['installation_method'])){
306                 return($item['values']['installation_method']);
307             }
308         }
309         return('root'); 
310     }
313     /*! \brief  Generate the HTML content for this plugin.
314      *          Actually renders the listing widget..
315      */
316     function execute()
317     {
318         // Get the selected release and store it in a session variable
319         //  to allow the configFilter to access it and display the
320         //  packages and items.
321         $res = $this->listing->execute();
322         $this->listing->setListingTypes($this->getListingTypes());
323         return($res);
324     }
327     /*! \brief      Returns a list of items which will then be displayed 
328      *               in the management-list. 
329      *              (The management class calls this method from its execute())
330      *  @return     Array   A list of items/objects for the listing. 
331      */
332     function getItemsToBeDisplayed()
333     {
334         $path = $this->selectedContainer;
335         $item = $this->dataModel->getItemByPath($path);
336         return($item);
337     }
340     /*! \brief  Returns a simply list of all distributions.
341      *          This list will then be used to generate the entries of the 
342      *           ItemSelectors in the listing class.
343      */
344     function getContainerList()
345     {
346         $data = $this->dataModel->getItemByPath('/root');
347         $res = array();
348         $res["/root"] = array("name" => "/", "desc" => "");
349         $res = array_merge($res,$this->__recurseItem($data));
350         return($res);
351     }
354     /*! \brief  Recursivly wlks through an item and collects all path and name info.
355      *          The reult can then be used to fill the ItemSelector.
356      *  @param  Array   The Item to recurse. 
357      *  @param  Array   The type of of objects to collect. 
358      *  @param  String  The parent path prefix which should be removed.
359      *  @return Array   An array containing Array[path] = name
360      */
361     function __recurseItem($item, $parent = "")
362     {
363         $res = array();
364         $path = preg_replace("/".preg_quote($parent,'/')."/","",$item['path']);
365         $res[$path] = array('name' => $item['name'],'desc'=>$item['type']);
366         if(count($item['children'])){
367             foreach($item['children'] as $child){
368                 $res = array_merge($res, $this->__recurseItem($child, $parent));
369             }
370         }
371         return($res);
372     }
375     /*! \brief   Returns a info list about all items we can manage,
376      *            this used to fill the listings <objectType> settings.
377      *  @return Array   An array with item info.
378      */
379     function getListingTypes()
380     {
381         $types= array();
382         $types['Distribution']['objectClass'] = 'Distribution';
383         $types['Distribution']['label'] = _('Distribution');
384         $types['Distribution']['image'] = 'images/lists/edit.png';
385         $types['Distribution']['category'] = 'Device';
386         $types['Distribution']['class'] = 'Device';
388         $types['Release']['objectClass'] = 'Release';
389         $types['Release']['label'] = _('Release');
390         $types['Release']['image'] = 'images/lists/delete.png';
391         $types['Release']['category'] = 'Device';
392         $types['Release']['class'] = 'Device';
394         $types['Component']['objectClass'] = 'Component';
395         $types['Component']['label'] = _('Component');
396         $types['Component']['image'] = 'plugins/users/images/select_user.png';
397         $types['Component']['category'] = 'Device';
398         $types['Component']['class'] = 'Device';
400         foreach($this->installationMethods as $method => $items){
401             foreach($items['items'] as $itemName => $item){
402                 $types[$itemName]['objectClass'] = $itemName;
403                 $types[$itemName]['label'] = $item['name'];
404                 $types[$itemName]['image'] = 'plugins/fai/images/fai_script.png';
405                 $types[$itemName]['category'] = 'Device';
406                 $types[$itemName]['class'] = 'Device';
407             }
408         }
410         return($types);
411     }
414     /*! \brief      The plugins ACL and plugin-property definition. 
415      *  @return 
416      */
417     public static function plInfo()
418     {
419         return (array(
420                     "plShortName"   => _("Config management"),
421                     "plDescription" => _("Config management"),
422                     "plSelfModify"  => FALSE,
423                     "plDepends"     => array(),
424                     "plPriority"    => 0,
425                     "plSection"     => array("administration"),
426                     "plCategory"    => array(
427                         "newConfigManagement" => array("description"  => _("Config management"),
428                             "objectClass"  => "FAKE_OC_newConfigManagement")),
429                     "plProvidedAcls"=> array()
430                     ));
431     }
434     /*! \brief  Acts on open requests.
435      *          (This action is received from the ConfigManagementListing class.)
436      *  @param  Array   The items ids. (May contain multiple ids)
437      *  @return
438      */
439     function openEntry($ids)
440     {
441         $id = $ids[0];
442         $item = $this->dataModel->getItemById($id);
443         $this->setCurrentContainer($item['path']);
444         return;
445     }
449     /*! \brief  Removes an entry from the listing.
450      */
451     function removeEntry($ids)
452     {
454         $item = $this->dataModel->getItemById($ids[0]);
456         // Is an config item.
457         if(isset($this->cfgItemMap[$item['type']])){
458             $release = preg_replace("/^.*\//","",$item['values']['__release']);
459             $path = $item['values']['__path'];
460             $rpc = $this->config->getRpcHandle();
461             $rpc->removeConfigItem($release, $path);
462             if(!$rpc->success()){
463                 msg_dialog::display(_("Error"), sprintf(_("Failed to remove: %s"), $rpc->get_error()),ERROR_DIALOG);
464                 return(NULL);
465             }else{
466                 $this->dataModel->removeItem($item['path']);
467             }
468         }else{
469             echo $item['type']." - are not handled yet!";
470         }
471     }
474     /*! \brief      Edits a selected list item.
475      */
476     function editEntry($ids)
477     {
478         // Update the template engine to use another type of item and
479         //  some other values.
480         $item = $this->dataModel->getItemById($ids[0]);
481         if(isset($this->cfgItemMap[$item['type']])){
482             $release = preg_replace("/^.*\//","",$item['values']['__release']);
483             $path = $item['values']['__path'];
484             $method = $this->cfgItemMap[$item['type']];
486             // Load item values on demand
487             if($item['status'] == '-'){
488                 $rpc = $this->config->getRpcHandle();
489                 $item['values']['itemValues'] = $rpc->getConfigItem($release, $path);
490                 $this->dataModel->setItemStatus($item['path'], 'fetched');
491                 $this->dataModel->setItemValues($item['path'], $item['values']);
492             }
494             $this->TemplateEngine->load($this->itemConfig);
495             $this->TemplateEngine->setTemplate($method.".tpl");
496             $this->TemplateEngine->setValues($item['type'],$item['values']['itemValues']);
497             $this->listing->setDialogObject($this->TemplateEngine);
498             $this->currentObject = $item;
499         }
500     }
503     /*! \brief  Initiates the creation of a new item
504      */
505     function newEntry($type)
506     {
507         // We've to add a config item
508         $this->TemplateEngine->load($this->itemConfig);
509         if(isset($this->cfgItemMap[$type])){
510             $method = $this->cfgItemMap[$type];
511             $this->TemplateEngine->setTemplate($method.".tpl");
512             $this->TemplateEngine->setValues($type,array());
513             $this->listing->setDialogObject($this->TemplateEngine);
514             $this->currentObject = NULL;
515         }elseif($type == 'Distribution'){
516             $this->TemplateEngine->setTemplate("root.tpl");
517             $this->TemplateEngine->setValues($type,array());
518             $this->listing->setDialogObject($this->TemplateEngine);
519             $this->currentObject = NULL;
520         }elseif($type == 'Release'){
521         }
522     }
525     /*! \brief  Extracts the item-path out of a path.
526      *          e.g. /debian/squeeze/test/module -> /test/module
527      */
528     function getItemPath($fullPath)
529     {
530         $fPath = $fullPath.'/';
531         while(preg_match("/\//", $fPath)){
532             $fPath = preg_replace("/\/[^\/]*$/","", $fPath);
533             $item = $this->dataModel->getItemByPath($fPath);
534             if(in_array($item['type'], array('Release', 'Distribution', 'root'))){
535                 return(preg_replace("/".preg_quote($item['path'],'/')."/", "", $fullPath));
536             }
537         }
538         return(NULL);
539     }
542     /*! \brief  Extracts the releaes path out of a path.
543      *          e.g. /debian/squeeze/test/module -> /debian/squeeze
544      */
545     function getReleasePath($fullPath)
546     {
547         $fullPath.='/';
548         while(preg_match("/\//", $fullPath)){
549             $fullPath = preg_replace("/\/[^\/]*$/","", $fullPath);
550             $item = $this->dataModel->getItemByPath($fullPath);
551             if($item['type'] == 'Release'){
552                 return($fullPath);
553             }
554         }
555         return(NULL);
556     }
557    
558  
559     function saveItemChanges()
560     {
561         $item = $this->currentObject;
563         // Null means a new  object has to be added.        
564         if($item == NULL){
566             // Save template engine modifications
567             $this->TemplateEngine->save_object();
568             $release = preg_replace("/^.*\//","", $this->getReleasePath($this->selectedContainer));
569             $type = $this->TemplateEngine->getItemType();
571             // Collect modified values
572             $values = array();
573             foreach($this->TemplateEngine->getWidgets() as $w){
574                 $values[$w->getName()] = $w->getValue();
575             }
576            
577             // Create the elements target path  
578             $path = $this->getItemPath($this->selectedContainer)."/".$values['name'];
580             // Add the new item
581             $rpc = $this->config->getRpcHandle();
582             $res = $rpc->setConfigItem($release, $path, $type, $values);
583             if(!$rpc->success()){
584                 msg_dialog::display(_("Error"), sprintf(_("Failed to load distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
585                 return(NULL);
586             }else{
588                 // We've successfully added the item, now add it to the tree.
589                 $this->dataModel->addItem($type, $this->selectedContainer, $values['name'], 
590                         array(    
591                             '__editable' => TRUE,
592                             '__removeable' => TRUE,
593                             '__path' => $path,
594                             '__release' => $this->getReleasePath($this->selectedContainer)
595                             ), '-' );
597                 // Finally - close the dialog. 
598                 $this->listing->clearDialogObject();
599             }
600         }else{
602             // Collect modified values.
603             $this->TemplateEngine->save_object();
604             $values = array();
605             foreach($this->TemplateEngine->getWidgets() as $w){
606                 $values[$w->getName()] = $w->getValue();
607             }
609             // Get the items release & path info
610             $release = preg_replace("/^.*\//","",$item['values']['__release']);
611             $path = $item['values']['__path'];
612     
613             // Write the modifications back to the server.
614             $rpc = $this->config->getRpcHandle();
615             $res = $rpc->setConfigItem($release, $path, $item['type'], $values);
616             if(!$rpc->success()){
617                 msg_dialog::display(_("Error"), sprintf(_("Failed to load distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
618                 return(NULL);
619             }else{
620         
621                 // Update the data model
622                 $item['values']['itemValues'] = $values;
623                 $this->dataModel->setItemValues($item['path'], $item['values']);
624                 $this->listing->clearDialogObject();
625             }
626         }
627     }
628     function remove_lock() {}
632 ?>