-
Notifications
You must be signed in to change notification settings - Fork 2
/
datamodel.itop-standard-email-synchro.xml
executable file
·1573 lines (1509 loc) · 60 KB
/
datamodel.itop-standard-email-synchro.xml
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
<?xml version="1.0" encoding="UTF-8"?>
<itop_design xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<classes>
<class id="MailInboxStandard" _delta="define">
<parent>MailInboxBase</parent>
<properties>
<category>grant_by_profile,application</category>
<abstract>false</abstract>
<key_type>autoincrement</key_type>
<db_table>mailinbox_standard</db_table>
<db_key_field>id</db_key_field>
<db_final_class_field>realclass</db_final_class_field>
<naming>
<format>%1$s</format>
<attributes>
<attribute id="login"/>
</attributes>
</naming>
<display_template/>
<icon>images/mailbox.png</icon>
<reconciliation>
<attributes>
<attribute id="server"/>
<attribute id="login"/>
<attribute id="protocol"/>
<attribute id="mailbox"/>
<attribute id="port"/>
</attributes>
</reconciliation>
</properties>
<fields>
<field id="behavior" xsi:type="AttributeEnum">
<values>
<value>create_only</value>
<value>update_only</value>
<value>both</value>
</values>
<sql>behavior</sql>
<default_value>both</default_value>
<is_null_allowed>false</is_null_allowed>
</field>
<field id="target_class" xsi:type="AttributeEnum">
<values>
<value>Incident</value>
<value>UserRequest</value>
<value>Change</value>
<value>RoutineChange</value>
<value>NormalChange</value>
<value>EmergencyChange</value>
<value>Problem</value>
</values>
<sql>target_class</sql>
<default_value>UserRequest</default_value>
<is_null_allowed>false</is_null_allowed>
</field>
<field id="ticket_default_values" xsi:type="AttributeText">
<sql>ticket_default_values</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="ticket_default_title" xsi:type="AttributeString">
<sql>ticket_default_title</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="title_pattern" xsi:type="AttributeString">
<sql>title_pattern</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="unknown_caller_behavior" xsi:type="AttributeEnum">
<values>
<value>create_contact</value>
<value>reject_email</value>
</values>
<sql>unknown_caller_behavior</sql>
<default_value>reject_email</default_value>
<is_null_allowed>false</is_null_allowed>
</field>
<field id="unknown_caller_rejection_reply" xsi:type="AttributeText">
<sql>unknown_caller_rejection_reply</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="caller_default_values" xsi:type="AttributeText">
<sql>caller_default_values</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="error_behavior" xsi:type="AttributeEnum">
<values>
<value>delete</value>
<value>mark_as_error</value>
</values>
<sql>error_behavior</sql>
<default_value>mark_as_error</default_value>
<is_null_allowed>false</is_null_allowed>
</field>
<field id="notify_errors_to" xsi:type="AttributeEmailAddress">
<sql>notify_errors_to</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="notify_errors_from" xsi:type="AttributeEmailAddress">
<sql>notify_errors_from</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="trace" xsi:type="AttributeEnum">
<values>
<value>yes</value>
<value>no</value>
</values>
<sql>trace</sql>
<default_value>no</default_value>
<is_null_allowed>false</is_null_allowed>
</field>
<field id="debug_trace" xsi:type="AttributeLongText">
<sql>debug_trace</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="email_storage" xsi:type="AttributeEnum">
<values>
<value>keep</value>
<value>delete</value>
<value>move</value>
</values>
<sql>email_storage</sql>
<default_value>keep</default_value>
<is_null_allowed>false</is_null_allowed>
</field>
<field id="target_folder" xsi:type="AttributeString">
<sql>target_folder</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
<field id="import_additional_contacts" xsi:type="AttributeEnum">
<values>
<value>never</value>
<value>only_on_creation</value>
<value>only_on_update</value>
<value>always</value>
</values>
<sql>import_additional_contacts</sql>
<default_value>never</default_value>
<is_null_allowed>false</is_null_allowed>
</field>
<field id="stimuli" xsi:type="AttributeText">
<sql>stimuli</sql>
<default_value/>
<is_null_allowed>true</is_null_allowed>
</field>
</fields>
<methods>
<method id="DisplayBareRelations">
<comment>/**
* Add an extra tab showing the debug trace
* @see cmdbAbstractObject::DisplayBareRelations()
*/</comment>
<static>false</static>
<access>public</access>
<type>Overload-cmdbAbstractObject</type>
<code><![CDATA[ function DisplayBareRelations(WebPage $oPage, $bEditMode = false)
{
parent::DisplayBareRelations($oPage, $bEditMode);
if (!$bEditMode)
{
$oPage->SetCurrentTab(Dict::S('MailInboxStandard:DebugTrace'));
$sAjaxUrl = addslashes(utils::GetAbsoluteUrlModulesRoot().basename(dirname(__FILE__)).'/ajax.php');
$iId = $this->GetKey();
if ($this->Get('trace') == 'yes')
{
$oPage->add('<p><button type="button" class="ibo-button ibo-is-regular ibo-is-neutral" id="debug_trace_refresh">'.Dict::S('UI:Button:Refresh').'</button></p>');
$oPage->add('<div id="debug_trace_output"></div>');
$oPage->add_ready_script(
<<<EOF
$('#debug_trace_refresh').click(function() {
$('#debug_trace_output').html('<img src="../images/indicator.gif"/>');
$.post('$sAjaxUrl', {operation: 'debug_trace', id: $iId }, function(data) {
$('#debug_trace_output').html(data);
});
});
$('#debug_trace_refresh').trigger('click');
EOF
);
}
else
{
$oPage->add('<div id="debug_trace_output"><p>'.Dict::S('MailInboxStandard:DebugTraceNotActive').'</p></div>');
}
}
}]]></code>
</method>
<method id="Trace">
<comment>/**
* Debug trace: activated/disabled by the configuration flag set for the base module...
* @param string $sText
*/</comment>
<static>false</static>
<access>public</access>
<type>Overload-cmdbAbstractObject</type>
<code><![CDATA[ public function Trace($sText)
{
parent::Trace($sText);
$iMaxTraceLength = 500*1024; // Maximum size of the Trace to keep in the database...
if ($this->Get('trace') == 'yes')
{
$sStampedText = date('Y-m-d H:i:s').' - '.$sText."\n";
$this->Set('debug_trace', mb_substr($this->Get('debug_trace').$sStampedText, -$iMaxTraceLength));
$this->DBUpdate();
}
}]]></code>
</method>
<method id="RecordAttChanges">
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function RecordAttChanges(array $aValues, array $aOrigValues)
{
// Do NOT record the changes on the 'debug trace' attribute
unset($aValues['debug_trace']);
parent::RecordAttChanges($aValues, $aOrigValues);
}]]></code>
</method>
<method id="DispatchEmail">
<comment>/**
* Initial dispatching of an incoming email: determines what to do with the email
* @param EmailReplica $oEmailReplica The EmailReplica associated with the email. A new replica (i.e. not yet in DB) one for new emails
* @return int An action code from EmailProcessor
*/</comment>
<static>false</static>
<access>public</access>
<type>Overload-DBObject</type>
<code> public function DispatchEmail(EmailReplica $oEmailReplica)
{
return parent::DispatchEmail($oEmailReplica);
}</code>
</method>
<method id="ProcessNewEmail">
<comment>/**
* Process an new (unread) incoming email
* @param EmailSource $oSource The source from which this email was read
* @param int $index The index of the message in the source
* @param EmailMessage $oEmail The decoded email
* @return Ticket The ticket created or updated in response to the email
*/</comment>
<static>false</static>
<access>public</access>
<type>Overload-DBObject</type>
<code><![CDATA[ public function ProcessNewEmail(EmailSource $oSource, $index, EmailMessage $oEmail)
{
$this->sLastError = null;
$this->Trace("Processing new eMail (index = $index)");
$oTicket = null;
if ($this->IsUndesired($oEmail))
{
$this->HandleError($oEmail, 'undesired_message', $oEmail->oRawEmail);
return null;
}
try
{
// Search if the caller email is an existing contact in iTop
$oCaller = $this->FindCaller($oEmail);
if ($oCaller === null)
{
// Cannot create/update a ticket if the caller is unknown
return null;
}
// Check whether we need to create a new ticket or to update an existing one
$oTicket = $this->GetRelatedTicket($oEmail);
switch($this->Get('behavior'))
{
case 'create_only':
$oTicket = $this->CreateTicketFromEmail($oEmail, $oCaller);
break;
case 'update_only':
if (!is_object($oTicket))
{
// No ticket associated with the incoming email, nothing to update, reject the email
$this->HandleError($oEmail, 'nothing_to_update', $oEmail->oRawEmail);
}
else
{
// Update the ticket with the incoming eMail
$this->UpdateTicketFromEmail($oTicket, $oEmail, $oCaller);
}
break;
default: // both: update or create as needed
if (!is_object($oTicket))
{
// Let's create a new ticket
$oTicket = $this->CreateTicketFromEmail($oEmail, $oCaller);
}
else
{
// Update the ticket with the incoming eMail
$this->UpdateTicketFromEmail($oTicket, $oEmail, $oCaller);
}
break;
}
return $oTicket;
}
catch(Exception $e)
{
$sExceptionMessage = $e->getMessage();
$sExceptionStack = $e->getTraceAsString();
$this->Trace("ERROR occurred during mail processing : $sExceptionMessage\n$sExceptionStack");
$this->HandleError($oEmail, 'error during processing', $oEmail->oRawEmail);
}
}]]></code>
</method>
<method id="FindCaller">
<comment>/**
* Search if the caller email is an existing contact in iTop, if not may create it
* depending on the mailinbox setting.
* {@inheritDoc}
* @see MailInboxBase::FindCaller()
*/</comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function FindCaller(EmailMessage $oEmail)
{
$oCaller = null;
$sContactQuery = 'SELECT Person WHERE email = :email';
$oSet = new DBObjectSet(DBObjectSearch::FromOQL($sContactQuery), array(), array('email' => $oEmail->sCallerEmail));
$sAdditionalDescription = '';
switch($oSet->Count())
{
case 1:
// Ok, the caller was found in iTop
$oCaller = $oSet->Fetch();
break;
case 0:
switch($this->Get('unknown_caller_behavior'))
{
case 'reject_email':
$this->Trace('No contact found for the email address "'.$oEmail->sCallerEmail.'", the email will not be processed');
$this->HandleError($oEmail, 'unknown_contact', $oEmail->oRawEmail);
return null;
break;
case 'create_contact':
default:
$this->Trace("Creating a new Person for the email: {$oEmail->sCallerEmail}");
$oCaller = new Person();
$oCaller->Set('email', $oEmail->sCallerEmail);
$sDefaultValues = $this->Get('caller_default_values');
$aDefaults = explode("\n", $sDefaultValues);
$aDefaultValues = array();
foreach($aDefaults as $sLine)
{
if (preg_match('/^([^:]+):(.*)$/', $sLine, $aMatches))
{
$sAttCode = trim($aMatches[1]);
$sValue = trim($aMatches[2]);
$aDefaultValues[$sAttCode] = $sValue;
}
}
$this->InitObjectFromDefaultValues($oCaller, $aDefaultValues);
try
{
$oCaller->DBInsert();
}
catch(Exception $e)
{
$this->Trace('Failed to create a Person for the email address "'.$oEmail->sCallerEmail.'".');
$this->Trace($e->getMessage());
$this->HandleError($oEmail, 'failed_to_create_contact', $oEmail->oRawEmail);
return null;
}
}
break;
default:
$this->Trace('Found '.$oSet->Count().' callers with the same email address "'.$oEmail->sCallerEmail.'", the first one will be used...');
// Multiple callers with the same email address !!!
$oCaller = $oSet->Fetch();
}
return $oCaller;
}]]></code>
</method>
<method id="GetRelatedTicket">
<comment>/**
*
* {@inheritDoc}
* @see MailInboxBase::GetRelatedTicket()
*/</comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function GetRelatedTicket(EmailMessage $oEmail)
{
// First check if there is any iTop object mentioned in the headers of the eMail
$oTicket = parent::GetRelatedTicket($oEmail);
if (!is_null($oTicket)){
return $oTicket;
}
if (MetaModel::GetModuleSetting('itop-standard-email-synchro', 'aggregate_replies', true) === true) {
if (array_key_exists('in-reply-to', $oEmail->aHeaders)) {
$sInReplyToMsgId = $oEmail->aHeaders['in-reply-to'];
$sOQL = "SELECT EmailReplica WHERE message_id = :in_reply_to";
$oSet = new DBObjectSet(DBObjectSearch::FromOQL($sOQL), array(), array('in_reply_to' => $sInReplyToMsgId));
$oSet->OptimizeColumnLoad(['EmailReplica'=>['ticket_id']]);
$iEmailReplicaCount = $oSet->Count();
if ($iEmailReplicaCount > 0){
/** @var EmailReplica $oEmailReplica */
$oEmailReplica = $oSet->Fetch();
if ($iEmailReplicaCount > 1) {
$this->Trace("iTop Simple Email Synchro: WARNING the message ({$oEmail->sUIDL}) replies to the message_id=".$sInReplyToMsgId."
This message_id corresponds to $iEmailReplicaCount email replica in iTop.");
}
$oTicket = MetaModel::GetObject('Ticket', $oEmailReplica->Get('ticket_id'), false);
if (is_null($oTicket)) {
$this->Trace("iTop Simple Email Synchro: WARNING the message ({$oEmail->sUIDL}) got a EmailReplica#{$oEmailReplica->GetKey()}
with the ticket_id={$oEmailReplica->Get('ticket_id')} but the ticket does not exist.");
} elseif (MetaModel::IsValidAttCode(get_class($oTicket), "operational_status") && $oTicket->Get("operational_status") === "closed") {
$this->Trace("iTop Simple Email Synchro: WARNING the message ({$oEmail->sUIDL}) is related to the CLOSED (operational_status) ticket {$oTicket->Get('id')}");
return null;
} elseif (MetaModel::IsValidAttCode(get_class($oTicket), "status") && $oTicket->Get("status") === "closed") {
$this->Trace("iTop Simple Email Synchro: WARNING the message ({$oEmail->sUIDL}) is related to the CLOSED (status) ticket {$oTicket->Get('id')}");
return null;
}
else {
return $oTicket;
}
}
}
}
// No associated ticket found by parsing the headers, check
// if the subject does not match a specific pattern
$sPattern = $this->FixPattern($this->Get('title_pattern'));
if(($sPattern != '') && (preg_match($sPattern, $oEmail->sSubject, $aMatches)))
{
$oFilter = DBSearch::FromOQL('SELECT Ticket WHERE ref = :ref');
foreach ($aMatches as $sMatch)
{
if (!empty($sMatch))
{
$this->Trace("iTop Simple Email Synchro: Retrieving ticket $sMatch (match by subject pattern)...");
$oSet = new DBObjectSet($oFilter, array(), array('ref' => $sMatch));
$oTicket = $oSet->Fetch();
if ($oTicket)
{
break;
}
}
}
}
return $oTicket;
}]]></code>
</method>
<method id="CreateTicketFromEmail">
<comment><![CDATA[/**
* Actual creation of the ticket from the incoming email. Overload this method
* to implement your own behavior, if needed
*
* @param EmailMessage $oEmail The decoded incoming email
* @param Contact $oCaller The contact corresponding to the "From" email address
*
* @return Ticket the created ticket or null in case of failure
* @throws \Exception if invalid target_class
*/]]></comment>
<static>false</static>
<access>public</access>
<type>Overload-DBObject</type>
<code><![CDATA[ public function CreateTicketFromEmail(EmailMessage $oEmail, Contact $oCaller)
{
// In case of error (exception...) set the behavior
if ($this->Get('error_behavior') == 'delete')
{
$this->SetNextAction(EmailProcessor::DELETE_MESSAGE); // Remove the message from the mailbox
}
else
{
$this->SetNextAction(EmailProcessor::MARK_MESSAGE_AS_ERROR); // Keep the message in the mailbox, but marked as error
}
$this->Trace("Creating a new Ticket from eMail '".$oEmail->sSubject."'");
if (!MetaModel::IsValidClass($this->Get('target_class')))
{
throw new Exception('Invalid "ticket_class" configured: "'.$this->Get('target_class').'" is not a valid class. Cannot create such an object.');
}
$iCurrentUserId = UserRights::GetUserId();
$bInsertChangeUserId = false;
// Set changes author to mail author and create a new Change
if(method_exists('UserRights', 'GetUserFromPerson') && $oCaller !== null){
$oUser = UserRights::GetUserFromPerson($oCaller, true);
if($oUser !== null){
CMDBObject::SetTrackUserId($oUser->GetKey());
$oCMDBChange = CMDBObject::GetCurrentChange();
CMDBObject::SetCurrentChange(null);
$bInsertChangeUserId = true;
}
}
$oTicket = MetaModel::NewObject($this->Get('target_class'));
$oTicket->Set('org_id', $oCaller->Get('org_id'));
if (MetaModel::IsValidAttCode(get_class($oTicket), 'caller_id'))
{
$oTicket->Set('caller_id', $oCaller->GetKey());
}
if (MetaModel::IsValidAttCode(get_class($oTicket), 'origin'))
{
$oTicket->Set('origin', 'mail');
}
if ($oEmail->sSubject == '')
{
$sDefaultSubject = ($this->Get('ticket_default_title') == '') ? Dict::S('MailInbox:NoSubject') : $this->Get('ticket_default_title');
$this->Trace("The incoming email has no subject, the ticket's title will be set to: '$sDefaultSubject'");
$oTicket->Set('title', $sDefaultSubject);
}
else
{
$oTicketTitleAttDef = MetaModel::GetAttributeDef(get_class($oTicket), 'title');
$iTitleMaxSize = $oTicketTitleAttDef->GetMaxSize();
$oTicket->Set('title', substr($oEmail->sSubject, 0, $iTitleMaxSize));
}
$aIgnoredAttachments = array();
// Insert the remaining attachments so that we know their ID and can reference them in the message's body
$aAddedAttachments = $this->AddAttachments($oTicket, $oEmail, true, $aIgnoredAttachments, $oCaller, $oUser); // Cannot insert them for real since the Ticket is not saved yet (we don't know its ID)
// we'll have to call UpdateAttachments once the ticket is properly saved
$oTicketDescriptionAttDef = MetaModel::GetAttributeDef(get_class($oTicket), 'description');
$bForPlainText = true; // Target format is plain text (by default)
if ($oTicketDescriptionAttDef instanceof AttributeHTML)
{
// Target format is HTML
$bForPlainText = false;
}
else if ($oTicketDescriptionAttDef instanceof AttributeText)
{
$aParams = $oTicketDescriptionAttDef->GetParams();
if (array_key_exists('format', $aParams) && ($aParams['format'] == 'html'))
{
// Target format is HTML
$bForPlainText = false;
}
}
$this->Trace("Target format for 'description': ".($bForPlainText ? 'text/plain' : 'text/html'));
$this->Trace("Email body format: ".$oEmail->sBodyFormat);
$sTicketDescription = $this->BuildDescription($oEmail, $aAddedAttachments, $aIgnoredAttachments, $bForPlainText);
$iDescriptionMaxSize = $oTicketDescriptionAttDef->GetMaxSize() - 1000; // Keep some room just in case...
if (mb_strlen($sTicketDescription) > $iDescriptionMaxSize)
{
$sMsg = "CreateTicketFromEmail: Truncated description for [{$oTicket->Get('title')}] actual length: ".mb_strlen($sTicketDescription)." maximum: $iDescriptionMaxSize";
IssueLog::Error($sMsg);
$this->Trace($sMsg);
// This has no effect, attachments have already been processed
$oEmail->aAttachments[] = array('content' => $sTicketDescription, 'filename' => ($bForPlainText ? 'original message.txt' : 'original message.html'), 'mimeType' => ($bForPlainText ? 'text/plain' : 'text/html'));
}
$oTicket->Set('description', $this->FitTextIn($sTicketDescription, $iDescriptionMaxSize));
// Default values
$sDefaultValues = $this->Get('ticket_default_values');
$aDefaults = explode("\n", $sDefaultValues);
$aDefaultValues = array();
foreach($aDefaults as $sLine)
{
if (preg_match('/^([^:]+):(.*)$/', $sLine, $aMatches))
{
$sAttCode = trim($aMatches[1]);
$sValue = trim($aMatches[2]);
$aDefaultValues[$sAttCode] = $sValue;
}
}
$this->InitObjectFromDefaultValues($oTicket, $aDefaultValues);
if (($this->Get('import_additional_contacts') == 'always') || ($this->Get('import_additional_contacts') == 'only_on_creation'))
{
$this->AddAdditionalContacts($oTicket, $oEmail);
}
$this->BeforeInsertTicket($oTicket, $oEmail, $oCaller);
$oTicket->DBInsert();
$this->Trace("Ticket ".$oTicket->GetName()." created.");
$this->AfterInsertTicket($oTicket, $oEmail, $oCaller, $aAddedAttachments);
// Restore previous change as current change
if($bInsertChangeUserId === true){
CMDBObject::SetTrackUserId($iCurrentUserId);
CMDBObject::SetCurrentChange($oCMDBChange);
}
return $oTicket;
}]]></code>
</method>
<method id="BuildDescription">
<comment><![CDATA[/**
* Build the 'description' of the ticket when creating a new ticket
* @param EmailMessage $oEmail The incoming Email
* @param bool $bForPlainText True if the desired output format is plain text, false if HTML
* @return string
*/]]></comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function BuildDescription(EmailMessage $oEmail, $aAddedAttachments, $aIgnoredAttachments, $bForPlainText)
{
$sTicketDescription = '';
if ($oEmail->sBodyFormat == 'text/html')
{
// Original message is in HTML
$this->Trace("Managing inline images...");
$sTicketDescription = $this->ManageInlineImages($oEmail->sBodyText, $aAddedAttachments, $aIgnoredAttachments, $bForPlainText);
if ($bForPlainText)
{
$this->Trace("Converting HTML to text using utils::HtmlToText...");
$sTicketDescription = utils::HtmlToText($oEmail->sBodyText);
}
}
else
{
// Original message is in plain text
$sTicketDescription = utils::TextToHtml($oEmail->sBodyText);
if (!$bForPlainText)
{
$this->Trace("Converting text to HTML using utils::TextToHtml...");
$sTicketDescription = utils::TextToHtml($oEmail->sBodyText);
}
}
if (empty($sTicketDescription))
{
$sTicketDescription = 'No description provided.';
}
return $sTicketDescription;
}]]></code>
</method>
<method id="AddAdditionalContacts">
<comment>/**
* Add the contacts in To: or CC: as additional contacts to the ticket (if they exist in the DB)
* @param Ticket $oTicket
* @param EmailMessage $oEmail
*/</comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function AddAdditionalContacts(Ticket $oTicket, EmailMessage $oEmail)
{
$oContactsSet = $oTicket->Get('contacts_list');
$aExistingContacts = array();
while($oLnk = $oContactsSet->Fetch())
{
$aExistingContacts[$oLnk->Get('contact_id')] = true;
}
$aAdditionalContacts = array_merge($oEmail->aTos, $oEmail->aCCs); // Take both the To: and CC:, no actual merge since the keys of the arrays are numeric (i.e. 0, 1, 2...)
foreach($aAdditionalContacts as $aInfo)
{
$sCallerEmail = $oTicket->Get('caller_id->email');
// Exclude the caller from the additional contacts
if ($aInfo['email'] != $sCallerEmail && $aInfo['email'] != $this->Get('login'))
{
$oContact = $this->FindAdditionalContact($aInfo['email']);
if (($oContact != null) && !array_key_exists($oContact->GetKey(), $aExistingContacts))
{
$oLnk = new lnkContactToTicket();
$oLnk->Set('contact_id', $oContact->GetKey());
$oContactsSet->AddItem($oLnk);
}
}
else
{
$this->Trace('Skipping "'.$aInfo['email'].'" from the email address in To/CC since it is the same as the caller\'s email or mailbox\'s email.');
}
}
$oTicket->Set('contacts_list', $oContactsSet);
}]]></code>
</method>
<method id="FindAdditionalContact">
<comment>/**
* Search if the CC email is an existing contact in iTop, if so return it, otherwise ignore it
* @param $sEmail string The email address to seach
* @return Contact | null
*/</comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function FindAdditionalContact($sEmail)
{
$oContact = null;
$sContactQuery = 'SELECT Contact WHERE email = :email';
$oSet = new DBObjectSet(DBObjectSearch::FromOQL($sContactQuery), array(), array('email' => $sEmail));
switch($oSet->Count())
{
case 1:
// Ok, the caller was found in iTop
$oContact = $oSet->Fetch();
$this->Trace('Found Contact::'.$oContact->GetKey().' ('.$oContact->GetName().') from the email address in To/CC "'.$sEmail.'".');
break;
case 0:
$this->Trace('No contact found with the email address in To/CC "'.$sEmail.'", email address ignored.');
break;
default:
$this->Trace('Found '.$oSet->Count().' contacts with the same email address in To/CC "'.$sEmail.'", the first one will be used...');
// Multiple contacts with the same email address !!!
$oContact = $oSet->Fetch();
}
return $oContact;
}]]></code>
</method>
<method id="BeforeInsertTicket">
<comment>/**
* Handler called just before inserting the ticket into the database
* Overload this method to adjust the values of the ticket at your will
* @param Ticket $oTicket
* @param EmailMessage $oEmail
* @param Contact $oCaller
*/</comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code> protected function BeforeInsertTicket(Ticket $oTicket, EmailMessage $oEmail, Contact $oCaller)
{
// Default implementation: do nothing
}</code>
</method>
<method id="AfterInsertTicket">
<comment>/**
* Finalize the processing after the insertion of the ticket in the database
* @param Ticket $oTicket The ticket being written
* @param EmailMessage $oEmail The source email
* @param Contact $oCaller The caller for this ticket, as passed to CreateTicket
* @param array $aAddedAttachments The array of attachments added to the ticket
*/</comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function AfterInsertTicket(Ticket $oTicket, EmailMessage $oEmail, Contact $oCaller, $aAddedAttachments)
{
// Process attachments
$this->UpdateAttachments($aAddedAttachments, $oTicket); // Now update the attachments since we know the ID of the ticket
// Shall we delete the source email immediately?
if ($this->Get('email_storage') == 'delete')
{
// Remove the processed message from the mailbox
$this->Trace("Ticket created, deleting the source eMail '".$oEmail->sSubject."'");
$this->SetNextAction(EmailProcessor::DELETE_MESSAGE);
}
else if ($this->Get('email_storage') == 'move')
{
// Remove the processed message from the mailbox
$this->Trace("Ticket created, move the source eMail '".$oEmail->sSubject."'");
$this->SetNextAction(EmailProcessor::MOVE_MESSAGE);
}
else
{
// Keep the message in the mailbox
$this->SetNextAction(EmailProcessor::NO_ACTION);
}
}]]></code>
</method>
<method id="UpdateTicketFromEmail">
<comment><![CDATA[/**
* Actual update of a ticket from the incoming email. Overload this method
* to implement your own behavior, if needed
* @param Ticket $oTicket The ticket to update
* @param EmailMessage $oEmail The decoded incoming email
* @param Contact $oCaller The contact corresponding to the "From" email address
* @return void
*/]]></comment>
<static>false</static>
<access>public</access>
<type>Overload-DBObject</type>
<code><![CDATA[ public function UpdateTicketFromEmail(Ticket $oTicket, EmailMessage $oEmail, Contact $oCaller)
{
// In case of error (exception...) set the behavior
if ($this->Get('error_behavior') == 'delete')
{
$this->SetNextAction(EmailProcessor::DELETE_MESSAGE); // Remove the message from the mailbox
}
else
{
$this->SetNextAction(EmailProcessor::MARK_MESSAGE_AS_ERROR); // Keep the message in the mailbox, but marked as error
}
// Check that the ticket is of the expected class
if (!is_a($oTicket, $this->Get('target_class')))
{
$this->Trace("iTop Simple Email Synchro: Error: the incoming email refers to the ticket ".$oTicket->GetName()." of class ".get_class($oTicket).", but this mailbox is configured to process only tickets of class ".$this->Get('target_class'));
$this->SetNextAction(EmailProcessor::MARK_MESSAGE_AS_ERROR); // Keep the message in the mailbox, but marked as error
return;
}
// Try to extract what's new from the message's body
$this->Trace("iTop Simple Email Synchro: Updating the iTop ticket ".$oTicket->GetName()." from eMail '".$oEmail->sSubject."'");
$iCurrentUserId = UserRights::GetUserId();
$bInsertChangeUserId = false;
// Set changes author to mail author and create a new Change
if(method_exists('UserRights', 'GetUserFromPerson') && $oCaller !== null){
$oUser = UserRights::GetUserFromPerson($oCaller, true);
if($oUser !== null){
CMDBObject::SetTrackUserId($oUser->GetKey());
$oCMDBChange = CMDBObject::GetCurrentChange();
CMDBObject::SetCurrentChange(null);
$bInsertChangeUserId = true;
}
}
// Process attachments
$aIgnoredAttachments = array();
$aAddedAttachments = $this->AddAttachments($oTicket, $oEmail, true, $aIgnoredAttachments, $oCaller, $oUser);
$sCaseLogEntry = $this->BuildCaseLogEntry($oEmail, $aAddedAttachments, $aIgnoredAttachments);
$this->Trace($oEmail->sTrace);
// Write the log on behalf of the caller
$sCallerName = $oEmail->sCallerName;
if (empty($sCallerName))
{
$sCallerName = $oEmail->sCallerEmail;
}
// Determine which field to update
$sAttCode = 'public_log';
$aAttCodes = MetaModel::GetModuleSetting('itop-standard-email-synchro', 'ticket_log', array('UserRequest' => 'public_log', 'Incident' => 'public_log'));
if (array_key_exists(get_class($oTicket), $aAttCodes))
{
$sAttCode = $aAttCodes[get_class($oTicket)];
}
$oLog = $oTicket->Get($sAttCode);
if($bInsertChangeUserId === true){
$oLog->AddLogEntry($sCaseLogEntry, $sCallerName, $oUser->GetKey());
}
else{
$oLog->AddLogEntry($sCaseLogEntry, $sCallerName);
}
$oTicket->Set($sAttCode, $oLog);
if (($this->Get('import_additional_contacts') == 'always') || ($this->Get('import_additional_contacts') == 'only_on_update'))
{
$this->AddAdditionalContacts($oTicket, $oEmail);
}
$this->BeforeUpdateTicket($oTicket, $oEmail, $oCaller);
$oTicket->DBUpdate();
$this->Trace("Ticket ".$oTicket->GetName()." updated.");
$this->AfterUpdateTicket($oTicket, $oEmail, $oCaller);
// Restore previous change as current change
if($bInsertChangeUserId === true){
CMDBObject::SetTrackUserId($iCurrentUserId);
CMDBObject::SetCurrentChange($oCMDBChange);
}
return $oTicket;
}]]></code>
</method>
<method id="BuildCaseLogEntry">
<comment>/**
* Build the text/html to be inserted in the case log when the ticket is updated
* Starting with iTop 2.3.0, the format is always HTML
* @param EmailMessage $oEmail
* @return string The HTML text to be inserted in the case log
*/</comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function BuildCaseLogEntry(EmailMessage $oEmail, $aAddedAttachments, $aIgnoredAttachments)
{
$sCaseLogEntry = '';
$this->Trace("Email body format: ".$oEmail->sBodyFormat);
if ($oEmail->sBodyFormat == 'text/html')
{
$this->Trace("Extracting the new part using GetNewPartHTML...");
$sCaseLogEntry = $oEmail->GetNewPartHTML($oEmail->sBodyText);
if (strip_tags($sCaseLogEntry) == '')
{
// No new part (only blank tags)... we'd better use the whole text of the message
$sCaseLogEntry = $oEmail->sBodyText;
}
$this->Trace("Managing inline images...");
$sCaseLogEntry = $this->ManageInlineImages($sCaseLogEntry, $aAddedAttachments, $aIgnoredAttachments, false /* $bForPlainText */);
}
else
{
$this->Trace("Extracting the new part using GetNewPart...");
$sCaseLogEntry = $oEmail->GetNewPart($oEmail->sBodyText, $oEmail->sBodyFormat); // GetNewPart always returns a plain text version of the message
$sCaseLogEntry = utils::TextToHtml($sCaseLogEntry);
}
return $sCaseLogEntry;
}]]></code>
</method>
<method id="BeforeUpdateTicket">
<comment>/**
* Handler called before updating a ticket in the database
* Overload this method to alter the ticket at your will
* @param Ticket $oTicket
* @param EmailMessage $oEmail
* @param Contact $oCaller
*/</comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code> protected function BeforeUpdateTicket(Ticket $oTicket, EmailMessage $oEmail, Contact $oCaller)
{
// Default implementation: do nothing
}</code>
</method>
<method id="ApplyConfiguredStimulus">
<comment><![CDATA[/**
* Read the configuration in the 'stimuli' field (format: <state_code>:<stimulus_code>, one per line)
* and apply the corresponding stimulus according to the current state of the ticket
* @param ticket $oTicket
*/]]></comment>
<static>false</static>
<access>protected</access>
<type>Overload-DBObject</type>
<code><![CDATA[ protected function ApplyConfiguredStimulus(ticket $oTicket)
{
$sConf = $this->Get('stimuli');
$aConf = explode("\n", $sConf);
$aStateToStimulus = array();
foreach($aConf as $sLine)
{
if (preg_match('/^([^:]+):(.*)$/', $sLine, $aMatches))
{
$sState = trim($aMatches[1]);
$sStimulus = trim($aMatches[2]);
$aStateToStimulus[$sState] = $sStimulus;
}
elseif (!empty($sLine))
{
$this->Trace('Invalid line in the "stimuli" configuration: "'.$sLine.'". The expected format for each line is <state_code>:<stimulus_code>');
}
}
if (array_key_exists($oTicket->GetState(), $aStateToStimulus))
{
$sStimulusCode = $aStateToStimulus[$oTicket->GetState()];
$this->Trace('About to apply the stimulus: '.$sStimulusCode.' for the ticket in state: '.$oTicket->GetState());
// Check that applying the stimulus will not break the data integrity constaints (mandatory, must change)
$aTransitions = $oTicket->EnumTransitions();
$bCanApplyStimulus = true;
if (!isset($aTransitions[$sStimulusCode]))
{
$bCanApplyStimulus = false;
$this->Trace('The Stimulus '.$sStimulusCode.' for '.get_class($oTicket).' in state '.$oTicket->GetState().' has no effect (no transition). Ignored.');
}
else
{
$aTransitionDef = $aTransitions[$sStimulusCode];
$sTargetState = $aTransitionDef['target_state'];
$aTargetStates = MetaModel::EnumStates(get_class($oTicket));
$aTargetStateDef = $aTargetStates[$sTargetState];
$aExpectedAttributes = $aTargetStateDef['attribute_list'];
foreach($aExpectedAttributes as $sAttCode => $iExpectCode)
{
$oAttDef = MetaModel::GetAttributeDef(get_class($oTicket), $sAttCode);
if (($iExpectCode & OPT_ATT_MANDATORY) && ($oAttDef->IsNull($oTicket->Get($sAttCode))))
{
// Check if there is just one possible value, in which case, use it
$aArgs = array('this' => $oTicket);
// If the field is mandatory, set it to the only possible value
if ($oAttDef->IsExternalKey())
{
$oAllowedValues = MetaModel::GetAllowedValuesAsObjectSet(get_class($oTicket), $sAttCode, $aArgs);
if ($oAllowedValues->Count() == 1)
{
$oRemoteObj = $oAllowedValues->Fetch();
$oTicket->Set($sAttCode, $oRemoteObj->GetKey());
$this->Trace('Setting the mandatory External Key '.$sAttCode.' to the only allowed value: '.$oRemoteObj->GetKey());
}
else
{
$this->Trace('Cannot apply the stimulus since the attribute '.$sAttCode.' is mandatory in the target state '.$sTargetState.' and is neither currently set nor has just one allowed value.');
$bCanApplyStimulus = false;
}
}
else
{
$aAllowedValues = MetaModel::GetAllowedValues_att(get_class($oTicket), $sAttCode, $aArgs);
if (count($aAllowedValues) == 1)
{
$aValues = array_keys($aAllowedValues);