-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclass.MergingPlugin.php
More file actions
442 lines (394 loc) · 17.1 KB
/
class.MergingPlugin.php
File metadata and controls
442 lines (394 loc) · 17.1 KB
1
2
3
4
5
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
<?php
require_once (INCLUDE_DIR . 'class.signal.php');
require_once (INCLUDE_DIR . 'class.ticket.php');
require_once ('config.php');
define('TICKET_RELATION_TABLE', TABLE_PREFIX . 'ticket_relation');
class MergingPlugin extends Plugin {
const DEBUG = FALSE;
/**
* Which config to use (in config.php)
*
* @var string
*/
public $config_class = 'MergingPluginConfig';
/**
* Run on every instantiation of osTicket..
* needs to be concise
*
* {@inheritdoc}
*
* @see Plugin::bootstrap()
*/
function bootstrap() {
if($this->firstRun()){
if (! $this->configureFirstRun ()) {
return false;
}
}
ob_start();
register_shutdown_function(function () {
global $thisstaff;
$html = ob_get_clean();
$ticket = null;
if($thisstaff){
if($_REQUEST['id'] && ($ticket=Ticket::lookup($_REQUEST['id']))){
$html = $this->addContentBefore($html,
'/<a.*?href="#post-reply"(.|\n)*?<\/a>/',
$this->getActions($thisstaff, $ticket));
if($this->isChild($ticket) || $this->isMaster($ticket)){
$html = $this->addContentAfter($html,
'/<ul.*?class="tabs"(.|\n)*?(?=<\/ul>)/',
'<li><a id="ticket-thread-tab" href="#relations">' .
__('Relations') . '</a></li>');
$html = preg_replace('/(?<=' . $ticket->getSubject() . ').*?(?=<\/h3>)/',
' - ' . ($this->isMaster($ticket) ? __('MASTER') : __('CHILD')), $html);
$html = $this->addContentBefore($html,
'/(<\/div>(\s|\n)*){3}<div.*id="print-options">/',
$this->getRelationsTab($ticket));
}
} else if(strpos($_SERVER['REQUEST_URI'], "tickets.php")){
$html = $this->addContentAfter($html,
'/<div class="pull-right flush-right">/',
$this->getActions($thisstaff));
}
$html = str_replace("{MERGING_INSTALL_PATH}", self::getInstallPath(), $html);
}
print $html;
});
}
function firstRun() {
$sql = 'SHOW TABLES LIKE \'' . TICKET_RELATION_TABLE . '\'';
$res = db_query ( $sql );
return (db_num_rows ( $res ) == 0);
}
function configureFirstRun() {
if (! $this->insertSql ()) {
echo "First run configuration error. " . "Unable to create database tables!";
return false;
}
return true;
}
function insertSql(){
$result = false;
$sql = "CREATE TABLE IF NOT EXISTS `" . TICKET_RELATION_TABLE . "` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`agent_id` int(11) NOT NULL,
`master_id` int(11) NOT NULL,
`ticket_id` int(11) NOT NULL,
`date_merged` datetime NOT NULL,
PRIMARY KEY (`id`)
);";
$result = db_query($sql);
if(!$result)
return $result;
$sql = "ALTER TABLE `" . THREAD_EVENT_TABLE . "` CHANGE `state` `state` ENUM('created','closed','reopened',
'assigned','transferred','overdue','edited','viewed','error','collab','resent','merged',
'split') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
return db_query($sql);
}
function addContentBefore($html, $regex, $content){
if(preg_match($regex, $html, $match))
return str_replace($match[0], $content . $match[0], $html);
return $html;
}
function addContentAfter($html, $regex, $content){
if(preg_match($regex, $html, $match))
return str_replace($match[0], $match[0] . $content, $html);
return $html;
}
function getActions($staff, $ticket=null){
$result = '';
if($ticket)
$result = file_get_contents(__DIR__ . '/templates/merge-view.php');
else
$result = file_get_contents(__DIR__ . '/templates/merge.php');
$tickets = TicketModel::objects();
// -- Open and assigned to me
$assigned = Q::any(array(
'staff_id' => $staff->getId(),
));
// -- Open and assigned to a team of mine
if ($teams = array_filter($staff->getTeams()))
$assigned->add(array('team_id__in' => $teams));
$visibility = Q::any(new Q(array('status__state'=>'open', $assigned)));
// -- Routed to a department of mine
if (!$staff->showAssignedOnly() && ($depts=$staff->getDepts()))
$visibility->add(array('dept_id__in' => $depts));
$tickets->filter(Q::any($visibility));
$tickets->filter(array('status__state'=>'open'));
$tickets->values('ticket_id', 'number', 'cdata__subject');
$options = '';
foreach ($tickets as $T)
$options = $options . "<option value='" . $T['ticket_id'] . "'>" . $T['number'] . " | " . $T['cdata__subject'] . "</option>";
$result = str_replace("{MERGING_OPTIONS}", $options, $result);
$result = str_replace("{MERGING_TOOLTIP}", __('Merge'), $result);
$result = str_replace("{MERGING_PLACEHOLDER}", __('Select a ticket'), $result);
if($ticket)
$result = str_replace("{MERGING_TICKET_ID}", $ticket->getId(), $result);
return $result;
}
function getRelationsTab($ticket){
$result = $this->isMaster($ticket) ? $this->getMasterRelationsTab($ticket)
: $this->getChildRelationsTab($ticket);
$result = str_replace("{MERGING_TRANSLATE_NUMBER}", __('Number'), $result);
$result = str_replace("{MERGING_TRANSLATE_PRIORITY}", __('Priority'), $result);
$result = str_replace("{MERGING_TRANSLATE_DEPARTMENT}", __('Department'), $result);
$result = str_replace("{MERGING_TRANSLATE_SUBJECT}", __('Subject'), $result);
$result = str_replace("{MERGING_TRANSLATE_DATE_MERGED}", __('Date merged'), $result);
$result = str_replace("{MERGING_TRANSLATE_FROM}", __('From'), $result);
$result = str_replace("{MERGING_TRANSLATE_CLOSED_BY}", __('Closed by'), $result);
return $result;
}
function getMasterRelationsTab($ticket){
$result = file_get_contents(__DIR__ . '/templates/relationstab-master.php');
$childcontent = '';
$children = $this->getChildren($ticket);
foreach ($children as $T) {
$childcontent = $childcontent . '<tr id="' . $T->getId() . '">
<td nowrap>
<a class="Icon ' . strtolower($T->getSource()) . 'Ticket preview"
title="Preview Ticket"
href="tickets.php?id=' . $T->getId() . '"
data-preview="#tickets/' . $T->getId() . '/preview"
>' . $T->getNumber() . '</a>
</td>
<td align="center" nowrap>' . (Format::datetime($this->getDateMerged($T)) ?: $date_fallback) . '</td>
<td>
<div style="max-width: 279px; max-height: 1.2em"
class="link truncate"
href="tickets.php?id=' . $T->getId() . '">' . $T->getSubject() . '</div>
</td>
<td nowrap>
<div>
<span class="truncate">' . Format::htmlchars($T->getDeptName()) . '</span>
</div>
</td>
<td nowrap>
<div>
<span class="truncate">' . (Format::htmlchars($T->getStaff() ? $T->getStaff()->getName() : __('Unknown'))) . '</span>
</div>
</td>
<td nowrap>
<div data-toggle="tooltip" title="' . __('Split') . '" style="height: 26px;">
<button type="submit" class="action-button" onclick="$.ajax({
type: \'POST\',
url: \'../include/{MERGING_INSTALL_PATH}/ajax.php\',
data: ({master: ' . $ticket->getId() . ',ticket: ' . $T->getId() . ',a: \'split\'}),
success: function(data) {
location.reload();
}
});">
<i class="icon-trash"></i>
</button>
</div>
</td>
</tr>';
}
$result = str_replace("{MERGING_CHILD_TICKETS}", $childcontent, $result);
$result = str_replace("{MERGING_TRANSLATE_CHILD_TICKETS}", __('Child tickets'), $result);
return $result;
}
function getChildRelationsTab($ticket){
$result = file_get_contents(__DIR__ . '/templates/relationstab-child.php');
$master = $this->getMaster($ticket);
$result = str_replace("{MERGING_ID}", $master->getId(), $result);
$result = str_replace("{MERGING_SOURCE}", strtolower($master->getSource()), $result);
$result = str_replace("{MERGING_NUMBER}", $master->getNumber(), $result);
$result = str_replace("{MERGING_PRIORITY}", $master->getPriority(), $result);
$result = str_replace("{MERGING_DEPARTMENT}", $master->getDeptName(), $result);
$result = str_replace("{MERGING_SUBJECT}", $master->getSubject(), $result);
$result = str_replace("{MERGING_DATE_MERGED}", $this->getDateMerged($ticket), $result);
$result = str_replace("{MERGING_TRANSLATE_MASTER_TICKET}", __('Master ticket'), $result);
return $result;
}
function merge($master, $tids){
global $thisstaff;
$mergingplugin = new MergingPlugin;
$config = $mergingplugin->getConfig();
if(!self::canBeMaster($master)){
Messages::error(__('Ticket selected for master cannot be one.'));
return false;
}
$tickets = array();
foreach(explode(',', $tids) as $tid){
//Master ticket can't be child ticket aswell.
if($tid == $master->getId())
continue;
//Proper ID?
$temp = Ticket::lookup($tid);
if(!$temp)
continue;
if(!self::canBeChild($temp)){
Messages::warning(sprintf(__('Ticket #%s cannot be a child.'), $temp->getNumber()));
continue;
}
if(!$temp->isCloseable()){
Messages::warning(sprintf(__('Ticket #%s cannot be closed.'), $temp->getNumber()));
continue;
}
$tickets[] = $temp;
}
unset($temp);
if(empty($tickets)){
Messages::error(__('Select at least one viable ticket'));
return false;
}
foreach($tickets as $temp){
$temp->setStatus(TicketStatus::lookup($config->get('childstatus')));
if($config->get('copyrecipients')){
$master->addCollaborator($temp->getUser(), array(), $error, true);
if ($collabs = $temp->getThread()->getParticipants()) {
foreach ($collabs as $c)
$master->addCollaborator($c->getUser(), array(), $error, true);
}
}
$sql='INSERT INTO '.TICKET_RELATION_TABLE.' (`id`, `agent_id`, `master_id`, `ticket_id`, `date_merged`)
VALUES(NULL, '.$thisstaff->getId().', '.$master->getId().', '.$temp->getId().', NOW())';
db_query($sql);
self::setChild($temp, true);
$master->logEvent('merged', array('child' => $temp->getSubject(), 'id' => $temp->getId()));
}
self::setMaster($master, true);
return true;
}
function split($master, $tid){
if($tid == $master->getId())
return false;
$ticket = Ticket::lookup($tid);
if(!$ticket || !self::isChild($ticket))
return false;
$sql='DELETE FROM '.TICKET_RELATION_TABLE.' WHERE master_id = ' . $master->getId() . ' AND ticket_id = ' . $tid;
db_query($sql);
self::setChild($ticket, false);
if(!self::getChildren($master))
self::setMaster($master, false);
$master->logEvent('split', array('child' => $ticket->getSubject(), 'id' => $tid));
return true;
}
function massSplit($tids){
global $thisstaff;
foreach($tids as $key => $tid){
if(!($temp = Ticket::lookup($tid)))
continue;
if(self::isMaster($temp))
foreach(self::getChildren($temp) as $ticket)
self::split($temp, $ticket->getId());
else if(self::isChild($temp))
self::split(self::getMaster($temp), $tid);
else
Messages::warning(sprintf(__('Ticket #%s is not merged.'), $temp->getNumber()));
}
return true;
}
function isMaster($ticket){
if(!isset($ticket->master)){
$sql='SELECT ticket_id FROM '.TICKET_RELATION_TABLE.' WHERE master_id = ' . $ticket->getId();
if($res=db_query($sql))
self::setMaster($ticket, db_num_rows($res));
}
return $ticket->master;
}
function canBeMaster($ticket){
if(self::isMaster($ticket))
return true;
if(self::isChild($ticket))
return false;
return true;
}
function isChild($ticket){
if(!isset($ticket->child)){
$sql='SELECT ticket_id, date_merged FROM '.TICKET_RELATION_TABLE.' WHERE ticket_id = ' . $ticket->getId();
if($res=db_query($sql)){
$nr = db_num_rows($res);
self::setChild($ticket, $nr);
if($nr){
list($tid, $datem) = db_fetch_row($res);
self::setDateMerged($ticket, $datem);
}
}
}
return $ticket->child;
}
function canBeChild($ticket){
return !self::isMaster($ticket) && !self::isChild($ticket);
}
function setMaster($ticket, $var){
$ticket->master = (boolean)$var;
}
function setChild($ticket, $var){
$ticket->child = (boolean)$var;
}
function getDateMerged($ticket){
return (!self::isChild($ticket) || !isset($ticket->dateMerged)) ? false : $ticket->dateMerged;
}
function setDateMerged($ticket, $date){
$ticket->dateMerged = $date;
}
function getChildren($ticket){
if(!self::isMaster($ticket))
return array();
$sql='SELECT ticket_id, date_merged FROM '.TICKET_RELATION_TABLE.' WHERE master_id = ' . $ticket->getId();
$ret = array();
if(($res=db_query($sql)) && db_num_rows($res))
while(list($id, $tmpdate)=db_fetch_row($res))
if($temp=Ticket::lookup($id)){
self::setDateMerged($temp, $tmpdate);
self::setChild($temp, true);
$ret[] = $temp;
}
return $ret;
}
function getMaster($ticket){
if(!self::isChild($ticket))
return array();
$sql='SELECT master_id FROM '.TICKET_RELATION_TABLE.' WHERE ticket_id = ' . $ticket->getId();
if(($res=db_query($sql)) && db_num_rows($res)) {
list($id)=db_fetch_row($res);
if ($temp=Ticket::lookup($id)) {
self::setMaster($temp, true);
return $temp;
}
}
return false;
}
/**
* Required stub.
*
* {@inheritdoc}
*
* @see Plugin::uninstall()
*/
function uninstall() {
$errors = array ();
$result = false;
$sql = "DROP TABLE IF EXISTS `" . TICKET_RELATION_TABLE . "`;";
db_query($sql);
$sql = "ALTER TABLE `" . THREAD_EVENT_TABLE . "` CHANGE `state` `state` ENUM('created','closed','reopened',
'assigned','transferred','overdue','edited','viewed','error','collab','resent'
) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;";
db_query($sql);
parent::uninstall ( $errors );
}
/**
* Plugins seem to want this.
*/
public function getForm() {
return array ();
}
}
class MergedEvent extends ThreadEvent {
static $icon = 'code-fork';
static $state = 'merged';
function getDescription($mode=self::MODE_STAFF) {
return sprintf($this->template(__('<b>{somebody}</b> merged this ticket with %s{data.id}%s<b>{data.child}</b>%s {timestamp}')),
'<a href="/scp/tickets.php?id=', '">', '</a>');
}
}
class SplitEvent extends ThreadEvent {
static $icon = 'share-alt';
static $state = 'split';
function getDescription($mode=self::MODE_STAFF) {
return sprintf($this->template(__('<b>{somebody}</b> split this ticket from %s{data.id}%s<b>{data.child}</b>%s {timestamp}')),
'<a href="/scp/tickets.php?id=', '">', '</a>');
}
}