Code

Added last check, ..... ....
[gosa.git] / plugins / admin / systems / class_glpiPrinterAccount.inc
1 <?php
3 class glpiPrinterAccount extends plugin
4 {
5   /* CLI vars */
6   var $cli_summary= "Manage server basic objects";
7   var $cli_description= "Some longer text\nfor help";
8   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
10   /* attribute list for save action */
11   var $ignore_account= FALSE;
12   var $attributes= array("ID","name","contact","ramSize","flags_serial","flags_par","flags_usb",
13       "tech_num","comments","date_mod","location","domain","network","contact_num","serial","otherserial",
14       "type","is_template","FK_glpi_enterprise","deleted");
16   var $ID                 ;       // Is set if this entry is edited 
17   var $name               = "";    // This should be the dn of this entry 
18   var $FK_glpi_enterprise = 0;     // Manufacturer id
19   var $tech_num           = "";    // Technical responsible person
20   var $contact_num        = "";    // Contact person
21   
22   var $comments           = "";    // Comment
23   
24   var $type               = 0;     // printer type id
25   var $serial             = "";   
26   var $otherserial        = "";  
27   var $ramSize            = 0;
28   var $flags_serial       = false;
29   var $flags_par          = false;
30   var $flags_usb          = false;
32   var $date_mod           = "";    // Modification timestamp
33   
34   var $location           = 0;     // Not used yet
35   var $domain             = 0;     // ? Set to 0
36   var $network            = 0;     // ? Set to 0 
38   var $is_template        = 0;     // Used as template ?
39   var $contact            = "";    // Empty
40   var $deleted            = "N";   // Deleted entries should have this set to Y
42   var $editManufacturer   = false;
44   /* Not necessary, cause we use mysql databse */
45   var $objectclasses= array("whatever");
47   /* Used to remember if this was an account (simply: is this an edited entry) */
48   var $initially_was_account = false;
50   /* Remember current dialog */
51   var $edit_type            = false;
52   var $edit_os              = false;
54   var $data;
55   var $handle = NULL;               // Glpi class handle used to query database
57   var $cur_dialog = NULL;           // This contains the sub dialog handle
59   var $orig_dn;                     // To check if dn, has changed 
60   var $ui;                          // Some GOsa specific user informations 
61   
62   var $usedDevices      = array();  // Which devices are currently selected 
63   var $usedAttachments  = array();  // Used Attachments 
64   var $usedCartridges   = array();  // Used Cartridges
66   /* Contructor 
67      Sets default values and checks if we already have an existing glpi account
68    */
69   function glpiPrinterAccount ($config, $dn= NULL)
70   {
71     plugin::plugin ($config, $dn);
72     $this->ui= get_userinfo();
74     $this->is_account = false;
76     /* Abort class construction, if no db is defined */
77     if(!isset($this->config->data['SERVERS']['GLPI'])){
78       return;
79     }
81     // Get informations about databse connection
82     $this->data = $this->config->data['SERVERS']['GLPI'];
84     // Abort if mysql extension is missing 
85     if(!is_callable("mysql_connect")){
86       return;
87     }
89     // Create handle of glpi class, and check if database connection is established 
90     $this->handle = new glpiDB($this->data['SERVER'],$this->data['LOGIN'],$this->data['PASSWORD'],$this->data['DB']);
92     if(!$this->handle->is_connected){
93       return;
94     } 
96     // If this dn is already used in database, then get all informations for this entry 
97     if($this->handle->is_printer_account($this->dn)){
98       $this->is_account = true;
99       $tmp = ($this->handle->getPrinterInformations($this->dn));
101       foreach(array("tech_num","FK_glpi_enterprise","type","comments","contact_num","flags_serial","flags_par","flags_usb","ramSize") as $attr){
102         $this->$attr = $tmp[0][$attr];
103       }
104       
105       $atts = $this->handle->getAssignPrinterAttachments($tmp[0]['ID']);
106       foreach($atts as $attachment){
107         $this->usedAttachments[$attachment['FK_doc']]=$attachment['FK_doc']; 
108       }
110       $cart= $this->handle->getUsedCartridges($tmp[0]['ID']);
111       foreach($cart as $key => $cartridge){
112         $this->usedCartridges[$key]=$cartridge; 
113         $this->usedCartridges[$key]['status']="exists"; 
114       }
117     }else{
118       $this->is_account = false;
119     }
121     /* set defaults */
122     $this->name                 = $this->dn;
123     $this->orig_dn              = $this->dn;
124     $this->initially_was_account = $this->is_account;
125   }
127   function execute()
128   {
129     /* Call parent execute */
130     plugin::execute();
132     /* Fill templating stuff */
133     $smarty= get_smarty();
134     $display= "";
136     $smarty->assign("CartridgesACL",chkacl($this->acl,"Cartridges"));
138     /*  Assign smarty defaults 
139         To avoid undefined indexes, if there is an error with the glpi db
140      */ 
141     foreach(array("PrinterTypeKeys","PrinterTypes","ManufacturerKeys","Manufacturers","Attachments","AttachmentKeys") as $attr){
142       $smarty->assign($attr,array());
143       $smarty->assign($attr."ACL"," disabled ");
144     }
145     foreach(array("type","FK_glpi_enterprise","tech_num","contact_num","comments","flags_serial","flags_par","flags_usb") as $attr){
146       $smarty->assign($attr,"");
147       $smarty->assign($attr."ACL"," disabled ");
148     }
150     /* Check if there is a glpi database server defined 
151       */
152     if(!isset($this->config->data['SERVERS']['GLPI'])){
153       print_red(_("There is no server with valid glpi database service."));
154       return($smarty->fetch(get_template_path('glpiPrinter.tpl', TRUE)));
155     }
157     $this->data = $this->config->data['SERVERS']['GLPI'];
159     /* Check if we can call mysql_connect 
160        If we can't, there is no the mysql-php extension
161      */
162     if(!is_callable("mysql_connect")){
163       print_red(_("Can't connect to glpi database, the php-mysql extension is missing."));
164       return($smarty->fetch(get_template_path('glpiPrinter.tpl', TRUE)));
165     }
167     $this->handle = new glpiDB($this->data['SERVER'],$this->data['LOGIN'],$this->data['PASSWORD'],$this->data['DB']);
169     /*  If handle == false, abort
170         Seems that the server, username and or password is wrong
171      */
172     if(!$this->handle->is_connected){
173       print_red(_("Can't connect to glpi database, check configuration twice."));
174       return($smarty->fetch(get_template_path('glpiPrinter.tpl', TRUE)));
175     } 
177     /*  All checks are ok
178         Lets handle Posts, templates etc below ...
179      */
180     
181     $users = $this->handle->getUsers();
182     $ldap= $this->config->get_ldap_link();
184     
185     /*  ##########################################################################
186      *  Some tab management   
187      */
189     /* Do we need to flip is_account state? */
190     if (isset($_POST['modify_state'])){
191       $this->is_account= !$this->is_account;
192     }
194     /* Show tab dialog headers */
195     if ($this->is_account){
196       $display= $this->show_header(_("Remove inventory service"),
197           _("This server has inventory features enabled. You can disable them by clicking below."));
198     } else {
199       $display= $this->show_header(_("Add inventory service"),
200           _("This server has inventory features disabled. You can enable them by clicking below."));
201       return ($display);
202     }
204     
205     /*  ##########################################################################
206      *  Printer type management 
207      *  Dialog 
208      */
210     /* Printer type management
211      */
212     if(isset($_POST['edit_type'])){
213       $this->dialog = true;
214       $this->edit_type=true;
215     }
217     /* This closes the printer type editing dialog
218      */
219     if(isset($_POST['close_edit_type'])){
220       $this->edit_type=false;
221       $this->dialog = false;
222     }
224     /* This appends a new printer to our sytem types
225      */
226     if((isset($_POST['add_type']))&&(!empty($_POST['type_string']))){
227     
228       $tmp = $this->handle->getPrinterTypes();
229       $allok = true;
230       foreach($tmp as $id => $name){
231         if(trim($name) == trim($_POST['type_string'])){
232           $allok = false;
233         }
234       }
235       if($allok){
236         $this->handle->addPrinterType($_POST['type_string']);  
237       }else{
238         print_red(sprintf(_("Can't rename given printer type to '%s', because this type name already exists."),$_POST['type_string']));
239       }
240     }
242     /* Remove selected type from our printer types list
243      */
244     if((isset($_POST['del_type']))&&(!empty($_POST['select_type']))){
245       $tmp = $this->handle->is_printerTypeUsed($_POST['select_type']);
246       if(count($tmp)){
247         $str = "";
248         foreach($tmp as $id => $name){
249           $str .= $name.", ";
250         }
251         $str = preg_replace("/, $/","",$str); 
252         print_red(sprintf(_("Can't delete printer type, it is still in use by '%s'."),$str));
253       }else{
254         $this->handle->removePrinterType($_POST['select_type']);  
255       }
256     }
258     /* Rename selected printer type to given string
259      */
260     if((isset($_POST['rename_type']))&&(!empty($_POST['select_type']))&&(!empty($_POST['type_string']))){
261       $tmp = $this->handle->getPrinterTypes();
262       $allok = true;
263       foreach($tmp as $id => $name){
264         if(trim($name) == trim($_POST['type_string'])){
265           $allok = false;
266         }
267       }
268       if($allok){
269         $this->handle->updatePrinterType($_POST['type_string'],$_POST['select_type']);
270       }else{
271         print_red(sprintf(_("Can't rename given printer type to '%s', because this type name already exists."),$_POST['type_string']));
272       }
273     }
275     /* Someone wants to edit the printer types ... 
276        So, lets open a new dialog which provides some buttons to edit the types
277      */
278     if($this->edit_type){
279       $smarty->assign("PrinterTypes",            $this->handle->getPrinterTypes());
280       $smarty->assign("PrinterTypeKeys",         array_flip($this->handle->getPrinterTypes()));
281       $display= $smarty->fetch(get_template_path('glpi_edit_printer_type.tpl', TRUE));
282       return($display);
283     }
286     /*  ##########################################################################
287      *  Edit manufacturers 
288      *  Dialog 
289      */
291     /* Open dialog which allows to edit the manufacturers
292      */
293     if(isset($_POST['edit_manufacturer'])){
294       $this->cur_dialog = new glpiManufacturer($this->config,$this->dn);
295       $this->dialog = true;
296       $this->editManufacturer =true;
297     }
299     /* Close manufacturer editing dialog
300      */
301     if((isset($_POST['close_edit_manufacturer']))&&($this->editManufacturer)){
302       $this->dialog = false;
303       $this->cur_dialog = false;
304       $this->editManufacturer=false;
305     }
308     /*  ##########################################################################
309      *  Technical responsible person
310      *  Contact person 
311      *  Dialog 
312      */
314     /* Show dialog to select a new contact person
315      * Select a contact person
316      */
317     if(isset($_POST['SelectContactPerson'])){
318       $this->addUser = "contact";
319       $this->cur_dialog= new glpiSelectUser($this->config,$this->dn,"user_tech_num");
320     }
322     /* Selecte technical responsible person
323      */
324     if(isset($_POST['SelectTechPerson'])){
325       $this->addUser ="tech";
326       $this->cur_dialog= new glpiSelectUser($this->config,$this->dn,"user_tech_num");
327     }
329     /* Abort user selection
330      */
331     $smarty->assign("AbortSelectUser","SelectUserCancel");
332     if(isset($_POST['SelectUserCancel'])){
333       $this->dialog = false;
334       $this->addUser ="";
335       $this->cur_dialog = false;
336     }
338     /* Technical responsible/contact person selected */
339     if(isset($_GET['act'])&&($_GET['act']=="user_tech_num")){
341       /* Get posted id */
342       $id = base64_decode($_GET['id']);
344       /* Check if user is already created in glpi database */
345       if(!in_array($id,$users)){
347         /* If this user doesn't exists in glpi db, we must create him */
348         $atr = $ldap->fetch($ldap->cat($id));
349         $tmp = array();
350         $use = array( "cn"              =>"name",
351             "mail"            =>"email",
352             "telephoneNumber" =>"phone");
354         /* Create array */
355         foreach($use as $gosa => $glpi){
356           if(isset($atr[$gosa])){
357             $tmp[$glpi]= $atr[$gosa][0];
358           }
359         }
361         /* Add this user */
362         $this->handle->addUser($tmp,$id);
363       }
365       /* Re-read users */
366       $users = ($this->handle->getUsers());
368       /* Get user */
369       $tmp = array_flip($users);
370       $id=$tmp[$id];
372       /* Use user id, close dialog */
373       if($this->addUser == "tech"){
374         $this->tech_num = $id;
375       }else{
376         $this->contact_num = $id;
377       }
378       $this->cur_dialog   = false;
379       $this->dialog= false;
380     }
383     /*  ##########################################################################
384      *  Handle attachments 
385      */
386     
387     /* Attachment pool was closed with use
388      */
389     if(isset($_POST['UseAttachment'])){
390       if(count($this->cur_dialog->check())){
391         foreach($this->cur_dialog->check() as $msg){
392           print_red($msg);
393         }
394       }else{
395         $this->cur_dialog->save_object();
396         $this->usedAttachments = $this->cur_dialog->save();
397         $this->cur_dialog = false;
398         $this->edit_type = false; 
399       }
400     }
401    
402     /* Attachment pool was closed with abort
403      */ 
404     if(isset($_POST['AbortAttachment'])){
405       $this->cur_dialog = false;
406       $this->edit_type = false; 
407     }
409     /* Open Attachment pool to add/edit Attachments
410      */
411     if(isset($_POST['AddAttachment'])){
412       $this->cur_dialog = new glpiAttachmentPool($this->config,$this->dn,$this->usedAttachments);
413       $this->dialog = true;
414     }
415     
416     /* Remove Attachment from this tab 
417      */
418     $once = true;
419     foreach($_POST as $name => $value){
420       if((preg_match("/^delAttachment_/",$name))&&($once)){
421         $once= false;
422         $name = preg_replace("/^delAttachment_/","",$name);
423         $entry = preg_replace("/_.*$/","",$name);
424         if(isset($this->usedAttachments[$entry])){
425           unset($this->usedAttachments[$entry]);
426         }
427       }
428     }
429     if((isset($_POST['RemoveAttachment']))&&(isset($_POST['Attachments']))){
430       if(isset($this->usedAttachments[$_POST['Attachments']])){
431         unset($this->usedAttachments[$_POST['Attachments']]);
432       }
433     }
435     /*  ##########################################################################
436      *  Printer Cartridge handling 
437      */
439     /* Abort cartridge select dialog
440      */
441     if(isset($_POST['SelectCartridgeCancel'])){
442       $this->cur_dialog = false;
443       $this->edit_type = false; 
444     }
446     /* Get selected cartridges and add them to our list 
447      */ 
448     if(isset($_POST['SelectCartridgeSave'])){
449       $this->cur_dialog->save_object();
450       $carts = $this->cur_dialog->save();
451       foreach($carts as $cart){
452         $cart['status'] = "new";
453         $this->usedCartridges[] = $cart;
454       }
455       $this->cur_dialog = false;
456       $this->edit_type = false; 
457     }
459     /* Remove cartridge  
460      */
461     if((isset($_POST['RemoveCartridge']))&&(isset($_POST['Cartridges']))){
463       foreach($_POST['Cartridges'] as $cartID){
465         if(isset($this->usedCartridges[$cartID])){
466           if($this->usedCartridges[$cartID]['status'] == "exists"){
467             $this->usedCartridges[$cartID]['status'] = "deleted";
468           }else{
469             unset($this->usedCartridges[$cartID]);
470           }
471         }
472       }
473     }
475     /* Open Attachment pool to add/edit Attachments
476      */
477     if(isset($_POST['AddCartridge'])){
478       $this->cur_dialog = new glpiPrinterCartridges($this->config,$this->dn,$this->type);
479       $this->dialog = true;
480     }
483     /*  ##########################################################################
484      *  Draw Dialogs
485      */
486     /* if( cur_dialog != false || cur_dialog != NULL) 
487      * There is a dialog which wants to be displayed 
488      */
489     if($this->cur_dialog){
490       $this->cur_dialog->save_object();
491       $this->dialog=true;
492       $this->cur_dialog->parent = &$this;
493       return($this->cur_dialog->execute());
494     }else{
495       $this->dialog= false;
496     }
499     /*  ##########################################################################
500      *  Assign listbox / checkbox .... values to smarty  
501      */
502     /* Assign smarty defaults */ 
503     foreach(array("PrinterTypes","PrinterTypeKeys","Manufacturers","TechnicalResponsibles","Attachments") as $attr){
504       $smarty->assign($attr,array());
505       $smarty->assign($attr."ACL",chkacl($this->acl,$attr));
506     }
508     /* Assign some vars to smarty 
509      */
510     foreach(array("type","FK_glpi_enterprise","tech_num","contact_num","flags_serial","flags_par","flags_usb") as $attr){
511       $smarty->assign($attr,"");
512       $smarty->assign($attr."ACL",chkacl($this->acl,$attr));
513     }
516     /* Assign ACLs to smarty*/
517     foreach($this->attributes as $attr){
518       $smarty->assign($attr."ACL",chkacl($this->acl,$attr));
519     }
521     $smarty->assign("comments",               $this->comments);
522     $smarty->assign("flags_serial",            $this->flags_serial);
523     $smarty->assign("flags_par",               $this->flags_par);
524     $smarty->assign("flags_usb",               $this->flags_usb);
526     /* Assign system types 
527      */
528     $smarty->assign("PrinterTypes",           $this->handle->getPrinterTypes());
529     $smarty->assign("PrinterTypeKeys",        array_flip($this->handle->getPrinterTypes()));
530     $smarty->assign("type",                   $this->type);
532     /* Append manufacturers
533      */
534     $smarty->assign("ManufacturerKeys",       array_flip($this->handle->getEnterprises()));
535     $smarty->assign("Manufacturers",          $this->handle->getEnterprises());
536     $smarty->assign("FK_glpi_enterprise",     $this->FK_glpi_enterprise);
538     /* Assign used Attachments
539     */
541     $divlist = new divSelectBox("glpiAttachmentsList");
542     $divlist-> SetHeight(120);
543     $atts = $this->getUsedAttachments(true);
544     $downlink = "<a href='get_attachment.php?id=%s' target='_blank'>%s</a>";
545     $del_link = "<input type='image' src='images/edittrash.png' name='delAttachment_%s'>";
546     foreach($atts as $id => $attachment){
547       $divlist->AddEntry
548           (
549         array(
550             array("string"=>$attachment['name']),
551             array("string"=>$attachment['mime']),
552             array("string"=>sprintf($downlink,$id,$attachment['filename'])),
553             array("string"=>sprintf($del_link,$attachment['ID']),"attach"=>"style='border-right:0px;'"),
554              )
555           );
556     }
558     $smarty->assign("AttachmentsDiv"          ,$divlist->DrawList());
559     $smarty->assign("Attachments",            $this->getUsedAttachments());
560     $smarty->assign("AttachmentKeys",         array_flip($this->getUsedAttachments()));
562     /* Assign Cartridges 
563      */
564     $smarty->assign("Cartridges",            $this->getUsedCartridges());
565     $smarty->assign("CartridgeKeys",         $this->getUsedCartridges(true));
567     /*  ##########################################################################
568      *  Assign contact and technical responsible person 
569      */
570     if(isset($users[$this->contact_num])){
571       $tr = $ldap->fetch($ldap->cat($users[$this->contact_num]));
572       $str = "";
573       if(isset($tr['givenName'][0])){   $str .= $tr['givenName'][0]." ";      }
574       if(isset($tr['sn'][0])) {         $str .= $tr['sn'][0]." ";             }
575       if(isset($tr['uid'][0])){         $str .= "[".$tr['uid'][0]."]";        }
576       $smarty->assign("contact_num",               $str);
577     }else{
578       $smarty->assign("contact_num",               _("N/A"));
579     }
581     /* Handle tech person 
582        Assign name ... to smarty, if set
583      */ 
584     if(isset($users[$this->tech_num])){
585       $tr = $ldap->fetch($ldap->cat($users[$this->tech_num]));
586       $str = "";
587       if(isset($tr['givenName'][0])){   $str .= $tr['givenName'][0]." ";      }
588       if(isset($tr['sn'][0])) {         $str .= $tr['sn'][0]." ";             }
589       if(isset($tr['uid'][0])){         $str .= "[".$tr['uid'][0]."]";        }
590       $smarty->assign("tech_num",               $str);
591     }else{
592       $smarty->assign("tech_num",               _("N/A"));
593     }
595     /* If theres a cartridge selected, you can't change the printer type.
596      */ 
597     $disp = true;
599     foreach($this->usedCartridges as $cart){
600       if($cart['status'] != "deleted"){
601         $disp = false;
602       }
603     }
604     if($disp==false){
605       $smarty->assign("typeACL","disabled");
606     }
608     $display.= $smarty->fetch(get_template_path('glpiPrinter.tpl', TRUE));
609     return($display);
610   }
612   function remove_from_parent()
613   {
614     $this->handle = new glpiDB($this->data['SERVER'],$this->data['LOGIN'],$this->data['PASSWORD'],$this->data['DB']);
615     if($this->initially_was_account){
616       $this->handle->removePrinterInformations($this->dn); 
617     }
618   }
621   /* Save data to object */
622   function save_object()
623   {
624     if(isset($_POST['glpiPrinterFlagsPosted'])){
625       plugin::save_object();
626       foreach($this->attributes as $attrs){
627         if(isset($_POST[$attrs])){
628           $this->$attrs = $_POST[$attrs];
629         }
630       }
632       foreach(array("flags_serial","flags_par","flags_usb") as $checkboxes){
633         if(isset($_POST[$checkboxes])){
634           $this->$checkboxes = 1;
635         }else{
636           $this->$checkboxes = 0;
637         }
638       }
639     }
641   }
644   /* Check supplied data */
645   function check()
646   {
647     $message= array();
649     //    if($this->TechnicalResponsible == ""){
650     //      $message[] = _("Please select a technical responsible person for this entry.");
651     //    }
653     return ($message);
654   }
656   /* Save to LDAP */
657   function save()
658   {
659     if($this->is_account){
660         $attrs = array();
661       $this->date_mod = date("Y-m-d H:i:s");
662       foreach($this->attributes as $attr){
663         $attrs[$attr] = $this->$attr;
664       }
665       $attrs['name'] = $this->dn;
666       unset($attrs['ID']);
667       $this->handle = new glpiDB($this->data['SERVER'],$this->data['LOGIN'],$this->data['PASSWORD'],$this->data['DB']);
668       if($this->initially_was_account&&$this->is_account){
669         $this->handle->updatePrinterInformations($attrs,$this->dn);
670       }elseif($this->is_account){
671         $this->handle->addPrinterInformations($attrs,$this->dn);
672       }
673       $tmp = $this->handle->getPrinterInformations($this->dn);
674       $this->handle->addAttachmentsToPrinter($this->usedAttachments,$tmp[0]['ID']);
676       foreach($this->usedCartridges as $cart){
677         if($cart['status'] == "deleted"){
678           $this->handle->removeCartridgeFromPrinter($cart['ID']);
679         }elseif($cart['status'] == "new"){
680           $this->handle->addCartridgeFromPrinter($tmp[0]['ID'],$cart['type_ID']);
681         }
682       }
683     }
684   }
686   /* Return used attachments */
687   function getUsedAttachments($divlist = false)
688   {
689     $atts =$this->handle->getAttachments();
690     $ret = array();
691     foreach($atts as $entry){
692       if(in_array($entry['ID'],$this->usedAttachments)){
693         if($divlist){
694           $ret[$entry['ID']] = $entry;
695         }else{
696           $cm ="";
697           if(isset($entry['comment'])){
698             $cm=" [".$entry['comment']."]";
699           }
700           if(isset($entry['mime'])){
701             $cm.=" -".$entry['mime']."";
702           }
704           $ret[$entry['ID']]= $entry['name'].$cm;
705         }
706       }
707     }
708     return($ret);
709   }
711   function getUsedCartridges($flip = false)
712   {
713     $ret = array();
714     foreach($this->usedCartridges as $key => $value){
715       if($value['status'] == "deleted") continue;
716       if($flip){
717         $ret[$key] = $key;    
718       }else{
719         $ret[$key] = $value['name']." [".$value['type_name']."] "._("since")." :".$value['date_use'];
720       }
721     }
722     return($ret);
723   }  
727 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
728 ?>