savedsearch_alert.class.php 12.8 KB
Newer Older
1 2 3 4
<?php
/**
 * ---------------------------------------------------------------------
 * GLPI - Gestionnaire Libre de Parc Informatique
5
 * Copyright (C) 2015-2018 Teclib' and contributors.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 *
 * http://glpi-project.org
 *
 * based on GLPI - Gestionnaire Libre de Parc Informatique
 * Copyright (C) 2003-2014 by the INDEPNET Development Team.
 *
 * ---------------------------------------------------------------------
 *
 * LICENSE
 *
 * This file is part of GLPI.
 *
 * GLPI is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GLPI is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GLPI. If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------
 */

if (!defined('GLPI_ROOT')) {
   die("Sorry. You can't access this file directly");
}

/**
 * Saved search alerts
**/
class SavedSearch_Alert extends CommonDBChild {

   // From CommonDBChild
   static public $itemtype = 'SavedSearch';
   static public $items_id = 'savedsearches_id';
45
   public $dohistory       = true;
46
   protected $displaylist  = false;
47 48 49 50 51 52 53 54

   const OP_LESS     = 0;
   const OP_LESSEQ   = 1;
   const OP_EQ       = 2;
   const OP_NOT      = 3;
   const OP_GREATEQ  = 4;
   const OP_GREAT    = 5;

55
   static function getTypeName($nb = 0) {
56 57 58 59
      return _n('Saved search alert', 'Saved searches alerts', $nb);
   }


60
   function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

      // can exists for template
      if (($item->getType() == 'SavedSearch')
          && SavedSearch::canView()) {
         $nb = 0;
         if ($_SESSION['glpishow_count_on_tabs']) {
            $nb = countElementsInTable($this->getTable(),
                                       ['savedsearches_id' => $item->getID()]);
         }
         return self::createTabEntry(self::getTypeName(Session::getPluralNumber()), $nb);
      }
      return '';
   }


76
   static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
77 78 79 80 81
      self::showForSavedSearch($item, $withtemplate);
      return true;
   }


82
   function defineTabs($options = []) {
83

84
      $ong = [];
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
      $this->addDefaultFormTab($ong);
      $this->addStandardTab('Log', $ong, $options);

      return $ong;
   }


   /**
    * Print the form
    *
    * @param integer $ID      integer ID of the item
    * @param array   $options array
    *     - target for the Form
    *     - computers_id ID of the computer for add process
    *
    * @return true if displayed  false if item not found or not right to display
   **/
102
   function showForm($ID, $options = []) {
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

      /*if (!Session::haveRight("savedsearch", UPDATE)) {
         return false;
      }*/

      $search = new SavedSearch();
      if ($ID > 0) {
         $this->check($ID, READ);
         $search->getFromDB($this->fields['savedsearches_id']);
      } else {
         $this->check(-1, CREATE, $options);
         $search->getFromDB($options['savedsearches_id']);
      }

      $count = null;
      try {
         if ($data = $search->execute()) {
            $count = $data['data']['totalcount'];
         }
      } catch (\RuntimeException $e) {
123
         Toolbox::logError($e);
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
         $pass = true;
      }

      $this->showFormHeader($options);

      if ($this->isNewID($ID)) {
         echo Html::hidden('savedsearches_id', ['value' => $options['savedsearches_id']]);
      }

      echo "<tr class='tab_bg_1'>";
      echo "<td>" . __('Saved search') ."</td>";
      echo "<td>";
      echo $search->getLink();
      if ($count !== null) {
         echo "<span class='primary-bg primary-fg count nofloat'>$count</span></a>";
      }
      echo "</td>";
      echo "<td>".__('Name')."</td>";
      echo "<td>";
      Html::autocompletionTextField($this, "name");
      echo "</td></tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td>";
      echo __('Operator');
      echo Html::showToolTip(__('Compare number of results the search returns against the specified value with selected operator'));
      echo "</td>";
      echo "<td>";
      Dropdown::showFromArray(
         'operator',
         $this->getOperators(),
155
         ['value' => $this->getField('operator')]
156 157 158 159 160 161 162 163 164 165 166
      );
      echo "</td><td>".__('Value')."</td>";
      echo "<td>";
      echo "<input type='number' min='0' name='value' value='" .$this->getField('value') . "' required='required'/>";
      echo "</td></tr>";

      echo "<tr class='tab_bg_1'>";
      echo "<td>" . __('Active') . "</td>";
      echo "<td>";
      Dropdown::showYesNo('is_active', $this->getField('is_active'));
      echo "</td>";
amma35's avatar
amma35 committed
167 168
      echo "<td colspan='2'></td>";
      echo "</tr>";
169 170 171 172 173 174 175 176 177 178 179 180 181 182
      $this->showFormButtons($options);

      return true;
   }


   /**
    * Print the searches alerts
    *
    * @param SavedSearch $search       Object instance
    * @param boolean     $withtemplate Template or basic item (default '')
    *
    * @return void
   **/
183
   static function showForSavedSearch(SavedSearch $search, $withtemplate = 0) {
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
      global $DB;

      $ID = $search->getID();

      if (!$search->getFromDB($ID)
          || !$search->can($ID, READ)) {
         return false;
      }
      $canedit = $search->canEdit($ID);

      echo "<div class='center'>";

      echo "<div class='firstbloc'>";

      $iterator = $DB->request([
         'FROM'   => Notification::getTable(),
         'WHERE'  => [
            'itemtype'  => self::getType(),
            'event'     => 'alert' . ($search->getField('is_private') ? '' : '_' . $search->getID())
         ]
      ]);

      if (!$iterator->numRows()) {
         echo "<span class='required'><strong>" . __('Notification does not exists!') . "</strong></span>";
208
         if ($canedit) {
209
            echo "<br/><a href='{$search->getFormURLWithID($search->fields['id'])}&amp;create_notif=true'>"
210 211 212
               . __('create it now') . "</a>";
            $canedit = false;
         }
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
      } else {
         echo _n('Notification used:', 'Notifications used:', $iterator->numRows()) . "&nbsp;";
         $first = true;
         while ($row = $iterator->next()) {
            if (!$first) {
               echo ', ';
            }
            if (Session::haveRight('notification', UPDATE)) {
               $url = Notification::getFormURLWithID($row['id']);
               echo "<a href='$url'>" . $row['name'] . "</a>";
            } else {
               echo $row['name'];
            }
            $first = false;
         }
      }
      echo '</div>';

      if ($canedit
          && !(!empty($withtemplate) && ($withtemplate == 2))) {
         echo "<div class='firstbloc'>".
               "<a class='vsubmit' href='" . self::getFormURL() . "?savedsearches_id=$ID&amp;withtemplate=".
                  $withtemplate."'>";
         echo __('Add an alert');
         echo "</a></div>\n";
      }

      $iterator = $DB->request([
         'FROM'   => self::getTable(),
         'WHERE'  => ['savedsearches_id' => $ID]
      ]);

      echo "<table class='tab_cadre_fixehov'>";

      $colspan = 4;
      if ($iterator->numrows()) {
         echo "<tr class='noHover'><th colspan='$colspan'>".self::getTypeName($iterator->numrows()).
            "</th></tr>";

         $header = "<tr><th>".__('Name')."</th>";
         $header .= "<th>".__('Operator')."</th>";
         $header .= "<th>".__('Value')."</th>";
         $header .= "<th>".__('Active')."</th>";
         $header .= "</tr>";
         echo $header;

         $alert = new self();
         while ($data = $iterator->next()) {
            $alert->getFromDB($data['id']);
            echo "<tr class='tab_bg_2'>";
            echo "<td>".$alert->getLink()."</td>";
            echo "<td>".self::getOperators($data['operator'])."</td>";
            echo "<td>".$data['value']."</td>";
            echo "<td>".Dropdown::getYesNo($data['is_active'])."</td>";
            echo "</tr>";
            Session::addToNavigateListItems(__CLASS__, $data['id']);
         }
         echo $header;
      } else {
         echo "<tr class='tab_bg_2'><th colspan='$colspan'>".__('No item found')."</th></tr>";
      }

      echo "</table>";
      echo "</div>";
   }

   /**
    * Get operators
    *
    * @param integer $id ID for the operator to retrieve, or null for the full list
    *
    * @return string|array
    */
   static function getOperators($id = null) {
      $ops = [
         self::OP_LESS     => '<',
         self::OP_LESSEQ   => '<=',
         self::OP_EQ       => '=',
         self::OP_NOT      => '!=',
         self::OP_GREATEQ  => '>=',
         self::OP_GREAT    => '>'
      ];
      return ($id === null ? $ops : $ops[$id]);
   }

   static function cronInfo($name) {
      switch ($name) {
         case 'send' :
            return ['description' => __('Saved searches alerts')];
      }
303
      return [];
304 305 306 307 308 309 310
   }

   /**
    * Send saved searches alerts
    *
    * @param Crontask $task Crontask instance
    *
311
    * @return int : <0 : need to run again, 0:nothing to do, >0:ok
312 313 314 315 316 317
    */
   static public function cronSavedSearchesAlerts($task) {
      global $DB;

      $iterator = $DB->request([
         'FROM'   => self::getTable(),
318
         'WHERE'  => ['is_active' => true]
319 320 321 322 323
      ]);

      if ($iterator->numrows()) {
         $savedsearch = new SavedSearch();

324
         $cli_logged = null;
325 326 327 328 329
         if (!isset($_SESSION['glpiname'])) {
            //required from search class
            $_SESSION['glpiname'] = 'crontab';
         }

330 331 332 333
         while ($row = $iterator->next()) {
            //execute saved search to get results
            try {
               $savedsearch->getFromDB($row['savedsearches_id']);
334 335 336 337 338 339 340 341
               if (isCommandLine() && $cli_logged != $savedsearch->fields['users_id']) {
                  //search requires a logged in user...
                  $user = new User();
                  $user->getFromDB($savedsearch->fields['users_id']);
                  $auth = new Auth();
                  $auth->user = $user;
                  $auth->auth_succeded = true;
                  Session::init($auth);
342
                  $_SESSION['glpinotification_to_myself'] = true; // Force sending of notification
343 344 345
                  $cli_logged = $savedsearch->fields['users_id'];
               }

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
               $data = $savedsearch->execute(true);
               $count = (int)$data['data']['totalcount'];
               $value = (int)$row['value'];

               $notify = false;
               $tr_op = null;

               switch ($row['operator']) {
                  case self::OP_LESS:
                     $notify = $count < $value;
                     $tr_op = __('less than');
                     break;
                  case self::OP_LESSEQ:
                     $notify = $count <= $value;
                     $tr_op = __('less or equals than');
                     break;
                  case self::OP_EQ:
                     $notify = $count == $value;
                     $tr_op = __('equals to');
                     break;
                  case self::OP_NOT:
                     $notify = $count != $value;
                     $tr_op = __('not equals to');
                     break;
                  case self::OP_GREATEQ:
                     $notify = $count >= $value;
                     $tr_op = __('greater or equals than');
                     break;
                  case self::OP_GREAT:
                     $notify = $count > $value;
                     $tr_op = __('greater than');
377
                     break;
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
                  default:
                     throw new \RuntimeException("Unknonw operator '{$row['operator']}'");
               }

               //TRANS : %1$s is the name of the saved search,
               //        %2$s is the comparison translated text
               //        %3$s is the value compared to
               $data['msg'] = sprintf(
                  __('Results count for %1$s is %2$s %3$s'),
                  $savedsearch->getName(),
                  $tr_op,
                  $value
               );

               if ($notify) {
                  $event = 'alert' . ($savedsearch->getField('is_private') ? '' : '_' . $savedsearch->getID());
                  $alert = new self();
                  $alert->getFromDB($row['id']);
                  $data['savedsearch'] = $savedsearch;
                  NotificationEvent::raiseEvent($event, $alert, $data);
398
                  $task->addVolume(1);
399 400
               }
            } catch (\Exception $e) {
401
               Toolbox::logError($e);
402 403
            }
         }
404
         return 1;
405
      }
406
      return 0;
407
   }
408 409 410 411

   function getItemsForLog($itemtype, $items_id) {
      return ['new' => $this];
   }
412
}