knowbaseitem.class.php
Go to the documentation of this file.
00001 <?php
00002 /*
00003  * @version $Id: knowbaseitem.class.php 20572 2013-03-29 17:26:40Z moyo $
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 if (!defined('GLPI_ROOT')) {
00035    die("Sorry. You can't access directly to this file");
00036 }
00037 
00038 // CLASSE knowledgebase
00039 
00040 class KnowbaseItem extends CommonDBTM {
00041 
00042    // For visibility checks
00043    protected $users     = array();
00044    protected $groups    = array();
00045    protected $profiles  = array();
00046    protected $entities  = array();
00047 
00048 
00049    static function getTypeName($nb=0) {
00050       return __('Knowledge base');
00051    }
00052 
00053 
00054    static function canCreate() {
00055       return (Session::haveRight('knowbase', 'w') || Session::haveRight('faq', 'w'));
00056    }
00057 
00058 
00059    static function canView() {
00060       global $CFG_GLPI;
00061 
00062       return (Session::haveRight('knowbase', 'r')
00063               || Session::haveRight('faq', 'r')
00064               || ((Session::getLoginUserID() === false) && $CFG_GLPI["use_public_faq"]));
00065    }
00066 
00067 
00068    function canViewItem() {
00069       global $CFG_GLPI;
00070 
00071       if ($this->fields['users_id'] == Session::getLoginUserID()) {
00072          return true;
00073       }
00074       if (Session::haveRight('knowbase_admin', '1')) {
00075          return true;
00076       }
00077 
00078       if ($this->fields["is_faq"]) {
00079          return (((Session::haveRight('knowbase', 'r') || Session::haveRight('faq', 'r'))
00080                   && $this->haveVisibilityAccess())
00081                  || ((Session::getLoginUserID() === false) && $this->isPubliclyVisible()));
00082       }
00083       return (Session::haveRight("knowbase", "r") && $this->haveVisibilityAccess());
00084    }
00085 
00086 
00087    function canUpdateItem() {
00088 
00089       // Personal knowbase or visibility and write access
00090       return (Session::haveRight('knowbase_admin', '1')
00091               || ($this->fields['users_id'] == Session::getLoginUserID())
00092               || ((($this->fields["is_faq"] && Session::haveRight("faq", "w"))
00093                    || (!$this->fields["is_faq"] && Session::haveRight("knowbase", "w")))
00094                   && $this->haveVisibilityAccess()));
00095    }
00096    /**
00097     * Get the search page URL for the current classe
00098     *
00099     * @since version 0.84
00100     *
00101     * @param $full path or relative one (true by default)
00102    **/
00103    static function getSearchURL($full=true) {
00104       global $CFG_GLPI;
00105 
00106       $dir = ($full ? $CFG_GLPI['root_doc'] : '');
00107 
00108       if (isset($_SESSION['glpiactiveprofile'])
00109           && ($_SESSION['glpiactiveprofile']['interface'] == "central")) {
00110          return "$dir/front/knowbaseitem.php";
00111       }
00112       return "$dir/front/helpdesk.faq.php";
00113    }
00114 
00115 
00116   function defineTabs($options=array()) {
00117 
00118       $ong = array();
00119       $this->addStandardTab(__CLASS__, $ong, $options);
00120       $this->addStandardTab('Document_Item', $ong, $options);
00121 
00122       return $ong;
00123    }
00124 
00125 
00126    function getTabNameForItem(CommonGLPI $item, $withtemplate=0) {
00127 
00128       if (!$withtemplate) {
00129          switch ($item->getType()) {
00130             case __CLASS__ :
00131                $ong[1] = $this->getTypeName(1);
00132                if ($item->canUpdate()) {
00133                   if ($_SESSION['glpishow_count_on_tabs']) {
00134                      $ong[2] = self::createTabEntry(__('Targets'),
00135                                                     $item->countVisibilities());
00136                   } else {
00137                      $ong[2] = __('Targets');
00138                   }
00139                }
00140                return $ong;
00141          }
00142       }
00143       return '';
00144    }
00145 
00146 
00147    static function displayTabContentForItem(CommonGLPI $item, $tabnum=1, $withtemplate=0) {
00148 
00149       if ($item->getType() == __CLASS__) {
00150          switch($tabnum) {
00151             case 1 :
00152                $item->showMenu();
00153                break;
00154 
00155             case 2 :
00156                $item->showVisibility();
00157                break;
00158          }
00159       }
00160       return true;
00161    }
00162 
00163 
00164    /**
00165     * Actions done at the end of the getEmpty function
00166     *
00167     *@return nothing
00168    **/
00169    function post_getEmpty() {
00170 
00171       if (Session::haveRight("faq", "w")
00172           && !Session::haveRight("knowbase", "w")) {
00173          $this->fields["is_faq"] = 1;
00174       }
00175    }
00176 
00177 
00178    /**
00179     * @since version 0.83
00180    **/
00181    function post_getFromDB() {
00182 
00183       // Users
00184       $this->users    = KnowbaseItem_User::getUsers($this->fields['id']);
00185 
00186       // Entities
00187       $this->entities = Entity_KnowbaseItem::getEntities($this->fields['id']);
00188 
00189       // Group / entities
00190       $this->groups   = Group_KnowbaseItem::getGroups($this->fields['id']);
00191 
00192       // Profile / entities
00193       $this->profiles = KnowbaseItem_Profile::getProfiles($this->fields['id']);
00194    }
00195 
00196 
00197    /**
00198     * @see CommonDBTM::cleanDBonPurge()
00199     *
00200     * @since version 0.83.1
00201    **/
00202    function cleanDBonPurge() {
00203 
00204       $class = new KnowbaseItem_User();
00205       $class->cleanDBonItemDelete($this->getType(), $this->fields['id']);
00206       $class = new Entity_KnowbaseItem();
00207       $class->cleanDBonItemDelete($this->getType(), $this->fields['id']);
00208       $class = new Group_KnowbaseItem();
00209       $class->cleanDBonItemDelete($this->getType(), $this->fields['id']);
00210       $class = new KnowbaseItem_Profile();
00211       $class->cleanDBonItemDelete($this->getType(), $this->fields['id']);
00212    }
00213 
00214 
00215    /**
00216     * @since version 0.84
00217     *
00218     * @see CommonDBTM::doSpecificMassiveActions()
00219    **/
00220    function doSpecificMassiveActions($input=array()) {
00221 
00222       $res = array('ok'      => 0,
00223                    'ko'      => 0,
00224                    'noright' => 0);
00225 
00226       switch ($input['action']) {
00227          case "deletevisibility":
00228             foreach ($input['item'] as $type => $items) {
00229                if (in_array($type, array('Entity_KnowbaseItem', 'Group_KnowbaseItem',
00230                                          'KnowbaseItem_Profile', 'KnowbaseItem_User'))) {
00231                   $item = new $type();
00232                   foreach ($items as $key => $val) {
00233                      if ($item->can($key,'w')) {
00234                         if ($item->delete(array('id' => $key))) {
00235                            $res['ok']++;
00236                         } else {
00237                            $res['ko']++;
00238                         }
00239                      } else {
00240                         $res['noright']++;
00241                      }
00242                   }
00243                }
00244             }
00245 
00246             break;
00247 
00248          default :
00249             return parent::doSpecificMassiveActions($input);
00250       }
00251       return $res;
00252    }
00253 
00254 
00255    /**
00256     * @since version 0.83
00257    **/
00258    function countVisibilities() {
00259 
00260       return (count($this->entities)
00261               + count($this->users)
00262               + count($this->groups)
00263               + count($this->profiles));
00264    }
00265 
00266 
00267    /**
00268     * Check is this item if visible to everybody (anonymous users)
00269     *
00270     * @since version 0.83
00271     *
00272     * @return Boolean
00273    **/
00274    function isPubliclyVisible() {
00275       global $CFG_GLPI;
00276 
00277       if (!$CFG_GLPI['use_public_faq']) {
00278          return false;
00279       }
00280 
00281       if (isset($this->entities[0])) { // Browse root entity rights
00282          foreach ($this->entities[0] as $entity) {
00283             if ($entity['is_recursive']) {
00284                return true;
00285             }
00286          }
00287       }
00288       return false;
00289    }
00290 
00291 
00292    /**
00293     * Is the login user have access to KnowbaseItem based on visibility configuration
00294     *
00295     * @since version 0.83
00296     *
00297     * @return boolean
00298    **/
00299    function haveVisibilityAccess() {
00300 
00301       // No public knowbaseitem right : no visibility check
00302       if (!Session::haveRight('faq', 'r')
00303           && !Session::haveRight('knowbase', 'r') ) {
00304          return false;
00305       }
00306 
00307       // Author
00308       if ($this->fields['users_id'] == Session::getLoginUserID()) {
00309          return true;
00310       }
00311       // Admin
00312       if (Session::haveRight('knowbase_admin', '1')) {
00313          return true;
00314       }
00315       // Users
00316       if (isset($this->users[Session::getLoginUserID()])) {
00317          return true;
00318       }
00319 
00320       // Groups
00321       if (count($this->groups)
00322           && isset($_SESSION["glpigroups"]) && count($_SESSION["glpigroups"])) {
00323 
00324          foreach ($this->groups as $key => $data) {
00325             foreach ($data as $group) {
00326                if (in_array($group['groups_id'], $_SESSION["glpigroups"])) {
00327                   // All the group
00328                   if ($group['entities_id'] < 0) {
00329                      return true;
00330                   }
00331                   // Restrict to entities
00332                   $entities = array($group['entities_id']);
00333                   if ($group['is_recursive']) {
00334                      $entities = getSonsOf('glpi_entities', $group['entities_id']);
00335                   }
00336                   if (Session::haveAccessToOneOfEntities($entities, true)) {
00337                      return true;
00338                   }
00339                }
00340             }
00341          }
00342       }
00343 
00344       // Entities
00345       if (count($this->entities)
00346           && isset($_SESSION["glpiactiveentities"]) && count($_SESSION["glpiactiveentities"])) {
00347 
00348          foreach ($this->entities as $key => $data) {
00349             foreach ($data as $entity) {
00350                $entities = array($entity['entities_id']);
00351                if ($entity['is_recursive']) {
00352                   $entities = getSonsOf('glpi_entities', $entity['entities_id']);
00353                }
00354                if (Session::haveAccessToOneOfEntities($entities, true)) {
00355                   return true;
00356                }
00357             }
00358          }
00359       }
00360 
00361       // Profiles
00362       if (count($this->profiles)
00363           && isset($_SESSION["glpiactiveprofile"]) && isset($_SESSION["glpiactiveprofile"]['id'])) {
00364 
00365          if (isset($this->profiles[$_SESSION["glpiactiveprofile"]['id']])) {
00366             foreach ($this->profiles[$_SESSION["glpiactiveprofile"]['id']] as $profile) {
00367                // All the profile
00368                if ($profile['entities_id'] < 0) {
00369                   return true;
00370                }
00371                // Restrict to entities
00372                $entities = array($profile['entities_id']);
00373                if ($profile['is_recursive']) {
00374                   $entities = getSonsOf('glpi_entities', $profile['entities_id']);
00375                }
00376                if (Session::haveAccessToOneOfEntities($entities, true)) {
00377                   return true;
00378                }
00379             }
00380          }
00381       }
00382 
00383       return false;
00384    }
00385 
00386 
00387    /**
00388    * Return visibility joins to add to SQL
00389    *
00390    * @since version 0.83
00391    *
00392    * @param $forceall force all joins (false by default)
00393    *
00394    * @return string joins to add
00395    **/
00396    static function addVisibilityJoins($forceall=false) {
00397 
00398       $join = '';
00399 
00400       // Users
00401       $join .= " LEFT JOIN `glpi_knowbaseitems_users`
00402                      ON (`glpi_knowbaseitems_users`.`knowbaseitems_id` = `glpi_knowbaseitems`.`id`) ";
00403 
00404       // Groups
00405       if ($forceall
00406           || (isset($_SESSION["glpigroups"]) && count($_SESSION["glpigroups"]))) {
00407          $join .= " LEFT JOIN `glpi_groups_knowbaseitems`
00408                         ON (`glpi_groups_knowbaseitems`.`knowbaseitems_id`
00409                               = `glpi_knowbaseitems`.`id`) ";
00410       }
00411 
00412       // Profiles
00413       if ($forceall
00414           || (isset($_SESSION["glpiactiveprofile"])
00415               && isset($_SESSION["glpiactiveprofile"]['id']))) {
00416          $join .= " LEFT JOIN `glpi_knowbaseitems_profiles`
00417                         ON (`glpi_knowbaseitems_profiles`.`knowbaseitems_id`
00418                               = `glpi_knowbaseitems`.`id`) ";
00419       }
00420 
00421       // Entities
00422       if ($forceall
00423           || !Session::getLoginUserID()
00424           || (isset($_SESSION["glpiactiveentities"]) && count($_SESSION["glpiactiveentities"]))) {
00425          $join .= " LEFT JOIN `glpi_entities_knowbaseitems`
00426                         ON (`glpi_entities_knowbaseitems`.`knowbaseitems_id`
00427                               = `glpi_knowbaseitems`.`id`) ";
00428       }
00429 
00430       return $join;
00431    }
00432 
00433 
00434    /**
00435     * Return visibility SQL restriction to add
00436     *
00437     * @since version 0.83
00438     *
00439     * @return string restrict to add
00440    **/
00441    static function addVisibilityRestrict() {
00442 
00443       $restrict = '';
00444       if (Session::getLoginUserID()) {
00445          $restrict = "(`glpi_knowbaseitems_users`.`users_id` = '".Session::getLoginUserID()."' ";
00446 
00447          // Users
00448          $restrict .= " OR `glpi_knowbaseitems_users`.`users_id` = '".Session::getLoginUserID()."' ";
00449 
00450          // Groups
00451          if (isset($_SESSION["glpigroups"]) && count($_SESSION["glpigroups"])) {
00452             $restrict .= " OR (`glpi_groups_knowbaseitems`.`groups_id`
00453                                     IN ('".implode("','",$_SESSION["glpigroups"])."')
00454                                AND (`glpi_groups_knowbaseitems`.`entities_id` < 0
00455                                     ".getEntitiesRestrictRequest("OR", "glpi_groups_knowbaseitems",
00456                                                                  '', '', true).")) ";
00457          }
00458 
00459          // Profiles
00460          if (isset($_SESSION["glpiactiveprofile"])
00461              && isset($_SESSION["glpiactiveprofile"]['id'])) {
00462             $restrict .= " OR (`glpi_knowbaseitems_profiles`.`profiles_id`
00463                                     = '".$_SESSION["glpiactiveprofile"]['id']."'
00464                                AND (`glpi_knowbaseitems_profiles`.`entities_id` < 0
00465                                     ".getEntitiesRestrictRequest("OR", "glpi_knowbaseitems_profiles",
00466                                                                  '', '', true).")) ";
00467          }
00468 
00469          // Entities
00470          if (isset($_SESSION["glpiactiveentities"]) && count($_SESSION["glpiactiveentities"])) {
00471             // Force complete SQL not summary when access to all entities
00472             $restrict .= getEntitiesRestrictRequest("OR", "glpi_entities_knowbaseitems", '', '',
00473                                                     true, true);
00474          }
00475 
00476          $restrict .= ") ";
00477       } else {
00478          $restrict = '1';
00479       }
00480       return $restrict;
00481    }
00482 
00483 
00484    /**
00485     * @see CommonDBTM::prepareInputForAdd()
00486    **/
00487    function prepareInputForAdd($input) {
00488 
00489       // set new date if not exists
00490       if (!isset($input["date"]) || empty($input["date"])) {
00491          $input["date"] = $_SESSION["glpi_currenttime"];
00492       }
00493       // set users_id
00494 
00495       // set title for question if empty
00496       if (isset($input["name"]) && empty($input["name"])) {
00497          $input["name"] = __('New item');
00498       }
00499 
00500       if (Session::haveRight("faq", "w")
00501           && !Session::haveRight("knowbase", "w")) {
00502          $input["is_faq"] = 1;
00503       }
00504       if (!Session::haveRight("faq", "w")
00505           && Session::haveRight("knowbase", "w")) {
00506          $input["is_faq"] = 0;
00507       }
00508       return $input;
00509    }
00510 
00511 
00512    /**
00513     * @see CommonDBTM::prepareInputForUpdate()
00514    **/
00515    function prepareInputForUpdate($input) {
00516 
00517       // set title for question if empty
00518       if (isset($input["name"]) && empty($input["name"])) {
00519          $input["name"] = __('New item');
00520       }
00521       return $input;
00522    }
00523 
00524 
00525    /**
00526     * Print out an HTML "<form>" for knowbase item
00527     *
00528     * @param $ID
00529     * @param $options array
00530     *     - target for the Form
00531     *
00532     * @return nothing (display the form)
00533    **/
00534    function showForm($ID, $options=array()) {
00535 
00536       // show kb item form
00537       if (!Session::haveRight("knowbase","w" )
00538           && !Session::haveRight("faq","w")) {
00539          return false;
00540       }
00541 
00542       $this->initForm($ID, $options);
00543       $canedit = $this->can($ID,'w');
00544       $canrecu = $this->can($ID,'recursive');
00545 
00546       if ($canedit) {
00547          // Load ticket solution
00548          if (empty($ID)
00549              && isset($options['item_itemtype']) && !empty($options['item_itemtype'])
00550              && isset($options['item_items_id']) && !empty($options['item_items_id'])) {
00551 
00552             if ($item = getItemForItemtype($options['item_itemtype'])) {
00553                if ($item->getFromDB($options['item_items_id'])) {
00554                   $this->fields['name']   = $item->getField('name');
00555                   $this->fields['answer'] = $item->getField('solution');
00556                   if ($item->isField('itilcategories_id')) {
00557                      $ic = new ItilCategory();
00558                      if ($ic->getFromDB($item->getField('itilcategories_id'))) {
00559                         $this->fields['knowbaseitemcategories_id']
00560                               = $ic->getField('knowbaseitemcategories_id');
00561                      }
00562                   }
00563                }
00564             }
00565          }
00566          echo "<div id='contenukb'>";
00567          Html::initEditorSystem('answer');
00568 
00569          echo "<form method='post' id='form_kb' name='form_kb' action=\"".$this->getFormUrl()."\">";
00570 
00571          if (!empty($ID)) {
00572             echo "<input type='hidden' name='id' value='$ID'>\n";
00573          }
00574 
00575          echo "<fieldset>";
00576          echo "<legend>".__('Category name')."</legend>";
00577          echo "<div class='center'>".__('Select a category for this item')."&nbsp;";
00578          KnowbaseItemCategory::dropdown(array('value' => $this->fields["knowbaseitemcategories_id"]));
00579          echo "</div></fieldset>";
00580 
00581          echo "<fieldset>";
00582          echo "<legend>".__('Subject')."</legend>";
00583          echo "<div class='center'>";
00584          echo "<textarea cols='80' rows='2' name='name'>".$this->fields["name"]."</textarea>";
00585          echo "</div></fieldset>";
00586 
00587          echo "<fieldset>";
00588          echo "<legend>".__('Content')."</legend>";
00589          echo "<div class='center spaced'>";
00590          echo "<textarea cols='80' rows='30' id='answer' name='answer'>".$this->fields["answer"];
00591          echo "</textarea></div></fieldset>";
00592 
00593 
00594          if (!empty($ID)) {
00595             echo "<fieldset>";
00596             echo "<legend></legend>";
00597             echo "<div class='baskb'>";
00598             if ($this->fields["users_id"]) {
00599                //TRANS: %s is the writer name
00600                printf(__('%1$s: %2$s'), __('Writer'), getUserName($this->fields["users_id"],"1"));
00601             }
00602 
00603             echo "<span class='baskb_right'>";
00604             if ($this->fields["date_mod"]) {
00605                //TRANS: %s is the datetime of update
00606                printf(__('Last update on %s'), Html::convDateTime($this->fields["date_mod"]));
00607             }
00608 
00609             echo "</span><br>";
00610 
00611             if ($this->fields["date"]) {
00612                //TRANS: %s is the datetime of insertion
00613                printf(__('Created on %s'), Html::convDateTime($this->fields["date"]));
00614             }
00615 
00616             echo "<span class='baskb_right'>";
00617             //TRANS: %d is the number of view
00618             printf(_n('%d view', '%d views', $this->fields["view"]),$this->fields["view"]);
00619             echo "</span></div>";
00620 
00621             echo "</fieldset>";
00622          }
00623 
00624          echo "<p class='center'>";
00625 
00626 //          if (Session::isMultiEntitiesMode()) {
00627 //             _e('Entity');
00628 //             Entity::dropdown(array('value'    => $this->fields["entities_id"],
00629 //                                    'comments' => 0 ));
00630 //             _e('Child entities: ');
00631 //             if ($canrecu) {
00632 //                Dropdown::showYesNo("is_recursive", $this->fields["is_recursive"]);
00633 //             } else {
00634 //                echo Dropdown::getYesNo($this->fields["is_recursive"]);
00635 //             }
00636 //          }
00637 //          echo "<br><br>" .
00638          echo __('Put this item in the FAQ')."&nbsp;";
00639 
00640          if (Session::haveRight("faq","w")
00641              && Session::haveRight("knowbase","w")) {
00642             Dropdown::showYesNo('is_faq', $this->fields["is_faq"]);
00643          } else {
00644             echo Dropdown::getYesNo($this->fields["is_faq"]);
00645          }
00646 
00647          echo "<br><br>";
00648          if ($ID > 0) {
00649             echo "<input type='submit' class='submit' name='update' value=\""._sx('button','Save')."\">";
00650          } else {
00651             echo "<input type='hidden' name='users_id' value=\"".Session::getLoginUserID()."\">";
00652             echo "<input type='submit' class='submit' name='add' value=\""._sx('button','Add')."\">";
00653          }
00654 
00655          echo "<span class='big_space'>";
00656          echo "<input type='reset' class='submit' value=\""._sx('button','Blank')."\"></span>";
00657          echo "</p>";
00658          Html::closeForm();
00659          echo "</div>";
00660          return true;
00661       }
00662       //  ELSE Cannot edit
00663       return false;
00664    } // function showForm
00665 
00666 
00667    /**
00668     * Add kb item to the public FAQ
00669     *
00670     * @return nothing
00671    **/
00672    function addToFaq() {
00673       global $DB;
00674 
00675       $DB->query("UPDATE `".$this->getTable()."`
00676                   SET `is_faq` = '1'
00677                   WHERE `id` = '".$this->fields['id']."'");
00678 
00679       if (isset($_SESSION['glpi_faqcategories'])) {
00680          unset($_SESSION['glpi_faqcategories']);
00681       }
00682    }
00683 
00684 
00685    /**
00686     * Print out an HTML Menu for knowbase item
00687     *
00688     * @return nothing (display the form)
00689    **/
00690    function showMenu() {
00691       global $CFG_GLPI;
00692 
00693       $ID = $this->fields['id'];
00694       if (!$this->can($ID,'r')
00695           || (Session::getLoginUserID() === false)) {
00696          return false;
00697       }
00698 
00699       $edit    = $this->can($ID, 'w');
00700       $isFAQ   = $this->fields["is_faq"];
00701       $editFAQ = Session::haveRight("faq", "w");
00702 
00703       echo "<table class='tab_cadre_fixe'><tr><th colspan='3'>";
00704       if ($isFAQ) {
00705          _e('This item is part of the FAQ');
00706       } else {
00707          _e('This item is not part of the FAQ');
00708       }
00709       echo "</th></tr>\n";
00710 
00711       if ($edit) {
00712          echo "<tr class='tab_bg_1'>";
00713          if ($editFAQ) {
00714             echo "<td class='center' width='33%'>";
00715             if ($isFAQ) {
00716                Html::showSimpleForm(static::getFormURL(), 'update',
00717                                     __('Delete this item from the FAQ'),
00718                                     array('id'     => $ID,
00719                                           'is_faq' => 0),
00720                                     $CFG_GLPI["root_doc"]."/pics/faqremove.png");
00721             } else  {
00722                Html::showSimpleForm(static::getFormURL(), 'update', __('Put this item in the FAQ'),
00723                                     array('id'     => $ID,
00724                                           'is_faq' => 1),
00725                                     $CFG_GLPI["root_doc"]."/pics/faqadd.png");
00726             }
00727             echo "</td>\n";
00728          }
00729          echo "<td class='center' width='34%'><a href=\"".
00730                $CFG_GLPI["root_doc"]."/front/knowbaseitem.form.php?id=$ID&amp;modify=yes\">";
00731          echo "<img src=\"".$CFG_GLPI["root_doc"]."/pics/faqedit.png\" alt=\"".__s('Edit').
00732                "\" title=\"".__s('Edit')."\"></a></td>\n";
00733          echo "<td class='center' width='33%'>";
00734          Html::showSimpleForm(static::getFormURL(), 'delete', _x('button', 'Delete permanently'),
00735                               array('id' => $ID), $CFG_GLPI["root_doc"]."/pics/faqdelete.png", '',
00736                               __("Are you sure you want to delete this item?"));
00737 
00738          echo "</td>";
00739          echo "</tr>";
00740       }
00741       echo "</table><br>";
00742    }
00743 
00744 
00745    /**
00746     * Increase the view counter of the current knowbaseitem
00747     *
00748     * @since version 0.83
00749     */
00750    function updateCounter() {
00751       global $DB;
00752 
00753       //update counter view
00754       $query = "UPDATE `glpi_knowbaseitems`
00755                 SET `view` = `view`+1
00756                 WHERE `id` = '".$this->getID()."'";
00757 
00758       $DB->query($query);
00759    }
00760 
00761 
00762    /**
00763     * Print out (html) show item : question and answer
00764     *
00765     * @param $linkusers_id       display users_id link (true by default)
00766     * @param $options      array of options
00767     *
00768     * @return nothing (display item : question and answer)
00769    **/
00770    function showFull($linkusers_id=true, $options=array()) {
00771       global $DB, $CFG_GLPI;
00772 
00773       if (!$this->can($this->fields['id'],'r')) {
00774          return false;
00775       }
00776 
00777       // show item : question and answer
00778       if (!Session::haveRight("user", "r")) {
00779          $linkusers_id = false;
00780       }
00781 
00782       $inpopup = strpos($_SERVER['PHP_SELF'],"popup.php");
00783 
00784       $this->updateCounter();
00785 
00786       $knowbaseitemcategories_id = $this->fields["knowbaseitemcategories_id"];
00787       $fullcategoryname          = getTreeValueCompleteName("glpi_knowbaseitemcategories",
00788                                                             $knowbaseitemcategories_id);
00789 
00790       if (!$inpopup) {
00791          $this->showTabs($options);
00792       }
00793       $options['colspan'] = 2;
00794       $options['canedit'] = 0; // Hide the buttons
00795       $this->showFormHeader($options);
00796 
00797       $tmp = "<a href='".$this->getSearchURL().
00798              "?knowbaseitemcategories_id=$knowbaseitemcategories_id'>".$fullcategoryname."</a>";
00799       echo "<tr class='tab_bg_3'><th colspan='4'>".sprintf(__('%1$s: %2$s'), __('Category'), $tmp);
00800       echo "</th></tr>";
00801 
00802       echo "<tr class='tab_bg_3'><td class='left' colspan='4'><h2>".__('Subject')."</h2>";
00803       echo $this->fields["name"];
00804 
00805       echo "</td></tr>";
00806       echo "<tr class='tab_bg_3'><td class='left' colspan='4'><h2>".__('Content')."</h2>\n";
00807 
00808       echo "<div id='kbanswer'>";
00809       echo Toolbox::unclean_html_cross_side_scripting_deep($this->fields["answer"]);
00810       echo "</div>";
00811       echo "</td></tr>";
00812 
00813       echo "<tr><th class='tdkb'  colspan='2'>";
00814       if ($this->fields["users_id"]) {
00815          // Integer because true may be 2 and getUserName return array
00816          if ($linkusers_id) {
00817             $linkusers_id = 1;
00818          } else {
00819             $linkusers_id = 0;
00820          }
00821 
00822          printf(__('%1$s: %2$s'), __('Writer'), getUserName($this->fields["users_id"],
00823                 $linkusers_id));
00824          echo "<br>";
00825       }
00826 
00827       if ($this->fields["date"]) {
00828          //TRANS: %s is the datetime of update
00829          printf(__('Created on %s'), Html::convDateTime($this->fields["date"]));
00830       }
00831 
00832       if ($this->countVisibilities() == 0) {
00833          echo "<br><span class='red'>".__('Unpublished')."</span>";
00834       }
00835       echo "</th>";
00836       echo "<th class='tdkb' colspan='2'>";
00837 
00838       if ($this->fields["date_mod"]) {
00839          //TRANS: %s is the datetime of update
00840          printf(__('Last update on %s'), Html::convDateTime($this->fields["date_mod"]));
00841          echo "<br>";
00842       }
00843       echo sprintf(_n('%d view', '%d views', $this->fields["view"]), $this->fields["view"]).
00844            "</th></tr>";
00845 
00846       $this->showFormButtons($options);
00847       if (!$inpopup) {
00848          $this->addDivForTabs();
00849       }
00850 
00851       return true;
00852    }
00853 
00854 
00855    /**
00856     * Print out an HTML form for Search knowbase item
00857     *
00858     * @param $options   $_GET
00859     *
00860     * @return nothing (display the form)
00861    **/
00862    function searchForm($options) {
00863       global $CFG_GLPI;
00864 
00865       if (!$CFG_GLPI["use_public_faq"]
00866           && !Session::haveRight("knowbase","r")
00867           && !Session::haveRight("faq","r")) {
00868          return false;
00869       }
00870 
00871       // Default values of parameters
00872       $params["contains"]                  = "";
00873       $params["target"]                    = $_SERVER['PHP_SELF'];
00874 
00875       if (is_array($options) && count($options)) {
00876          foreach ($options as $key => $val) {
00877             $params[$key] = $val;
00878          }
00879       }
00880 
00881       echo "<div>";
00882 
00883       echo "<form method='get' action='".$this->getSearchURL()."'>";
00884       echo "<table class='tab_cadre_fixe'>";
00885       echo "<tr class='tab_bg_2'><td class='right' width='50%'>";
00886       echo "<input type='text' size='50' name='contains' value=\"".
00887              stripslashes(Html::cleanInputText($params["contains"]))."\"></td>";
00888       echo "<td class='left'>";
00889       echo "<input type='submit' value=\""._sx('button','Search')."\" class='submit'></td></tr>";
00890       echo "</table>";
00891       if (isset($options['item_itemtype'])
00892           && isset($options['item_items_id'])) {
00893          echo "<input type='hidden' name='item_itemtype' value='".$options['item_itemtype']."'>";
00894          echo "<input type='hidden' name='item_items_id' value='".$options['item_items_id']."'>";
00895       }
00896       Html::closeForm();
00897 
00898       echo "</div>";
00899    }
00900 
00901 
00902    /**
00903     * Print out an HTML "<form>" for Search knowbase item
00904     *
00905     * @since version 0.84
00906     *
00907     * @param $options   $_GET
00908     *
00909     * @return nothing (display the form)
00910    **/
00911    function showBrowseForm($options) {
00912       global $CFG_GLPI;
00913 
00914       if (!$CFG_GLPI["use_public_faq"]
00915           && !Session::haveRight("knowbase","r")
00916           && !Session::haveRight("faq","r")) {
00917          return false;
00918       }
00919 
00920       // Default values of parameters
00921       $params["knowbaseitemcategories_id"] = "";
00922 
00923       if (is_array($options) && count($options)) {
00924          foreach ($options as $key => $val) {
00925             $params[$key] = $val;
00926          }
00927       }
00928       $faq = !Session::haveRight("knowbase","r");
00929 
00930       // Category select not for anonymous FAQ
00931       if (Session::getLoginUserID()
00932           && !$faq) {
00933          echo "<div>";
00934          echo "<form method='get' action='".$this->getSearchURL()."'>";
00935          echo "<table class='tab_cadre_fixe'>";
00936          echo "<tr class='tab_bg_2'><td class='right' width='50%'>".__('Category')."&nbsp;";
00937          KnowbaseItemCategory::dropdown(array('value' => $params["knowbaseitemcategories_id"]));
00938          echo "</td><td class='left'>";
00939          echo "<input type='submit' value=\""._sx('button','Post')."\" class='submit'></td>";
00940          echo "</tr></table>";
00941          if (isset($options['item_itemtype'])
00942              && isset($options['item_items_id'])) {
00943             echo "<input type='hidden' name='item_itemtype' value='".$options['item_itemtype']."'>";
00944             echo "<input type='hidden' name='item_items_id' value='".$options['item_items_id']."'>";
00945          }
00946          Html::closeForm();
00947          echo "</div>";
00948       }
00949    }
00950 
00951 
00952    /**
00953     * Print out an HTML form for Search knowbase item
00954     *
00955     * @since version 0.84
00956     *
00957     * @param $options   $_GET
00958     *
00959     * @return nothing (display the form)
00960    **/
00961    function showManageForm($options) {
00962       global $CFG_GLPI;
00963 
00964       if (!Session::haveRight("knowbase","w")
00965           && !Session::haveRight("faq","w")) {
00966          return false;
00967       }
00968       $params['unpublished'] = 'my';
00969       if (is_array($options) && count($options)) {
00970          foreach ($options as $key => $val) {
00971             $params[$key] = $val;
00972          }
00973       }
00974 
00975       $faq = !Session::haveRight("knowbase","w");
00976 
00977       echo "<div>";
00978       echo "<form method='get' action='".$this->getSearchURL()."'>";
00979       echo "<table class='tab_cadre_fixe'>";
00980       echo "<tr class='tab_bg_2'><td class='right' width='50%'>";
00981       $values = array('myunpublished' => __('My unpublished articles'),
00982                       'allmy'         => __('All my articles'));
00983       if (Session::haveRight('knowbase_admin', '1')) {
00984          $values['allunpublished'] = __('All unpublished articles');
00985       }
00986       Dropdown::showFromArray('unpublished', $values, array('value' => $params['unpublished']));
00987       echo "</td><td class='left'>";
00988       echo "<input type='submit' value=\""._sx('button','Post')."\" class='submit'></td>";
00989       echo "</tr></table>";
00990       Html::closeForm();
00991       echo "</div>";
00992    }
00993 
00994 
00995    /**
00996     * Build request for showList
00997     *
00998     * @since version 0.83
00999     *
01000     * @param $params array  (contains, knowbaseitemcategories_id, faq)
01001     * @param $type   string search type : browse / search (default search)
01002     *
01003     * @return String : SQL request
01004    **/
01005    static function getListRequest(array $params, $type='search') {
01006       global $DB;
01007 
01008       // Lists kb Items
01009       $where = "";
01010       $order = "";
01011       $score = "";
01012       $join  = self::addVisibilityJoins(true);
01013 
01014       switch ($type) {
01015          case 'myunpublished' :
01016             break;
01017 
01018          case 'allmy' :
01019             break;
01020 
01021          case 'allunpublished' :
01022             break;
01023 
01024          default :
01025             // Build query
01026             if (Session::getLoginUserID() && $type != 'myunpublished') {
01027                $where = self::addVisibilityRestrict()." AND ";
01028             } else {
01029                // Anonymous access
01030                if (Session::isMultiEntitiesMode()) {
01031                   $where = " (`glpi_entities_knowbaseitems`.`entities_id` = '0'
01032                               AND `glpi_entities_knowbaseitems`.`is_recursive` = '1')
01033                            AND ";
01034                }
01035             }
01036             break;
01037       }
01038 
01039       if ($params['faq']) { // helpdesk
01040          $where .= " (`glpi_knowbaseitems`.`is_faq` = '1')
01041                       AND ";
01042       }
01043 
01044       // a search with $contains
01045       switch ($type) {
01046          case 'allmy' :
01047             $where .= "`glpi_knowbaseitems`.`users_id` = '".Session::getLoginUserID()."'";
01048             break;
01049 
01050          case 'myunpublished' :
01051             $where .= "`glpi_knowbaseitems`.`users_id` = '".Session::getLoginUserID()."'
01052                         AND (`glpi_entities_knowbaseitems`.`entities_id` IS NULL
01053                               AND `glpi_knowbaseitems_profiles`.`profiles_id` IS NULL
01054                               AND `glpi_groups_knowbaseitems`.`groups_id` IS NULL
01055                               AND `glpi_knowbaseitems_users`.`users_id` IS NULL)";
01056             break;
01057 
01058          case 'allunpublished' :
01059             // Only published
01060             $where .= "(`glpi_entities_knowbaseitems`.`entities_id` IS NULL
01061                               AND `glpi_knowbaseitems_profiles`.`profiles_id` IS NULL
01062                               AND `glpi_groups_knowbaseitems`.`groups_id` IS NULL
01063                               AND `glpi_knowbaseitems_users`.`users_id` IS NULL)";
01064             break;
01065 
01066          case 'search' :
01067             if (strlen($params["contains"]) > 0) {
01068                $search  = Toolbox::unclean_cross_side_scripting_deep($params["contains"]);
01069 
01070                $score   = " ,MATCH(`glpi_knowbaseitems`.`name`, `glpi_knowbaseitems`.`answer`)
01071                            AGAINST('$search' IN BOOLEAN MODE) AS SCORE ";
01072 
01073                $where_1 = $where." MATCH(`glpi_knowbaseitems`.`name`, `glpi_knowbaseitems`.`answer`)
01074                           AGAINST('$search' IN BOOLEAN MODE) ";
01075 
01076                $order   = "ORDER BY `SCORE` DESC";
01077 
01078                // preliminar query to allow alternate search if no result with fulltext
01079                $query_1   = "SELECT COUNT(`glpi_knowbaseitems`.`id`)
01080                              FROM `glpi_knowbaseitems`
01081                              $join
01082                              WHERE $where_1";
01083                $result_1  = $DB->query($query_1);
01084                $numrows_1 = $DB->result($result_1,0,0);
01085 
01086                if ($numrows_1 <= 0) {// not result this fulltext try with alternate search
01087                   $search1 = array(/* 1 */   '/\\\"/',
01088                                    /* 2 */   "/\+/",
01089                                    /* 3 */   "/\*/",
01090                                    /* 4 */   "/~/",
01091                                    /* 5 */   "/</",
01092                                    /* 6 */   "/>/",
01093                                    /* 7 */   "/\(/",
01094                                    /* 8 */   "/\)/",
01095                                    /* 9 */   "/\-/");
01096                   $contains = preg_replace($search1,"", $params["contains"]);
01097                   $where   .= " (`glpi_knowbaseitems`.`name` ".Search::makeTextSearch($contains)."
01098                                  OR `glpi_knowbaseitems`.`answer` ".Search::makeTextSearch($contains).")";
01099                } else {
01100                   $where = $where_1;
01101                }
01102             }
01103             break;
01104 
01105          case 'browse' :
01106             $where .= " (`glpi_knowbaseitems`.`knowbaseitemcategories_id`
01107                            = '".$params["knowbaseitemcategories_id"]."')";
01108             $order  = " ORDER BY `glpi_knowbaseitems`.`name` ASC";
01109             break;
01110       }
01111 
01112       $query = "SELECT DISTINCT `glpi_knowbaseitems`.*,
01113                        `glpi_knowbaseitemcategories`.`completename` AS category
01114                        $score
01115                 FROM `glpi_knowbaseitems`
01116                 $join
01117                 LEFT JOIN `glpi_knowbaseitemcategories`
01118                      ON (`glpi_knowbaseitemcategories`.`id`
01119                            = `glpi_knowbaseitems`.`knowbaseitemcategories_id`)
01120                 WHERE $where
01121                 $order";
01122 
01123       return $query;
01124    }
01125 
01126 
01127    /**
01128     * Print out list kb item
01129     *
01130     * @param $options            $_GET
01131     * @param $type      string   search type : browse / search (default search)
01132    **/
01133    static function showList($options, $type='search') {
01134       global $DB, $CFG_GLPI;
01135 
01136       // Default values of parameters
01137       $params['faq']                       = !Session::haveRight("knowbase","r");
01138       $params["start"]                     = "0";
01139       $params["knowbaseitemcategories_id"] = "0";
01140       $params["contains"]                  = "";
01141       $params["target"]                    = $_SERVER['PHP_SELF'];
01142 
01143       if (is_array($options) && count($options)) {
01144          foreach ($options as $key => $val) {
01145             $params[$key] = $val;
01146          }
01147       }
01148       $ki = new self();
01149       switch ($type) {
01150          case 'myunpublished' :
01151             if (!Session::haveRight('knowbase','w') && !Session::haveRight('faq','w')) {
01152                return false;
01153             }
01154             break;
01155 
01156          case 'allunpublished' :
01157             if (!Session::haveRight('knowbase_admin',1)) {
01158                return false;
01159             }
01160             break;
01161 
01162          default :
01163             break;
01164       }
01165 
01166       if (!$params["start"]) {
01167          $params["start"] = 0;
01168       }
01169 
01170       $query = self::getListRequest($params, $type);
01171 
01172       // Get it from database
01173       if ($result = $DB->query($query)) {
01174          $KbCategory = new KnowbaseItemCategory();
01175          $title      = "";
01176          if ($KbCategory->getFromDB($params["knowbaseitemcategories_id"])) {
01177             $title = (empty($KbCategory->fields['name']) ?"(".$params['knowbaseitemcategories_id'].")"
01178                                                          : $KbCategory->fields['name']);
01179             $title = sprintf(__('%1$s: %2$s'), __('Category'), $title);
01180          }
01181 
01182          Session::initNavigateListItems('KnowbaseItem', $title);
01183 
01184          $numrows    = $DB->numrows($result);
01185          $list_limit = $_SESSION['glpilist_limit'];
01186 
01187          $showwriter = in_array($type, array('myunpublished', 'allunpublished', 'allmy'));
01188 
01189          // Limit the result, if no limit applies, use prior result
01190          if (($numrows > $list_limit)
01191              && !isset($_GET['export_all'])) {
01192             $query_limit   = $query ." LIMIT ".intval($params["start"]).", ".intval($list_limit)." ";
01193             $result_limit  = $DB->query($query_limit);
01194             $numrows_limit = $DB->numrows($result_limit);
01195 
01196          } else {
01197             $numrows_limit = $numrows;
01198             $result_limit  = $result;
01199          }
01200 
01201          if ($numrows_limit > 0) {
01202             // Set display type for export if define
01203             $output_type = Search::HTML_OUTPUT;
01204 
01205             if (isset($_GET["display_type"])) {
01206                $output_type = $_GET["display_type"];
01207             }
01208 
01209             // Pager
01210             $parameters = "start=".$params["start"]."&amp;knowbaseitemcategories_id=".
01211                           $params['knowbaseitemcategories_id']."&amp;contains=".
01212                           $params["contains"]."&amp;is_faq=".$params['faq'];
01213 
01214             if (isset($options['item_itemtype'])
01215                 && isset($options['item_items_id'])) {
01216                $parameters .= "&amp;item_items_id=".$options['item_items_id']."&amp;item_itemtype=".
01217                                $options['item_itemtype'];
01218             }
01219 
01220             if ($output_type == Search::HTML_OUTPUT) {
01221                Html::printPager($params['start'], $numrows,
01222                                 Toolbox::getItemTypeSearchURL('KnowbaseItem'), $parameters,
01223                                 'KnowbaseItem');
01224             }
01225 
01226             $nbcols = 1;
01227             // Display List Header
01228             echo Search::showHeader($output_type, $numrows_limit+1, $nbcols);
01229 
01230             $header_num = 1;
01231             echo Search::showHeaderItem($output_type, __('Subject'), $header_num);
01232 
01233             if ($output_type != Search::HTML_OUTPUT) {
01234                echo Search::showHeaderItem($output_type, __('Content'), $header_num);
01235             }
01236 
01237             if ($showwriter) {
01238                echo Search::showHeaderItem($output_type, __('Writer'), $header_num);
01239             }
01240             echo Search::showHeaderItem($output_type, __('Category'), $header_num);
01241 
01242             if (isset($options['item_itemtype'])
01243                 && isset($options['item_items_id'])
01244                 && ($output_type == Search::HTML_OUTPUT)) {
01245                echo Search::showHeaderItem($output_type, '&nbsp;', $header_num);
01246             }
01247 
01248             // Num of the row (1=header_line)
01249             $row_num = 1;
01250             for ($i=0 ; $i<$numrows_limit ; $i++) {
01251                $data = $DB->fetch_assoc($result_limit);
01252 
01253                Session::addToNavigateListItems('KnowbaseItem', $data["id"]);
01254                // Column num
01255                $item_num = 1;
01256                $row_num++;
01257                echo Search::showNewLine($output_type, $i%2);
01258 
01259                if ($output_type == Search::HTML_OUTPUT) {
01260                   if (isset($options['item_itemtype'])
01261                       && isset($options['item_items_id'])) {
01262                      $href = " href='#' onClick=\"var w = window.open('".$CFG_GLPI["root_doc"].
01263                               "/front/popup.php?popup=show_kb&amp;id=".$data['id']."' ,'glpipopup', ".
01264                               "'height=400, width=1000, top=100, left=100, scrollbars=yes' );".
01265                               "w.focus();\"" ;
01266                   } else {
01267                      $href = " href=\"".$CFG_GLPI['root_doc']."/front/knowbaseitem.form.php?id=".
01268                                     $data["id"]."\" ";
01269                   }
01270 
01271                   echo Search::showItem($output_type,
01272                                         "<div class='kb'><a ".
01273                                           ($data['is_faq']?" class='pubfaq' ":" class='knowbase' ").
01274                                           " $href>".Html::resume_text($data["name"], 80)."</a></div>
01275                                           <div class='kb_resume'>".
01276                                           Html::resume_text(Html::clean(Toolbox::unclean_cross_side_scripting_deep($data["answer"])),
01277                                                             600)."</div>",
01278                                         $item_num, $row_num);
01279                } else {
01280                   echo Search::showItem($output_type, $data["name"], $item_num, $row_num);
01281                   echo Search::showItem($output_type,
01282                      Html::clean(Toolbox::unclean_cross_side_scripting_deep(html_entity_decode($data["answer"],
01283                                                                                                ENT_QUOTES,
01284                                                                                                "UTF-8"))),
01285                                 $item_num, $row_num);
01286                }
01287 
01288                if ($showwriter) {
01289                   echo Search::showItem($output_type, getUserName($data["users_id"], 1), $item_num, $row_num);
01290                }
01291 
01292                $categ = $data["category"];
01293                if ($output_type == Search::HTML_OUTPUT) {
01294                   $cathref = $ki->getSearchURL()."?knowbaseitemcategories_id=".
01295                               $data["knowbaseitemcategories_id"].'&amp;forcetab=Knowbase$2';
01296                   $categ   = "<a href='$cathref'>".$categ.'</a>';
01297                }
01298                echo Search::showItem($output_type, $categ, $item_num, $row_num);
01299 
01300 
01301                if (isset($options['item_itemtype'])
01302                    && isset($options['item_items_id'])
01303                    && ($output_type == Search::HTML_OUTPUT)) {
01304 
01305                   $content = "<a href='".Toolbox::getItemTypeFormURL($options['item_itemtype']).
01306                                "?load_kb_sol=".$data['id']."&amp;id=".$options['item_items_id'].
01307                                "&amp;forcetab=".$options['item_itemtype']."$2'>".
01308                                __('Use as a solution')."</a>";
01309                   echo Search::showItem($output_type, $content, $item_num, $row_num);
01310                }
01311 
01312 
01313                // End Line
01314                echo Search::showEndLine($output_type);
01315             }
01316 
01317             // Display footer
01318             if (($output_type == Search::PDF_OUTPUT_LANDSCAPE)
01319                 || ($output_type == Search::PDF_OUTPUT_PORTRAIT)) {
01320                echo Search::showFooter($output_type,
01321                                        Dropdown::getDropdownName("glpi_knowbaseitemcategories",
01322                                                                  $params['knowbaseitemcategories_id']));
01323             } else {
01324                echo Search::showFooter($output_type);
01325             }
01326             echo "<br>";
01327             if ($output_type == Search::HTML_OUTPUT) {
01328                Html::printPager($params['start'], $numrows,
01329                                 Toolbox::getItemTypeSearchURL('KnowbaseItem'), $parameters,
01330                                 'KnowbaseItem');
01331             }
01332 
01333          } else {
01334             echo "<div class='center b'>".__('No item found')."</div>";
01335          }
01336       }
01337    }
01338 
01339 
01340    /**
01341     * Print out list recent or popular kb/faq
01342     *
01343     * @param $type      type : recent / popular / not published
01344     *
01345     * @return nothing (display table)
01346    **/
01347    static function showRecentPopular($type) {
01348       global $DB, $CFG_GLPI;
01349 
01350       $faq = !Session::haveRight("knowbase","r");
01351 
01352       if ($type == "recent") {
01353          $orderby = "ORDER BY `date` DESC";
01354          $title   = __('Recent entries');
01355       } else if ($type == 'lastupdate') {
01356          $orderby = "ORDER BY `date_mod` DESC";
01357          $title   = __('Last updated entries');
01358       } else {
01359          $orderby = "ORDER BY `view` DESC";
01360          $title   = __('Most popular questions');
01361       }
01362 
01363       $faq_limit = "";
01364       // Force all joins for not published to verify no visibility set
01365       $join = self::addVisibilityJoins(true);
01366 
01367       if (Session::getLoginUserID()) {
01368          $faq_limit .= "WHERE ".self::addVisibilityRestrict();
01369       } else {
01370          // Anonymous access
01371          if (Session::isMultiEntitiesMode()) {
01372             $faq_limit .= " WHERE (`glpi_entities_knowbaseitems`.`entities_id` = '0'
01373                                    AND `glpi_entities_knowbaseitems`.`is_recursive` = '1')";
01374          } else {
01375             $faq_limit .= " WHERE 1";
01376          }
01377       }
01378 
01379 
01380       // Only published
01381       $faq_limit .= " AND (`glpi_entities_knowbaseitems`.`entities_id` IS NOT NULL
01382                            OR `glpi_knowbaseitems_profiles`.`profiles_id` IS NOT NULL
01383                            OR `glpi_groups_knowbaseitems`.`groups_id` IS NOT NULL
01384                            OR `glpi_knowbaseitems_users`.`users_id` IS NOT NULL)";
01385 
01386       if ($faq) { // FAQ
01387          $faq_limit .= " AND (`glpi_knowbaseitems`.`is_faq` = '1')";
01388       }
01389 
01390       $query = "SELECT DISTINCT `glpi_knowbaseitems`.*
01391                 FROM `glpi_knowbaseitems`
01392                 $join
01393                 $faq_limit
01394                 $orderby
01395                 LIMIT 10";
01396 
01397       $result = $DB->query($query);
01398       $number = $DB->numrows($result);
01399 
01400       if ($number > 0) {
01401          echo "<table class='tab_cadrehov'>";
01402          echo "<tr><th>".$title."</th></tr>";
01403          while ($data = $DB->fetch_assoc($result)) {
01404             echo "<tr class='tab_bg_2'><td class='left'>";
01405             echo "<a ".($data['is_faq']?" class='pubfaq' ":" class='knowbase' ")." href=\"".
01406                   $CFG_GLPI["root_doc"]."/front/knowbaseitem.form.php?id=".$data["id"]."\">".
01407                   Html::resume_text($data["name"],80)."</a></td></tr>";
01408          }
01409          echo "</table>";
01410       }
01411    }
01412 
01413 
01414 
01415    function getSearchOptions() {
01416 
01417       $tab                      = array();
01418       $tab['common']            = __('Characteristics');
01419 
01420       $tab[2]['table']          = $this->getTable();
01421       $tab[2]['field']          = 'id';
01422       $tab[2]['name']           = __('ID');
01423       $tab[2]['massiveaction']  = false;
01424       $tab[2]['datatype']       = 'number';
01425 
01426       $tab[4]['table']          = 'glpi_knowbaseitemcategories';
01427       $tab[4]['field']          = 'name';
01428       $tab[4]['name']           = __('Category');
01429       $tab[4]['datatype']       = 'dropdown';
01430 
01431       $tab[5]['table']          = $this->getTable();
01432       $tab[5]['field']          = 'date';
01433       $tab[5]['name']           = __('Date');
01434       $tab[5]['datatype']       = 'datetime';
01435       $tab[5]['massiveaction']  = false;
01436 
01437       $tab[6]['table']          = $this->getTable();
01438       $tab[6]['field']          = 'name';
01439       $tab[6]['name']           = __('Subject');
01440       $tab[6]['datatype']       = 'text';
01441 
01442       $tab[7]['table']          = $this->getTable();
01443       $tab[7]['field']          = 'answer';
01444       $tab[7]['name']           = __('Content');
01445       $tab[7]['datatype']       = 'text';
01446       $tab[7]['htmltext']       = true;
01447 
01448       $tab[8]['table']          = $this->getTable();
01449       $tab[8]['field']          = 'is_faq';
01450       $tab[8]['name']           = __('FAQ item');
01451       $tab[8]['datatype']       = 'bool';
01452 
01453       $tab[9]['table']          = $this->getTable();
01454       $tab[9]['field']          = 'view';
01455       $tab[9]['name']           = _n('View', 'Views', 2);
01456       $tab[9]['datatype']       = 'integer';
01457       $tab[9]['massiveaction']  = false;
01458 
01459       $tab[19]['table']         = $this->getTable();
01460       $tab[19]['field']         = 'date_mod';
01461       $tab[19]['name']          = __('Last update');
01462       $tab[19]['datatype']      = 'datetime';
01463       $tab[19]['massiveaction'] = false;
01464 
01465       $tab[70]['table']         = 'glpi_users';
01466       $tab[70]['field']         = 'name';
01467       $tab[70]['name']          = __('User');
01468       $tab[70]['massiveaction'] = false;
01469       $tab[70]['datatype']      = 'dropdown';
01470       $tab[70]['right']         = 'all';
01471 
01472       $tab[80]['table']         = 'glpi_entities';
01473       $tab[80]['field']         = 'completename';
01474       $tab[80]['name']          = __('Entity');
01475       $tab[80]['massiveaction'] = false;
01476       $tab[80]['datatype']      = 'dropdown';
01477 
01478       $tab[86]['table']         = $this->getTable();
01479       $tab[86]['field']         = 'is_recursive';
01480       $tab[86]['name']          = __('Child entities');
01481       $tab[86]['datatype']      = 'bool';
01482 
01483       return $tab;
01484    }
01485 
01486 
01487    /**
01488     * Show visibility config for a knowbaseitem
01489     *
01490     * @since version 0.83
01491    **/
01492    function showVisibility() {
01493       global $DB, $CFG_GLPI;
01494 
01495       $ID      = $this->fields['id'];
01496       $canedit = $this->can($ID,'w');
01497 
01498       echo "<div class='center'>";
01499 
01500       $rand = mt_rand();
01501       $nb   = count($this->users) + count($this->groups) + count($this->profiles)
01502               + count($this->entities);
01503 
01504       if ($canedit) {
01505          echo "<div class='firstbloc'>";
01506          echo "<form name='knowbaseitemvisibility_form$rand' id='knowbaseitemvisibility_form$rand' ";
01507          echo " method='post' action='".Toolbox::getItemTypeFormURL('KnowbaseItem')."'>";
01508          echo "<input type='hidden' name='knowbaseitems_id' value='$ID'>";
01509          echo "<table class='tab_cadre_fixe'>";
01510          echo "<tr class='tab_bg_1'><th colspan='4'>".__('Add a target')."</th></tr>";
01511          echo "<tr class='tab_bg_2'><td width='100px'>";
01512 
01513          $types = array('Entity', 'Group', 'Profile', 'User');
01514 
01515          $addrand = Dropdown::showItemTypes('_type', $types);
01516          $params  = array('type'  => '__VALUE__',
01517                           'right' => ($this->getfield('is_faq') ? 'faq' : 'knowbase'));
01518 
01519          Ajax::updateItemOnSelectEvent("dropdown__type".$addrand,"visibility$rand",
01520                                        $CFG_GLPI["root_doc"]."/ajax/visibility.php",
01521                                        $params);
01522 
01523          echo "</td>";
01524          echo "<td><span id='visibility$rand'></span>";
01525          echo "</td></tr>";
01526          echo "</table>";
01527          Html::closeForm();
01528          echo "</div>";
01529       }
01530 
01531 
01532       echo "<div class='spaced'>";
01533       if ($canedit && $nb) {
01534          Html::openMassiveActionsForm('mass'.__CLASS__.$rand);
01535          $paramsma = array('num_displayed'
01536                               => $nb,
01537                            'specific_actions'
01538                               => array('deletevisibility' => _x('button', 'Delete permanently')) );
01539 
01540          if ($this->fields['users_id'] != Session::getLoginUserID()) {
01541             $paramsma['confirm']
01542                = __('Caution! You are not the author of this element. Delete targets can result in loss of access to that element.');
01543          }
01544          Html::showMassiveActions(__CLASS__, $paramsma);
01545       }
01546       echo "<table class='tab_cadre_fixehov'>";
01547       echo "<tr>";
01548       if ($canedit && $nb) {
01549          echo "<th width='10'>";
01550          echo Html::checkAllAsCheckbox('mass'.__CLASS__.$rand);
01551          echo "</th>";
01552       }
01553       echo "<th>".__('Type')."</th>";
01554       echo "<th>"._n('Recipient', 'Recipients', 2)."</th>";
01555       echo "</tr>";
01556 
01557       // Users
01558       if (count($this->users)) {
01559          foreach ($this->users as $key => $val) {
01560             foreach ($val as $data) {
01561                echo "<tr class='tab_bg_1'>";
01562                if ($canedit) {
01563                   echo "<td>";
01564                   echo "<input type='checkbox' name='item[KnowbaseItem_User][".$data["id"]."]'
01565                          value='1'>";
01566                   echo "</td>";
01567                }
01568                echo "<td>".__('User')."</td>";
01569                echo "<td>".getUserName($data['users_id'])."</td>";
01570                echo "</tr>";
01571             }
01572          }
01573       }
01574 
01575       // Groups
01576       if (count($this->groups)) {
01577          foreach ($this->groups as $key => $val) {
01578             foreach ($val as $data) {
01579                echo "<tr class='tab_bg_1'>";
01580                if ($canedit) {
01581                   echo "<td>";
01582                   echo "<input type='checkbox' name='item[Group_KnowbaseItem][".$data["id"]."]'
01583                          value='1'>";
01584                   echo "</td>";
01585                }
01586                echo "<td>".__('Group')."</td>";
01587                echo "<td>";
01588                $names     = Dropdown::getDropdownName('glpi_groups', $data['groups_id'],1);
01589                $groupname = sprintf(__('%1$s %2$s'), $names["name"],
01590                                     Html::showToolTip($names["comment"], array('display' => false)));
01591                if ($data['entities_id'] >= 0) {
01592                   $groupname = sprintf(__('%1$s / %2$s'), $groupname,
01593                                        Dropdown::getDropdownName('glpi_entities',
01594                                                                  $data['entities_id']));
01595                   if ($data['is_recursive']) {
01596                      $groupname = sprintf(__('%1$s %2$s'), $groupname,
01597                                           "<span class='b'>(".__('R').")</span>");
01598                   }
01599                }
01600                echo $groupname;
01601                echo "</td>";
01602                echo "</tr>";
01603             }
01604          }
01605       }
01606 
01607       // Entity
01608       if (count($this->entities)) {
01609          foreach ($this->entities as $key => $val) {
01610             foreach ($val as $data) {
01611                echo "<tr class='tab_bg_1'>";
01612                if ($canedit) {
01613                   echo "<td>";
01614                   echo "<input type='checkbox' name='item[Entity_KnowbaseItem][".$data["id"]."]'
01615                          value='1'>";
01616                   echo "</td>";
01617                }
01618                echo "<td>".__('Entity')."</td>";
01619                echo "<td>";
01620                $names      = Dropdown::getDropdownName('glpi_entities', $data['entities_id'],1);
01621                $entityname = sprintf(__('%1$s %2$s'), $names["name"],
01622                                     Html::showToolTip($names["comment"], array('display' => false)));
01623                if ($data['is_recursive']) {
01624                   $entityname = sprintf(__('%1$s %2$s'), $entityname,
01625                                         "<span class='b'>(".__('R').")</span>");
01626                }
01627                echo $entityname;
01628                echo "</td>";
01629                echo "</tr>";
01630             }
01631          }
01632       }
01633 
01634       // Profiles
01635       if (count($this->profiles)) {
01636          foreach ($this->profiles as $key => $val) {
01637             foreach ($val as $data) {
01638                echo "<tr class='tab_bg_1'>";
01639                if ($canedit) {
01640                   echo "<td>";
01641                   echo "<input type='checkbox' name='item[KnowbaseItem_Profile][".$data["id"]."]'
01642                          value='1'>";
01643                   echo "</td>";
01644                }
01645                echo "<td>"._n('Profile', 'Profiles', 1)."</td>";
01646                echo "<td>";
01647                $names       = Dropdown::getDropdownName('glpi_profiles', $data['profiles_id'], 1);
01648                $profilename = sprintf(__('%1$s %2$s'), $names["name"],
01649                                     Html::showToolTip($names["comment"], array('display' => false)));
01650                if ($data['entities_id'] >= 0) {
01651                   $profilename = sprintf(__('%1$s / %2$s'), $profilename,
01652                                        Dropdown::getDropdownName('glpi_entities',
01653                                                                  $data['entities_id']));
01654                   if ($data['is_recursive']) {
01655                      $profilename = sprintf(__('%1$s %2$s'), $profilename,
01656                                         "<span class='b'>(".__('R').")</span>");
01657                   }
01658                }
01659                echo $profilename;
01660                echo "</td>";
01661                echo "</tr>";
01662             }
01663          }
01664       }
01665 
01666       echo "</table>";
01667       if ($canedit && $nb) {
01668          $paramsma['ontop'] =false;
01669          Html::showMassiveActions(__CLASS__, $paramsma);
01670          Html::closeForm();
01671       }
01672 
01673       echo "</div>";
01674       // Add items
01675 
01676       return true;
01677    }
01678 
01679 
01680 }
01681 ?>