Code

Updated distribution template
[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         // Define distribution paramters.
40         $dOpt1 = array('description' => _('Name'), 'default' => '', 'value' => '', 'required' => true,
41                 'type' => 'string', 'display' => _('Name'));
42         $dOpt2 = array('description' => _('Distribution type'), 'default' => 'deb', 'value' => 'deb', 'required' => true,
43                 'type' => 'combobox', 'display' => _('Distribution type'), 'values' => array("deb" => 'deb', "rpm" => 'rpm'));
44         $dOpt3 = array('description' => _('Mirror Url'), 'default' => '', 'value' => '', 'required' => false,
45                 'type' => 'string', 'display' => _('Mirror Url'));
46         $dOpt4 = array('description' => _('Method'), 'default' => 'puppet', 'value' => 'puppet', 'required' => false,
47                 'type' => 'combobox', 'display' => _('Installation method'), 'values'=>array('puppet'=>_('Puppet')));
49         // Define release parameters
50         $rOpt1 = array('description' => _('Name'), 'default' => '', 'value' => '', 'required' => true,
51                 'type' => 'string', 'display' => _('Name'));
53         $items['Distribution']['container'] = array('Release');
54         $items['Distribution']['name'] = 'Distribution';
55         $items['Distribution']['description'] = _('Distribution');
56         $items['Distribution']['options']['name'] = $dOpt1;
57         $items['Distribution']['options']['mirror'] = $dOpt3;
58         $items['Distribution']['options']['installation_type'] = $dOpt2;
59         $items['Distribution']['options']['installation_method'] = $dOpt4;
61         $items['Release']['container'] = array('Release', '__CFG_ITEMS__');
62         $items['Release']['name'] = 'Release';
63         $items['Release']['description'] = _('Release');
64         $items['Release']['options']['name'] = $rOpt1;
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                 $this->dataModel->addItem('Distribution','/root', $dist['name'], $dist);
156                 if(isset($dist['releases'])){
158                     // Sort releases by name length
159                     $sort = array();
160                     foreach($dist['releases'] as $id => $release){
161                         $sort[strlen($release['name']) . $release['name']]  = $id;
162                     }
163                     uksort($sort, "strnatcasecmp");   
165                     // Append release tags
166                     foreach($sort as $id){
167                         $release = $dist['releases'][$id];
168                         $names = preg_split("/\//", $release['name']);
169     
170                         $rPath = "";
171                         $distPath = "/root/{$dist['name']}";
172                         foreach($names as $rName){
173                             $rPath .= '/'.$rName;
174                             
175                             
176                             $this->dataModel->addItem('Release',$distPath, $rName, $release);
177     
178                             print_a(array('Release',$distPath, $rName, $release));
179                             $distPath .= $rPath;
180                         }
181                     }
182                 }
183             }
184         }
185     }
188     /*! \brief  Keep track of posted values and populate those 
189      *           which are interesting for us.
190      *          Inspects the _POST and _GET values.
191      */
192     function save_object()
193     {
194         // Update the listing class, this is necessary to get post
195         //  actions from it.
196         $this->listing->save_object();
198         // Get the selected distribution and release from the listing widget.
199         $cont = $this->listing->getSelectedContainer();
200         if(isset($_POST['ROOT'])){
201             $this->setCurrentContainer('/root');
202         }elseif(isset($_POST['BACK'])){
203             $path = $this->selectedContainer;
204             if($this->dataModel->itemExistsByPath($path)){
205                 $data = $this->dataModel->getItemByPath($path);
206                 if($data['parentPath']){
207                     $this->setCurrentContainer($data['parentPath']);
208                 }
209             }
210         }else{
211             $this->setCurrentContainer($cont);
212         }
213     }
216     /*! \brief  Load extended sub-objecte like 'config items' or 'packages'
217      *           for the given release path.
218      *  @param  String  The release path to load sub-objects for.
219      *  @return NULL 
220      */
221     function updateItemList($path)
222     {
223         // Fist get Item and check if it is an release 
224         if($this->dataModel->itemExistsByPath($path)){
225             $data = $this->dataModel->getItemByPath($path);
227             // Only releases can contain config-items.
228             if($data['type'] == 'Release' && $data['status'] != "fetched"){
231                 // Request all config items for the selected release via rpc.
232                 $rpc = $this->config->getRpcHandle();
233                 $res = $rpc->listConfigItems($data['name']);
234                 if(!$rpc->success()){
235                     msg_dialog::display(_("Error"),sprintf(_("Failed to load distributions: %s"),$rpc->get_error()),ERROR_DIALOG);
236                 }else{
237             
238                     if(!$res) return;
240                     // Sort entries by path length 
241                     $sLen = array();
242                     foreach($res as $itemPath => $type){
243                         $sLen[strlen($itemPath)."_".$itemPath] = $itemPath;
244                     }
245                     uksort($sLen, "strnatcasecmp");   
247                     // Walk through each entry and then try to add it to the model
248                     foreach($sLen as $unused => $itemPath){
250                         // Do not add the root element '/'
251                         if($itemPath == "/") continue;
253                         $type = $res[$itemPath];
254                 
255                         // Append the items-path to the current path to create the 
256                         //  effective item path in the data model.
257                         $targetPath = trim($path."/".$itemPath);
259                         // Remove trailing and duplicated slashes
260                         $targetPath = rtrim($targetPath, '/');
261                         $targetPath = preg_replace("/\/\/*/","/", $targetPath);
263                         // Extract the items name
264                         $name = preg_replace("/^.*\//","", $targetPath);
265     
266                         // Cleanup the path and then add the item.
267                         $targetPath = preg_replace("/[^\/]*$/","", $targetPath);
268                         $targetPath = rtrim($targetPath,'/');
269                         $this->dataModel->addItem($type, $targetPath, $name,array(),'-' ); 
270                     }
271                     $this->dataModel->setItemStatus($path, 'fetched');
272                 }
273             }
274         }
275     }
278     /*! \brief  Sets the currently selected container and item path. 
279      *  @param  String  The path of the container to set.
280      *  @param  String  The path of the item to set.
281      *  @return 
282      */
283     function setCurrentContainer($cont)
284     {
285         $this->selectedContainer = $cont;
287         // Update list of items within the selected container. 
288         $this->updateItemList($this->selectedContainer);
290         // Transfer checked values back to the listing class.
291         $this->listing->setContainers($this->getContainerList());
292         $this->listing->setContainer($cont);
294         // Update the list of addable sub objects
295         $this->addableContainerItems = $this->getAddableContainersPerPath($cont);
296     }
299     function getAddableContainersPerPath($path)
300     {
301         $currentItem = $this->dataModel->getItemByPath($path);
302         $method = $this->getInstallationMethodPerPath($path);
304         // Get allowed items for the currently selected method 
305         //  merge in root elements, they are allowed everywhere.
306         $allowedItems = $this->itemsPerMethod[$method];
307         $allowedItems = array_merge($allowedItems, $this->itemsPerMethod['root']);
309         // Get addable items
310         $possibleItems = $this->itemConfig[$currentItem['type']]['container'];
311         return(array_unique(array_intersect($allowedItems, $possibleItems)));
312     }
314     
315     function getInstallationMethodPerPath($path)
316     {
317         $path .= '/';
318         while(preg_match("/\//", $path)){
319             $path = preg_replace("/\/[^\/]*$/","",$path);
320             $item = $this->dataModel->getItemByPath($path);
321             if(isset($item['values']['installation_method'])){
322                 return($item['values']['installation_method']);
323             }
324         }
325         return('root'); 
326     }
329     /*! \brief  Generate the HTML content for this plugin.
330      *          Actually renders the listing widget..
331      */
332     function execute()
333     {
334         // Get the selected release and store it in a session variable
335         //  to allow the configFilter to access it and display the
336         //  packages and items.
337         $res = $this->listing->execute();
338         $this->listing->setListingTypes($this->getListingTypes());
339         return($res);
340     }
343     /*! \brief      Returns a list of items which will then be displayed 
344      *               in the management-list. 
345      *              (The management class calls this method from its execute())
346      *  @return     Array   A list of items/objects for the listing. 
347      */
348     function getItemsToBeDisplayed()
349     {
350         $path = $this->selectedContainer;
351         $item = $this->dataModel->getItemByPath($path);
352         return($item);
353     }
356     /*! \brief  Returns a simply list of all distributions.
357      *          This list will then be used to generate the entries of the 
358      *           ItemSelectors in the listing class.
359      */
360     function getContainerList()
361     {
362         $data = $this->dataModel->getItemByPath('/root');
363         $res = array();
364         $res["/root"] = array("name" => "/", "desc" => "");
365         $res = array_merge($res,$this->__recurseItem($data));
366         return($res);
367     }
370     /*! \brief  Recursivly wlks through an item and collects all path and name info.
371      *          The reult can then be used to fill the ItemSelector.
372      *  @param  Array   The Item to recurse. 
373      *  @param  Array   The type of of objects to collect. 
374      *  @param  String  The parent path prefix which should be removed.
375      *  @return Array   An array containing Array[path] = name
376      */
377     function __recurseItem($item, $parent = "")
378     {
379         $res = array();
380         $path = preg_replace("/".preg_quote($parent,'/')."/","",$item['path']);
381         $res[$path] = array('name' => $item['name'],'desc'=>$item['type']);
382         if(count($item['children'])){
383             foreach($item['children'] as $child){
384                 $res = array_merge($res, $this->__recurseItem($child, $parent));
385             }
386         }
387         return($res);
388     }
391     /*! \brief   Returns a info list about all items we can manage,
392      *            this used to fill the listings <objectType> settings.
393      *  @return Array   An array with item info.
394      */
395     function getListingTypes()
396     {
397         $types= array();
398         $types['Distribution']['objectClass'] = 'Distribution';
399         $types['Distribution']['label'] = _('Distribution');
400         $types['Distribution']['image'] = 'images/lists/edit.png';
401         $types['Distribution']['category'] = 'Device';
402         $types['Distribution']['class'] = 'Device';
404         $types['Release']['objectClass'] = 'Release';
405         $types['Release']['label'] = _('Release');
406         $types['Release']['image'] = 'images/lists/delete.png';
407         $types['Release']['category'] = 'Device';
408         $types['Release']['class'] = 'Device';
410         $types['Component']['objectClass'] = 'Component';
411         $types['Component']['label'] = _('Component');
412         $types['Component']['image'] = 'plugins/users/images/select_user.png';
413         $types['Component']['category'] = 'Device';
414         $types['Component']['class'] = 'Device';
416         foreach($this->installationMethods as $method => $items){
417             foreach($items['items'] as $itemName => $item){
418                 $types[$itemName]['objectClass'] = $itemName;
419                 $types[$itemName]['label'] = $item['name'];
420                 $types[$itemName]['image'] = 'plugins/fai/images/fai_script.png';
421                 $types[$itemName]['category'] = 'Device';
422                 $types[$itemName]['class'] = 'Device';
423             }
424         }
426         return($types);
427     }
430     /*! \brief      The plugins ACL and plugin-property definition. 
431      *  @return 
432      */
433     public static function plInfo()
434     {
435         return (array(
436                     "plShortName"   => _("Config management"),
437                     "plDescription" => _("Config management"),
438                     "plSelfModify"  => FALSE,
439                     "plDepends"     => array(),
440                     "plPriority"    => 0,
441                     "plSection"     => array("administration"),
442                     "plCategory"    => array(
443                         "newConfigManagement" => array("description"  => _("Config management"),
444                             "objectClass"  => "FAKE_OC_newConfigManagement")),
445                     "plProvidedAcls"=> array()
446                     ));
447     }
450     /*! \brief  Acts on open requests.
451      *          (This action is received from the ConfigManagementListing class.)
452      *  @param  Array   The items ids. (May contain multiple ids)
453      *  @return
454      */
455     function openEntry($ids)
456     {
457         $id = $ids[0];
458         $item = $this->dataModel->getItemById($id);
459         $this->setCurrentContainer($item['path']);
460         return;
461     }
465     /*! \brief  Removes an entry from the listing.
466      */
467     function removeEntry($ids)
468     {
469         foreach($ids as $id){
470             $item = $this->dataModel->getItemById($id);
472             // Is an config item.
473             if($this->cfgItemMap[$item['type']] != 'root'){
474                 $release = preg_replace("/^.*\//","", $this->getReleasePath($item['path']));
475                 $path = $this->getItemPath($item['path']);
477                 $rpc = $this->config->getRpcHandle();
478                 $rpc->removeConfigItem($release, $path);
479                 if(!$rpc->success()){
480                     msg_dialog::display(_("Error"), sprintf(_("Failed to remove: %s"), $rpc->get_error()),ERROR_DIALOG);
481                     return(NULL);
482                 }else{
483                     $this->dataModel->removeItem($item['path']);
484                 }
485             }else{
486                 echo $item['type']." - are not handled yet!";
487             }
488         }
489     }
491     function getUsedNamesForPath($path)
492     {
493         $item = $this->dataModel->getItemByPath($path);
494         $names = array();
495         foreach($item['children'] as $path => $data){
496             $names[] = $data['name'];
497         }
498         return($names);
499     }
502     /*! \brief      Edits a selected list item.
503      */
504     function editEntry($ids)
505     {
506         $item = $this->dataModel->getItemById($ids[0]);
507         $release = preg_replace("/^.*\//","", $this->getReleasePath($item['path']));
508         $path = $this->getItemPath($item['path']);
509         $method = $this->cfgItemMap[$item['type']];
511         // Load item values on demand
512         if($this->cfgItemMap[$item['type']] != 'root'){
513             if($item['status'] == '-'){
514                 $rpc = $this->config->getRpcHandle();
515                 $item['values'] = $rpc->getConfigItem($release, $path);
516                 $this->dataModel->setItemStatus($item['path'], 'fetched');
517                 $this->dataModel->setItemValues($item['path'], $item['values']);
518             }
519         }
521         $this->TemplateEngine->load($this->itemConfig);
522         $this->TemplateEngine->setTemplate($method.".tpl");
523         $this->TemplateEngine->setValues($item['type'],$item['values']);
524         $this->listing->setDialogObject($this->TemplateEngine);
525         $this->currentObject = $item;
526     }
529     /*! \brief  Initiates the creation of a new item
530      */
531     function newEntry($type)
532     {
533         // We've to add a config item
534         $this->TemplateEngine->load($this->itemConfig);
535         if($this->cfgItemMap[$type] != 'root'){
536             $method = $this->cfgItemMap[$type];
537             $this->TemplateEngine->setTemplate($method.".tpl");
538             $this->TemplateEngine->setValues($type,array());
539             $this->listing->setDialogObject($this->TemplateEngine);
540             $this->currentObject = NULL;
541         }else{
542             $this->TemplateEngine->setTemplate("root.tpl");
543             $this->TemplateEngine->setValues($type,array());
544             $this->listing->setDialogObject($this->TemplateEngine);
545             $this->currentObject = NULL;
546         }
547     }
550     /*! \brief  Extracts the item-path out of a path.
551      *          e.g. /debian/squeeze/test/module -> /test/module
552      */
553     function getItemPath($fullPath)
554     {
555         $fPath = $fullPath.'/';
556         while(preg_match("/\//", $fPath)){
557             $fPath = preg_replace("/\/[^\/]*$/","", $fPath);
558             $item = $this->dataModel->getItemByPath($fPath);
559             if(in_array($item['type'], array('Release', 'Distribution', 'root'))){
560                 return(preg_replace("/".preg_quote($item['path'],'/')."/", "", $fullPath));
561             }
562         }
563         return(NULL);
564     }
567     /*! \brief  Extracts the releaes path out of a path.
568      *          e.g. /debian/squeeze/test/module -> /debian/squeeze
569      */
570     function getReleasePath($fullPath)
571     {
572         $fullPath.='/';
573         while(preg_match("/\//", $fullPath)){
574             $fullPath = preg_replace("/\/[^\/]*$/","", $fullPath);
575             $item = $this->dataModel->getItemByPath($fullPath);
576             if($item['type'] == 'Release'){
577                 return($fullPath);
578             }
579         }
580         return(NULL);
581     }
582    
583  
584     function saveItemChanges()
585     {
586         // Save template engine modifications and validate values.
587         $this->TemplateEngine->save_object();
588         $msgs = $this->TemplateEngine->check();
590         // Get values to be saved
591         $values = array();
592         foreach($this->TemplateEngine->getWidgets() as $w){
593             $values[$w->getName()] = $w->getValue();
594         }
595            
596         // No input error were found, now check that we do not use the same name twice.
597         if(!count($msgs)){
598             $usedNames = $this->getUsedNamesForPath($this->selectedContainer);
600             // Allow the item to keep its name.
601             if($this->currentObject != NULL && isset($this->currentObject['values']['name'])){
602                 $usedNames = array_remove_entries(array($this->currentObject['values']['name']), $usedNames);
603             }
604             if(in_array($values['name'],$usedNames)){
605                 $msgs[] = msgPool::duplicated(_("Name"));
606             }
607         }
609         // Display errors
610         if(count($msgs)){
611             msg_dialog::displayChecks($msgs);
612             return;
613         }
615         // Get the item type to be saved
616         $item = $this->currentObject;
617         $type = $this->TemplateEngine->getItemType();
618         if($this->cfgItemMap[$type] == 'root'){
619             echo "{$type} Cannot be saved yet";
620             $this->listing->clearDialogObject();
621             return;
622         }
624         // Save a CONFIG-ITEM object.
625         if($this->cfgItemMap[$type] != 'root'){
627             // Get paths 
628             $release = preg_replace("/^.*\//","", $this->getReleasePath($this->selectedContainer));
629             $newPath = $this->selectedContainer."/".$values['name'];
630             $newItemPath = $this->getItemPath($this->selectedContainer)."/".$values['name'];
631             if($item){
632                 $oldPath = $item['path'];
633                 $oldItemPath = $this->getItemPath($item['path']);
634             }
636             // If this is a new item, then create it now.
637             if($item == NULL){
639                 // Add the new item
640                 $rpc = $this->config->getRpcHandle();
641                 $res = $rpc->setConfigItem($release, $newItemPath, $type, $values);
642                 if(!$rpc->success()){
643                     msg_dialog::display(_("Error"), sprintf(_("Failed to load distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
644                     return(NULL);
645                 }else{
647                     // We've successfully added the item, now add it to the tree.
648                     $this->dataModel->addItem($type, $this->selectedContainer, $values['name'],array(), '-' );
650                     // Finally - close the dialog. 
651                     $this->listing->clearDialogObject();
652                 }
653             }else{
655                 // Write the modifications back to the server.
656                 $rpc = $this->config->getRpcHandle();
657                 $res = $rpc->setConfigItem($release, $oldItemPath, $type, $values);
658                 if(!$rpc->success()){
659                     msg_dialog::display(_("Error"), sprintf(_("Failed to load distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
660                     return(NULL);
661                 }else{
662             
663                     // Update the data model
664                     $this->dataModel->setItemValues($oldPath, $values);
665                     if($oldPath != $newPath){
666                         $this->dataModel->moveItem($oldPath, $newPath);
667                     }
668                     $this->listing->clearDialogObject();
669                 }
670             }
671         }
672     }
673     function remove_lock() {}
677 ?>