forked from Combodo/approval-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.approval-base.php
2251 lines (2084 loc) · 65.1 KB
/
main.approval-base.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
/**
* Copyright (C) 2013-2020 Combodo SARL
*
* This file is part of iTop.
*
* iTop is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* iTop is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
*/
/**
* Module approval-base
*
* @author Erwan Taloc <[email protected]>
* @author Romain Quetiez <[email protected]>
* @author Denis Flaven <[email protected]>
* @license http://www.opensource.org/licenses/gpl-3.0.html LGPL
*/
use Combodo\iTop\ApprovalBase\Renderer\AbstractRenderer;
use Combodo\iTop\ApprovalBase\Renderer\BackofficeRenderer;
/**
* An approval process associated to an object
* Derive this class to implement an approval process
* - A few abstract functions have to be defined to implement parallel and/or serialize approvals
* - Advanced behavior can be implemented by overloading some of the methods (e.g. GetDisplayStatus to change the way it is displayed)
*
**/
abstract class _ApprovalScheme_ extends DBObject
{
const XML_LEGACY_VERSION = '1.7';
/**
* Compare static::XML_LEGACY_VERSION with ITOP_DESIGN_LATEST_VERSION and returns true if the later is <= to the former.
* If static::XML_LEGACY_VERSION, return false
*
* @return bool
*
* @since 3.1.0
*/
public static function UseLegacy(){
return static::XML_LEGACY_VERSION !== '' ? version_compare(ITOP_DESIGN_LATEST_VERSION, static::XML_LEGACY_VERSION, '<=') : false;
}
/** @var $oRenderer AbstractRenderer */
private $oRenderer;
/**
* @throws \CoreException
*/
public function __construct($aRow = null, $sClassAlias = '', $aAttToLoad = null, $aExtendedDataSpec = null)
{
parent::__construct($aRow, $sClassAlias, $aAttToLoad, $aExtendedDataSpec);
$this->oRenderer = new BackofficeRenderer();
}
/**
* @return \Combodo\iTop\ApprovalBase\Renderer\AbstractRenderer
*/
public function GetRenderer()
{
return $this->oRenderer;
}
/**
* @param \Combodo\iTop\ApprovalBase\Renderer\AbstractRenderer $oRenderer
*
* @return $this
*/
public function SetRenderer($oRenderer)
{
$this->oRenderer = $oRenderer;
return $this;
}
/**
* Can be overriden for simulation purposes (troubleshooting, tutorial)
*/
public function Now()
{
return time();
}
/**
* Helper to decode the approval sequences (steps)
*/
public function GetSteps()
{
$sStepsRaw = $this->Get('steps');
if (empty($sStepsRaw))
{
$aSteps = array();
}
else
{
$aSteps = unserialize($sStepsRaw);
}
return $aSteps;
}
/**
* Helper to encode the approval sequences (steps)
*/
protected function SetSteps($aSteps)
{
$this->Set('steps', serialize($aSteps));
}
/**
* Official mean to declare a new step at the end of the existing sequence
*
* @param array $aContact An array of array('class' => ..., 'id' => ...)
* @param integer $iTimeoutSec The timeout duration if (0 to disable the timeout feature)
* @param boolean $bApproveOnTimeout Set to true to approve in case of timeout for the current step
* @param integer $iExitCondition EXIT_ON_... _FIRST_REJECT, _FIRST_APPROVE, _FIRST_REPLY defaults to the legacy behavior
* @param boolean $bReusePreviousAnswers Set to true to recycle an answer given by an approver at a previous step (if any)
* @return void
*/
public function AddStep($aContacts, $iTimeoutSec = 0, $bApproveOnTimeout = true, $iExitCondition = self::EXIT_ON_FIRST_REJECT, $bReusePreviousAnswers = true)
{
$aApprovers = array();
foreach($aContacts as $aApproverData)
{
if (!MetaModel::IsValidClass($aApproverData['class']))
{
throw new Exception("Approval plugin: Wrong class ".$aApproverData['class']." for the approver");
}
$aApproverStatus = array(
'class' => $aApproverData['class'],
'id' => $aApproverData['id'],
'passcode' => mt_rand(11111,99999),
);
if (array_key_exists('forward', $aApproverData))
{
$aApproverStatus['forward'] = array();
foreach($aApproverData['forward'] as $aSubstituteData)
{
if (!MetaModel::IsValidClass($aSubstituteData['class']))
{
throw new Exception("Approval plugin: Wrong class ".$aApproverData['class']." for the approver");
}
$aSubstituteStatus = array(
'class' => $aSubstituteData['class'],
'id' => $aSubstituteData['id'],
'passcode' => mt_rand(11111,99999),
'timeout_percent' => $aSubstituteData['timeout_percent'],
);
if (array_key_exists('role', $aSubstituteData))
{
$aSubstituteStatus['role'] = $aSubstituteData['role'];
}
$aApproverStatus['forward'][] = $aSubstituteStatus;
}
}
$aApprovers[] = $aApproverStatus;
}
$aNewStep = array(
'timeout_sec' => $iTimeoutSec,
'timeout_approve' => $bApproveOnTimeout,
'exit_condition' => $iExitCondition,
'reuse_previous_answers' => $bReusePreviousAnswers,
'status' => 'idle',
'approvers' => $aApprovers,
);
$aSteps = $this->GetSteps();
$aSteps[] = $aNewStep;
$this->SetSteps($aSteps);
}
/**
* Alternative to AddStep: Adds a step IF the query returns at least one approver
*
* @param DBObject $oObject The source object (query arguments :this->attcode)
* @param string $sApproversQuery OQL giving the approvers
* @param integer $iTimeoutSec The timeout duration if (0 to disable the timeout feature)
* @param boolean $bApproveOnTimeout Set to true to approve in case of timeout for the current step
* @param integer $iExitCondition EXIT_ON_... _FIRST_REJECT, _FIRST_APPROVE, _FIRST_REPLY defaults to the legacy behavior
* @param boolean $bReusePreviousAnswers Set to true to recycle an answer given by an approver at a previous step (if any)
*
* @return bool true if a step has been added
* @throws \CoreException
* @throws \CoreUnexpectedValue
* @throws \MissingQueryArgument
* @throws \MySQLException
* @throws \MySQLHasGoneAwayException
* @throws \OQLException
* @throws \Exception
*/
public function AddStepFromQuery(DBObject $oObject, $sApproversQuery, $iTimeoutSec = 0, $bApproveOnTimeout = true, $iExitCondition = self::EXIT_ON_FIRST_REJECT, $bReusePreviousAnswers = true)
{
$bRet = false;
if ($sApproversQuery != '')
{
$oSearch=DBObjectSearch::FromOQL($sApproversQuery);
$oSearch->AllowAllData(true);
$oApproverSet = new DBObjectSet($oSearch, array(), $oObject->ToArgs('this'));
if ($oApproverSet->count() != 0)
{
$bRet = true;
$aContacts = array();
while ($oApprover = $oApproverSet->Fetch())
{
$sType = get_class($oApprover);
$aContacts[] = array(
'class' => $sType,
'id' => $oApprover->GetKey(),
);
}
$this->AddStep($aContacts, $iTimeoutSec, $bApproveOnTimeout, $iExitCondition, $bReusePreviousAnswers);
}
}
return $bRet;
}
/**
* Helper to build the button and associated dialog, if relevant, enabled, etc.
*
* @param $oPage
* @param $aStepData
* @param bool $bEditMode
*
* @return string
* @throws \ArchivedObjectException
* @throws \CoreException
*/
protected function GetReminderButton($oPage, $aStepData, $bEditMode = false)
{
$sRet = '';
if (MetaModel::GetModuleSetting('approval-base', 'enable_reminder', true))
{
if (($aStepData['status'] == 'ongoing') && ($this->Get('status') == 'ongoing'))
{
$aAwaited = $this->GetAwaitedReplies();
if (count($aAwaited) > 0)
{
$aReminders = array();
foreach ($aAwaited as $aData)
{
$oTarget = MetaModel::GetObject($aData['class'], $aData['id'], false, true);
if ($oTarget)
{
$aReminders[] = $oTarget->Get('friendlyname').' ('.$this->GetApproverEmailAddress($oTarget).')';
}
}
$sRet = '<button id="send_reminder" class="ibo-button ibo-is-regular ibo-is-neutral" >'.Dict::S('Approval:Remind-Btn').'</button>';
$sRet .= '<div id="send_reminder_dlg">'.Dict::S('Approval:Remind-DlgBody').'<ul><li>'.implode('</li><li>', $aReminders).'</li></ul></div>';
$sRet .= '<div id="send_reminder_reply"></div>';
$sDialogTitle = addslashes(Dict::S('Approval:Remind-DlgTitle'));
$sOkButtonLabel = addslashes(Dict::S('UI:Button:Ok'));
$sCancelButtonLabel = addslashes(Dict::S('UI:Button:Cancel'));
$iApproval = $this->GetKey();
$iCurrentStep = $this->Get('current_step');
$iEditMode = $bEditMode ? 1 : 0;
$oPage->add_ready_script(
<<<EOF
$('#send_reminder_dlg').dialog({
width: 400,
modal: true,
title: '$sDialogTitle',
autoOpen: false,
buttons: [
{ text: '$sOkButtonLabel', click: function(){
var me = $(this);
var oDialog = $(this).closest('.ui-dialog');
var oParams = {
'operation': 'send_reminder',
'approval_id': $iApproval,
'step': $iCurrentStep,
'edit_mode': $iEditMode,
};
oDialog.block();
$.post(GetAbsoluteUrlModulesRoot()+'approval-base/ajax.approval.php', oParams, function(data) {
me.dialog( "close" );
$('#send_reminder_reply').html(data);
oDialog.unblock();
});
} },
{ text: '$sCancelButtonLabel', click: function() {
$(this).dialog( "close" );
} }
],
});
$('#send_reminder').bind('click', function () {
$('#send_reminder_dlg')
.dialog('open');
return false;
});
EOF
);
}
}
}
return $sRet;
}
/**
* Render the status in HTML
*
* @param $oPage
* @param bool $bEditMode
*
* @return string
* @throws \ArchivedObjectException
* @throws \CoreException
* @throws \Exception
*/
public function GetDisplayStatus($oPage, $bEditMode = false)
{
$sIconOngoing = '<i class="approval-status-icon approval-status-icon--ongoing fas fa-hourglass-half"></i>';
$sIconApproved = '<i class="approval-status-icon approval-status-icon--approved fas fa-check"></i>';
$sIconRejected = '<i class="approval-status-icon approval-status-icon--rejected fas fa-times"></i>';
$sIconArrow = '<i class="fas fa-arrow-right approval-arrow-next"></i>';
if(static::UseLegacy()){
$oPage->add_style(
<<<CSS
.approval-status-icon{
font-size: 1em;
margin-right: 5px;
}
.approval-status-icon--ongoing{
}
.approval-status-icon--approved{
color: #558B2F;
}
.approval-status-icon--rejected{
color: #9B2C2C;
}
.approval-arrow-next{
font-size: 2rem;
color: #333;
vertical-align: middle;
line-height: 3.5rem;
padding: 0 10px;
}
.approval-step-idle {
background-color: #F6F6F1;
opacity: 0.4;
border-style: dashed;
border-width: 1px;
padding:10px;
}
.approval-step-start {
background-color: #F6F6F1;
border-style: solid;
border-width: 1px;
padding:10px;
}
.approval-step-ongoing {
background-color: #F6F6F1;
border-style: double;
border-width: 5px;
padding:10px;
}
.approval-step-done-ok {
background-color: #F6F6F1;
border-style: solid;
border-width: 2px;
padding:10px;
border-color: #69BB69;
}
.approval-step-done-ko {
background-color: #F6F6F1;
border-style: solid;
border-width: 2px;
padding:10px;
border-color: #BB6969;
}
.approval-idle{
opacity: 0.4;
}
.approval-timelimit {
font-weight: bolder;
}
.approval-theoreticallimit {
opacity: 0.4;
}
.approval-step-header {
margin: 5px;
font-weight: bolder;
}
div.approver-label {
padding: 10px;
padding-left: 16px;
margin: 5px;
margin-right: 0;
background-color: #A5CAFF;
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
border-radius: 6px;
}
div.approver-with-substitutes {
background: url(../images/minus.gif) no-repeat left;
cursor: pointer;
padding-left: 15px;
}
div.approver-with-substitutes-closed {
background: url(../images/plus.gif) no-repeat left;
}
tr.approval-substitutes td div{
padding-left: 15px;
}
.approval-substitutes.closed {
display: none;
}
#send_reminder {
margin-top: 5px;
width: 100%;
}
CSS
);
}
else {
$oPage->add_linked_stylesheet(utils::GetAbsoluteUrlModulesRoot().'approval-base/asset/css/status.css');
}
$sHtml = '';
// Add a header message in case the process has been aborted
$iAbortUser = $this->Get('abort_user_id');
if ($iAbortUser != 0)
{
if ($oUser = MetaModel::GetObject('User', $iAbortUser, false, true))
{
$sUserInfo = $oUser->GetFriendlyName();
}
else
{
$sUserInfo = 'User::'.$iAbortUser;
}
if (method_exists('AttributeDateTime', 'GetFormat'))
{
// Requires iTop >= 2.3.0
$sAbortDate = AttributeDateTime::GetFormat()->Format($this->Get('abort_date'));
}
else
{
// Compatibility with iTop < 2.3.0
$sAbortDate = $this->Get('abort_date');
}
$sAbortInfo = '<p>'.Dict::Format('Approval:Tab:End-Abort', $sUserInfo, $sAbortDate).'</p>';
$sAbortInfo .= '<p><quote>'.str_replace(array("\r\n", "\n", "\r"), "<br/>", htmlentities($this->Get('abort_comment'), ENT_QUOTES, 'UTF-8')).'</quote></p>';
$sHtml .= "<div id=\"abort_info\" class=\"header_message message_info ibo-alert ibo-is-information\" style=\"vertical-align:middle;\">\n";
$sHtml .= $sAbortInfo."\n";
$sHtml .= "</div>\n";
}
// Build the list of display information
$sArrow = $sIconArrow;
$aDisplayData = array();
$aDisplayData[] = array(
'date_html' => null,
'time_html' => null,
'content_html' => "<div class=\"approval-step approval-step-start\">".Dict::S('Approval:Tab:Start')."</div>\n",
);
$iStarted = AttributeDateTime::GetAsUnixSeconds($this->Get('started'));
$iLastEnd = $iStarted;
$sStarted = $this->GetDisplayTime($iStarted);
$sCurrDay = $this->GetDisplayDay($iStarted);
$aDisplayData[] = array(
'date_html' => $sCurrDay,
'time_html' => $sStarted,
'content_html' => $sArrow,
);
foreach($this->GetSteps() as $iStep => $aStepData)
{
switch ($aStepData['status'])
{
case 'done':
case 'timedout':
$iStepEnd = $aStepData['ended'];
$sTimeClass = '';
$sTimeInfo = '';
if ($aStepData['approved'])
{
$sDivClass = "approval-step-done-ok";
if ($aStepData['status'] == 'timedout')
{
$sStepSumary = Dict::S('Approval:Tab:StepSumary-OK-Timeout');
}
else
{
$sStepSumary = Dict::S('Approval:Tab:StepSumary-OK');
}
}
else
{
$sDivClass = "approval-step-done-ko";
if ($aStepData['status'] == 'timedout')
{
$sStepSumary = Dict::S('Approval:Tab:StepSumary-KO-Timeout');
}
else
{
$sStepSumary = Dict::S('Approval:Tab:StepSumary-KO');
}
}
$sArrowDivClass = "";
break;
case 'ongoing':
if ($iLastEnd && $aStepData['timeout_sec'] > 0)
{
$iStepEnd = $this->ComputeDeadline($iLastEnd, $aStepData['timeout_sec']);
$sTimeClass = 'approval-timelimit';
$sTimeInfo = Dict::S('Approval:Tab:StepEnd-Limit');
}
else
{
// The limit cannot be determined
$iStepEnd = 0;
$sTimeClass = '';
$sTimeInfo = '';
}
$sStepSumary = Dict::S('Approval:Tab:StepSumary-Ongoing');
$sDivClass = "approval-step-ongoing";
$sArrowDivClass = "approval-idle";
break;
case 'idle':
default:
if ($this->Get('status') == 'ongoing')
{
if ($iLastEnd && $aStepData['timeout_sec'] > 0)
{
$iStepEnd = $this->ComputeDeadline($iLastEnd, $aStepData['timeout_sec']);
$sTimeClass = 'approval-theoreticallimit';
$sTimeInfo = Dict::Format('Approval:Tab:StepEnd-Theoretical', round($aStepData['timeout_sec'] / 60));
}
else
{
// The limit cannot be determined
$iStepEnd = 0;
$sTimeClass = '';
$sTimeInfo = '';
}
}
else
{
// The process has been terminated before this step
$iStepEnd = 0;
$sTimeClass = '';
$sTimeInfo = '';
}
if ($this->Get('status') == 'ongoing')
{
$sStepSumary = Dict::S('Approval:Tab:StepSumary-Idle');
$sDivClass = "approval-step-idle";
$sArrowDivClass = "approval-idle";
}
else
{
$sStepSumary = Dict::S('Approval:Tab:StepSumary-Skipped');
$sDivClass = "approval-step-idle";
$sArrowDivClass = "approval-idle";
}
break;
}
$iLastEnd = $iStepEnd;
$sStepHtml = '<div class="approval-step-header">'.$sStepSumary.'</div>';
$sStepHtml .= '<table style="border-collapse: collapse;">';
foreach($aStepData['approvers'] as $aApproverData)
{
$oApprover = MetaModel::GetObject($aApproverData['class'], $aApproverData['id'], false, true);
$sTitleEsc = '';
if ($oApprover)
{
//$sApprover = $oApprover->GetHyperLink();
$sApprover = $oApprover->GetName();
}
else
{
$sApprover = $aApproverData['class'].'::'.$aApproverData['id'];
}
if (array_key_exists('approval', $aApproverData))
{
$bApproved = $aApproverData['approval'];
$sAnwserTimestamp = $aApproverData['answer_time'];
$sTitleHtml = $this->GetDisplayTime($aApproverData['answer_time']);
if (isset($aApproverData['comment']) && $aApproverData['comment'] != '')
{
$sTitleHtml .= '<br/>'.str_replace(array("\r\n", "\n", "\r"), "<br/>", htmlentities($aApproverData['comment'], ENT_QUOTES, 'UTF-8'));
}
if ($bApproved)
{
$sAnswer = $sIconApproved;
}
else
{
$sAnswer = $sIconRejected;
}
$sTitleEsc = addslashes($sTitleHtml);
// Not working in iTop <= 2.0.1
//$oPage->add_ready_script("$('#answer_$iStep"."_".$aApproverData['id']."').tooltip({items: 'div>img', content: '$sTitleEsc'});");
if(static::UseLegacy()){
$oPage->add_ready_script("$('#answer_$iStep"."_".$aApproverData['id']."_".$sAnwserTimestamp."').qtip( { content: '$sTitleEsc', show: 'mouseover', hide: 'mouseout', style: { name: 'dark', tip: 'leftTop' }, position: { corner: { target: 'rightMiddle', tooltip: 'leftTop' }} } );");
}
}
else
{
$sAnswer = $sIconOngoing;
$sAnwserTimestamp = '0';
if (($aStepData['status'] == 'ongoing') && !array_key_exists('forward', $aApproverData))
{
// Surround the icon with some meta data to allow a reply here
$sAnswer = "<span class=\"approval-replier\" approver_class=\"{$aApproverData['class']}\" approver_id=\"{$aApproverData['id']}\">$sAnswer</span>";
}
}
if (array_key_exists('forward', $aApproverData))
{
$bShowClosed = true;
static $iId = 0;
$sId = "substitutes_".$iId++;
if (array_key_exists('replier_index', $aApproverData))
{
$sApproverAnswer = $sIconOngoing;
}
else
{
// The answer is the one of the main approver
$sApproverAnswer = $sAnswer;
}
if (($aStepData['status'] == 'ongoing') && !array_key_exists('approval', $aApproverData))
{
// Surround the icon with some meta data to allow a reply here
$sApproverAnswer = "<span class=\"approval-replier\" approver_class=\"{$aApproverData['class']}\" approver_id=\"{$aApproverData['id']}\">$sApproverAnswer</span>";
}
$sApprover = "<div class=\"approver-with-substitutes\" id=\"{$sId}\">".$sApprover.'</div>';
$sSubstitutes = "<table id=\"content_$sId\">";
$sSubstitutes .= '<tr>';
$sSubstitutes .= '<td>'.$sApprover.'</td>';
$sSubstitutes .= '<td class="approval-substitutes">'.$sApproverAnswer.'</td>';
$sSubstitutes .= '</tr>';
foreach ($aApproverData['forward'] as $iReplierIndex => $aForwardData)
{
$oSubstitute = MetaModel::GetObject($aForwardData['class'], $aForwardData['id'], false, true);
if ($oSubstitute)
{
//$sSubstitute = $oSubstitute->GetHyperLink();
$sSubstitute = $oSubstitute->GetName();
}
else
{
$sSubstitute = $aForwardData['class'].'::'.$aForwardData['id'];
}
$sRole = isset($aForwardData['role']) ? ' ('.$aForwardData['role'].')' : '';
if (array_key_exists('replier_index', $aApproverData) && ($iReplierIndex == $aApproverData['replier_index']))
{
// The result is known and this replier is the one who did answer
$sSubstituteAnswer = $sAnswer;
$sSubstituteClass = "";
$bShowClosed = false;
}
elseif(array_key_exists('sent_time', $aForwardData))
{
$sSubstituteAnswer = $sIconOngoing;
$sSubstituteClass = "";
$bShowClosed = false;
if (($aStepData['status'] == 'ongoing') && !array_key_exists('approval', $aApproverData))
{
// Surround the icon with some meta data to allow a reply here
$sSubstituteAnswer = "<span class=\"approval-replier\" approver_class=\"{$aApproverData['class']}\" approver_id=\"{$aApproverData['id']}\" substitute_class=\"{$aForwardData['class']}\" substitute_id=\"{$aForwardData['id']}\">$sSubstituteAnswer</span>";
}
}
else
{
$sSubstituteAnswer = '';
$sSubstituteClass = "approval-idle";
}
$sSubstitutes .= '<tr class="approval-substitutes">';
//$sSubstitutes .= '<td>'.$aForwardData['timeout_percent'].'%: '.$sSubstitute.$sRole.'</td>';
$sSubstitutes .= "<td><div class=\"$sSubstituteClass\">".$sSubstitute.$sRole.'</div></td>';
$sSubstitutes .= '<td>'.$sSubstituteAnswer.'</td>';
$sSubstitutes .= '</tr>';
}
$sSubstitutes .= '</table>';
$sApprover = $sSubstitutes;
$oPage->add_ready_script("$('#{$sId}').click( function() { $('#content_{$sId} .approval-substitutes').toggleClass('closed'); } );\n");
$oPage->add_ready_script("$('#{$sId}').click( function() { $(this).toggleClass('approver-with-substitutes-closed'); } );\n");
if ($bShowClosed)
{
// Close it for the first display
$oPage->add_ready_script("$('#content_{$sId} .approval-substitutes').toggleClass('closed');");
$oPage->add_ready_script("$('#{$sId}').toggleClass('approver-with-substitutes-closed');");
}
}
$sStepHtml .= '<tr>';
$sAnswerHtml = '';
if (strlen($sAnswer) > 0)
{
$sTooltip = '';
if(!empty($sTitleEsc)){
$sTooltip = 'data-tooltip-content="'.$sTitleEsc.'" data-tooltip-html-enabled="true"';
}
$sAnswerHtml = '<span class="approver-answer" '.$sTooltip.'id="answer_'.$iStep.'_'.$aApproverData['id'].'_'.$sAnwserTimestamp.'">'.$sAnswer.'</span>';
}
$sStepHtml .= '<td style="vertical-align: top;"><div class="approver-label">'.$sAnswerHtml.$sApprover.'</div></td>';
$sStepHtml .= '</tr>';
}
// Add a button to send a reminder for the current step (if relevant)
//
$sReminderHtml = $this->GetReminderButton($oPage, $aStepData, $bEditMode);
if (strlen($sReminderHtml) > 0)
{
$sStepHtml .= '<tr>';
$sStepHtml .= '<td colspan="2" align="center">'.$sReminderHtml.'</td>';
$sStepHtml .= '</tr>';
}
$sStepHtml .= '</table>';
$aDisplayData[] = array(
'date_html' => null,
'time_html' => null,
'content_html' => "<div class=\"approval-step $sDivClass\">$sStepHtml</div>\n",
);
// New feature: the array entry 'exit_condition' might be missing
$iExitCondition = isset($aStepData['exit_condition']) ? $aStepData['exit_condition'] : self::EXIT_ON_FIRST_REJECT;
switch($iExitCondition)
{
case self::EXIT_ON_FIRST_REPLY:
$sExplainCondition = Dict::S('Approval:Tab:StepEnd-Condition-FirstReply');
break;
case self::EXIT_ON_FIRST_APPROVE:
$sExplainCondition = Dict::S('Approval:Tab:StepEnd-Condition-FirstApprove');
break;
case self::EXIT_ON_FIRST_REJECT:
default:
$sExplainCondition = Dict::S('Approval:Tab:StepEnd-Condition-FirstReject');
break;
}
if ($iStepEnd)
{
// Display the date iif it has changed
//
if ($this->GetDisplayDay($iStepEnd) != $sCurrDay)
{
$sStepEndDate = $this->GetDisplayDay($iStepEnd);
$sCurrDay = $sStepEndDate;
}
else
{
// Same day
$sStepEndDate = ' ';
}
$aDisplayData[] = array(
'date_html' => '<span class="'.$sTimeClass.'" title="'.$sTimeInfo.'">'.$sStepEndDate.'</span>',
'time_html' => '<span class="'.$sTimeClass.'" title="'.$sTimeInfo.'">'.$this->GetDisplayTime($iStepEnd).'</span>',
'content_html' => "<div class=\"$sArrowDivClass\" title=\"$sExplainCondition\">".$sArrow."</div>\n",
);
}
else
{
$aDisplayData[] = array(
'date_html' => '',
'time_html' => '',
'content_html' => "<div class=\"$sArrowDivClass\" title=\"$sExplainCondition\">".$sArrow."</div>\n",
);
}
}
switch ($this->Get('status'))
{
case 'ongoing':
$sFinalStatus = $sIconOngoing;
$sDivClass = "approval-step-idle";
break;
case 'accepted':
$sFinalStatus = $sIconApproved;
$sDivClass = "approval-step-done-ok";
break;
case 'rejected':
$sFinalStatus = $sIconRejected;
$sDivClass = "approval-step-done-ko";
break;
}
$aDisplayData[] = array(
'date_html' => null,
'time_html' => null,
'content_html' => "<div id=\"final_result\" class=\"approval-step $sDivClass\"><div style=\"display: inline-block; vertical-align: middle;\">".$sFinalStatus.Dict::S('Approval:Tab:End')."</div></div>\n",
);
// Diplay the information
//
$sHtml .= "<table id=\"process_status_table\">\n";
$sHtml .= "<tr>\n";
$sHtml .= "<td colspan=\"2\"></td>\n";
foreach($aDisplayData as $aDisplayEvent)
{
if (!is_null($aDisplayEvent['date_html']))
{
if (strlen($aDisplayEvent['date_html']) > 0)
{
$sHtml .= "<td colspan=\"2\">".$aDisplayEvent['date_html']."</td>\n";
}
else
{
$sHtml .= "<td colspan=\"2\"> </td>\n";
}
}
}
$sHtml .= "</tr>\n";
$sHtml .= "<tr>\n";
$sHtml .= "<td colspan=\"2\"></td>\n";
foreach($aDisplayData as $aDisplayEvent)
{
if (!is_null($aDisplayEvent['time_html']))
{
if (strlen($aDisplayEvent['time_html']) > 0)
{
$sHtml .= "<td colspan=\"2\">".$aDisplayEvent['time_html']."</td>\n";
}
else
{
$sHtml .= "<td> </td>\n";
}
}
}
$sHtml .= "</tr>\n";
$sHtml .= "<tr style=\"vertical-align:middle;\">\n";
$sHtml .= "<td></td>\n";
foreach($aDisplayData as $aDisplayEvent)
{
if ($aDisplayEvent['content_html'])
{
$sHtml .= "<td>".$aDisplayEvent['content_html']."</td>\n";
}
}
$sHtml .= "</tr>\n";
$sHtml .= "</table>\n";
$sLastError = $this->Get('last_error');
if (strlen($sLastError) > 0)
{
$sHtml .= '<p>'.Dict::Format('Approval:Tab:Error', $sLastError).'</p>';
}
return $sHtml;
}
/** Helper to record the end of the process in several cases
* - normal termination
* - abort
*
* @param string $bApproved
*
* @throws \ArchivedObjectException
* @throws \CoreCannotSaveObjectException
* @throws \CoreException
* @throws \CoreUnexpectedValue
*/
protected function RecordEnd($bApproved)
{
$this->Set('ended', $this->Now());
$this->Set('status', $bApproved ? 'accepted' : 'rejected');
$this->DBUpdate();
if ($oObject = MetaModel::GetObject($this->Get('obj_class'), $this->Get('obj_key'), false, true))
{
if ($bApproved)
{
$this->DoApprove($oObject);
}
else
{
$this->DoReject($oObject);
}
if ($oObject->IsModified())
{
$oObject->DBUpdate();
}
}
}
/**
* Start the step <current_step>, or terminates if either...
* - the last step executed has been rejected
* - there is no more step to process
*
* On termination: determines + records the final status
* and invokes the relevant verb (DoApprove/DoReject)
*
* @throws \CoreException
*/
public function StartNextStep()
{
$aSteps = $this->GetSteps();
$iCurrentStep = $this->Get('current_step');
// Determine the status for the previous step (if any)
//
if (array_key_exists($iCurrentStep - 1, $aSteps))
{
$aPrevStep = $aSteps[$iCurrentStep - 1];
$bPrevApproved = $aPrevStep['approved'];
}
else
{
// Starting...
$bPrevApproved = true;
}
if ($bPrevApproved && array_key_exists($iCurrentStep, $aSteps))
{
// Actually continue with the next step
//
$aStepData = &$aSteps[$iCurrentStep];
$aStepData['status'] = 'ongoing';
$aStepData['started'] = $this->Now();
$this->SetSteps($aSteps);
$this->Set('timeout', $this->ComputeTimeout());
$this->DBUpdate();
// New capability that appeared in 2.5.0, thus could be missing in the data structure
// in such a case the default is FALSE (though the default behavior for newly created schemes will by TRUE!)
$bReusePreviousAnswers = array_key_exists('reuse_previous_answers', $aStepData) ? $aStepData['reuse_previous_answers'] : false;
$oObject = MetaModel::GetObject($this->Get('obj_class'), $this->Get('obj_key'), true, true);
if ($bReusePreviousAnswers)
{
foreach ($aStepData['approvers'] as &$aApproverData)
{
$oApprover = MetaModel::GetObject($aApproverData['class'], $aApproverData['id'], false, true);
if ($oApprover)
{
list($iReplyStep, $bApproved, $sComment) = $this->FindAnswer($iCurrentStep, $aApproverData);
if ($iReplyStep !== null)
{
// Note: the step must be 1-based
$sNewComment = Dict::Format('Approval:Comment-Reused', $iReplyStep + 1, $sComment);
$this->OnAnswer($iCurrentStep, $oApprover, $bApproved, null, $sNewComment);
// Something may happen within OnAnswer (and already saved into the DB)
if ($this->Get('current_step') != $iCurrentStep)
{
// The step has been concluded. Exit the prodedure ASAP!
break;
}
}
}
}
// Some step data might have changed... refresh the local variables (avoids sending an email when an answer has been reused)
$aSteps = $this->GetSteps();
$aStepData = &$aSteps[$iCurrentStep];
}
if ($this->Get('current_step') == $iCurrentStep)
{
foreach ($aStepData['approvers'] as &$aApproverData)
{
if (!array_key_exists('approval', $aApproverData))
{
$oApprover = MetaModel::GetObject($aApproverData['class'], $aApproverData['id'], false, true);
if ($oApprover)
{
$this->SendApprovalRequest($oApprover, $oObject, $aApproverData['passcode']);
}
}
}
}
}
else
{
// Done !
//
$this->RecordEnd($bPrevApproved);
}