/
class.thread.php
3442 lines (2903 loc) · 109 KB
/
class.thread.php
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*********************************************************************
class.thread.php
Thread of things!
XXX: Please DO NOT add any ticket related logic! use ticket class.
Peter Rotich <peter@osticket.com>
Copyright (c) 2006-2013 osTicket
http://www.osticket.com
Released under the GNU General Public License WITHOUT ANY WARRANTY.
See LICENSE.TXT for details.
vim: expandtab sw=4 ts=4 sts=4:
**********************************************************************/
include_once(INCLUDE_DIR.'class.ticket.php');
include_once(INCLUDE_DIR.'class.draft.php');
include_once(INCLUDE_DIR.'class.role.php');
//Ticket thread.
class Thread extends VerySimpleModel
implements Searchable {
static $meta = array(
'table' => THREAD_TABLE,
'pk' => array('id'),
'joins' => array(
'ticket' => array(
'constraint' => array(
'object_type' => "'T'",
'object_id' => 'Ticket.ticket_id',
),
),
'task' => array(
'constraint' => array(
'object_type' => "'A'",
'object_id' => 'Task.id',
),
),
'collaborators' => array(
'reverse' => 'Collaborator.thread',
),
'referrals' => array(
'reverse' => 'ThreadReferral.thread',
),
'entries' => array(
'reverse' => 'ThreadEntry.thread',
),
'events' => array(
'reverse' => 'ThreadEvent.thread',
'broker' => 'ThreadEvents',
),
),
);
const MODE_STAFF = 1;
const MODE_CLIENT = 2;
var $_object;
var $_entries;
var $_collaborators; // Cache for collabs
var $_participants;
function getId() {
return $this->id;
}
function getObjectId() {
return $this->object_id;
}
function getObjectType() {
return $this->object_type;
}
function getObject() {
if (!$this->_object)
$this->_object = ObjectModel::lookup(
$this->getObjectId(), $this->getObjectType());
return $this->_object;
}
function getNumAttachments() {
return Attachment::objects()->filter(array(
'thread_entry__thread' => $this
))->count();
}
function getNumEntries() {
return $this->entries->count();
}
function getEntries($criteria=false) {
if (!isset($this->_entries)) {
$this->_entries = $this->entries->annotate(array(
'has_attachments' => SqlAggregate::COUNT(SqlCase::N()
->when(array('attachments__inline'=>0), 1)
->otherwise(null)
),
));
$this->_entries->exclude(array('flags__hasbit'=>ThreadEntry::FLAG_HIDDEN));
if ($criteria)
$this->_entries->filter($criteria);
}
return $this->_entries;
}
// Referrals
function getNumReferrals() {
return $this->referrals->count();
}
function getReferrals() {
return $this->referrals;
}
// Collaborators
function getNumCollaborators() {
return $this->getCollaborators()->count();
}
function getNumActiveCollaborators() {
if (!isset($this->ht['active_collaborators']))
$this->ht['active_collaborators'] = count($this->getActiveCollaborators());
return $this->ht['active_collaborators'];
}
function getActiveCollaborators() {
$collaborators = $this->getCollaborators();
$active = array();
foreach ($collaborators as $c) {
if ($c->isActive())
$active[] = $c;
}
return $active;
}
function getCollaborators($criteria=array()) {
if ($this->_collaborators && !$criteria)
return $this->_collaborators;
$collaborators = $this->collaborators
->filter(array('thread_id' => $this->getId()));
if (isset($criteria['isactive']))
$collaborators->filter(array('flags__hasbit'=>Collaborator::FLAG_ACTIVE));
// TODO: sort by name of the user
$collaborators->order_by('user__name');
if (!$criteria)
$this->_collaborators = $collaborators;
return $collaborators;
}
function isCollaborator($user) {
return $this->collaborators->findFirst(array(
'user_id' => $user->getId(),
'thread_id' => $this->getId()));
}
function addCollaborator($user, $vars, &$errors, $event=true) {
global $cfg, $thisstaff;
if (!$user)
return null;
if ($this->isCollaborator($user))
return false;
$vars = array_merge(array(
'threadId' => $this->getId(),
'userId' => $user->getId()), $vars ?: array());
if (!($c=Collaborator::add($vars, $errors)))
return null;
$c->active = true;
// Disable Agent Collabs (if configured) for User created tickets
if (!$thisstaff && $this->object_type === 'T'
&& $cfg->disableAgentCollaborators()
&& Staff::lookup($user->getDefaultEmailAddress()))
$c->active = false;
$this->_collaborators = null;
if ($event) {
$vars['add'] = true;
$this->logCollaboratorEvents($user, $vars);
}
return $c;
}
function updateCollaborators($vars, &$errors) {
global $thisstaff;
if (!$thisstaff) return;
//Deletes
if($vars['del'] && ($ids=array_filter($vars['del']))) {
$collabs = array();
foreach ($ids as $k => $cid) {
if (($c=Collaborator::lookup($cid))
&& ($c->getThreadId() == $this->getId())
&& $c->delete())
$collabs[] = $c;
$this->logCollaboratorEvents($c, $vars);
}
}
//statuses
$cids = null;
if($vars['cid'] && ($cids=array_filter($vars['cid']))) {
$this->collaborators->filter(array(
'thread_id' => $this->getId(),
'id__in' => $cids
))->update(array(
'updated' => SqlFunction::NOW(),
));
foreach ($vars['cid'] as $c) {
$collab = Collaborator::lookup($c);
if (($collab instanceof Collaborator)) {
$collab->setFlag(Collaborator::FLAG_ACTIVE, true);
$collab->save();
}
}
}
$inactive = $this->collaborators->filter(array(
'thread_id' => $this->getId(),
Q::not(array('id__in' => $cids ?: array(0)))
));
if($inactive) {
foreach ($inactive as $i) {
$i->setFlag(Collaborator::FLAG_ACTIVE, false);
$i->save();
}
$inactive->update(array(
'updated' => SqlFunction::NOW(),
));
}
unset($this->ht['active_collaborators']);
$this->_collaborators = null;
return true;
}
function logCollaboratorEvents($collaborator, $vars) {
$name = $collaborator->getName()->getOriginal();
$userId = (get_class($collaborator) == 'User')
? $collaborator->getId() : $collaborator->user_id;
$action = $vars['del'] ? 'object.deleted' : 'object.created';
$addDel = $vars['del'] ? 'del' : 'add';
$this->getEvents()->log($this->getObject(), 'collab', array(
$addDel => array($userId => array('name' => $name))
));
$type = array('type' => 'collab', $addDel => array($userId => array(
'name' => $name,
'src' => @$vars['source'],
)));
Signal::send($action, $this->getObject(), $type);
}
//UserList of participants (collaborators)
function getParticipants() {
if (!isset($this->_participants)) {
$list = new UserList();
if ($collabs = $this->getActiveCollaborators()) {
foreach ($collabs as $c)
$list->add($c);
}
$this->_participants = $list;
}
return $this->_participants;
}
// MailingList of recipients (collaborators)
function getRecipients() {
$list = new MailingList();
if ($collabs = $this->getActiveCollaborators()) {
foreach ($collabs as $c)
$list->addCc($c);
}
return $list;
}
function getReferral($id, $type) {
return $this->referrals->findFirst(array(
'object_id' => $id,
'object_type' => $type));
}
function isReferred($to=null, $strict=false) {
if (is_null($to) || !$this->referrals)
return ($this->referrals && $this->referrals->count());
switch (true) {
case $to instanceof Staff:
// Referred to the staff
if ($this->getReferral($to->getId(),
ObjectModel::OBJECT_TYPE_STAFF))
return true;
// Strict check only checks the Agent
if ($strict)
return false;
// Referred to staff's department
if ($this->referrals->findFirst(array(
'object_id__in' => $to->getDepts(),
'object_type' => ObjectModel::OBJECT_TYPE_DEPT)))
return true;
// Referred to staff's teams
if ($to->getTeams() && $this->referrals->findFirst(array(
'object_id__in' => $to->getTeams(),
'object_type' => ObjectModel::OBJECT_TYPE_TEAM
)))
return true;
return false;
break;
case $to instanceof Team:
//Referred to a Team
return ($this->getReferral($to->getId(),
ObjectModel::OBJECT_TYPE_TEAM));
break;
case $to instanceof Dept:
// Refered to the dept
return ($this->getReferral($to->getId(),
ObjectModel::OBJECT_TYPE_DEPT));
break;
}
return false;
}
function refer($to) {
if ($this->isReferred($to, true))
return false;
$vars = array('thread_id' => $this->getId());
switch (true) {
case $to instanceof Staff:
$vars['object_id'] = $to->getId();
$vars['object_type'] = ObjectModel::OBJECT_TYPE_STAFF;
break;
case $to instanceof Team:
$vars['object_id'] = $to->getId();
$vars['object_type'] = ObjectModel::OBJECT_TYPE_TEAM;
break;
case $to instanceof Dept:
$vars['object_id'] = $to->getId();
$vars['object_type'] = ObjectModel::OBJECT_TYPE_DEPT;
break;
default:
return false;
}
return ThreadReferral::create($vars);
}
// Render thread
function render($type=false, $options=array()) {
$mode = $options['mode'] ?: self::MODE_STAFF;
// Register thread actions prior to rendering the thread.
if (!class_exists('tea_showemailheaders'))
include_once INCLUDE_DIR . 'class.thread_actions.php';
$entries = $this->getEntries();
if ($type && is_array($type)) {
$visibility = Q::all(array('type__in' => $type));
if ($type['user_id']) {
$visibility->add(array('user_id' => $type['user_id']));
$visibility->ored = true;
}
$entries->filter($visibility);
}
if ($options['sort'] && !strcasecmp($options['sort'], 'DESC'))
$entries->order_by('-id');
// Precache all the attachments on this thread
AttachmentFile::objects()->filter(array(
'attachments__thread_entry__thread__id' => $this->id
))->all();
$events = $this->getEvents();
$inc = ($mode == self::MODE_STAFF) ? STAFFINC_DIR : CLIENTINC_DIR;
include $inc . 'templates/thread-entries.tmpl.php';
}
function getEntry($id) {
return ThreadEntry::lookup($id, $this->getId());
}
function getEvents() {
return $this->events;
}
/**
* postEmail
*
* After some security and sanity checks, attaches the body and subject
* of the message in reply to this thread item
*
* Parameters:
* mailinfo - (array) of information about the email, with at least the
* following keys
* - mid - (string) email message-id
* - name - (string) personal name of email originator
* - email - (string<email>) originating email address
* - subject - (string) email subject line (decoded)
* - body - (string) email message body (decoded)
*/
function postEmail($mailinfo, $entry=null) {
// +==================+===================+=============+
// | Orig Thread-Type | Reply Thread-Type | Requires |
// +==================+===================+=============+
// | * | Message (M) | From: Owner |
// | * | Note (N) | From: Staff |
// | Response (R) | Message (M) | |
// | Message (M) | Response (R) | From: Staff |
// +------------------+-------------------+-------------+
if (!$object = $this->getObject()) {
// How should someone find this thread?
return false;
}
elseif ($object instanceof Ticket && (
!$mailinfo['staffId']
&& $object->isClosed()
&& !$object->isReopenable()
)) {
// Ticket is closed, not reopenable, and email was not submitted
// by an agent. Email cannot be submitted
return false;
}
$vars = array(
'mid' => $mailinfo['mid'],
'header' => $mailinfo['header'],
'poster' => $mailinfo['name'],
'origin' => 'Email',
'source' => 'Email',
'ip' => '',
'reply_to' => $entry,
'recipients' => $mailinfo['recipients'],
'thread_entry_recipients' => $mailinfo['thread_entry_recipients'],
'to-email-id' => $mailinfo['to-email-id'],
'autorespond' => !isset($mailinfo['passive']),
);
// XXX: Is this necessary?
if ($object instanceof Ticket)
$vars['ticketId'] = $object->getId();
if ($object instanceof Task)
$vars['taskId'] = $object->getId();
$errors = array();
if (isset($mailinfo['attachments']))
$vars['attachments'] = $mailinfo['attachments'];
$body = $mailinfo['message'];
// extra handling for determining Cc collabs
if ($mailinfo['email']) {
$staffSenderId = Staff::getIdByEmail($mailinfo['email']);
if (!$staffSenderId) {
$senderId = UserEmailModel::getIdByEmail($mailinfo['email']);
if ($senderId) {
$mailinfo['userId'] = $senderId;
if ($object instanceof Ticket && $senderId != $object->user_id && $senderId != $object->staff_id) {
$mailinfo['userClass'] = 'C';
$collaboratorId = Collaborator::getIdByUserId($senderId, $this->getId());
$collaborator = Collaborator::lookup($collaboratorId);
if ($collaborator && ($collaborator->isCc()))
$vars['thread-type'] = 'M';
}
}
}
}
// Attempt to determine the user posting the entry and the
// corresponding entry type by the information determined by the
// mail parser (via the In-Reply-To header)
switch ($mailinfo['userClass']) {
case 'C': # Thread collaborator
$vars['flags'] = ThreadEntry::FLAG_COLLABORATOR;
case 'U': # Ticket owner
$vars['thread-type'] = 'M';
$vars['userId'] = $mailinfo['userId'];
break;
case 'A': # System administrator
case 'S': # Staff member (agent)
$vars['thread-type'] = 'N';
$vars['staffId'] = $mailinfo['staffId'];
if ($vars['staffId'])
$vars['poster'] = Staff::lookup($mailinfo['staffId']);
break;
// The user type was not identified by the mail parsing system. It
// is likely that the In-Reply-To and References headers were not
// properly brokered by the user's mail client. Use the old logic to
// determine the post type.
default:
// Disambiguate if the user happens also to be a staff member of
// the system. The current ticket owner should _always_ post
// messages instead of notes or responses
if ($object instanceof Ticket
&& strcasecmp($mailinfo['email'], $object->getEmail()) == 0
) {
$vars['thread-type'] = 'M';
$vars['userId'] = $object->getUserId();
}
// Consider collaborator role (disambiguate staff members as
// collaborators). Normally, the block above should match based
// on the Referenced message-id header
elseif ($C = $this->collaborators->filter(array(
'user__emails__address' => $mailinfo['email']
))->first()) {
$vars['thread-type'] = 'M';
// XXX: There's no way that mailinfo[userId] would be set
$vars['userId'] = $mailinfo['userId'] ?: $C->getUserId();
$vars['flags'] = ThreadEntry::FLAG_COLLABORATOR;
}
// Don't process the email -- it came FROM this system
elseif (Email::getIdByEmail($mailinfo['email'])) {
return false;
}
}
// Ensure we record the name of the person posting
$vars['poster'] = $vars['poster']
?: $mailinfo['name'] ?: $mailinfo['email'];
// TODO: Consider security constraints
if (!$vars['thread-type']) {
//XXX: Are we potentially leaking the email address to
// collaborators?
// Try not to destroy the format of the body
$header = sprintf(
_S('Received From: %1$s <%2$s>') . "\n\n",
$mailinfo['name'], $mailinfo['email']);
if ($body instanceof HtmlThreadEntryBody)
$header = nl2br(Format::htmlchars($header));
// Add the banner to the top of the message
if ($body instanceof ThreadEntryBody)
$body->prepend($header);
$vars['userId'] = 0; //Unknown user! //XXX: Assume ticket owner?
$vars['thread-type'] = 'M';
}
if ($mailinfo['system_emails']
&& ($t = $this->getObject())
&& $t instanceof Ticket)
$t->systemReferral($mailinfo['system_emails']);
switch ($vars['thread-type']) {
case 'M':
$vars['message'] = $body;
if ($object instanceof Threadable) {
$entry = $object->postThreadEntry('M', $vars);
if ($this->getObjectType() == 'C') {
if ($object->isChild()) {
$parent = Ticket::lookup($object->getPid());
ThreadEntry::setExtra(array($entry), array('thread' => $this->getId()), $parent->getThread()->getId());
}
}
return $entry;
}
elseif ($this instanceof ObjectThread)
return $this->addMessage($vars, $errors);
break;
case 'N':
$vars['note'] = $body;
if ($object instanceof Threadable)
return $object->postThreadEntry('N', $vars);
elseif ($this instanceof ObjectThread)
return $this->addNote($vars, $errors);
break;
}
throw new Exception('Unable to continue thread via email.');
// Currently impossible, but indicate that this thread object could
// not append the incoming email.
return false;
}
function deleteAttachments() {
$deleted = Attachment::objects()->filter(array(
'thread_entry__thread' => $this,
))->delete();
if ($deleted)
AttachmentFile::deleteOrphans();
return $deleted;
}
function removeCollaborators() {
return Collaborator::objects()
->filter(array('thread_id'=>$this->getId()))
->delete();
}
function deleteReferrals() {
return ThreadReferral::objects()
->filter(array('thread_id'=>$this->getId()))
->delete();
}
function setExtra($mergedThread, $info='') {
if ($info && $info['extra']) {
$extra = json_decode($info['extra'], true);
$entries = ThreadEntry::objects()->filter(array('thread_id' => $info['threadId']));
foreach ($entries as $entry)
$entry->saveExtra($entry, array('thread' => $info['threadId']), $mergedThread->getId());
} else
ThreadEntry::setExtra($this->getEntries(), array('thread' => $this->getId()), $mergedThread->getId());
$this->object_type = 'C';
$number = Ticket::objects()->filter(array('ticket_id'=>$this->getObjectId()))->values_flat('number')->first();
$this->extra = json_encode(array('ticket_id' => $mergedThread->getObjectId(), 'number' => $extra['number'] ?: $number[0]));
$this->save();
}
/**
* Function: lookupByEmailHeaders
*
* Attempt to locate a thread by the email headers. It should be
* considered a secondary lookup to ThreadEntry::lookupByEmailHeaders(),
* which should find an actual thread entry, which should be possible
* for all email communcation which is associated with a thread entry.
* The only time where this is useful is for threads which triggered
* email communication without a thread entry, for instance, like
* tickets created without an initial message.
*/
static function lookupByEmailHeaders(&$mailinfo) {
$possibles = array();
foreach (array('mid', 'in-reply-to', 'references') as $header) {
$matches = array();
if (!isset($mailinfo[$header]) || !$mailinfo[$header])
continue;
// Header may have multiple entries (usually separated by
// spaces ( )
elseif (!preg_match_all('/<([^>@]+@[^>]+)>/', $mailinfo[$header],
$matches))
continue;
// The References header will have the most recent message-id
// (parent) on the far right.
// @see rfc 1036, section 2.2.5
// @see http://www.jwz.org/doc/threading.html
$possibles = array_merge($possibles, array_reverse($matches[1]));
}
// Add the message id if it is embedded in the body
$match = array();
if (preg_match('`(?:class="mid-|Ref-Mid: )([^"\s]*)(?:$|")`',
$mailinfo['message'], $match)
&& !in_array($match[1], $possibles)
) {
$possibles[] = $match[1];
}
foreach ($possibles as $mid) {
// Attempt to detect the ticket and user ids from the
// message-id header. If the message originated from
// osTicket, the Mailer class can break it apart. If it came
// from this help desk, the 'loopback' property will be set
// to true.
$mid_info = osTicket\Mail\Mailer::decodeMessageId($mid);
if (!$mid_info || !$mid_info['loopback'])
continue;
if (isset($mid_info['uid'])
&& @$mid_info['threadId']
&& ($t = Thread::lookup($mid_info['threadId']))
) {
if (@$mid_info['userId']) {
$mailinfo['userId'] = $mid_info['userId'];
}
elseif (@$mid_info['staffId']) {
$mailinfo['staffId'] = $mid_info['staffId'];
}
// ThreadEntry was positively identified
return $t;
}
}
return null;
}
static function getSearchableFields() {
return array(
'lastmessage' => new DatetimeField(array(
'label' => __('Last Message'),
)),
'lastresponse' => new DatetimeField(array(
'label' => __('Last Response'),
)),
);
}
static function supportsCustomData() {
false;
}
function delete() {
//Self delete
if (!parent::delete())
return false;
// Clear email meta data (header..etc)
ThreadEntryEmailInfo::objects()
->filter(array('thread_entry__thread' => $this))
->update(array('headers' => null));
// Mass delete entries
$this->deleteAttachments();
$this->removeCollaborators();
$this->deleteReferrals();
$this->entries->delete();
// Null out the events
$this->events->update(array('thread_id' => 0));
return true;
}
static function create($vars=false) {
$inst = new static($vars);
$inst->created = SqlFunction::NOW();
return $inst;
}
}
class ThreadEntryEmailInfo extends VerySimpleModel {
static $meta = array(
'table' => THREAD_ENTRY_EMAIL_TABLE,
'pk' => array('id'),
'joins' => array(
'thread_entry' => array(
'constraint' => array('thread_entry_id' => 'ThreadEntry.id'),
),
),
);
}
class ThreadEntryMergeInfo extends VerySimpleModel {
static $meta = array(
'table' => THREAD_ENTRY_MERGE_TABLE,
'pk' => array('id'),
'joins' => array(
'thread_entry' => array(
'constraint' => array('thread_entry_id' => 'ThreadEntry.id'),
),
),
);
}
class ThreadEntry extends VerySimpleModel
implements TemplateVariable {
static $meta = array(
'table' => THREAD_ENTRY_TABLE,
'pk' => array('id'),
'select_related' => array('staff', 'user', 'email_info'),
'ordering' => array('created', 'id'),
'joins' => array(
'thread' => array(
'constraint' => array('thread_id' => 'Thread.id'),
),
'parent' => array(
'constraint' => array('pid' => 'ThreadEntry.id'),
'null' => true,
),
'children' => array(
'reverse' => 'ThreadEntry.parent',
),
'email_info' => array(
'reverse' => 'ThreadEntryEmailInfo.thread_entry',
'list' => false,
),
'merge_info' => array(
'reverse' => 'ThreadEntryMergeInfo.thread_entry',
'list' => false,
),
'attachments' => array(
'reverse' => 'Attachment.thread_entry',
'null' => true,
),
'staff' => array(
'constraint' => array('staff_id' => 'Staff.staff_id'),
'null' => true,
),
'user' => array(
'constraint' => array('user_id' => 'User.id'),
'null' => true,
),
),
);
const FLAG_ORIGINAL_MESSAGE = 0x0001;
const FLAG_EDITED = 0x0002;
const FLAG_HIDDEN = 0x0004;
const FLAG_GUARDED = 0x0008; // No replace on edit
const FLAG_RESENT = 0x0010;
const FLAG_COLLABORATOR = 0x0020; // Message from collaborator
const FLAG_BALANCED = 0x0040; // HTML does not need to be balanced on ::display()
const FLAG_SYSTEM = 0x0080; // Entry is a system note.
const FLAG_REPLY_ALL = 0x00100; // Agent response, reply all
const FLAG_REPLY_USER = 0x00200; // Agent response, reply to User
const FLAG_CHILD = 0x00400; // Entry is from a child Ticket
const PERM_EDIT = 'thread.edit';
var $_headers;
var $_body;
var $_thread;
var $_actions;
var $is_autoreply;
var $is_bounce;
static protected $perms = array(
self::PERM_EDIT => array(
'title' => /* @trans */ 'Edit Thread',
'desc' => /* @trans */ 'Ability to edit thread items of other agents',
),
);
// Thread entry types
static protected $types = array(
'M' => 'message',
'R' => 'response',
'N' => 'note',
);
function getTypeName() {
return self::$types[$this->type];
}
function postEmail($mailinfo) {
global $ost;
if (!($thread = $this->getThread()))
// Kind of hard to continue a discussion without a thread ...
return false;
elseif ($this->getEmailMessageId() == $mailinfo['mid'])
// Reporting success so the email can be moved or deleted.
return true;
// Mail sent by this system will have a predictable message-id
// If this incoming mail matches the code, then it very likely
// originated from this system and looped
$info = osTicket\Mail\Mailer::decodeMessageId($mailinfo['mid']);
if ($info && $info['loopback']) {
// This mail was sent by this system. It was received due to
// some kind of mail delivery loop. It should not be considered
// a response to an existing thread entry
if ($ost)
$ost->log(LOG_ERR, _S('Email loop detected'), sprintf(
_S('It appears as though %s is being used as a forwarded or fetched email account and is also being used as a user / system account. Please correct the loop or seek technical assistance.\n\n%s'),
$mailinfo['email'], $mailinfo['header']),
// This is quite intentional -- don't continue the loop
false,
// Force the message, even if logging is disabled
true);
return $this;
}
return $thread->postEmail($mailinfo, $this);
}
function getId() {
return $this->id;
}
function getPid() {
return $this->get('pid', 0);
}
function getParent() {
return $this->parent;
}
function getType() {
return $this->type;
}
function getSource() {
return $this->source;
}
function getPoster() {
return $this->poster;
}
function getTitle() {
return $this->title;
}
function getBody() {
if (!isset($this->_body)) {
$body = $this->body;
if ($body == null && $this->getNumAttachments()) {
$attachments = Attachment::objects()
->filter(array(
'inline' => 1,
'object_id' => $this->getId(),
'type' => ObjectModel::OBJECT_TYPE_THREAD,
'file__type__in' => array('text/html','text/plain'))
);
foreach ($attachments as $a)
if ($a->inline && ($f=$a->getFile()))
$body .= $f->getData();
}
$this->_body = ThreadEntryBody::fromFormattedText($body, $this->format,
array('balanced' => $this->hasFlag(self::FLAG_BALANCED))
);
}
return $this->_body;
}
function setBody($body) {
global $cfg;
if (!$body instanceof ThreadEntryBody) {
if ($cfg->isRichTextEnabled())
$body = new HtmlThreadEntryBody($body);
else
$body = new TextThreadEntryBody($body);
}
$this->format = $body->getType();
$this->body = (string) $body;
return $this->save();
}
function getMessage() {
return $this->getBody();
}
function getCreateDate() {
return $this->created;
}
function getUpdateDate() {
return $this->updated;
}
function getNumAttachments() {
return $this->attachments->count();
}
function getEmailMessageId() {
if ($this->email_info)
return $this->email_info->mid;
}
function getEmailHeaderArray() {
require_once(INCLUDE_DIR.'class.mailparse.php');