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];
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']);
170 $rPath = "";
171 $distPath = "/root/{$dist['name']}";
172 foreach($names as $rName){
173 $rPath .= '/'.$rName;
174 $this->dataModel->addItem('Release',$distPath, $rName, $release);
175 $distPath .= $rPath;
176 }
177 }
178 }
179 }
180 }
181 }
184 /*! \brief Keep track of posted values and populate those
185 * which are interesting for us.
186 * Inspects the _POST and _GET values.
187 */
188 function save_object()
189 {
190 // Update the listing class, this is necessary to get post
191 // actions from it.
192 $this->listing->save_object();
194 // Get the selected distribution and release from the listing widget.
195 $cont = $this->listing->getSelectedContainer();
196 if(isset($_POST['ROOT'])){
197 $this->setCurrentContainer('/root');
198 }elseif(isset($_POST['BACK'])){
199 $path = $this->selectedContainer;
200 if($this->dataModel->itemExistsByPath($path)){
201 $data = $this->dataModel->getItemByPath($path);
202 if($data['parentPath']){
203 $this->setCurrentContainer($data['parentPath']);
204 }
205 }
206 }else{
207 $this->setCurrentContainer($cont);
208 }
209 }
212 /*! \brief Load extended sub-objecte like 'config items' or 'packages'
213 * for the given release path.
214 * @param String The release path to load sub-objects for.
215 * @return NULL
216 */
217 function updateItemList($path)
218 {
219 // Fist get Item and check if it is an release
220 if($this->dataModel->itemExistsByPath($path)){
221 $data = $this->dataModel->getItemByPath($path);
223 // Only releases can contain config-items.
224 if($data['type'] == 'Release' && $data['status'] != "fetched"){
227 // Request all config items for the selected release via rpc.
228 $rpc = $this->config->getRpcHandle();
229 $res = $rpc->listConfigItems($data['name']);
230 if(!$rpc->success()){
231 msg_dialog::display(_("Error"),sprintf(_("Failed to load distributions: %s"),$rpc->get_error()),ERROR_DIALOG);
232 }else{
234 if(!$res) return;
236 // Sort entries by path length
237 $sLen = array();
238 foreach($res as $itemPath => $type){
239 $sLen[strlen($itemPath)."_".$itemPath] = $itemPath;
240 }
241 uksort($sLen, "strnatcasecmp");
243 // Walk through each entry and then try to add it to the model
244 foreach($sLen as $unused => $itemPath){
246 // Do not add the root element '/'
247 if($itemPath == "/") continue;
249 $type = $res[$itemPath];
251 // Append the items-path to the current path to create the
252 // effective item path in the data model.
253 $targetPath = trim($path."/".$itemPath);
255 // Remove trailing and duplicated slashes
256 $targetPath = rtrim($targetPath, '/');
257 $targetPath = preg_replace("/\/\/*/","/", $targetPath);
259 // Extract the items name
260 $name = preg_replace("/^.*\//","", $targetPath);
262 // Cleanup the path and then add the item.
263 $targetPath = preg_replace("/[^\/]*$/","", $targetPath);
264 $targetPath = rtrim($targetPath,'/');
265 $this->dataModel->addItem($type, $targetPath, $name,array(),'-' );
266 }
267 $this->dataModel->setItemStatus($path, 'fetched');
268 }
269 }
270 }
271 }
274 /*! \brief Sets the currently selected container and item path.
275 * @param String The path of the container to set.
276 * @param String The path of the item to set.
277 * @return
278 */
279 function setCurrentContainer($cont)
280 {
281 $this->selectedContainer = $cont;
283 // Update list of items within the selected container.
284 $this->updateItemList($this->selectedContainer);
286 // Transfer checked values back to the listing class.
287 $this->listing->setContainers($this->getContainerList());
288 $this->listing->setContainer($cont);
290 // Update the list of addable sub objects
291 $this->addableContainerItems = $this->getAddableContainersPerPath($cont);
292 }
295 function getAddableContainersPerPath($path)
296 {
297 $currentItem = $this->dataModel->getItemByPath($path);
298 $method = $this->getInstallationMethodPerPath($path);
300 // Get allowed items for the currently selected method
301 // merge in root elements, they are allowed everywhere.
302 $allowedItems = $this->itemsPerMethod[$method];
303 $allowedItems = array_merge($allowedItems, $this->itemsPerMethod['root']);
305 // Get addable items
306 $possibleItems = $this->itemConfig[$currentItem['type']]['container'];
307 return(array_unique(array_intersect($allowedItems, $possibleItems)));
308 }
311 function getInstallationMethodPerPath($path)
312 {
313 $path .= '/';
314 while(preg_match("/\//", $path)){
315 $path = preg_replace("/\/[^\/]*$/","",$path);
316 $item = $this->dataModel->getItemByPath($path);
317 if(isset($item['values']['installation_method'])){
318 return($item['values']['installation_method']);
319 }
320 }
321 return('root');
322 }
325 /*! \brief Generate the HTML content for this plugin.
326 * Actually renders the listing widget..
327 */
328 function execute()
329 {
330 // Get the selected release and store it in a session variable
331 // to allow the configFilter to access it and display the
332 // packages and items.
333 $res = $this->listing->execute();
334 $this->listing->setListingTypes($this->getListingTypes());
335 return($res);
336 }
339 /*! \brief Returns a list of items which will then be displayed
340 * in the management-list.
341 * (The management class calls this method from its execute())
342 * @return Array A list of items/objects for the listing.
343 */
344 function getItemsToBeDisplayed()
345 {
346 $path = $this->selectedContainer;
347 $item = $this->dataModel->getItemByPath($path);
348 return($item);
349 }
352 /*! \brief Returns a simply list of all distributions.
353 * This list will then be used to generate the entries of the
354 * ItemSelectors in the listing class.
355 */
356 function getContainerList()
357 {
358 $data = $this->dataModel->getItemByPath('/root');
359 $res = array();
360 $res["/root"] = array("name" => "/", "desc" => "");
361 $res = array_merge($res,$this->__recurseItem($data));
362 return($res);
363 }
366 /*! \brief Recursivly wlks through an item and collects all path and name info.
367 * The reult can then be used to fill the ItemSelector.
368 * @param Array The Item to recurse.
369 * @param Array The type of of objects to collect.
370 * @param String The parent path prefix which should be removed.
371 * @return Array An array containing Array[path] = name
372 */
373 function __recurseItem($item, $parent = "")
374 {
375 $res = array();
376 $path = preg_replace("/".preg_quote($parent,'/')."/","",$item['path']);
377 $res[$path] = array('name' => $item['name'],'desc'=>$item['type']);
378 if(count($item['children'])){
379 foreach($item['children'] as $child){
380 $res = array_merge($res, $this->__recurseItem($child, $parent));
381 }
382 }
383 return($res);
384 }
387 /*! \brief Returns a info list about all items we can manage,
388 * this used to fill the listings <objectType> settings.
389 * @return Array An array with item info.
390 */
391 function getListingTypes()
392 {
393 $types= array();
394 $types['Distribution']['objectClass'] = 'Distribution';
395 $types['Distribution']['label'] = _('Distribution');
396 $types['Distribution']['image'] = 'images/lists/edit.png';
397 $types['Distribution']['category'] = 'Device';
398 $types['Distribution']['class'] = 'Device';
400 $types['Release']['objectClass'] = 'Release';
401 $types['Release']['label'] = _('Release');
402 $types['Release']['image'] = 'images/lists/delete.png';
403 $types['Release']['category'] = 'Device';
404 $types['Release']['class'] = 'Device';
406 $types['Component']['objectClass'] = 'Component';
407 $types['Component']['label'] = _('Component');
408 $types['Component']['image'] = 'plugins/users/images/select_user.png';
409 $types['Component']['category'] = 'Device';
410 $types['Component']['class'] = 'Device';
412 foreach($this->installationMethods as $method => $items){
413 foreach($items['items'] as $itemName => $item){
414 $types[$itemName]['objectClass'] = $itemName;
415 $types[$itemName]['label'] = $item['name'];
416 $types[$itemName]['image'] = 'plugins/fai/images/fai_script.png';
417 $types[$itemName]['category'] = 'Device';
418 $types[$itemName]['class'] = 'Device';
419 }
420 }
422 return($types);
423 }
426 /*! \brief The plugins ACL and plugin-property definition.
427 * @return
428 */
429 public static function plInfo()
430 {
431 return (array(
432 "plShortName" => _("Config management"),
433 "plDescription" => _("Config management"),
434 "plSelfModify" => FALSE,
435 "plDepends" => array(),
436 "plPriority" => 0,
437 "plSection" => array("administration"),
438 "plCategory" => array(
439 "newConfigManagement" => array("description" => _("Config management"),
440 "objectClass" => "FAKE_OC_newConfigManagement")),
441 "plProvidedAcls"=> array()
442 ));
443 }
446 /*! \brief Acts on open requests.
447 * (This action is received from the ConfigManagementListing class.)
448 * @param Array The items ids. (May contain multiple ids)
449 * @return
450 */
451 function openEntry($ids)
452 {
453 $id = $ids[0];
454 $item = $this->dataModel->getItemById($id);
455 $this->setCurrentContainer($item['path']);
456 return;
457 }
461 /*! \brief Removes an entry from the listing.
462 */
463 function removeEntry($ids)
464 {
465 foreach($ids as $id){
466 $item = $this->dataModel->getItemById($id);
468 // Is an config item.
469 if($this->cfgItemMap[$item['type']] != 'root'){
470 $release = preg_replace("/^.*\//","", $this->getReleasePath($item['path']));
471 $path = $this->getItemPath($item['path']);
473 $rpc = $this->config->getRpcHandle();
474 $rpc->removeConfigItem($release, $path);
475 if(!$rpc->success()){
476 msg_dialog::display(_("Error"), sprintf(_("Failed to remove: %s"), $rpc->get_error()),ERROR_DIALOG);
477 return(NULL);
478 }else{
479 $this->dataModel->removeItem($item['path']);
480 }
481 }else{
482 echo $item['type']." - are not handled yet!";
483 }
484 }
485 }
487 function getUsedNamesForPath($path)
488 {
489 $item = $this->dataModel->getItemByPath($path);
490 $names = array();
491 foreach($item['children'] as $path => $data){
492 $names[] = $data['name'];
493 }
494 return($names);
495 }
498 /*! \brief Edits a selected list item.
499 */
500 function editEntry($ids)
501 {
502 $item = $this->dataModel->getItemById($ids[0]);
503 $release = preg_replace("/^.*\//","", $this->getReleasePath($item['path']));
504 $path = $this->getItemPath($item['path']);
505 $method = $this->cfgItemMap[$item['type']];
507 // Load item values on demand
508 if($this->cfgItemMap[$item['type']] != 'root'){
509 if($item['status'] == '-'){
510 $rpc = $this->config->getRpcHandle();
511 $item['values'] = $rpc->getConfigItem($release, $path);
512 $this->dataModel->setItemStatus($item['path'], 'fetched');
513 $this->dataModel->setItemValues($item['path'], $item['values']);
514 }
515 }
517 $this->TemplateEngine->load($this->itemConfig);
518 $this->TemplateEngine->setTemplate($method.".tpl");
519 $this->TemplateEngine->setValues($item['type'],$item['values']);
520 $this->listing->setDialogObject($this->TemplateEngine);
521 $this->currentObject = $item;
522 }
525 /*! \brief Initiates the creation of a new item
526 */
527 function newEntry($type)
528 {
529 // We've to add a config item
530 $this->TemplateEngine->load($this->itemConfig);
531 if($this->cfgItemMap[$type] != 'root'){
532 $method = $this->cfgItemMap[$type];
533 $this->TemplateEngine->setTemplate($method.".tpl");
534 $this->TemplateEngine->setValues($type,array());
535 $this->listing->setDialogObject($this->TemplateEngine);
536 $this->currentObject = NULL;
537 }else{
538 $this->TemplateEngine->setTemplate("root.tpl");
539 $this->TemplateEngine->setValues($type,array());
540 $this->listing->setDialogObject($this->TemplateEngine);
541 $this->currentObject = NULL;
542 }
543 }
546 /*! \brief Extracts the item-path out of a path.
547 * e.g. /debian/squeeze/test/module -> /test/module
548 */
549 function getItemPath($fullPath)
550 {
551 $fPath = $fullPath.'/';
552 while(preg_match("/\//", $fPath)){
553 $fPath = preg_replace("/\/[^\/]*$/","", $fPath);
554 $item = $this->dataModel->getItemByPath($fPath);
555 if(in_array($item['type'], array('Release', 'Distribution', 'root'))){
556 return(preg_replace("/".preg_quote($item['path'],'/')."/", "", $fullPath));
557 }
558 }
559 return(NULL);
560 }
563 /*! \brief Extracts the releaes path out of a path.
564 * e.g. /debian/squeeze/test/module -> /debian/squeeze
565 */
566 function getReleasePath($fullPath)
567 {
568 $fullPath.='/';
569 while(preg_match("/\//", $fullPath)){
570 $fullPath = preg_replace("/\/[^\/]*$/","", $fullPath);
571 $item = $this->dataModel->getItemByPath($fullPath);
572 if($item['type'] == 'Release'){
573 return($fullPath);
574 }
575 }
576 return(NULL);
577 }
580 function saveItemChanges()
581 {
582 // Save template engine modifications and validate values.
583 $this->TemplateEngine->save_object();
584 $msgs = $this->TemplateEngine->check();
586 // Get values to be saved
587 $values = array();
588 foreach($this->TemplateEngine->getWidgets() as $w){
589 $values[$w->getName()] = $w->getValue();
590 }
592 // No input error were found, now check that we do not use the same name twice.
593 if(!count($msgs)){
594 $usedNames = $this->getUsedNamesForPath($this->selectedContainer);
596 // Allow the item to keep its name.
597 if($this->currentObject != NULL && isset($this->currentObject['values']['name'])){
598 $usedNames = array_remove_entries(array($this->currentObject['values']['name']), $usedNames);
599 }
600 if(in_array($values['name'],$usedNames)){
601 $msgs[] = msgPool::duplicated(_("Name"));
602 }
603 }
605 // Display errors
606 if(count($msgs)){
607 msg_dialog::displayChecks($msgs);
608 return;
609 }
611 // Get the item type to be saved
612 $item = $this->currentObject;
613 $type = $this->TemplateEngine->getItemType();
614 if($this->cfgItemMap[$type] == 'root'){
616 // We've to create a new distribution
617 if($type == 'Distribution'){
618 $name = $values['name'];
619 $itype = $values['installation_type'];
620 $imethod = $values['installation_method'];
621 $mirror = $values['mirror'];
623 // Initiate the rpc request.
624 $rpc = $this->config->getRpcHandle();
625 $res = $rpc->createDistribution($name, $itype, array('mirror'=>$mirror, 'install_method' => $imethod));
626 if(!$rpc->success()){
627 msg_dialog::display(_("Error"), sprintf(_("Failed to save distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
628 return(NULL);
629 }else{
631 // We've successfully added the item, now add it to the tree.
632 $this->dataModel->addItem($type, $this->selectedContainer, $values['name'],array(), '-' );
634 // Finally - close the dialog.
635 $this->listing->clearDialogObject();
636 }
639 $this->listing->clearDialogObject();
641 }else{
643 echo "{$type} Cannot be saved yet";
644 $this->listing->clearDialogObject();
645 return;
646 }
647 }
649 // Save a CONFIG-ITEM object.
650 if($this->cfgItemMap[$type] != 'root'){
652 // Get paths
653 $release = preg_replace("/^.*\//","", $this->getReleasePath($this->selectedContainer));
654 $newPath = $this->selectedContainer."/".$values['name'];
655 $newItemPath = $this->getItemPath($this->selectedContainer)."/".$values['name'];
656 if($item){
657 $oldPath = $item['path'];
658 $oldItemPath = $this->getItemPath($item['path']);
659 }
661 // If this is a new item, then create it now.
662 if($item == NULL){
664 // Add the new item
665 $rpc = $this->config->getRpcHandle();
666 $res = $rpc->setConfigItem($release, $newItemPath, $type, $values);
667 if(!$rpc->success()){
668 msg_dialog::display(_("Error"), sprintf(_("Failed to load distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
669 return(NULL);
670 }else{
672 // We've successfully added the item, now add it to the tree.
673 $this->dataModel->addItem($type, $this->selectedContainer, $values['name'],array(), '-' );
675 // Finally - close the dialog.
676 $this->listing->clearDialogObject();
677 }
678 }else{
680 // Write the modifications back to the server.
681 $rpc = $this->config->getRpcHandle();
682 $res = $rpc->setConfigItem($release, $oldItemPath, $type, $values);
683 if(!$rpc->success()){
684 msg_dialog::display(_("Error"), sprintf(_("Failed to load distributions: %s"), $rpc->get_error()),ERROR_DIALOG);
685 return(NULL);
686 }else{
688 // Update the data model
689 $this->dataModel->setItemValues($oldPath, $values);
690 if($oldPath != $newPath){
691 $this->dataModel->moveItem($oldPath, $newPath);
692 }
693 $this->listing->clearDialogObject();
694 }
695 }
696 }
697 }
698 function remove_lock() {}
699 }
702 ?>