cartridge.class.php
Go to the documentation of this file.
00001 <?php
00002 /*
00003  * @version $Id: cartridge.class.php 21364 2013-07-19 15:38:35Z yllen $
00004  -------------------------------------------------------------------------
00005  GLPI - Gestionnaire Libre de Parc Informatique
00006  Copyright (C) 2003-2013 by the INDEPNET Development Team.
00007 
00008  http://indepnet.net/   http://glpi-project.org
00009  -------------------------------------------------------------------------
00010 
00011  LICENSE
00012 
00013  This file is part of GLPI.
00014 
00015  GLPI is free software; you can redistribute it and/or modify
00016  it under the terms of the GNU General Public License as published by
00017  the Free Software Foundation; either version 2 of the License, or
00018  (at your option) any later version.
00019 
00020  GLPI is distributed in the hope that it will be useful,
00021  but WITHOUT ANY WARRANTY; without even the implied warranty of
00022  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00023  GNU General Public License for more details.
00024 
00025  You should have received a copy of the GNU General Public License
00026  along with GLPI. If not, see <http://www.gnu.org/licenses/>.
00027  --------------------------------------------------------------------------
00028  */
00029 
00030 /** @file
00031 * @brief
00032 */
00033 
00034 
00035 if (!defined('GLPI_ROOT')) {
00036    die("Sorry. You can't access directly to this file");
00037 }
00038 
00039 //!  Cartridge Class
00040 /**
00041  * This class is used to manage the cartridges.
00042  * @see CartridgeItem
00043  * @author Julien Dombre
00044  **/
00045 class Cartridge extends CommonDBChild {
00046 
00047    // From CommonDBTM
00048    static protected $forward_entity_to = array('Infocom');
00049    public $dohistory                   = true;
00050 
00051    // From CommonDBChild
00052    static public $itemtype             = 'CartridgeItem';
00053    static public $items_id             = 'cartridgeitems_id';
00054 
00055 
00056 
00057    /**
00058     * @since version 0.84
00059    **/
00060    function getForbiddenStandardMassiveAction() {
00061 
00062       $forbidden   = parent::getForbiddenStandardMassiveAction();
00063       $forbidden[] = 'update';
00064       return $forbidden;
00065    }
00066 
00067 
00068    function showSpecificMassiveActionsParameters($input=array()) {
00069 
00070       switch ($input['action']) {
00071          case "updatepages" :
00072             if (!isset($input['maxpages'])) {
00073                $input['maxpages'] = '';
00074             }
00075             echo "<input type='text' name='pages' value=\"".$input['maxpages']."\" size='6'>";
00076             echo "<br><br><input type='submit' name='massiveaction' class='submit' value='".
00077                            _sx('button', 'Update')."'>";
00078             return true;
00079       }
00080       return false;
00081    }
00082 
00083 
00084    static function getNameField() {
00085       return 'id';
00086    }
00087 
00088    static function getTypeName($nb=0) {
00089       return _n('Cartridge', 'Cartridges', $nb);
00090    }
00091 
00092 
00093    function prepareInputForAdd($input) {
00094 
00095       $item = static::getItemFromArray(static::$itemtype, static::$items_id, $input);
00096       if ($item === false) {
00097          return false;
00098       }
00099 
00100       return array("cartridgeitems_id" => $item->fields["id"],
00101                    "entities_id"       => $item->getEntityID(),
00102                    "date_in"           => date("Y-m-d"));
00103    }
00104 
00105 
00106    function post_addItem() {
00107 
00108       Infocom::cloneItem('CartridgeItem', $this->fields["cartridgeitems_id"], $this->fields['id'],
00109                          $this->getType());
00110       parent::post_addItem();
00111    }
00112 
00113 
00114    function post_updateItem($history=1) {
00115 
00116       if (in_array('pages', $this->updates)) {
00117          $printer = new Printer();
00118          if ($printer->getFromDB($this->fields['printers_id'])
00119              && (($this->fields['pages'] > $printer->getField('last_pages_counter'))
00120                  || ($this->oldvalues['pages'] == $printer->getField('last_pages_counter')))) {
00121 
00122             $printer->update(array('id'                 => $printer->getID(),
00123                                    'last_pages_counter' => $this->fields['pages'] ));
00124          }
00125       }
00126       parent::post_updateItem($history);
00127    }
00128 
00129    /**
00130     * @since version 0.84
00131     *
00132     * @see CommonDBTM::getPreAdditionalInfosForName
00133    **/
00134    function getPreAdditionalInfosForName() {
00135 
00136       $ci = new CartridgeItem();
00137       if ($ci->getFromDB($this->fields['cartridgeitems_id'])) {
00138          return $ci->getName();
00139       }
00140       return '';
00141    }
00142 
00143    /**
00144     * @since version 0.84
00145     *
00146     * @see CommonDBTM::doSpecificMassiveActions()
00147    **/
00148    function doSpecificMassiveActions($input=array()) {
00149 
00150       $res = array('ok'      => 0,
00151                    'ko'      => 0,
00152                    'noright' => 0);
00153 
00154       switch ($input['action']) {
00155          case "uninstall" :
00156             foreach ($input["item"] as $key => $val) {
00157                if ($val == 1) {
00158                   if ($this->can($key,'w')) {
00159                      if ($this->uninstall($key)) {
00160                         $res['ok']++;
00161                      } else {
00162                         $res['ko']++;
00163                      }
00164                   } else {
00165                      $res['noright']++;
00166                   }
00167                }
00168             }
00169             break;
00170 
00171          case "updatepages" :
00172             if (isset($input['pages'])) {
00173                foreach ($input["item"] as $key => $val) {
00174                   if ($val == 1) {
00175                      if ($this->can($key,'w')) {
00176                         if ($this->update(array('id' => $key,
00177                                                 'pages' => $input['pages']))) {
00178                            $res['ok']++;
00179                         } else {
00180                            $res['ko']++;
00181                         }
00182                      } else {
00183                         $res['noright']++;
00184                      }
00185                   }
00186                }
00187             } else {
00188                $res['ko']++;
00189             }
00190             break;
00191 
00192          default :
00193             return parent::doSpecificMassiveActions($input);
00194       }
00195       return $res;
00196    }
00197 
00198 
00199    /**
00200     * @see CommonDBTM::restore()
00201     */
00202    function restore(array $input, $history=1) {
00203       global $DB;
00204 
00205       $query = "UPDATE `".$this->getTable()."`
00206                 SET `date_out` = NULL,
00207                     `date_use` = NULL,
00208                     `printers_id` = '0'
00209                 WHERE `id`='".$input["id"]."'";
00210       if ($result = $DB->query($query)
00211           && ($DB->affected_rows() > 0)) {
00212          return true;
00213       }
00214       return false;
00215    }
00216 
00217    /**
00218     * Link a cartridge to a printer.
00219     *
00220     * Link the first unused cartridge of type $Tid to the printer $pID
00221     *
00222     * @param $tID : cartridge type identifier
00223     * @param $pID : printer identifier
00224     *
00225     * @return boolean : true for success
00226    **/
00227    function install($pID, $tID) {
00228       global $DB;
00229 
00230       // Get first unused cartridge
00231       $query = "SELECT `id`
00232                 FROM `".$this->getTable()."`
00233                 WHERE (`cartridgeitems_id` = '$tID'
00234                        AND `date_use` IS NULL)";
00235       $result = $DB->query($query);
00236 
00237       if ($DB->numrows($result)>0) {
00238          $cID = $DB->result($result,0,0);
00239          // Mise a jour cartouche en prenant garde aux insertion multiples
00240          $query = "UPDATE `".$this->getTable()."`
00241                    SET `date_use` = '".date("Y-m-d")."',
00242                        `printers_id` = '$pID'
00243                    WHERE (`id`='$cID'
00244                           AND `date_use` IS NULL)";
00245 
00246          if ($result = $DB->query($query)
00247              && ($DB->affected_rows() > 0)) {
00248             $changes[0] = '0';
00249             $changes[1] = '';
00250             $changes[2] = __('Installing a cartridge');
00251             Log::history($pID, 'Printer', $changes, 0, Log::HISTORY_LOG_SIMPLE_MESSAGE);
00252             return true;
00253          }
00254 
00255       } else {
00256          Session::addMessageAfterRedirect(__('No free cartridge'), false, ERROR);
00257       }
00258       return false;
00259    }
00260 
00261 
00262    /**
00263     * UnLink a cartridge linked to a printer
00264     *
00265     * UnLink the cartridge identified by $ID
00266     *
00267     * @param $ID : cartridge identifier
00268     *
00269     * @return boolean
00270    **/
00271    function uninstall($ID) {
00272       global $DB;
00273 
00274       if ($this->getFromDB($ID)) {
00275          $printer = new Printer();
00276          $toadd = '';
00277          if ($printer->getFromDB($this->getField("printers_id"))) {
00278             $toadd.= ", `pages` = '".$printer->fields['last_pages_counter']."' ";
00279          }
00280 
00281          $query = "UPDATE`".$this->getTable()."`
00282                    SET `date_out` = '".date("Y-m-d")."'
00283                      $toadd
00284                    WHERE `id`='$ID'";
00285 
00286          if ($result = $DB->query($query)
00287              && ($DB->affected_rows() > 0)) {
00288             $changes[0] = '0';
00289             $changes[1] = '';
00290             $changes[2] = __('Uninstalling a cartridge');
00291             Log::history($this->getField("printers_id"), 'Printer', $changes,
00292                          0, Log::HISTORY_LOG_SIMPLE_MESSAGE);
00293 
00294             return true;
00295          }
00296          return false;
00297       }
00298    }
00299 
00300 
00301    /**
00302     * Print the cartridge count HTML array for the cartridge item $tID
00303     *
00304     * @param $tID              integer: cartridge item identifier.
00305      *@param $alarm_threshold  integer: threshold alarm value.
00306     * @param $nohtml           integer: Return value without HTML tags (default 0)
00307     *
00308     * @return string to display
00309    **/
00310    static function getCount($tID, $alarm_threshold, $nohtml=0) {
00311       global $DB;
00312 
00313       /// TODO to be more useful permit to have several columns and display number in it
00314       // Get total
00315       $total = self::getTotalNumber($tID);
00316       $out   = "";
00317       if ($total != 0) {
00318          $unused     = self::getUnusedNumber($tID);
00319          $used       = self::getUsedNumber($tID);
00320          $old        = self::getOldNumber($tID);
00321          $highlight  = "";
00322          if ($unused <= $alarm_threshold) {
00323             $highlight = "tab_bg_1_2";
00324          }
00325 
00326          if (!$nohtml) {
00327             $out .= "<table  class='tab_format $highlight' width='100%'><tr><td>";
00328             $out .= __('Total')."</td><td>$total";
00329             $out .= "</td><td class='b'>";
00330             $out .= _nx('cartridge','New','New',$unused);
00331             $out .= "</td><td class='b'>$unused</td><tr>";
00332             $out .= "<tr><td>";
00333             $out .= _nx('cartridge','Used','Used',$used);
00334             $out .= "</td><td>$used</span></td><td>";
00335             $out .= _nx('cartridge','Worn','Worn',$old);
00336             $out .= "</td><td>$old</span></td></tr></table>";
00337 
00338          } else {
00339             //TRANS : for display cartridges count : %1$d is the total number,
00340             //        %2$d the new one, %3$d the used one, %4$d worn one
00341             $out .= sprintf(__('Total: %1$d (%2$d new, %3$d used, %4$d worn)'),
00342                             $total ,$unused, $used, $old);
00343          }
00344 
00345       } else {
00346          if (!$nohtml) {
00347             $out .= "<div class='tab_bg_1_2'><i>".__('No cartridge')."</i></div>";
00348          } else {
00349             $out .= __('No cartridge');
00350          }
00351       }
00352       return $out;
00353    }
00354 
00355 
00356    /**
00357     * count how many cartbridge for the cartridge item $tID
00358     *
00359     * @param $tID integer: cartridge item identifier.
00360     *
00361     * @return integer : number of cartridge counted.
00362    **/
00363    static function getTotalNumber($tID) {
00364       global $DB;
00365 
00366       $query = "SELECT id
00367                 FROM `glpi_cartridges`
00368                 WHERE (`cartridgeitems_id` = '$tID')";
00369       $result = $DB->query($query);
00370       return $DB->numrows($result);
00371    }
00372 
00373 
00374    /**
00375     * count how many cartridge used for the cartridge item $tID
00376     *
00377     * @param $tID integer: cartridge item identifier.
00378     *
00379     * @return integer : number of cartridge used counted.
00380    **/
00381    static function getUsedNumber($tID) {
00382       global $DB;
00383 
00384       $query = "SELECT id
00385                 FROM `glpi_cartridges`
00386                 WHERE (`cartridgeitems_id` = '$tID'
00387                        AND `date_use` IS NOT NULL
00388                        AND `date_out` IS NULL)";
00389       $result = $DB->query($query);
00390       return $DB->numrows($result);
00391    }
00392 
00393 
00394    /**
00395     * count how many old cartbridge for the cartridge item $tID
00396     *
00397     * @param $tID integer: cartridge item identifier.
00398     *
00399     * @return integer : number of old cartridge counted.
00400    **/
00401    static function getOldNumber($tID) {
00402       global $DB;
00403 
00404       $query = "SELECT id
00405                 FROM `glpi_cartridges`
00406                 WHERE (`cartridgeitems_id` = '$tID'
00407                        AND `date_out` IS NOT NULL)";
00408       $result = $DB->query($query);
00409       return $DB->numrows($result);
00410    }
00411 
00412 
00413    /**
00414     * count how many cartbridge unused for the cartridge item $tID
00415     *
00416     * @param $tID integer: cartridge item identifier.
00417     *
00418     * @return integer : number of cartridge unused counted.
00419    **/
00420    static function getUnusedNumber($tID) {
00421       global $DB;
00422 
00423       $query = "SELECT id
00424                 FROM `glpi_cartridges`
00425                 WHERE (`cartridgeitems_id` = '$tID'
00426                        AND `date_use` IS NULL)";
00427       $result = $DB->query($query);
00428       return $DB->numrows($result);
00429    }
00430 
00431 
00432    /**
00433     * Get the dict value for the status of a cartridge
00434     *
00435     * @param $date_use  date : date of use
00436     * @param $date_out  date : date of delete
00437     *
00438     * @return string : dict value for the cartridge status.
00439    **/
00440    static function getStatus($date_use, $date_out) {
00441 
00442       if (is_null($date_use) || empty($date_use)) {
00443          return _x('cartridge', 'New');
00444       }
00445       if (is_null($date_out) || empty($date_out)) {
00446          return _x('cartridge', 'Used');
00447       }
00448       return _x('cartridge', 'Worn');
00449    }
00450 
00451 
00452    /**
00453     * Print out the cartridges of a defined type
00454     *
00455     * @param $cartitem  object   of CartridgeItem class
00456     * @param $show_old  boolean  show old cartridges or not (default 0)
00457     *
00458     * @return Nothing (displays)
00459    **/
00460    static function showForCartridgeItem(CartridgeItem $cartitem, $show_old=0) {
00461       global $DB, $CFG_GLPI;
00462 
00463       $tID = $cartitem->getField('id');
00464       if (!$cartitem->can($tID,'r')) {
00465          return false;
00466       }
00467       $canedit = $cartitem->can($tID,'w');
00468 
00469       $query = "SELECT COUNT(*) AS count
00470                 FROM `glpi_cartridges`
00471                 WHERE (`cartridgeitems_id` = '$tID')";
00472 
00473       if ($result = $DB->query($query)) {
00474          $total  = $DB->result($result, 0, "count");
00475 
00476          if (!$show_old) { // NEW
00477             $where = " AND `glpi_cartridges`.`date_out` IS NULL";
00478          } else { //OLD
00479             $where = " AND `glpi_cartridges`.`date_out` IS NOT NULL";
00480          }
00481 
00482          $stock_time       = 0;
00483          $use_time         = 0;
00484          $pages_printed    = 0;
00485          $nb_pages_printed = 0;
00486          $ORDER = " `glpi_cartridges`.`date_use` ASC,
00487                     `glpi_cartridges`.`date_out` DESC,
00488                     `glpi_cartridges`.`date_in`";
00489 
00490          if (!$show_old) {
00491             $ORDER = " `glpi_cartridges`.`date_out` ASC,
00492                        `glpi_cartridges`.`date_use` ASC,
00493                        `glpi_cartridges`.`date_in`";
00494          }
00495          $query = "SELECT `glpi_cartridges`.*,
00496                         `glpi_printers`.`id` AS printID,
00497                         `glpi_printers`.`name` AS printname,
00498                         `glpi_printers`.`init_pages_counter`
00499                    FROM `glpi_cartridges`
00500                    LEFT JOIN `glpi_printers`
00501                         ON (`glpi_cartridges`.`printers_id` = `glpi_printers`.`id`)
00502                    WHERE `glpi_cartridges`.`cartridgeitems_id` = '$tID'
00503                          $where
00504                    ORDER BY $ORDER";
00505 
00506          $result = $DB->query($query);
00507          $number = $DB->numrows($result);
00508 
00509          echo "<div class='spaced'>";
00510          if ($canedit && $number) {
00511             $rand = mt_rand();
00512             Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
00513             $actions = array('delete'  => _x('button', 'Delete permanently'),
00514                              'activate_infocoms'
00515                                        => __('Enable the financial and administrative information'),
00516                              'restore' => __('Back to stock'));
00517             $paramsma = array('num_displayed'    => $number,
00518                               'specific_actions' => $actions,
00519                               'rand'             => $rand);
00520             Html::showMassiveActions(__CLASS__, $paramsma);
00521          }
00522          echo "<table class='tab_cadre_fixe'>";
00523          if (!$show_old) {
00524             echo "<tr><th colspan='".($canedit?'7':'6')."'>".self::getCount($tID,-1)."</th>";
00525             echo "</tr>";
00526          } else { // Old
00527             echo "<tr><th colspan='".($canedit?'9':'8')."'>".__('Worn cartridges')."</th>";
00528             echo "</tr>";
00529          }
00530          $i = 0;
00531          echo "<tr>";
00532          if ($canedit && $number) {
00533             echo "<th width='10'>";
00534             Html::checkAllAsCheckbox('mass'.__CLASS__.$rand);
00535             echo "</th>";
00536          }
00537          echo "<th>".__('ID')."</th>";
00538          echo "<th>".__('State')."</th>";
00539          echo "<th>".__('Add date')."</th><th>".__('Use date')."</th>";
00540          echo "<th>".__('Used on')."</th>";
00541 
00542 
00543          if ($show_old) {
00544             echo "<th>".__('End date')."</th>";
00545             echo "<th>".__('Printer counter')."</th>";
00546          }
00547 
00548          echo "<th width='18%'>".__('Financial and administrative information')."</th>";
00549          echo "</tr>";
00550       }
00551 
00552 
00553       $pages = array();
00554 
00555       if ($number) {
00556          while ($data = $DB->fetch_assoc($result)) {
00557             $date_in  = Html::convDate($data["date_in"]);
00558             $date_use = Html::convDate($data["date_use"]);
00559             $date_out = Html::convDate($data["date_out"]);
00560             $printer  = $data["printers_id"];
00561             $page     = $data["pages"];
00562 
00563             echo "<tr class='tab_bg_1'>";
00564             if ($canedit) {
00565                echo "<td width='10'>";
00566                Html::showMassiveActionCheckBox(__CLASS__, $data["id"]);
00567                echo "</td>";
00568             }
00569             echo "<td>".$data['id'].'</td>';
00570             echo "<td class='center'>".self::getStatus($data["date_use"], $data["date_out"]);
00571             echo "</td><td class='center'>".$date_in."</td>";
00572             echo "<td class='center'>".$date_use."</td>";
00573             echo "<td class='center'>";
00574             if (!is_null($date_use)) {
00575                if ($data["printID"] > 0) {
00576                   $printname = $data["printname"];
00577                   if ($_SESSION['glpiis_ids_visible'] || empty($printname)) {
00578                      $printname = sprintf(__('%1$s (%2$s)'), $printname, $data["printID"]);
00579                   }
00580                   echo "<a href='".$CFG_GLPI["root_doc"]."/front/printer.form.php?id=".
00581                         $data["printID"]."'><span class='b'>".$printname."</span></a>";
00582                } else {
00583                   echo NOT_AVAILABLE;
00584                }
00585                $tmp_dbeg       = explode("-",$data["date_in"]);
00586                $tmp_dend       = explode("-",$data["date_use"]);
00587                $stock_time_tmp = mktime(0, 0, 0, $tmp_dend[1], $tmp_dend[2], $tmp_dend[0])
00588                                  - mktime(0, 0, 0, $tmp_dbeg[1], $tmp_dbeg[2], $tmp_dbeg[0]);
00589                $stock_time    += $stock_time_tmp;
00590             }
00591             if ($show_old) {
00592                echo "</td><td class='center'>";
00593                echo $date_out;
00594                $tmp_dbeg      = explode("-",$data["date_use"]);
00595                $tmp_dend      = explode("-",$data["date_out"]);
00596                $use_time_tmp  = mktime(0, 0, 0, $tmp_dend[1], $tmp_dend[2], $tmp_dend[0])
00597                                  - mktime(0, 0, 0, $tmp_dbeg[1], $tmp_dbeg[2], $tmp_dbeg[0]);
00598                $use_time     += $use_time_tmp;
00599             }
00600 
00601             echo "</td>";
00602             if ($show_old) {
00603                // Get initial counter page
00604                if (!isset($pages[$printer])) {
00605                   $pages[$printer] = $data['init_pages_counter'];
00606                }
00607                echo "<td class='center'>";
00608                if ($pages[$printer] < $data['pages']) {
00609                   $pages_printed   += $data['pages']-$pages[$printer];
00610                   $nb_pages_printed++;
00611                   $pp               = $data['pages']-$pages[$printer];
00612                   printf(_n('%d printed page','%d printed pages',$pp), $pp);
00613                   $pages[$printer]  = $data['pages'];
00614                } else if ($data['pages'] != 0) {
00615                   echo "<span class='tab_bg_1_2'>".__('Counter error')."</span>";
00616                }
00617                echo "</td>";
00618             }
00619             echo "<td class='center'>";
00620             Infocom::showDisplayLink('Cartridge',$data["id"],1);
00621             echo "</td>";
00622             echo "</tr>";
00623          }
00624          if ($show_old
00625              && ($number > 0)) {
00626             if ($nb_pages_printed == 0) {
00627                 $nb_pages_printed = 1;
00628             }
00629             echo "<tr class='tab_bg_2'><td colspan='".($canedit?'4':'3')."'>&nbsp;</td>";
00630             echo "<td class='center b'>".__('Average time in stock')."<br>";
00631             echo round($stock_time/$number/60/60/24/30.5,1)." ".__('month')."</td>";
00632             echo "<td>&nbsp;</td>";
00633             echo "<td class='center b'>".__('Average time in use')."<br>";
00634             echo round($use_time/$number/60/60/24/30.5,1)." ".__('month')."</td>";
00635             echo "<td class='center b'>".__('Average number of printed pages')."<br>";
00636             echo round($pages_printed/$nb_pages_printed)."</td>";
00637             echo "<td colspan='".($canedit?'3':'1')."'>&nbsp;</td></tr>";
00638          }
00639       }
00640       echo "</table>";
00641       if ($canedit && $number) {
00642          $paramsma['ontop'] = false;
00643          Html::showMassiveActions(__CLASS__, $paramsma);
00644          Html::closeForm();
00645       }
00646       echo "</div>\n\n";
00647    }
00648 
00649 
00650    /**
00651     * Print out a link to add directly a new cartridge from a cartridge item.
00652     *
00653     * @param $cartitem  CartridgeItem object
00654     *
00655     * @return Nothing (displays)
00656    **/
00657    static function showAddForm(CartridgeItem $cartitem) {
00658       global $CFG_GLPI;
00659 
00660       $ID = $cartitem->getField('id');
00661       if (!$cartitem->can($ID, 'w')) {
00662          return false;
00663       }
00664       if ($ID > 0) {
00665          echo "<div class='firstbloc'>";
00666          echo "<form method='post' action=\"".static::getFormURL()."\">";
00667          echo "<table class='tab_cadre_fixe'>";
00668          echo "<tr><td class='center tab_bg_2'>";
00669          echo "<input type='hidden' name='cartridgeitems_id' value='$ID'>\n";
00670          Dropdown::showInteger('to_add',1,1,100);
00671          echo " <input type='submit' name='add' value=\"".__s('Add cartridges')."\"
00672                 class='submit'>";
00673          echo "</td></tr>";
00674          echo "</table>";
00675          Html::closeForm();
00676          echo "</div>";
00677       }
00678    }
00679 
00680 
00681    /**
00682     * Show installed cartridges
00683     *
00684     * @since version 0.84 (before showInstalled)
00685     *
00686     * @param $printer            Printer object
00687     * @param $old       boolean  old cartridges or not ? (default 0)
00688     *
00689     * @return nothing (display)
00690    **/
00691    static function showForPrinter(Printer $printer, $old=0) {
00692       global $DB, $CFG_GLPI;
00693 
00694       $instID = $printer->getField('id');
00695       if (!Session::haveRight("cartridge","r")) {
00696          return false;
00697       }
00698       $canedit = Session::haveRight("cartridge", "w");
00699       $rand    = mt_rand();
00700 
00701       $query = "SELECT `glpi_cartridgeitems`.`id` AS tID,
00702                        `glpi_cartridgeitems`.`is_deleted`,
00703                        `glpi_cartridgeitems`.`ref` AS ref,
00704                        `glpi_cartridgeitems`.`name` AS type,
00705                        `glpi_cartridges`.`id`,
00706                        `glpi_cartridges`.`pages` AS pages,
00707                        `glpi_cartridges`.`date_use` AS date_use,
00708                        `glpi_cartridges`.`date_out` AS date_out,
00709                        `glpi_cartridges`.`date_in` AS date_in
00710                 FROM `glpi_cartridges`,
00711                      `glpi_cartridgeitems`
00712                 WHERE (`glpi_cartridges`.`date_out` IS ".($old?"NOT":"")." NULL
00713                        AND `glpi_cartridges`.`printers_id` = '$instID'
00714                        AND `glpi_cartridges`.`cartridgeitems_id` = `glpi_cartridgeitems`.`id`)
00715                 ORDER BY `glpi_cartridges`.`date_out` ASC,
00716                          `glpi_cartridges`.`date_use` DESC,
00717                          `glpi_cartridges`.`date_in`";
00718 
00719       $result = $DB->query($query);
00720       $number = $DB->numrows($result);
00721       $i      = 0;
00722 
00723 
00724       if ($canedit && !$old) {
00725          echo "<div class='firstbloc'>";
00726          echo "<form method='post' action=\"".static::getFormURL()."\">";
00727          echo "<table class='tab_cadre_fixe'>";
00728          echo "<tr><td class='center tab_bg_2' width='50%'>";
00729          echo "<input type='hidden' name='printers_id' value='$instID'>\n";
00730          $installok = false;
00731          if (CartridgeItem::dropdownForPrinter($printer)) {
00732             $installok = true;
00733          } else {
00734             _e('No cartridge available');
00735          }
00736 
00737          echo "</td><td><input type='submit' name='install' value=\""._sx('button','Install')."\"
00738                          ".($installok?'':'disabled')." class='submit'>";
00739          echo "</td></tr>";
00740          echo "</table>";
00741          Html::closeForm();
00742          echo "</div>";
00743       }
00744 
00745       echo "<div id='viewcartridge$rand'></div>";
00746 
00747       $pages = $printer->fields['init_pages_counter'];
00748       echo "<div class='spaced'>";
00749       if ($canedit && $number) {
00750          Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
00751          if (!$old) {
00752             $actions = array('uninstall' => __('End of life'));
00753          } else {
00754             $actions = array('updatepages' => __('Update printer counter'),
00755                              'delete'      => _x('button', 'Delete permanently'));
00756          }
00757          $paramsma = array('num_displayed'    => $number,
00758                            'specific_actions' => $actions,
00759                            'rand'             => $rand,
00760                            'extraparams'      => array('maxpages' => $printer->fields['last_pages_counter']));
00761          Html::showMassiveActions(__CLASS__, $paramsma);
00762       }
00763       echo "<table class='tab_cadre_fixehov'>";
00764       if ($old == 0) {
00765          echo "<tr><th colspan='".($canedit?'5':'4')."'>".__('Used cartridges')."</th></tr>";
00766       } else {
00767          echo "<tr><th colspan='".($canedit?'8':'7')."'>".__('Worn cartridges')."</th></tr>";
00768       }
00769       echo "<tr>";
00770       if ($canedit) {
00771          echo "<th width='10'>";
00772          Html::checkAllAsCheckbox('mass'.__CLASS__.$rand);
00773          echo "</th>";
00774       }
00775       echo "<th>".__('ID')."</th><th>"._n('Cartridge model','Cartridge models',1)."</th>";
00776       echo "<th>".__('Add date')."</th>";
00777       echo "<th>".__('Use date')."</th>";
00778       if ($old != 0) {
00779          echo "<th>".__('End date')."</th>";
00780          echo "<th>".__('Printer counter')."</th>";
00781          echo "<th>".__('Printed pages')."</th>";
00782       }
00783       echo "</tr>";
00784       $stock_time       = 0;
00785       $use_time         = 0;
00786       $pages_printed    = 0;
00787       $nb_pages_printed = 0;
00788 
00789       while ($data = $DB->fetch_assoc($result)) {
00790          $cart_id    = $data["id"];
00791          $date_in    = Html::convDate($data["date_in"]);
00792          $date_use   = Html::convDate($data["date_use"]);
00793          $date_out   = Html::convDate($data["date_out"]);
00794          $viewitemjs = ($canedit ? "style='cursor:pointer' onClick=\"viewEditCartridge".$data['id'].
00795                         "$rand();\"" : '');
00796          echo "<tr class='tab_bg_1".($data["is_deleted"]?"_2":"")."'>";
00797          if ($canedit) {
00798             echo "<td width='10'>";
00799             Html::showMassiveActionCheckBox(__CLASS__, $data["id"]);
00800             echo "</td>";
00801          }
00802          echo "<td class='center' $viewitemjs>";
00803          if ($canedit) {
00804             echo "\n<script type='text/javascript' >\n";
00805             echo "function viewEditCartridge". $data["id"]."$rand() {\n";
00806             $params = array('type'        => __CLASS__,
00807                             'parenttype'  => 'Printer',
00808                             'printers_id' => $printer->fields["id"],
00809                             'id'          => $data["id"]);
00810             Ajax::updateItemJsCode("viewcartridge$rand",
00811                                    $CFG_GLPI["root_doc"]."/ajax/viewsubitem.php", $params);
00812             echo "};";
00813             echo "</script>\n";
00814          }
00815          echo $data["id"]."</td>";
00816          echo "<td class='center' $viewitemjs>";
00817          echo "<a href=\"".$CFG_GLPI["root_doc"]."/front/cartridgeitem.form.php?id=".$data["tID"]."\">";
00818          printf(__('%1$s - %2$s'), $data["type"], $data["ref"]);
00819          echo "</a></td>";
00820          echo "<td class='center' $viewitemjs>".$date_in."</td>";
00821          echo "<td class='center' $viewitemjs>".$date_use."</td>";
00822 
00823          $tmp_dbeg       = explode("-", $data["date_in"]);
00824          $tmp_dend       = explode("-", $data["date_use"]);
00825 
00826          $stock_time_tmp = mktime(0, 0, 0, $tmp_dend[1], $tmp_dend[2], $tmp_dend[0])
00827                            - mktime(0, 0, 0, $tmp_dbeg[1], $tmp_dbeg[2], $tmp_dbeg[0]);
00828          $stock_time    += $stock_time_tmp;
00829          if ($old != 0) {
00830             echo "<td class='center' $viewitemjs>".$date_out;
00831 
00832             $tmp_dbeg      = explode("-", $data["date_use"]);
00833             $tmp_dend      = explode("-", $data["date_out"]);
00834 
00835             $use_time_tmp  = mktime(0, 0, 0, $tmp_dend[1], $tmp_dend[2], $tmp_dend[0])
00836                               - mktime(0, 0, 0, $tmp_dbeg[1], $tmp_dbeg[2], $tmp_dbeg[0]);
00837             $use_time     += $use_time_tmp;
00838 
00839             echo "</td><td class='numeric' $viewitemjs>".$data['pages']."</td>";
00840             echo "<td class='numeric' $viewitemjs>";
00841 
00842             if ($pages < $data['pages']) {
00843                $pages_printed   += $data['pages']-$pages;
00844                $nb_pages_printed++;
00845                $pp               = $data['pages']-$pages;
00846                echo $pp;
00847                $pages            = $data['pages'];
00848             } else {
00849                echo "&nbsp;";
00850             }
00851             echo "</td>";
00852          }
00853          echo "</tr>";
00854       }
00855       if ($old) { // Print average
00856          if ($number > 0) {
00857             if ($nb_pages_printed == 0) {
00858                $nb_pages_printed = 1;
00859             }
00860             echo "<tr class='tab_bg_2'><td colspan='".($canedit?"4":'3')."'>&nbsp;</td>";
00861             echo "<td class='center b'>".__('Average time in stock')."<br>";
00862             $time_stock = round($stock_time/$number/60/60/24/30.5,1);
00863             echo sprintf(_n('%d month', '%d months', $time_stock), $time_stock)."</td>";
00864             echo "<td class='center b'>".__('Average time in use')."<br>";
00865             $time_use = round($use_time/$number/60/60/24/30.5,1);
00866             echo sprintf(_n('%d month', '%d months', $time_use), $time_use)."</td>";
00867             echo "<td class='center b' colspan='2'>".__('Average number of printed pages')."<br>";
00868             echo round($pages_printed/$nb_pages_printed)."</td>";
00869             echo "</tr>";
00870          }
00871       }
00872       echo "</table>";
00873       if ($canedit && $number) {
00874          $paramsma['ontop'] = false;
00875          Html::showMassiveActions(__CLASS__, $paramsma);
00876          Html::closeForm();
00877       }
00878       echo "</div>\n\n";
00879    }
00880 
00881 
00882    /** form for Cartridge
00883     *
00884     * @since version 0.84
00885     *
00886     * @param $ID      integer  Id of the cartridge
00887     * @param $options array    of possible options:
00888     *     - parent Object : the printers where the cartridge is used
00889    **/
00890    function showForm($ID, $options=array()) {
00891       global $DB, $CFG_GLPI;
00892 
00893       if (isset($options['parent']) && !empty($options['parent'])) {
00894          $printer = $options['parent'];
00895       }
00896       if (!$this->getFromDB($ID)) {
00897          return false;
00898       }
00899       $printer = new Printer;
00900       $printer->check($this->getField('printers_id'),'w');
00901 
00902       $cartitem = new CartridgeItem;
00903       $cartitem->getFromDB($this->getField('cartridgeitems_id'),'w');
00904 
00905       $is_old  = !empty($this->fields['date_out']);
00906       $is_used = !empty($this->fields['date_use']);
00907 
00908       $options['colspan'] = 2;
00909       $options['candel']  = false; // Do not permit delete here
00910       $options['canedit'] = $is_used; // Do not permit edit if cart is not used
00911       $this->showFormHeader($options);
00912 
00913       echo "<tr class='tab_bg_1'>";
00914       echo "<td>"._n('Printer','Printers',1)."</td><td>";
00915       echo $printer->getLink();
00916       echo "<input type='hidden' name='printers_id' value='".$this->getField('printers_id')."'>\n";
00917       echo "<input type='hidden' name='cartridgeitems_id' value='".
00918              $this->getField('cartridgeitems_id')."'>\n";
00919       echo "</td>\n";
00920       echo "<td>"._n('Cartridge model','Cartridge models',1)."</td>";
00921       echo "<td>".$cartitem->getLink()."</td></tr>\n";
00922 
00923       echo "<tr class='tab_bg_1'>";
00924       echo "<td>".__('Add date')."</td>";
00925       echo "<td>".Html::convDate($this->fields["date_in"])."</td>";
00926 
00927       echo "<td>".__('Use date')."</td><td>";
00928       if ($is_used && !$is_old) {
00929          Html::showDateFormItem("date_use", $this->fields["date_use"], false, true,
00930                                 $this->fields["date_in"]);
00931       } else {
00932          echo Html::convDate($this->fields["date_use"]);
00933       }
00934       echo "</td></tr>\n";
00935 
00936       if ($is_old) {
00937          echo "<tr class='tab_bg_1'>";
00938          echo "<td>".__('End date')."</td><td>";
00939          Html::showDateFormItem("date_out", $this->fields["date_out"], false, true,
00940                                 $this->fields["date_use"]);
00941          echo "</td>";
00942          echo "<td>".__('Printer counter')."</td><td>";
00943          echo "<input type='text' name='pages' value=\"".$this->fields['pages']."\">";
00944          echo "</td></tr>\n";
00945       }
00946       $this->showFormButtons($options);
00947 
00948       return true;
00949    }
00950 
00951 
00952    /**
00953     * Get notification parameters by entity
00954     *
00955     * @param entity the entity (default 0)
00956     */
00957    static function getNotificationParameters($entity=0) {
00958       global $DB, $CFG_GLPI;
00959 
00960       //Look for parameters for this entity
00961       $query = "SELECT `cartridges_alert_repeat`
00962                 FROM `glpi_entities`
00963                 WHERE `id` = '$entity'";
00964       $iterator = $DB->request($query);
00965 
00966       if (!$iterator->numrows()) {
00967          //No specific parameters defined, taking global configuration params
00968          return $CFG_GLPI['cartridges_alert_repeat'];
00969 
00970       } else {
00971          $datas = $iterator->next();
00972          //This entity uses global parameters -> return global config
00973          if ($datas['cartridges_alert_repeat'] == -1) {
00974             return $CFG_GLPI['cartridges_alert_repeat'];
00975          }
00976          // ELSE Special configuration for this entity
00977          return $datas['cartridges_alert_repeat'];
00978       }
00979    }
00980 
00981 
00982    function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
00983 
00984       if (!$withtemplate
00985           && Session::haveRight("cartridge","r"))
00986          switch ($item->getType()) {
00987             case 'Printer' :
00988                if ($_SESSION['glpishow_count_on_tabs']) {
00989                   return self::createTabEntry(self::getTypeName(2), self::countForPrinter($item));
00990                }
00991                return self::getTypeName(2);
00992 
00993             case 'CartridgeItem' :
00994                if ($_SESSION['glpishow_count_on_tabs']) {
00995                   return self::createTabEntry(self::getTypeName(2),
00996                                               self::countForCartridgeItem($item));
00997                }
00998                return self::getTypeName(2);
00999       }
01000       return '';
01001    }
01002 
01003 
01004    static function countForCartridgeItem(CartridgeItem $item) {
01005 
01006       $restrict = "`glpi_cartridges`.`cartridgeitems_id` = '".$item->getField('id') ."'";
01007 
01008       return countElementsInTable(array('glpi_cartridges'), $restrict);
01009    }
01010 
01011 
01012    /**
01013     * @param $item Printer object
01014    **/
01015    static function countForPrinter(Printer $item) {
01016 
01017       $restrict = "`glpi_cartridges`.`printers_id` = '".$item->getField('id') ."'";
01018 
01019       return countElementsInTable(array('glpi_cartridges'), $restrict);
01020    }
01021 
01022 
01023    static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
01024 
01025       switch ($item->getType()) {
01026          case 'Printer' :
01027             self::showForPrinter($item);
01028             self::showForPrinter($item, 1);
01029             return true;
01030 
01031          case 'CartridgeItem' :
01032             self::showAddForm($item);
01033             self::showForCartridgeItem($item);
01034             self::showForCartridgeItem($item, 1);
01035             return true;
01036       }
01037    }
01038 }
01039 ?>