ticket.class.php

verdanatech, 11/21/2018 02:19 PM

Download (31.4 KB)

 
1
<?php
2
/**
3
 * @version $Id: ticket.class.php 270 2018-09-12 13:20:03Z yllen $
4
 -------------------------------------------------------------------------
5

6
 LICENSE
7

8
 This file is part of Behaviors plugin for GLPI.
9

10
 Behaviors is free software: you can redistribute it and/or modify
11
 it under the terms of the GNU Affero General Public License as published by
12
 the Free Software Foundation, either version 3 of the License, or
13
 (at your option) any later version.
14

15
 Behaviors is distributed in the hope that it will be useful,
16
 but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18
 GNU Affero General Public License for more details.
19

20
 You should have received a copy of the GNU Affero General Public License
21
 along with Behaviors. If not, see <http://www.gnu.org/licenses/>.
22

23
 @package   behaviors
24
 @author    Remi Collet, Nelly Mahu-Lasson
25
 @copyright Copyright (c) 2010-2018 Behaviors plugin team
26
 @license   AGPL License 3.0 or (at your option) any later version
27
            http://www.gnu.org/licenses/agpl-3.0-standalone.html
28
 @link      https://forge.glpi-project.org/projects/behaviors
29
 @link      http://www.glpi-project.org/
30
 @since     2010
31

32
 --------------------------------------------------------------------------
33
*/
34

    
35
class PluginBehaviorsTicket {
36

    
37
   const LAST_TECH_ASSIGN                     = 50;
38
   const LAST_GROUP_ASSIGN                    = 51;
39
   const LAST_SUPPLIER_ASSIGN                 = 52;
40
   const LAST_WATCHER_ADDED                   = 53;
41
   const SUPERVISOR_LAST_GROUP_ASSIGN         = 54;
42
   const LAST_GROUP_ASSIGN_WITHOUT_SUPERVISOR = 55;
43

    
44

    
45

    
46
   static function addEvents(NotificationTargetTicket $target) {
47

    
48
      $config = PluginBehaviorsConfig::getInstance();
49

    
50
      if ($config->getField('add_notif')) {
51
         Plugin::loadLang('behaviors');
52
         $target->events['plugin_behaviors_ticketreopen']
53
         = sprintf(__('%1$s (%2$s)'), __('Reopen ticket', 'behaviors'), __('Behaviors'));
54
         $target->events['plugin_behaviors_ticketstatus']
55
         = sprintf(__('%1$s (%2$s)'), __('Change status', 'behaviors'), __('Behaviors'));
56
         $target->events['plugin_behaviors_ticketwaiting']
57
         = sprintf(__('%1$s (%2$s)'), __('Ticket waiting', 'behaviors'), __('Behaviors'));
58
         PluginBehaviorsDocument_Item::addEvents($target);
59
      }
60
   }
61

    
62

    
63
   static function addTargets(NotificationTargetTicket $target) {
64

    
65
      // No new recipients for globals notifications
66
      $alert = ['alertnotclosed', 'recall', 'recall_ola'];
67
      if (!in_array($target->raiseevent, $alert)) {
68
         $target->addTarget(self::LAST_TECH_ASSIGN ,
69
                            sprintf(__('%1$s (%2$s)'), __('Last technician assigned', 'behaviors'),
70
                                    __('Behaviors')));
71
         $target->addTarget(self::LAST_GROUP_ASSIGN ,
72
                            sprintf(__('%1$s (%2$s)'), __('Last group assigned', 'behaviors'),
73
                                    __('Behaviors')));
74
         $target->addTarget(self::LAST_SUPPLIER_ASSIGN ,
75
                            sprintf(__('%1$s (%2$s)'), __('Last supplier assigned', 'behaviors'),
76
                                    __('Behaviors')));
77
         $target->addTarget(self::LAST_WATCHER_ADDED ,
78
                            sprintf(__('%1$s (%2$s)'), __('Last watcher added', 'behaviors'),
79
                                    __('Behaviors')));
80
         $target->addTarget(self::SUPERVISOR_LAST_GROUP_ASSIGN,
81
                            sprintf(__('%1$s (%2$s)'), __('Supervisor of last group assigned', 'behaviors'),
82
                                    __('Behaviors')));
83
         $target->addTarget(self::LAST_GROUP_ASSIGN_WITHOUT_SUPERVISOR,
84
                            sprintf(__('%1$s (%2$s)'),
85
                                    __('Last group assigned without supersivor', 'behaviors'),
86
                                    __('Behaviors')));
87
      }
88
   }
89

    
90

    
91
   static function addActionTargets(NotificationTargetTicket $target) {
92

    
93
      switch ($target->data['items_id']) {
94
         case self::LAST_TECH_ASSIGN :
95
            self::getLastLinkedUserByType(CommonITILActor::ASSIGN, $target);
96
             break;
97

    
98
         case self::LAST_GROUP_ASSIGN :
99
            self::getLastLinkedGroupByType(CommonITILActor::ASSIGN, $target);
100
            break;
101

    
102
         case self::LAST_SUPPLIER_ASSIGN :
103
            self::getLastSupplierAddress($target);
104
            break;
105

    
106
         case self::LAST_WATCHER_ADDED :
107
            self::getLastLinkedUserByType(CommonITILActor::OBSERVER, $target);
108
            break;
109

    
110
         case self::SUPERVISOR_LAST_GROUP_ASSIGN :
111
            self::getLastLinkedGroupByType(CommonITILActor::ASSIGN, $target, 1);
112
            break;
113

    
114
         case self::LAST_GROUP_ASSIGN_WITHOUT_SUPERVISOR :
115
            self::getLastLinkedGroupByType(CommonITILActor::ASSIGN, $target, 2);
116
            break;
117
      }
118
   }
119

    
120

    
121
   static function getLastLinkedUserByType($type, $target) {
122
      global $DB, $CFG_GLPI;
123

    
124
      $dbu           = new DbUtils();
125
      $userlinktable = $dbu->getTableForItemType($target->obj->userlinkclass);
126
      $fkfield       = $target->obj->getForeignKeyField();
127

    
128
      $last = "SELECT MAX(`id`) AS lastid
129
               FROM `$userlinktable`
130
               WHERE `$userlinktable`.`$fkfield` = '".$target->obj->fields["id"]."'
131
                      AND `$userlinktable`.`type` = '$type'";
132
      $result = $DB->query($last);
133

    
134
      $querylast = '';
135
      if ($data = $DB->fetch_assoc($result)) {
136
         $object = new $target->obj->userlinkclass();
137
         if ($object->getFromDB($data['lastid'])) {
138
            $querylast = " AND `$userlinktable`.`users_id` = '".$object->fields['users_id']."'";
139
         }
140
      }
141

    
142
      //Look for the user by his id
143
      $query =  "SELECT DISTINCT `glpi_users`.`id` AS users_id,
144
                                 `glpi_users`.`language` AS language,
145
                      `$userlinktable`.`use_notification` AS notif,
146
                      `$userlinktable`.`alternative_email` AS altemail
147
                FROM `$userlinktable`
148
                LEFT JOIN `glpi_users` ON (`$userlinktable`.`users_id` = `glpi_users`.`id`)
149
                INNER JOIN `glpi_profiles_users`
150
                ON (`glpi_profiles_users`.`users_id` = `glpi_users`.`id` ".
151
                     $dbu->getEntitiesRestrictRequest("AND", "glpi_profiles_users", "entities_id",
152
                           $target->getEntity(), true).")
153
                WHERE `$userlinktable`.`$fkfield` = '".$target->obj->fields["id"]."'
154
                      AND `$userlinktable`.`type` = '$type'
155
                      $querylast";
156

    
157
      foreach ($DB->request($query) as $data) {
158
         //Add the user email and language in the notified users list
159
         if ($data['notif']) {
160
            $author_email = UserEmail::getDefaultForUser($data['users_id']);
161
            $author_lang  = $data["language"];
162
            $author_id    = $data['users_id'];
163

    
164
            if (!empty($data['altemail'])
165
                && ($data['altemail'] != $author_email)
166
                && NotificationMailing::isUserAddressValid($data['altemail'])) {
167
               $author_email = $data['altemail'];
168
            }
169
            if (empty($author_lang)) {
170
               $author_lang = $CFG_GLPI["language"];
171
            }
172
            if (empty($author_id)) {
173
               $author_id = -1;
174
            }
175
            $target->addToRecipientsList(['email'    => $author_email,
176
                                         'language' => $author_lang,
177
                                         'users_id' => $author_id]);
178
         }
179
      }
180

    
181
      // Anonymous user
182
      foreach ($DB->request(['SELECT' => 'alternative_email',
183
                             'FROM'   => $userlinktable,
184
                             'WHERE'  => [$fkfield           => $target->obj->fields["id"],
185
                                          'users_id'         => 0,
186
                                          'use_notification' => 1,
187
                                          'type'             => $type]]) as $data) {
188
         if (NotificationMailing::isUserAddressValid($data['alternative_email'])) {
189
            $target->addToRecipientsList(['email'    => $data['alternative_email'],
190
                                          'language' => $CFG_GLPI["language"],
191
                                          'users_id' => -1]);
192
         }
193
      }
194
   }
195

    
196

    
197
   static function getLastLinkedGroupByType($type, $target, $supervisor=0) {
198
      global $DB;
199

    
200
      $dbu            = new DbUtils();
201
      $grouplinktable = $dbu->getTableForItemType($target->obj->grouplinkclass);
202
      $fkfield        = $target->obj->getForeignKeyField();
203

    
204
      $last = "SELECT MAX(`id`) AS lastid
205
               FROM `$grouplinktable`
206
               WHERE `$grouplinktable`.`$fkfield` = '".$target->obj->fields["id"]."'
207
                     AND `$grouplinktable`.`type` = '$type'";
208
      $result = $DB->request($last);
209

    
210
      $querylast = '';
211
      if ($data = $result->next()) {
212
         $object    = new $target->obj->grouplinkclass();
213
         if ($object->getFromDB($data['lastid'])) {
214
            $querylast = " AND `groups_id` = '".$object->fields['groups_id']."'";
215
         }
216
      }
217

    
218
      //Look for the user by his id
219
      $query = "SELECT `groups_id`
220
                FROM `$grouplinktable`
221
                WHERE `$grouplinktable`.`$fkfield` = '".$target->obj->fields["id"]."'
222
                      AND `$grouplinktable`.`type` = '$type'
223
                      $querylast";
224

    
225
      foreach ($DB->request($query) as $data) {
226
         //Add the group in the notified users list
227
         self::addForGroup($supervisor, $object->fields['groups_id'], $target);
228
      }
229
   }
230

    
231

    
232
   static  function getLastSupplierAddress($target) {
233
      global $DB;
234

    
235
      if (!$target->options['sendprivate']
236
          && $target->obj->countSuppliers(CommonITILActor::ASSIGN)) {
237

    
238
         $dbu               = new DbUtils();
239
         $supplierlinktable = $dbu->getTableForItemType($target->obj->supplierlinkclass);
240
         $fkfield           = $target->obj->getForeignKeyField();
241

    
242
         $last = "SELECT MAX(`id`) AS lastid
243
                  FROM `$supplierlinktable`
244
                  WHERE `$supplierlinktable`.`$fkfield` = '".$target->obj->fields["id"]."'";
245

    
246
         $result = $DB->query($last);
247
         $data = $DB->fetch_assoc($result);
248

    
249
         $querylast = '';
250
         $object = new $target->obj->supplierlinkclass();
251
         if ($object->getFromDB($data['lastid'])) {
252
            $querylast = " AND `$supplierlinktable`.`suppliers_id` = '".$object->fields['suppliers_id']."'";
253
         }
254
         $query = "SELECT DISTINCT `glpi_suppliers`.`email` AS email,
255
                                   `glpi_suppliers`.`name` AS name
256
                   FROM `$supplierlinktable`
257
                   LEFT JOIN `glpi_suppliers`
258
                      ON (`$supplierlinktable`.`suppliers_id` = `glpi_suppliers`.`id`)
259
                   WHERE `$supplierlinktable`.`$fkfield` = '".$target->obj->getID()."'
260
                         $querylast";
261

    
262
         foreach ($DB->request($query) as $data) {
263
            $target->addToRecipientsList($data);
264
         }
265
      }
266
   }
267

    
268

    
269
   static function beforeAdd(Ticket $ticket) {
270
      global $DB;
271

    
272
        //verificando se a solicitação não está vindo da API
273
        if (!empty(ini_get('session.use_cookies'))) {
274

    
275
            if (!is_array($ticket->input) || !count($ticket->input)) {
276
               // Already cancel by another plugin
277
               return false;
278
            }
279
      
280
            $dbu = new DbUtils();
281
      
282
            //Toolbox::logDebug("PluginBehaviorsTicket::beforeAdd(), Ticket=", $ticket);
283
            $config = PluginBehaviorsConfig::getInstance();
284
      
285
            if ($config->getField('tickets_id_format')) {
286
               $max = 0;
287
               $sql = 'SELECT MAX( id ) AS max
288
                       FROM `glpi_tickets`';
289
               foreach ($DB->request($sql) as $data) {
290
                  $max = $data['max'];
291
               }
292
               $want = date($config->getField('tickets_id_format'));
293
               if ($max < $want) {
294
                  $DB->query("ALTER TABLE `glpi_tickets` AUTO_INCREMENT=$want");
295
               }
296
            }
297
      
298
            if (!isset($ticket->input['_auto_import'])
299
                && isset($_SESSION['glpiactiveprofile']['interface'])
300
                && ($_SESSION['glpiactiveprofile']['interface'] == 'central')) {
301
      
302
               if ($config->getField('is_requester_mandatory')
303
                   && ((is_array($ticket->input['_users_id_requester'])
304
                        && empty($ticket->input['_users_id_requester']))
305
                       || (!is_array($ticket->input['_users_id_requester'])
306
                           && !$ticket->input['_users_id_requester']))
307
                   && (!isset($ticket->input['_users_id_requester_notif']['alternative_email'])
308
                       || empty($ticket->input['_users_id_requester_notif']['alternative_email']))) {
309
                  Session::addMessageAfterRedirect(__('Requester is mandatory', 'behaviors'), true, ERROR);
310
                  $ticket->input = [];
311
                  return true;
312
      
313
               }
314
            }
315
            if ($config->getField('use_requester_item_group')
316
                && isset($ticket->input['items_id'])
317
                && (is_array($ticket->input['items_id']))) {
318
               foreach ($ticket->input['items_id'] as $type => $items) {
319
                  if (($item = $dbu->getItemForItemtype($type))
320
                      && (!isset($ticket->input['_groups_id_requester'])
321
                          || ($ticket->input['_groups_id_requester'] <= 0))) {
322
      
323
                     if ($item->isField('groups_id')) {
324
                        foreach ($items as $itemid) {
325
                           if ($item->getFromDB($itemid)) {
326
                              $ticket->input['_groups_id_requester'] = $item->getField('groups_id');
327
                           }
328
                        }
329
                     }
330
                  }
331
              }
332
            }
333
      
334
            // No Auto set Import for external source -> Duplicate from Ticket->prepareInputForAdd()
335
            if (!isset($ticket->input['_auto_import'])) {
336
               if (!isset($ticket->input['_users_id_requester'])) {
337
                  if ($uid = Session::getLoginUserID()) {
338
                     $ticket->input['_users_id_requester'] = $uid;
339
                  }
340
               }
341
            }
342
      
343
            if ($config->getField('use_requester_user_group')
344
                && (isset($ticket->input['_users_id_requester'])
345
                    && ($ticket->input['_users_id_requester'] > 0))
346
                && (!isset($ticket->input['_groups_id_requester'])
347
                    || ($ticket->input['_groups_id_requester'] <= 0)
348
                    ||  empty($ticket->input['_groups_id_requester']))) {
349
      
350
                  if ($config->getField('use_requester_user_group') == 1) {
351
                     // First group
352
                     $ticket->input['_groups_id_requester']
353
                        = PluginBehaviorsUser::getRequesterGroup($ticket->input['entities_id'],
354
                                                                 $ticket->input['_users_id_requester'],
355
                                                                 true);
356
                  } else {
357
                     // All groups
358
                     $g = PluginBehaviorsUser::getRequesterGroup($ticket->input['entities_id'],
359
                                                                 $ticket->input['_users_id_requester'],
360
                                                                 false);
361
                     if (count($g)) {
362
                        $ticket->input['_groups_id_requester'] = array_shift($g);
363
                     }
364
                     if (count($g)) {
365
                        $ticket->input['_additional_groups_requesters'] = $g;
366
                     }
367
                  }
368
            }
369
        }
370

    
371
   }
372

    
373

    
374
   static function afterPrepareAdd(Ticket $ticket) {
375
      global $DB;
376

    
377
      if (!is_array($ticket->input) || !count($ticket->input)) {
378
         // Already cancel by another plugin
379
         return false;
380
      }
381

    
382
      // Toolbox::logDebug("PluginBehaviorsTicket::afterPrepareAdd(), Ticket=", $ticket);
383
      $config = PluginBehaviorsConfig::getInstance();
384

    
385
      if ($config->getField('use_assign_user_group')
386
          && isset($ticket->input['_users_id_assign'])
387
          && ($ticket->input['_users_id_assign'] > 0)
388
          && (!isset($ticket->input['_groups_id_assign'])
389
              || ($ticket->input['_groups_id_assign'] <= 0))) {
390

    
391
         if ($config->getField('use_assign_user_group')==1) {
392
            // First group
393
            $ticket->input['_groups_id_assign']
394
               = PluginBehaviorsUser::getTechnicianGroup($ticket->input['entities_id'],
395
                                                         $ticket->input['_users_id_assign'],
396
                                                         true);
397
         } else {
398
            // All groups
399
            $ticket->input['_additional_groups_assigns']
400
               = PluginBehaviorsUser::getTechnicianGroup($ticket->input['entities_id'],
401
                                                         $ticket->input['_users_id_assign'],
402
                                                         false);
403
         }
404
      }
405
   }
406

    
407

    
408
   static function beforeUpdate(Ticket $ticket) {
409
      global $DB;
410

    
411
      if (!is_array($ticket->input) || !count($ticket->input)) {
412
         // Already cancel by another plugin
413
         return false;
414
      }
415

    
416
      $dbu = new DbUtils();
417

    
418
      //Toolbox::logDebug("PluginBehaviorsTicket::beforeUpdate(), Ticket=", $ticket);
419
      $config = PluginBehaviorsConfig::getInstance();
420

    
421
      // Check is the connected user is a tech
422
      if (!is_numeric(Session::getLoginUserID(false))
423
          || !Session::haveRight('ticket', UPDATE)) {
424
         return false; // No check
425
      }
426

    
427
      if (isset($ticket->input['date'])) {
428
         if ($config->getField('is_ticketdate_locked')) {
429
            unset($ticket->input['date']);
430
         }
431
      }
432

    
433
      if (isset($ticket->input['_read_date_mod'])
434
          && $config->getField('use_lock')
435
          && ($ticket->input['_read_date_mod'] != $ticket->fields['date_mod'])) {
436

    
437
         $msg = sprintf(__('%1$s (%2$s)'), __("Can't save, item have been updated", "behaviors"),
438
                           $dbu->getUserName($ticket->fields['users_id_lastupdater']).', '.
439
                           Html::convDateTime($ticket->fields['date_mod']));
440

    
441
         Session::addMessageAfterRedirect($msg, true, ERROR);
442
         return $ticket->input = false;
443
      }
444

    
445
      if (isset($ticket->input['status'])
446
          && in_array($ticket->input['status'], array_merge(Ticket::getSolvedStatusArray(),
447
                                                            Ticket::getclosedStatusArray()))) {
448

    
449
         $soluce = $DB->request(['FROM'    => 'glpi_itilsolutions',
450
                                 'WHERE'   => ['itemtype'   => 'Ticket',
451
                                 'items_id'   => $ticket->input['id']]]);
452

    
453
         if ($config->getField('is_ticketsolutiontype_mandatory')
454
             && !count($soluce)) {
455
            unset($ticket->input['status']);
456
            Session::addMessageAfterRedirect(__("Type of solution is mandatory before ticket is solved/closed",
457
                                                'behaviors'), true, ERROR);
458
         }
459
         if ($config->getField('is_ticketsolution_mandatory')
460
             && !count($soluce)) {
461
            unset($ticket->input['status']);
462
            Session::addMessageAfterRedirect(__("Description of solution is mandatory before ticket is solved/closed",
463
                                                'behaviors'), true, ERROR);
464
         }
465

    
466
         $dur     = (isset($ticket->input['actiontime'])
467
                        ? $ticket->input['actiontime']
468
                        : $ticket->fields['actiontime']);
469
         $cat    = (isset($ticket->input['itilcategories_id'])
470
                        ? $ticket->input['itilcategories_id']
471
                        : $ticket->fields['itilcategories_id']);
472
         $loc    = (isset($ticket->input['locations_id'])
473
                        ? $ticket->input['locations_id']
474
                        : $ticket->fields['locations_id']);
475

    
476
         // Wand to solve/close the ticket
477
         if ($config->getField('is_ticketrealtime_mandatory')) {
478
            if (!$dur) {
479
               unset($ticket->input['status']);
480
               Session::addMessageAfterRedirect(__("Duration is mandatory before ticket is solved/closed",
481
                                                   'behaviors'), true, ERROR);
482
            }
483
         }
484
         if ($config->getField('is_ticketcategory_mandatory')) {
485
            if (!$cat) {
486
               unset($ticket->input['status']);
487
               Session::addMessageAfterRedirect(__("Category is mandatory before ticket is solved/closed",
488
                                                   'behaviors'), true, ERROR);
489
            }
490
         }
491
         if ($config->getField('is_tickettech_mandatory')) {
492
            if (($ticket->countUsers(CommonITILActor::ASSIGN) == 0)
493
                && !isset($input["_itil_assign"]['users_id'])) {
494
               unset($ticket->input['status']);
495
               Session::addMessageAfterRedirect(__("Technician assigned is mandatory before ticket is solved/closed",
496
                                                   'behaviors'), true, ERROR);
497
            }
498
         }
499
         if ($config->getField('is_tickettechgroup_mandatory')) {
500
            if (($ticket->countGroups(CommonITILActor::ASSIGN) == 0)
501
                && !isset($input["_itil_assign"]['groups_id'])) {
502
               unset($ticket->input['status']);
503
               Session::addMessageAfterRedirect(__("Group of technicians assigned is mandatory before ticket is solved/closed",
504
                                                'behaviors'), true, ERROR);
505
            }
506
         }
507
         if ($config->getField('is_ticketlocation_mandatory')) {
508
            if (!$loc) {
509
               unset($ticket->input['status']);
510
               Session::addMessageAfterRedirect(__("Location is mandatory before ticket is solved/closed",
511
                                                   'behaviors'), true, ERROR);
512
            }
513
         }
514
         if ($config->getField('is_tickettasktodo')) {
515
            foreach($DB->request(['FROM'  => 'glpi_tickettasks',
516
                                  'WHERE' => ['tickets_id' => $ticket->getField('id')]]) as $task) {
517
               if ($task['state'] == 1) {
518
                  Session::addMessageAfterRedirect(__("You cannot solve/close a ticket with task do to",
519
                                                   'behaviors'), true, ERROR);
520
                  unset($ticket->input['status']);
521
               }
522
            }
523
         }
524
      }
525

    
526
      if ($config->getField('use_requester_item_group')
527
          && isset($ticket->input['items_id'])
528
          && (is_array($ticket->input['items_id']))) {
529
         foreach ($ticket->input['items_id'] as $type => $items) {
530
            foreach ($items as $number => $id) {
531
               if (($item = $dbu->getItemForItemtype($type))
532
                   && !isset($ticket->input['_itil_requester']['groups_id'])) {
533
                  if ($item->isField('groups_id')) {
534
                     foreach ($items as $itemid) {
535
                        if ($item->getFromDB($itemid)) {
536
                           $ticket->input['_itil_requester']
537
                                 = ['_type' => 'group',
538
                                    'groups_id' => $item->getField('groups_id')];
539
                        }
540
                     }
541
                  }
542
               }
543
            }
544
         }
545
      }
546
   }
547

    
548

    
549
   static function onNewTicket() {
550

    
551
      if (isset($_SESSION['glpiactiveprofile']['interface'])
552
          && ($_SESSION['glpiactiveprofile']['interface'] == 'central')) {
553

    
554
         if (strstr($_SERVER['PHP_SELF'], "/front/ticket.form.php")
555
             && isset($_POST['id'])
556
             && ($_POST['id'] == 0)
557
             && !isset($_GET['id'])) {
558

    
559
            $config = PluginBehaviorsConfig::getInstance();
560

    
561
            // Only if config to add the "first" group
562
            if (($config->getField('use_requester_user_group') == 1)
563
                && isset($_POST['_users_id_requester']) && ($_POST['_users_id_requester'] > 0)
564
                && (!isset($_POST['_groups_id_requester'])
565
                    || ($_POST['_groups_id_requester'] <= 0)
566
                    || (isset($_SESSION['glpi_behaviors_auto_group'])
567
                        && ($_SESSION['glpi_behaviors_auto_group']
568
                              == $_POST['_groups_id_requester'])))) {
569

    
570
               // Select first group of this user
571
               $grp = PluginBehaviorsUser::getRequesterGroup($_POST['entities_id'],
572
                                                             $_POST['_users_id_requester'],
573
                                                             true);
574
               $_SESSION['glpi_behaviors_auto_group'] = $grp;
575
               $_REQUEST['_groups_id_requester']      = $grp;
576

    
577
            } else if (($config->getField('use_requester_user_group') == 1)
578
                && isset($_POST['_users_id_requester']) && ($_POST['_users_id_requester'] <= 0)
579
                && isset($_POST['_groups_id_requester'])
580
                && isset($_SESSION['glpi_behaviors_auto_group'])
581
                && ($_SESSION['glpi_behaviors_auto_group'] == $_POST['_groups_id_requester'])) {
582

    
583
               // clear user, so clear group
584
               $_SESSION['glpi_behaviors_auto_group'] = 0;
585
               $_REQUEST['_groups_id_requester']      = 0;
586
            } else {
587
               unset($_SESSION['glpi_behaviors_auto_group']);
588
            }
589
         } else if (strstr($_SERVER['PHP_SELF'], "/front/ticket.form.php")) {
590
            unset($_SESSION['glpi_behaviors_auto_group']);
591
         }
592
      }
593
   }
594

    
595

    
596
   static function afterUpdate(Ticket $ticket) {
597
      // Toolbox::logDebug("PluginBehaviorsTicket::afterUpdate(), Ticket=", $ticket);
598

    
599
      $config = PluginBehaviorsConfig::getInstance();
600

    
601
      if ($config->getField('add_notif')
602
          && in_array('status', $ticket->updates)) {
603

    
604
         if (in_array($ticket->oldvalues['status'],
605
                      array_merge(Ticket::getSolvedStatusArray(),
606
                                  Ticket::getClosedStatusArray()))
607
             && !in_array($ticket->input['status'],
608
                          array_merge(Ticket::getSolvedStatusArray(),
609
                                      Ticket::getClosedStatusArray()))) {
610

    
611
            NotificationEvent::raiseEvent('plugin_behaviors_ticketreopen', $ticket);
612

    
613
         } else if ($ticket->oldvalues['status'] <> $ticket->input['status']) {
614
            if ($ticket->input['status'] == CommonITILObject::WAITING) {
615
               NotificationEvent::raiseEvent('plugin_behaviors_ticketwaiting', $ticket);
616
            } else {
617
               NotificationEvent::raiseEvent('plugin_behaviors_ticketstatus', $ticket);
618
            }
619
         }
620
      }
621
   }
622

    
623

    
624
   static function preClone(Ticket $srce, Array $input) {
625
      global $DB;
626

    
627
      $config = PluginBehaviorsConfig::getInstance();
628
      $tickid = $srce->getField('id');
629

    
630
      $user_reques                  = $srce->getUsers(CommonITILActor::REQUESTER);
631
      $input['_users_id_requester'] = [];
632
      foreach ($user_reques as $users) {
633
         $input['_users_id_requester'][] = $users['users_id'];
634
      }
635
      $user_observ                 = $srce->getUsers(CommonITILActor::OBSERVER);
636
      $input['_users_id_observer'] = [];
637
      foreach ($user_observ as $users) {
638
         $input['_users_id_observer'][] = $users['users_id'];
639
      }
640
      $user_assign               = $srce->getUsers(CommonITILActor::ASSIGN);
641
      $input['_users_id_assign'] = [];
642
      foreach ($user_assign as $users) {
643
         $input['_users_id_assign'][] = $users['users_id'];
644
      }
645

    
646
      $group_reques                  = $srce->getGroups(CommonITILActor::REQUESTER);
647
      $input['_groups_id_requester'] = [];
648
      foreach ($group_reques as $groups) {
649
         $input['_groups_id_requester'][] = $groups['groups_id'];
650
      }
651
      $group_observ                  = $srce->getGroups(CommonITILActor::OBSERVER);
652
      $input['_groups_id_observer'] = [];
653
      foreach ($group_observ as $groups) {
654
         $input['_groups_id_observer'][] = $groups['groups_id'];
655
      }
656
      $group_assign                  = $srce->getGroups(CommonITILActor::ASSIGN);
657
      $input['_groups_id_assign'] = [];
658
      foreach ($group_assign as $groups) {
659
         $input['_groups_id_assign'][] = $ugroups['groups_id'];
660
      }
661

    
662
      $suppliers                     = $srce->getSuppliers(CommonITILActor::ASSIGN);
663
      $input['_suppliers_id_assign'] = [];
664
      foreach ($suppliers as $suppliers) {
665
         $input['_suppliers_id_assign'][] = $suppliers['groups_id'];
666
      }
667

    
668
      return $input;
669

    
670
   }
671

    
672

    
673
   static function postClone(Ticket $clone, $oldid) {
674
      global $DB;
675

    
676
      $dbu  = new DbUtils();
677
      $fkey = $dbu->getForeignKeyFieldForTable($clone->getTable());
678
      $crit = [$fkey => $oldid];
679

    
680
      // add items of tickets source
681
      $item = new Item_Ticket();
682
      foreach ($DB->request($item->getTable(), $crit) as $dataitem) {
683
         $input = ['itemtype'    => $dataitem['itemtype'],
684
                   'items_id'    => $dataitem['items_id'],
685
                   'tickets_id'  => $clone->getField('id')];
686
         $item->add($input);
687
      }
688

    
689
      // link new ticket to ticket source
690
      $link = new Ticket_Ticket();
691
      $inputlink = ['tickets_id_1'    => $clone->getField('id'),
692
                    'tickets_id_2'    => $oldid,
693
                    'link'            => 1];
694
      $link->add($inputlink);
695

    
696
      if ($dbu->countElementsInTable("glpi_documents_items",
697
                                     ['itemtype' => 'Ticket',
698
                                      'items_i'  => $oldid])) {
699
         $docitem = new Document_Item();
700
         foreach ($DB->request("glpi_documents_items", ['itemtype' => 'Ticket',
701
                                                        'items_id' => $oldid]) as $doc) {
702
            $inputdoc = ['documents_id' => $doc['documents_id'],
703
                         'items_id'     => $clone->getField('id'),
704
                         'itemtype'     => 'Ticket',
705
                         'entities_id'  => $doc['entities_id'],
706
                         'is_recursive' => $doc['is_recursive']];
707
            $docitem->add($inputdoc);
708
         }
709
      }
710
   }
711

    
712

    
713
   static function addForGroup($manager, $group_id, $target) {
714
      global $DB;
715

    
716
      $dbu= new DbUtils();
717

    
718
      // members/managers of the group allowed on object entity
719
      // filter group with 'is_assign' (attribute can be unset after notification)
720
      $query = "SELECT DISTINCT `glpi_users`.`id` AS users_id,
721
                               `glpi_users`.`language` AS language
722
               FROM `glpi_groups_users`
723
               INNER JOIN `glpi_users` ON (`glpi_groups_users`.`users_id` = `glpi_users`.`id`)
724
               INNER JOIN `glpi_profiles_users`
725
               ON (`glpi_profiles_users`.`users_id` = `glpi_users`.`id` ".
726
                   $dbu->getEntitiesRestrictRequest("AND", "glpi_profiles_users", "entities_id",
727
                                                    $target->getEntity(), true).")
728
               INNER JOIN `glpi_groups` ON (`glpi_groups_users`.`groups_id` = `glpi_groups`.`id`)
729
               WHERE `glpi_groups_users`.`groups_id` = '$group_id'
730
               AND `glpi_groups`.`is_notify`";
731

    
732
               if ($manager == 1) {
733
                  $query .= " AND `glpi_groups_users`.`is_manager` ";
734
               } else if ($manager == 2) {
735
                  $query .= " AND NOT `glpi_groups_users`.`is_manager` ";
736
               }
737

    
738
               foreach ($DB->request($query) as $data) {
739
                  $target->addToRecipientsList($data);
740
               }
741
   }
742

    
743

    
744

    
745
}