Code

Updated listing table summary
[gosa.git] / gosa-plugins / opsi / admin / opsiLicenses / class_licensePoolGeneric.inc
1 <?php
2 /*
3 * This code is part of GOsa (http://www.gosa-project.org)
4 * Copyright (C) 2003-2008 GONICUS GmbH
5 *
6 * ID: $$Id: class_opsiLicenses.inc 13520 2009-03-09 14:54:13Z hickert $$
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 */
24 class licensePoolGeneric extends plugin 
25 {
27   var $cn = "";
28   var $orig_cn = "";
29   var $description = "";
30   var $orig_dn    = "";
32   var $data       = array();
33   var $orig_data  = array();
34   var $productIds = array();
35   var $softwareIds= array();
36   var $licenses   = array();
37   var $orig_licenses   = array();
39   var $availableProductIds = array();
40   var $attributes =array("cn","description");
41   var $si = NULL;
43   var $opsiHosts = array();
45   var $licenseMap = array( 
46       "BOUNDTOHOST"=> "boundToHost",
47       "HOSTIDS"=> "usedByHost",
48       "LICENSEPOOLIDS"=> "licensePoolId",
49       "LICENSETYPE"=> "licenseModel",
50       "LICENSEKEYS"=> "licenseKey",
51       "MAXINSTALLATIONS"=> "maximumInstallations",
52       "EXPIRATIONDATE"=> "expirationDate",
53       "SOFTWARELICENSEID"=> "cn"
54       );
56   var $licenseContractMap = array( 
57       "CONCLUSIONDATE"=> "conclusionDate",
58       "NOTIFICATIONDATE"=> "notificationDate",
59       "NOTES"=> "description",
60       "PARTNER"=> "partner"
61       );
63   function __construct(&$config,$dn)
64   {
65     $this->config = $config;
66     $this->dn = $this->orig_dn = $dn;
68     // initialize gosa-si handle for opsi licenses
69     $this->si = new opsiLicenceHandler($this->config);
71     // Detect if this is a new or existings license
72     $this->is_account=TRUE;
73     if($this->dn == "new"){
74       $this->initially_was_account = FALSE;
75     }else{
76       $this->initially_was_account = TRUE;
78       // Extract pool name out of the fake dn.
79       $this->cn = $this->orig_cn = preg_replace("/^opsi:cn=([^,]*),.*$/","\\1",$dn);
80     }
82     $this->init();
83   }
85   
86   function init()
87   {
88     // Load local Boot Products 
89     $res = $this->si->get_local_products();
90     $this->availableProductIds=array();
91     if($this->si->is_error()){
92       msg_dialog::display(_("Error"),msgPool::siError($this->si->get_error()),ERROR_DIALOG);
93       $this->init_successfull = FALSE;
94       return(FALSE);
95     }
96     $this->availableProductIds=array_keys($res);
98     // Load opsi hosts
99     $res = $this->si->list_clients();
100     $this->opsiHosts=array();
101     if($this->si->is_error()){
102       msg_dialog::display(_("Error"),msgPool::siError($this->si->get_error()),ERROR_DIALOG);
103       $this->init_successfull = FALSE;
104       return(FALSE);
105     }
106     $this->opsiHosts=$res;
108     // Load Pool
109     if(!$this->initially_was_account){
110       $this->init_successfull = TRUE;
111     }else{
112       $res = $this->si->getPool($this->cn);
113       if($this->si->is_error()){    
114         $this->init_successfull = FALSE;
115         msg_dialog::display(_("Error"),msgPool::siError($this->si->get_error()),ERROR_DIALOG);
116         return(FALSE);
117       }else{
118         $this->data = $this->orig_data = $res;
119         $this->description = $this->data['description'][0];
121         // Load software IDs 
122         $this->softwareIds = array();
123         if(isset($this->data['softwareId'])){
124           for($i = 0; $i < $this->data['softwareId']['count']; $i++){
125             $this->softwareIds[] = $this->data['softwareId'][$i];
126           }
127         }
129         // Load product IDs 
130         $this->productIds = array();
131         if(isset($this->data['productId'])){
132           for($i = 0; $i < $this->data['productId']['count']; $i++){
133             $this->productIds[] = $this->data['productId'][$i];
134           }
135         }
137         // Load Licences 
138         $this->licenses = array();
139         if(isset($this->data['licenses'])){
140           for($i =0; $i< $this->data['licenses']['count']; $i++){
141             $license = $this->data['licenses'][$i];
143             // Do not parse invalid licenses
144             if(!is_array($license) || !isset($license['LICENSEPOOLIDS'])){
145               continue;
146             }
148             // Prepare Software License Key(s)
149             $upper = strtoupper($license['LICENSEPOOLIDS'][0]['VALUE']);
150             $license['LICENSEKEYS'] = $license['LICENSEKEYS'][0][$upper];
152             // Map license attributes to a useable format
153             $entry = array();
154             foreach($this->licenseMap as $source => $target){
155               $entry[$target] = "";
156               if(isset($license[$source])){
157                 if(count($license[$source]) >= 2){
158                   $entry[$target] = array();
159                   foreach($license[$source] as $sub){
160                     $entry[$target][] = $sub['VALUE'];
161                   }
162                 }elseif(isset($license[$source][0]['VALUE'])){
163                   $entry[$target] = $license[$source][0]['VALUE'];
164                 }
165               }
166             }
168             // Extract contract data
169             $lData= $license['LICENSECONTRACTDATA'][0];
170             foreach($this->licenseContractMap as $source => $target){
171               if(isset($lData[$source])){
172                 if(count($lData[$source]) >= 2){
173                   $entry[$target] = array();
174                   foreach($lData[$source] as $sub){
175                     $entry[$target][] = $sub['VALUE'];
176                   }
177                 }elseif(isset($lData[$source][0]['VALUE'])){
178                   $entry[$target] = $lData[$source][0]['VALUE'];
179                 }
180               }
181             }
183             // There are some multi value attributes - force them to be of type array.
184             foreach(array("boundToHost","usedByHost","licenseKey") as $attr){
185               if(!is_array($entry[$attr])){
186                 $entry[$attr] = array($entry[$attr]);
187               }
188             }
189             $entry['MODIFIED'] = FALSE;
190             $this->licenses[$entry['cn']] = $entry;
191           }
192         }
194         $this->orig_licenses = $this->licenses;
195         $this->init_successfull = TRUE;
196         return;
197       }
198     }
199   }
202   function execute()
203   {
204     plugin::execute();
205     // Handle initialization failures.
206     if(isset($_POST['retry_init'])) $this->init();
207     if(!$this->init_successfull){
208       $smarty = get_smarty();
209       $smarty->assign("init_successfull", $this->init_successfull);
210       return($smarty->fetch(get_template_path('licensePoolGeneric.tpl',TRUE,dirname(__FILE__))));
211     }
213     // Display dialogs! 
214     if($this->dialog instanceOf plugin){
215       $this->dialog->save_object();
216       $display = $this->dialog->execute();
217       $display.= "<hr><div class='plugin-actions'>";
218       if($this->acl_is_writeable("licenses")){
219         $display.="<button type='submit' name='license_finish'>".msgPool::okButton()."</button>";
220       }
221       $display.="<button type='submit' name='license_cancel'>".msgPool::cancelButton()."</button>";
222       $display.="</div>";
223       return($display);
224     }
226     $smarty = get_smarty();
228     // Assign ACls 
229     $plInfo = $this->plInfo();
230     foreach($plInfo['plProvidedAcls'] as $name => $desc){
231       $smarty->assign("{$name}ACL",$this->getacl($name));
232     }
233     foreach($this->attributes as $attr){
234       $smarty->assign($attr,$this->$attr);
235     }
236     $smarty->assign("init_successfull", $this->init_successfull);
237     $smarty->assign("availableProductIds", array_diff( $this->availableProductIds, $this->productIds));
238     $smarty->assign("productIds", $this->productIds);
239     $smarty->assign("softwareIds", $this->softwareIds);
240     $smarty->assign("licenses", $this->getLicenseList());
241     $smarty->assign("initially_was_account", $this->initially_was_account);
242     return($smarty->fetch(get_template_path('licensePoolGeneric.tpl',TRUE,dirname(__FILE__))));
243   }
246   // Creates a divSelectBox and fills it with license entries
247   function getLicenseList()
248   {
249     $list = new divSelectBox("test");
250     $list->setHeight(100);
251     if($this->acl_is_readable("licenses")){
252       $editlink = "<a href='?plug=".$_GET['plug']."&amp;act=edit&amp;id=%s'>%s</a>";
253       foreach($this->licenses as $i => $license){
254         $link = image("images/lists/edit.png","editLicense_{$i}");
255         if(preg_match("/w/", $this->getacl("licenses"))){
256           $link.= image("images/lists/trash.png","removeLicense_{$i}");
257         }
259         $maxInst = "";
260         if($license['maximumInstallations'] == 0){
261           $maxInst = _("unlimited");
262         }else{
263           $maxInst = $license['maximumInstallations'];
264         }
267         $map = array(
268           "VOLUME" => sprintf(_("Volume license (#%s)"), $maxInst),
269           "OEM"=>_("OEM"),
270           "RETAIL"=>_("Retail"),
271           "CONCURRENT"=>_("Concurrent"));
273         $f1 = array("string" => sprintf($editlink,$i,$license['cn']));
274         $f2 = array("string" => sprintf($editlink,$i,$map[$license['licenseModel']]));
275         $f6 = array("string" => $link, "attach" => "style='border-right: 0px; width:32px;'");
276         $list->addEntry(array($f1,$f2,$f6));
277       }
278     }
279     return($list->DrawList());
280   }
281  
282  
283   /* Save HTML inputs
284    */
285   function save_object()
286   {
287     // Allow license edit via href links
288     if(isset($_GET['act']) && $_GET['act'] == 'edit' && isset($_GET['id'])){
289       $id = trim($_GET['id']);
290       if(isset($this->licenses[$id])){
291         $this->dialog = new licenseGeneric($this->config,$this->dn,$this->licenses[$id], $this->opsiHosts);
292         $this->dialog->set_acl_category('opsi');
293         $this->dialog->set_acl_base($this->config->current['BASE']);
294       }
295     }
296   
297     // Close license edit dialogs.
298     if($this->dialog instanceOf plugin && isset($_POST['license_cancel'])){
299       $this->dialog = NULL;
300       return;
301     }
303     // Save license modifications
304     if($this->dialog instanceOf plugin && isset($_POST['license_finish'])){
305       $this->dialog->save_object();
306       $msgs = $this->dialog->check();
307       if(count($msgs)){
308         msg_dialog::displayChecks($msgs);
309       }else{
310         $attrs = $this->dialog->save();
311         $attrs['MODIFIED'] = TRUE;
312         $this->licenses[$attrs['cn']] = $attrs;
313         $this->dialog = NULL;
314       }
315       return;
316     }
318     if(isset($_POST['opsiLicensePoolPosted'])){
319       plugin::save_object();  
321       // Restore license cn, to avoid creating a copy...
322       if($this->initially_was_account) $this->cn = $this->orig_cn;
324       // We've to add prodcuts here 
325       if(preg_match("/w/",$this->getacl("productIds"))){
326         if(isset($_POST['availableProduct']) && isset($_POST['addProduct'])){
327           $pro = get_post('availableProduct');
328           if(isset($this->availableProductIds[$pro]) && !in_array($this->availableProductIds[$pro], $this->productIds)){
329             $this->productIds[] =$this->availableProductIds[$pro];
330           }
331         }
332       }
334       // We've to remove products here
335       if(preg_match("/w/",$this->getacl("productIds"))){
336         if(isset($_POST['productIds']) && isset($_POST['removeProduct'])){
337           foreach($_POST['productIds'] as $key){
338             if(isset($this->productIds[$key])){
339               unset($this->productIds[$key]);
340             }
341           }
342         }
343       }
345       // We've to add software here 
346       if(preg_match("/w/",$this->getacl("windowsSoftwareIds"))){
347         if(isset($_POST['newSoftwareId']) && isset($_POST['addSoftware'])){
348           $soft = trim(get_post('newSoftwareId'));
349           if(!empty($soft) && !in_array($soft, $this->softwareIds)){
350             $this->softwareIds[] = $soft;
351           }
352         }
353       }
355       // We've to remove software Ids here
356       if(preg_match("/w/",$this->getacl("windowsSoftwareIds"))){
357         if(isset($_POST['softwareIds']) && isset($_POST['removeSoftware'])){
358           foreach($_POST['softwareIds'] as $key){
359             if(isset($this->softwareIds[$key])){
360               unset($this->softwareIds[$key]);
361             }
362           }
363         }
364       }
366       // We've to create a new license
367       if(preg_match("/w/",$this->getacl("licenses"))){
368         if(isset($_POST['addLicense'])){
369           $this->dialog = new licenseGeneric($this->config,$this->dn,array(), $this->opsiHosts);
370           $this->dialog->set_acl_category('opsi');
371           $this->dialog->set_acl_base($this->config->current['BASE']);
372         }
373       }
375       // Search post for image button clicks.
376       if(preg_match("/r/",$this->getacl("licenses"))){
377         foreach($_POST as $name => $value){
378           if(preg_match("/^editLicense_/",$name)){
379             $id = preg_replace("/^editLicense_(.*)$/","\\1",$name);
380             if(isset($this->licenses[$id])){
381               $this->dialog = new licenseGeneric($this->config,$this->dn,$this->licenses[$id], $this->opsiHosts);
382               $this->dialog->set_acl_category('opsi');
383               $this->dialog->set_acl_base($this->config->current['BASE']);
384             }
385             break;
386           }
387           if(preg_match("/^removeLicense_/",$name)){
388             $id = preg_replace("/^removeLicense_(.*)$/","\\1",$name);
389             if(isset($this->licenses[$id])){
390               unset($this->licenses[$id]);
391             }
392             break;
393           }
394         }
395       }
396     }
397   }  
400   /* Check user input and return a list of 'invalid input' messages.
401    */
402   function check()
403   {
404     $message = plugin::check();
405     return($message);
406   }
407   
409  
410   /* Removes the object from the opsi database
411    */ 
412   function remove_from_parent()
413   {
414     $this->si->deletePool($this->orig_cn);
415     if($this->si->is_error()){
416       msg_dialog::display(_("Error"),msgPool::siError($this->si->get_error()),ERROR_DIALOG);
417     }else{
419       // Trigger remove signal
420       $this->handle_post_events("remove");
421     }
423     new log("remove","users/".get_class($this),$this->dn,array_keys($this->attrs),$this->si->get_error());
424   }
427   /* Saves object modifications
428    */  
429   function save()
430   {
431     plugin::save();
433     // Send modify/add events
434     $mode = "modify";
435     if($this->orig_dn == "new"){
436       $mode = "add";
437     }
439     // Create or update the pool
440     $this->si->createPool($this->cn, $this->description,$this->productIds,$this->softwareIds);#
441     if($this->si->is_error()){
442       msg_dialog::display(_("Error"),msgPool::siError($this->si->get_error()),ERROR_DIALOG);
443     }else{
444       $this->handle_post_events($mode);
445     }
447     // Create, remove or update licenses
448     $add    = array_diff_assoc($this->licenses,$this->orig_licenses);
449     $del    = array_diff_assoc($this->orig_licenses,$this->licenses);
450     $update = array_intersect($this->licenses,$this->orig_licenses);
452     // Remove licenses 
453     foreach($del as $license){
454       $this->si->removeLicenseFromPool($this->cn, $license['cn']);
455       if($this->si->is_error()){
456         msg_dialog::display(_("Error"),msgPool::siError($this->si->get_error()),ERROR_DIALOG);
457       }
458     }
459     
460     // Add licenses 
461     foreach($add as $license){
462       $this->si->createLicense(
463         $this->cn,  // Pool id
464         $license['cn'], 
465         $license['licenseKey'][0],
466         $license['licenseModel'],
467         $license['partner'],
468         $license['conclusionDate'],
469         $license['notificationDate'],
470         $license['description'],
471         $license['cn'],
472         $license['maximumInstallations'],
473         $license['boundToHost'],
474         $license['expirationDate']);
476       if($this->si->is_error()){
477         msg_dialog::display(_("Error"),msgPool::siError($this->si->get_error()),ERROR_DIALOG);
478       }
479     }
481     // Update licenses
482     foreach($update as $license){
484       // Do not save untouched licenses
485       if(!$license['MODIFIED']){
486         continue;
487       }
489       $this->si->createLicense(
490         $this->cn,  // Pool id
491         $license['cn'],
492         $license['licenseKey'][0],
493         $license['licenseModel'],
494         $license['partner'],
495         $license['conclusionDate'],
496         $license['notificationDate'],
497         $license['description'],
498         $license['cn'],
499         $license['maximumInstallations'],
500         $license['boundToHost'],
501         $license['expirationDate']);
503       if($this->si->is_error()){
504         msg_dialog::display(_("Error"),msgPool::siError($this->si->get_error()),ERROR_DIALOG);
505       }
506     }
508     // Log action
509     if($mode == "modify"){
510       new log("modify","users/".get_class($this),$this->dn,array_keys($this->attrs),$this->si->get_error());
511     }else{
512       new log("create","users/".get_class($this),$this->dn,array_keys($this->attrs),$this->si->get_error());
513     }
515     return 0;
516   }
517  
518   static function plInfo()
519   {
520     return (array(
521           "plShortName"   => _("Pool generic"),
522           "plDescription" => _("License pool generic"),
523           "plSelfModify"  => FALSE,
524           "plDepends"     => array(),
525           "plPriority"    => 7,
526           "plSection"     => array("administration"),
527           "plCategory"    => array("opsi"),
528           "plProvidedAcls"=> array(
529             "cn"                => _("Name"),
530             "description" => _("Description"),
531             "productIds"  => _("Applications"),
532             "windowsSoftwareIds"  => _("Windows software IDs"),
533             "licenses"  => _("Licenses"))
534           ));
535   }
539 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
540 ?>