-
Notifications
You must be signed in to change notification settings - Fork 2
/
pdfReport.php
1612 lines (1558 loc) · 66 KB
/
pdfReport.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
/**
* pdfReport Plugin for LimeSurvey
* Use question settings to create a report and send it by email.
*
* @author Denis Chenu <https://sondages.pro>
* @copyright 2015-2024 Denis Chenu <https://sondages.pro>
* @copyright 2017 Réseau en scène Languedoc-Roussillon <https://www.reseauenscene.fr/>
* @copyright 2015 Ingeus <http://www.ingeus.fr/>
* @license AGPL v3
* @version 2.3.1
*
* This program 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.
*
* This program 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 General Public License for more details.
*/
class pdfReport extends PluginBase
{
protected $storage = 'DbStorage';
protected static $description = 'Do a PDF report for question.';
protected static $name = 'pdfReport';
/**
* @var integer $sureyId
*/
private $surveyId;
/**
* @var integer $responseId
*/
private $responseId;
/** var boolean */
private static $pdfReportDone = false;
/**
* Register to needed event
*/
public function init()
{
/* Add the attribute */
$this->subscribe('newQuestionAttributes', 'addPdfReportAttribute');
/* Generate and save pdfReport when submit */
$this->subscribe('afterSurveyComplete', 'afterSurveyComplete');
/* Fill session survey if needed, and register before twig */
$this->subscribe('beforeSurveyPage');
/* Remove answers (and help) part And do needed pdf (hidden group) */
$this->subscribe('beforeQuestionRender', 'hideAnswerPart');
/* Allow printing on current */
$this->subscribe('newDirectRequest');
/* To replace if needed printanswer */
$this->subscribe('beforeControllerAction', 'setPrintAnswer');
}
/** @see event */
public function beforeSurveyPage()
{
$surveyId = $this->surveyId = $this->getEvent()->get('surveyId');
$language = App()->getlanguage();
$sessionSurvey = Yii::app()->session["survey_{$surveyId}"];
if (empty($sessionSurvey['fieldnamesInfo'])) {
return;
}
if (empty($sessionSurvey['srid'])) {
return;
}
if (!isset($sessionSurvey['pdfreport'])) {
$oSurvey = Survey::model()->findByPk($surveyId);
$criteria = new CDbCriteria();
$criteria->select = ['t.qid as qid', 'gid'];
$criteria->join = 'JOIN {{question_attributes}} as questionattributes ON ' . App()->getDb()->quoteColumnName("t.qid") . '=' . App()->getDb()->quoteColumnName("questionattributes.qid");
$criteria->condition = 't.sid = :sid and questionattributes.attribute = :attribute and questionattributes.value = :value';
$criteria->params = [':sid' => $surveyId, ':attribute' => 'pdfReport', ':value' => '<>0'];
/* language */
if (intval(App()->getConfig("versionnumber")) <= 3) {
$criteria->compare(App()->getDb()->quoteColumnName("t.language"), $language);
}
$oQuestionsQid = Question::model()->findAll($criteria);
$sessionPdfReports = array();
if (!empty($oQuestionsQid)) {
foreach ($oQuestionsQid as $oQuestionQid) {
switch ($oSurvey->format) {
case 'S':
$step = LimeExpressionManager::GetQuestionSeq($oQuestionQid->qid);
break;
case 'G':
$step = LimeExpressionManager::GetGroupSeq($oQuestionQid->gid);
break;
case 'A':
default:
$step = 0;
}
$sessionPdfReports[$oQuestionQid->qid] = $step;
}
}
$sessionSurvey['pdfreport'] = $sessionPdfReports;
Yii::app()->session["survey_{$surveyId}"] = $sessionSurvey;
}
$sessionPdfReports = $sessionSurvey['pdfreport'];
if (!empty($sessionPdfReports)) {
$this->subscribe('beforeTwigRenderTemplate', 'doPdfReportsByStep');
$this->unsubscribe('beforeQuestionRender');
$this->subscribe('beforeQuestionRender', 'beforeQuestionRender');
}
}
/**
* @see event
* register here to be after Expression manager, but still after QuestoionRender */
public function doPdfReportsByStep()
{
if (self::$pdfReportDone) {
return;
}
self::$pdfReportDone = true;
$this->unsubscribe('beforeTwigRenderTemplate');
$sessionSurvey = Yii::app()->session["survey_{$this->surveyId}"];
if (empty($sessionSurvey['pdfreport'])) {
return;
}
$prevStep = $sessionSurvey['prevstep'] ?? 0;
$actualStep = $sessionSurvey['step'] ?? 0;
if ($actualStep < $prevStep) {
return;
}
$sessionPdfReports = $sessionSurvey['pdfreport'];
foreach ($sessionPdfReports as $qid => $step) {
if ($prevStep < $step && $step <= $actualStep) {
$this->responseId = $sessionSurvey['srid'];
$this->doPdfReports($qid);
}
}
}
/**
* @see ls\pluginmanager\PluginBase->settings
*/
protected $settings = array(
'usetokenfilename' => array(
'type' => 'select',
'label' => 'Usage of token in filemane',
'options' => array(
'add' => 'Adding at start',
'alone' => 'Using only token',
'none' => 'Didn‘t use it',
),
'help' => 'For filename generation, way of using token value if exist and not empty.',
'default' => 'add',
),
'basicDocumentation' => array(
'type' => 'info',
'content' => '<div class="well">To allow user to get the file of the question number X at end : you can use this url:</div>',
),
/* This part is not active currently */
//~ 'basesavedirectory'=> array(
//~ 'type'=>'string',
//~ 'label'=>'Directory on the server to move the file (if question settings is set)',
//~ 'help'=>'You can use {SID} for survey id. Plugin didn`t create directory.',
//~ 'default'=>'',
//~ ),
//~ 'usetokenfilename' => array(
//~ 'type'=>'select',
//~ 'label'=>'Usage of token in filemane',
//~ 'options'=>array(
//~ 'add'=>'Adding at start',
//~ 'alone'=>'Using only token',
//~ 'none'=>'Didn\t use it',
//~ ),
//~ 'help'=>'For filename generation, way of using token value if exist and not empty.',
//~ 'default'=>'add',
//~ ),
);
/**
* @inheritdoc
*/
public function getPluginSettings($getValues = true)
{
if (!Permission::model()->hasGlobalPermission('settings', 'read')) {
throw new CHttpException(403);
}
$dowloadurl = Yii::app()->getController()->createUrl('plugins/direct', array('plugin' => $this->getName(), 'surveyid' => 'SID','qid' => 'QID'));
$dowloadurl = str_replace(array("SID","QID"), array("{SID}","{QID}"), $dowloadurl);
$helpString = sprintf($this->translate("To allow user to get the file of the question number X at end : you can use this url: %s. Replacing %s by the question number (LimeSurvey replace %s by the survey number)."), "<code>" . $dowloadurl . "</code>", "<code>{QID}</code>", "{SID}");
$this->settings['basicDocumentation']['content'] = "<div class='well'>{$helpString}</div>";
return parent::getPluginSettings($getValues);
}
/**
* @see questionHelper->getAttributesDefinitions()
*/
public function addPdfReportAttribute()
{
if (!$this->getEvent()) {
throw new CHttpException(403);
}
$pdfSettingsLink = Yii::app()->createUrl("admin/globalsettings", array("#" => 'presentation'));
$pdfReportAttribute = array(
'pdfReport' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 1,
'inputtype' => 'switch',
'default' => 0,
'help' => $this->translate('The pdf are saved inside question answers, it‘s better if you hide the question, else only answers part are hidden.'),
'caption' => $this->translate('Use this question as pdf report.'),
),
'pdfReportTitle' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 10,
'inputtype' => 'text',
'default' => '{SITENAME}',
'i18n' => true,
'expression' => 1,
'help' => sprintf($this->translate('Set it as header in the final pdf, same behaviour than PDF header title at %sLimeSurvey global settings%s.'), "<a href='$pdfSettingsLink'>", "</a>"),
'caption' => $this->translate('Title for the pdf.'),
),
'pdfReportSubTitle' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 11,
'inputtype' => 'text',
'default' => '{SURVEYNAME}',
'i18n' => true,
'expression' => 1,
'help' => sprintf($this->translate('Use as sub-header in the final pdf, same behaviour than PDF header string at %sLimeSurvey global settings%s.'), "<a href='$pdfSettingsLink'>", "</a>"),
'caption' => $this->translate('Sub title for the pdf.'),
),
'pdfReportContent' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 15,
'inputtype' => 'textarea',
'default' => "",
'i18n' => true,
'expression' => 1,
'help' => $this->translate('This allow better edition without HTML editor and/or XSS.'),
'caption' => $this->translate('Content of the PDF, leave empty to use question text.'),
'xssFilter' => false
),
'pdfReportPrintAnswer' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 20,
'inputtype' => 'singleselect',
'options' => array(
0 => gT('No'),
1 => $this->translate('Allow public download (with the link).'),
2 => $this->translate('Replace public print answer.'),
),
'default' => 0,
'help' => $this->translate('Allow to download pdf after submitted the survey, see plugin settings for url. Optionnaly replace the default print answer by a dowload link of the pdf.'),
'caption' => $this->translate('Replace public print answer.'),
),
'pdfReportSavedFileName' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 30,
'inputtype' => 'text',
'default' => '',
'i18n' => true,
'htmlOptions' => array(
'placeholder' => 'questioncode',
),
'expression' => 1,
'help' => $this->translate('By default usage of the question code. You don‘t have to put the .pdf part.'),
'caption' => $this->translate('Name of saved PDF file.'),
),
'pdfReportSanitizeSavedFileName' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 30,
'inputtype' => 'singleselect',//'buttongroup',
'options' => array(
'none' => $this->translate('No filter'),
'base' => $this->translate('Basic filter'),
'alphanumeric' => $this->translate('Alphanumeric only'),
'alphanumericlower' => $this->translate('Alphanumeric and lower case'),
),
'default' => 'base',
'help' => $this->translate('Basic filter try to remove invalid an dangerous character, use “no filter” with caution. If there are a filter, filename is limited to 254 character. With alphanumeric space was replaced by -.'),
'caption' => $this->translate('Sanitization of the file name.'),
),
'pdfReportSendByEmailMail' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 40,
'inputtype' => 'text',
'default' => '',
'i18n' => false,
'expression' => 1,
'help' => $this->translate('Optionnal email to send pdf Report. You can use Expression manager and multiple email. For multiple email : you must use <code>;</code> as separator. Each email was checked for validity.'),
'caption' => $this->translate('Send it by email to'),
),
'pdfReportSendByEmailContent' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 45,
'inputtype' => 'singleselect',//'buttongroup',
'options' => array(
'confirm' => $this->translate('Confirmation email'),
'admin_notification' => $this->translate('Basic admin notification'),
'admin_responses' => $this->translate('Detailed admin notification'),
),
'default' => 'admin_notification',
'i18n' => false,
'expression' => 1,
'help' => $this->translate('This don‘t deactivate limesurvey other email system. Remind to deactivate LimeSurvey system if you this one.'),
'caption' => $this->translate('Content and subject of the email'),
),
'pdfReportSendByEmailAttachment' => array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 50,
'inputtype' => 'switch',
'default' => 1,
'help' => $this->translate('Add existing attachements of the email templates from LimeSurvey.'),
'caption' => $this->translate('Add attachements of email'),
),
);
if (Yii::getPathOfAlias("limeMpdf")) {
$pdfReportAttribute['pdfReportPdfGenerator'] = array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 100,
'inputtype' => 'switch',
'default' => 1,
'help' => $this->translate('You have limeMpdf plugin allowing more class, but don‘t use pdfreport.css. Then if you need usage of pdfreport.css: you can choose to use old tcpdf system.'),
'caption' => $this->translate('Use limeMpdf'),
);
$pdfReportAttribute['pdfReportCreateToc'] = array(
'types' => '|', /* upload question type */
'category' => $this->translate('PDF report'),
'sortorder' => 110,
'inputtype' => 'switch',
'default' => 1,
'help' => $this->translate('Plugin limeMpdf allow table of content using h1, h2 etc … then adding title in your pdf set a table of contents.'),
'caption' => $this->translate('Create a PDF table of content'),
);
$pdfReportAttribute['pdfReportTitle']['help'] = sprintf(
$this->translate('Set it as header in the final pdf with %s, same behaviour than PDF header title at %sLimeSurvey global settings%s. Used as %s in %s of %s theme twig files.'),
"<strong>tcpdf</strong>",
"<a href='$pdfSettingsLink'>",
"</a>",
"<code>{{ title }}</code>",
"header.twig",
"<strong>limeMpdf</strong>"
);
$pdfReportAttribute['pdfReportSubTitle']['help'] = sprintf(
$this->translate('Set it as sub header in the final pdf with %s, same behaviour than PDF header string at %sLimeSurvey global settings%s. Used as %s in %s of %s theme twig files.'),
"<strong>tcpdf</strong>",
"<a href='$pdfSettingsLink'>",
"</a>",
"header.twig",
"<code>{{ subtitle }}</code>",
"<strong>limeMpdf</strong>"
);
}
if (method_exists($this->getEvent(), 'append')) {
$this->getEvent()->append('questionAttributes', $pdfReportAttribute);
} else {
$questionAttributes = (array)$this->event->get('questionAttributes');
$questionAttributes = array_merge($questionAttributes, $pdfReportAttribute);
$this->event->set('questionAttributes', $questionAttributes);
}
}
/**
* Do all the pdf after survey is submitted, and each action if needed
*/
public function afterSurveyComplete()
{
if (!$this->getEvent()) {
throw new CHttpException(403);
}
$this->surveyId = $this->getEvent()->get('surveyId');
$this->responseId = $this->getEvent()->get('responseId');
if (empty($this->responseId)) {
return;
}
$this->doPdfReports(null, true);
}
/**
* Do all the pdf after survey is submitted, and each action if needed
*/
public function beforeQuestionRender()
{
$this->doPdfReportsByStep();
$this->hideAnswerPart();
}
/**
* Do all the pdf after survey is submitted, and each action if needed
*/
public function hideAnswerPart()
{
if ($this->getEvent()->get('type') == '|') {
$oEvent = $this->getEvent();
$oQuestionPdfReport = QuestionAttribute::model()->find(
"attribute = :attribute and qid=:qid",
array(':attribute' => 'pdfReport',':qid' => $oEvent->get('qid'))
);
if ($oQuestionPdfReport && intval($oQuestionPdfReport->value)) {
$inputName = "{$oEvent->get('surveyId')}X{$oEvent->get('gid')}X{$oEvent->get('qid')}";
$sessionSurvey = Yii::app()->session["survey_{$this->surveyId}"];
$value = $sessionSurvey[$inputName] ?? "";
$value_count = $sessionSurvey["{$inputName}_filecount"] ?? 0;
$answers = \CHtml::hiddenField($inputName, $value, array('id' => 'java' . $inputName))
. \CHtml::hiddenField("{$inputName}_filecount", $value_count, array('id' => "java{$inputName}_filecount"));
$oEvent->set('answers', $answers);
$oEvent->set('file_valid_message', '');
$oEvent->set('valid_message', '');
$oEvent->set('class', $oEvent->get('class') . " pdfreport-question");
}
}
}
/**
* Do all reports needed
* @param integer $qid question id
* @param boiolena $$submit when action done
* @return @void
*/
private function doPdfReports($qid = null, $submit = false)
{
$language = Yii::app()->getLanguage();
if (!in_array($language, Survey::model()->findByPk($this->surveyId)->getAllLanguages())) {
$language = Survey::model()->findByPk($this->surveyId)->getAttribute('language');
}
// Only in next release $oQuestionAttribute = QuestionAttribute::model()->with('qid')->together()->findAll('sid=:sid and attribute=:attribute and value=:value',array(':sid'=>$iSid,':attribute'=>'pdfReport',':value'=>1));
$criteria = new CDbCriteria();
$criteria->select = 'question.qid as qid';
$criteria->join = 'LEFT JOIN {{questions}} as question ON ' . App()->getDb()->quoteColumnName("question.qid") . '=' . App()->getDb()->quoteColumnName("t.qid");
$criteria->condition = 'question.sid = :sid and attribute = :attribute and value = :value';
$criteria->params = array(':sid' => $this->surveyId,':attribute' => 'pdfReport',':value' => '1');
/* language */
if (intval(App()->getConfig("versionnumber")) <= 3) {
$criteria->compare(App()->getDb()->quoteColumnName("question.language"), $language);
}
if ($qid) {
$criteria->compare(App()->getDb()->quoteColumnName("question.qid"), $qid);
}
$aQuestionsQid = QuestionAttribute::model()->findAllAsArray($criteria, array(), true);
if ($aQuestionsQid) {
foreach ($aQuestionsQid as $aQuestionQid) {
$qid = $aQuestionQid['qid'];
$pdfFile = $this->pdfReportGetPdfFile($qid);
if ($pdfFile) {
if (intval(App()->getConfig("versionnumber")) <= 3) {
$oQuestion = Question::model()->findByPk(array('qid' => $qid,'language' => $language));
} else {
$oQuestion = Question::model()->findByPk($qid);
}
if ($oQuestion->type == "|") {
$this->pdfReportSaveInFileUpload($oQuestion);
$this->setSessionPrintAnswer($oQuestion);
}
if ($submit) {
$this->pdfReportSendByEmail($oQuestion);
}
unlink($pdfFile);
}
}
}
$sessionSurvey = Yii::app()->session["survey_{$this->surveyId}"];
$inputName = "476956X391X26989";
}
/**
* Replace print answer by own donwload
* @see beforeControllerAction
*/
public function setPrintAnswer()
{
if (!$this->getEvent()) {
throw new CHttpException(403);
}
if ($this->event->get('controller') == 'printanswers') {
$aPdfReportPrintRight = Yii::app()->session["pdfReportPrintRight"];
$surveyid = Yii::app()->getRequest()->getQuery('surveyid');
/* find if one question have print settings */
if (isset($aPdfReportPrintRight[$surveyid]['replace'])) {
$this->publicPdfDownload($surveyid, $aPdfReportPrintRight[$surveyid]['replace']);
$this->event->set('run', false);
}
}
}
public function newDirectRequest()
{
if (!$this->getEvent()) {
throw new CHttpException(403);
}
$oEvent = $this->event;
if ($oEvent->get('target') != get_class()) {
return;
}
/* The survey */
$surveyid = Yii::app()->getRequest()->getParam("surveyid", Yii::app()->getRequest()->getParam("sid"));
$oSurvey = Survey::model()->findByPk($surveyid);
if (!$oSurvey) {
throw new CHttpException(404, gT('Invalid survey ID'));
}
/* The language , is set to default if not in url */
$language = Yii::app()->getRequest()->getParam("lang", App()->getLanguage());
if (!in_array($language, $oSurvey->getAllLanguages())) {
$language = $oSurvey->language;
}
App()->setLanguage($language);
/* The question */
$qid = Yii::app()->getRequest()->getParam("qid");
if (empty($qid)) {
throw new CHttpException(400);
}
$aPdfAttribute = \QuestionAttribute::model()->find("qid = :qid AND attribute = :attribute", array(":qid" => $qid,":attribute" => 'pdfReport'));
if (empty($aPdfAttribute) || empty($aPdfAttribute->value)) {
throw new CHttpException(403);
}
$aAllowAttribute = \QuestionAttribute::model()->find("qid = :qid AND attribute = :attribute", array(":qid" => $qid,":attribute" => 'pdfReportPrintAnswer'));
if (empty($aAllowAttribute) || empty($aAllowAttribute->value)) {
throw new CHttpException(403);
}
/* Multi srid allowed */
$srid = Yii::app()->getRequest()->getParam("srid");
$currentSrid = isset($_SESSION['survey_' . $surveyid]['srid']) ? $_SESSION['survey_' . $surveyid]['srid'] : null;
$allowedSrid = null;
$aSessionPrintRigth = Yii::app()->session["pdfReportPrintRight"];
if (!empty($aSessionPrintRigth[$surveyid])) {
$allowedSrid = $aSessionPrintRigth[$surveyid]['srid'];
}
if (!empty($srid)) {
if ($srid != $currentSrid && $srid != $allowedSrid && !Permission::model()->hasSurveyPermission($surveyid, 'reponse', 'read')) {
throw new CHttpException(401);
}
}
if (empty($srid)) {
$srid = empty($currentSrid) ? $allowedSrid : $currentSrid;
}
if (empty($srid)) {
throw new CHttpException(400, 'Survey must be activated');
}
/* OK : settings and param checked : we can go */
$oResponse = Response::model($surveyid)->findByPk($srid);
$aQuestionFiles = $oResponse->getFiles($qid);
if (Yii::app()->getRequest()->getParam("reset") || empty($aQuestionFiles)) {
$this->surveyId = $surveyid;
$this->responseId = $srid;
$this->doPdfReports($qid);
}
$this->publicPdfDownload($surveyid, $qid, $srid);
}
/**
* Pdf download of a upload question type
* @param int $surveyid
* @param int $qid
* @param int $srid : responseId
* @return void
*/
private function publicPdfDownload($surveyid, $qid = null, $srid = null)
{
$oSurvey = Survey::model()->findByPk($surveyid);
if (!$oSurvey) {
throw new CHttpException(404, gT('Invalid survey ID'));
}
/* Control if allowed */
$currentSrid = isset($_SESSION['survey_' . $surveyid]['srid']) ? $_SESSION['survey_' . $surveyid]['srid'] : null;
$aSessionPrintRigth = Yii::app()->session["pdfReportPrintRight"];
$allowedSrid = isset($aSessionPrintRigth[$surveyid]['srid']) ? $aSessionPrintRigth[$surveyid]['srid'] : null;
if (!empty($srid)) {
if ($srid != $currentSrid && $srid != $allowedSrid && !Permission::model()->hasSurveyPermission($surveyid, 'reponse', 'read')) {
throw new CHttpException(401);
}
} else {
$srid = $allowedSrid ? $allowedSrid : $currentSrid;
}
if (empty($srid)) {
throw new CHttpException(400);
}
if (!$qid) {
$qid = $aSurveyPrintRigth['replace'];
}
// Ok we get the survey and the qid
$oResponse = Response::model($surveyid)->findByPk($srid);
$aQuestionFiles = $oResponse->getFiles($qid);
if (!$aQuestionFiles) {
throw new CHttpException(404, gT("Sorry, this file was not found."));
}
$aFile = $aQuestionFiles[0];
$sFileRealName = Yii::app()->getConfig('uploaddir') . "/surveys/" . $surveyid . "/files/" . $aFile['filename'];
if (file_exists($sFileRealName)) {
$mimeType = CFileHelper::getMimeType($sFileRealName, null, false);
if (is_null($mimeType)) {
$mimeType = "application/octet-stream";
}
@ob_clean();
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="' . rawurldecode($aFile['name']) . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($sFileRealName));
readfile($sFileRealName);
Yii::app()->end();
}
throw new CHttpException(404, gT("Sorry, this file was not found."));
}
/**
* set session for print answer to this question if settings
* @param Question $oQuestion
* @return void
*/
private function setSessionPrintAnswer($oQuestion)
{
$oQuestionAttribute = QuestionAttribute::model()->find(
"attribute=:attribute and qid=:qid",
array(':attribute' => 'pdfReportPrintAnswer',':qid' => $oQuestion->qid)
);
if (!$oQuestionAttribute) {
return;
}
if (!intval($oQuestionAttribute->value)) {
return;
}
$aSessionPrintRigth = Yii::app()->session["pdfReportPrintRight"];
if (empty($aSessionPrintRigth)) {
$aSessionPrintRigth = array();
}
/* reset for new srid */
if (!empty($aSessionPrintRigth[$oQuestion->sid]) && $aSessionPrintRigth[$oQuestion->sid]['srid'] != $this->responseId) {
$aSessionPrintRigth = array();
}
if (empty($aSessionPrintRigth[$oQuestion->sid])) {
$aSessionPrintRigth[$oQuestion->sid] = array(
'srid' => $this->responseId,
'allowed' => array(),
);
}
/* Always add it to allowed */
$aSessionPrintRigth[$oQuestion->sid]['allowed'][] = $oQuestion->qid;
/* Optionnally set it to replace */
if ($oQuestionAttribute->value == 2) {
$aSessionPrintRigth[$oQuestion->sid]['replace'] = $oQuestion->qid;
}
Yii::app()->session["pdfReportPrintRight"] = $aSessionPrintRigth;
}
/**
* Get a pdf file from a string
* @param integer $iQid
* @return string : URI for pdf file
*/
private function pdfReportGetPdfFile($iQid)
{
if (intval(App()->getConfig('versionnumber')) <= 3) {
$oQuestion = Question::model()->findByPk(array('qid' => $iQid,'language' => Yii::app()->getLanguage()));
} else {
$oQuestion = Question::model()->findByPk($iQid);
}
if (!$oQuestion) {
Yii::log("Question number {$iQid} invalid with current language", 'error', 'application.plugins.sendPdfReport');
return null;
}
$aQuestionsAttributes = QuestionAttribute::model()->getQuestionAttributes($iQid, Yii::app()->getLanguage());
if (empty($aQuestionsAttributes['pdfReportPdfGenerator'])) {
return $this->pdfReportTcpdfGenerator($oQuestion, $aQuestionsAttributes);
}
return $this->pdfReportMpdfGenerator($oQuestion, $aQuestionsAttributes);
}
private function pdfReportMpdfGenerator($oQuestion, $aQuestionsAttributes)
{
$sText = trim($aQuestionsAttributes['pdfReportContent'][Yii::app()->getLanguage()]);
if (empty($sText)) {
if (intval(App()->getConfig('versionnumber')) <= 3) {
$sText = $oQuestion->question;
} else {
$QuestionL10n = QuestionL10n::model()->find(
"qid = :qid AND language = :language",
array('qid' => $oQuestion->qid,'language' => Yii::app()->getLanguage())
);
if (!$QuestionL10n) {
Yii::log("Question number {$oQuestion->qid} invalid", 'error', 'application.plugins.sendPdfReport');
return null;
}
$sText = $QuestionL10n->question;
}
}
$sHeader = trim($aQuestionsAttributes['pdfReportTitle'][Yii::app()->getLanguage()]);
$sSubHeader = trim($aQuestionsAttributes['pdfReportSubTitle'][Yii::app()->getLanguage()]);
$sText = $this->EMProcessString($sText, $oQuestion->qid);
$sHeader = $this->EMProcessString($sHeader, $oQuestion->qid);
$sSubHeader = $this->EMProcessString($sSubHeader, $oQuestion->qid);
/* Fix html text */
/* tcpdf use br, mpdf use pagebreak */
$pdfSpecific = array('<br pagebreak="true" />','<br pagebreak="true"/>','<br pagebreak="true">','<pagebreak>', '<pagebreak />');
$pdfReplaced = array('<pagebreak>','<pagebreak>','<pagebreak>','<pagebreak>','<pagebreak>');
$sText = str_replace($pdfSpecific, $pdfReplaced, $sText);
/* OK, we go */
$pdfHelper = new \limeMpdf\helper\limeMpdfHelper($this->surveyId);
$extraOtions = array();
if ($aQuestionsAttributes['pdfReportCreateToc']) {
$extraOtions['h2bookmarks'] = Yii::app()->getConfig('pdfReportToc', array('H1' => 0, 'H2' => 1, 'H3' => 2));
$extraOtions['h2toc'] = Yii::app()->getConfig('pdfReportToc', array('H1' => 0, 'H2' => 1, 'H3' => 2));
}
if (!empty($extraOtions)) {
$pdfHelper->setOptions($extraOtions);
}
$pdfHelper->setTitle($sHeader, $sSubHeader);
$sFilePdfName = $this->pdfReportGetPdfFileName($oQuestion->title);
$pdfHelper->filename = $sFilePdfName;
$pdfHelper->doPdfContent($sText, \Mpdf\Output\Destination::FILE);
return $sFilePdfName;
}
private function pdfReportTcpdfGenerator($oQuestion, $aQuestionsAttributes)
{
$sText = trim($aQuestionsAttributes['pdfReportContent'][Yii::app()->getLanguage()]);
if (empty($sText)) {
if (intval(App()->getConfig('versionnumber')) <= 3) {
$sText = $oQuestion->question;
} else {
$QuestionL10n = QuestionL10n::model()->find(
"qid = :qid AND language = :language",
array('qid' => $oQuestion->qid,'language' => Yii::app()->getLanguage())
);
if (!$QuestionL10n) {
Yii::log("Question number {$oQuestion->qid} invalid with current language", 'error', 'application.plugins.sendPdfReport');
return null;
}
$sText = $QuestionL10n->question;
}
}
$sHeader = trim($aQuestionsAttributes['pdfReportTitle'][Yii::app()->getLanguage()]);
$sSubHeader = trim($aQuestionsAttributes['pdfReportSubTitle'][Yii::app()->getLanguage()]);
$sText = $this->EMProcessString($sText, $oQuestion->qid);
$sHeader = $this->EMProcessString($sHeader, $oQuestion->qid);
$sSubHeader = $this->EMProcessString($sSubHeader, $oQuestion->qid);
$sCssContent = $this->getTcpdfCss();
$sHeader = strip_tags($sHeader);
$sSubHeader = strip_tags($sSubHeader);
$aSurvey = getSurveyInfo($this->surveyId, Yii::app()->getLanguage());
$sSurveyName = $aSurvey['surveyls_title'];
if (!defined('K_PATH_IMAGES')) {
define('K_PATH_IMAGES', '');
}
Yii::setPathOfAlias('sendPdfReport', dirname(__FILE__));
Yii::import('application.libraries.admin.pdf', true);
Yii::import('application.helpers.pdfHelper');
Yii::import("sendPdfReport.helpers.pdfReportHelper");
$aPdfLanguageSettings = pdfHelper::getPdfLanguageSettings(Yii::app()->getLanguage());
$oPDF = new pdfReportHelper();
$oPDF->sImageBlank = realpath(dirname(__FILE__)) . "/blank.png";
$oPDF->sAbsoluteUrl = App()->request->getHostInfo();
$oPDF->sAbsolutePath = dirname(Yii::app()->request->scriptFile);
//~ $oPDF->SetCellPadding(0);
$tagvs = array(
'p' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
'div' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
'ul' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
'li' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
'pre' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
//~ 'h1' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
//~ 'h2' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
//~ 'h3' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
//~ 'h4' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
//~ 'h5' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
//~ 'h6' => array(0 => array('h' => 0, 'n' => 0), 1 => array('h' => 0, 'n' => 0)),
);
if (!empty(App()->getConfig("pdfreport_tagsv"))) {
$tagvs = array_merge($tagvs, App()->getConfig("pdfreport_tagsv"));
}
$oPDF->setHtmlVSpace($tagvs);
$pdfSpecific = array('<br pagebreak="true" />','<br pagebreak="true"/>','<br pagebreak="true">','<page>','</page>');
$pdfReplaced = array('<span>br pagebreak="true"</span>','<span>br pagebreak="true"</span>','<span>br pagebreak="true"</span>','<span>page</span>','<span>/page</span>');
$sText = str_replace($pdfSpecific, $pdfReplaced, $sText);
$oPurifier = new CHtmlPurifier();
$oPurifier->options = array(
'AutoFormat.RemoveEmpty' => false,
'Core.NormalizeNewlines' => false,
'CSS.AllowTricky' => true, // Allow display:none; (and other)
'CSS.Trusted' => true,
'Attr.EnableID' => true, // Allow to set id
'Attr.AllowedFrameTargets' => array('_blank','_self'),
'URI.AllowedSchemes' => array(
'http' => true,
'https' => true,
'mailto' => true,
'ftp' => true,
'nntp' => true,
'news' => true,
'data' => true,
)
);
/* With PHP8.2 : have Use of "self" in callables is deprecated in vendor/phpseclib/bcmath_compat/src/BCMath.php(492) */
$error_reporting = error_reporting();
error_reporting(0);
$sText = $oPurifier->purify($sText);
error_reporting($error_reporting);
$sHeader = $oPurifier->purify($sHeader);
$sSubHeader = $oPurifier->purify($sSubHeader);
$sText = str_replace($pdfReplaced, $pdfSpecific, $sText);
$sText = "<style>\n{$sCssContent}\n</style>\n$sText\n";
$aLogo = $this->pdfReportGetLogoPaths($this->surveyId);
if (!empty($aLogo['path'])) {
$oPDF->sLogoFile = $aLogo['path'];
}
$oPDF->initAnswerPDF($aSurvey, $aPdfLanguageSettings, $sHeader, $sSubHeader);
// output the HTML content
$errorReporting = error_reporting();
error_reporting(0);
$oPDF->writeHTML($sText, true, false, true, false, '');
error_reporting($errorReporting);
$oPDF->lastPage();
$sFilePdfName = $this->pdfReportGetPdfFileName($oQuestion->title);
$oPDF->Output($sFilePdfName, 'F');
Yii::log("getPdfFile done for {$oQuestion->qid} in {$this->surveyId} with tcpdf.", 'trace', 'application.plugins.sendPdfReport');
return $sFilePdfName;
}
/**
* Get the logo file name
* @return string : URI for pdf file
*/
private function pdfReportGetLogoPaths()
{
$aLogoNames = array(
'pdflogo.png',
'pdflogo.jpg',
'pdflogo.gif',
);
$surveyUploadDir = Yii::app()->getConfig('uploaddir') . "/surveys/" . $this->surveyId;
$surveyUploadUrl = Yii::app()->getConfig('uploadurl') . "/surveys/" . $this->surveyId;
$oTemplate = \Template::model()->getInstance(null, $this->surveyId);
$oSurvey = Survey::model()->findByPk($this->surveyId);
$templateUploadDir = $oTemplate->filesPath;
$templateUploadUrl = $oTemplate->sTemplateurl;
$templateUploadUrl .= isset($oTemplate->config->engine->filesdirectory) ? $oTemplate->config->engine->filesdirectory . "/" : "";
$aDirectories = array(
array(
'path' => $surveyUploadDir . "/files/",
'url' => $surveyUploadUrl . "/files/",
),
array(
'path' => $surveyUploadDir . "/images/",
'url' => $surveyUploadUrl . "/images/",
),
array(
'path' => $templateUploadDir,
'url' => $templateUploadUrl,
),
);
foreach ($aDirectories as $aDir) {
foreach ($aLogoNames as $sLogoName) {
if (is_file($aDir['path'] . $sLogoName)) {
return array(
'path' => $aDir['path'] . $sLogoName,
'url' => $aDir['url'] . $sLogoName,
);
}
}
}
return array('error' => "File not found in your survey.");
}
/**
* Save the generated file in file upload
* @param object question object
* @return void
*/
private function pdfReportSaveInFileUpload($oQuestion)
{
if ($oQuestion->type != '|') {
return;
}
$oSurvey = Survey::model()->findByPk($this->surveyId);
if (!$oSurvey || $oSurvey->active != 'Y') {
return;
}
$sAnswerColumn = "{$this->surveyId}X{$oQuestion->gid}X{$oQuestion->qid}";
$sAnswerCountColumn = "{$sAnswerColumn}_filecount";
$uploadSurveyDir = App()->getConfig("uploaddir")
. DIRECTORY_SEPARATOR
. "surveys"
. DIRECTORY_SEPARATOR
. $this->surveyId
. DIRECTORY_SEPARATOR
. "files"
. DIRECTORY_SEPARATOR;
if (!is_dir($uploadSurveyDir)) {
mkdir($uploadSurveyDir, 0777, true);
}
$fileName = $this->pdfReportGetPdfFileName($oQuestion->title);
$fileSize = 0.001 * filesize($fileName); // Same than controller
$reportSavedFileName = $this->pdfReportGetPdfSavedFileName($oQuestion);
$sDestinationFileName = 'fu_' . hexdec(crc32($this->responseId . rand(1, 10000) . $oQuestion->title));
if (!copy($fileName, $uploadSurveyDir . $sDestinationFileName)) {
Yii::log("Error moving file $fileName to $uploadSurveyDir", 'error', 'application.plugins.pdfReport');
return;
}
$aAnswer = array(
array(
'title' => '',
'comment' => '',
'size' => $fileSize,
'filename' => $sDestinationFileName,
'name' => $reportSavedFileName,
'ext' => 'pdf'
)
);
$oResponse = Response::model($this->surveyId)->find('id=:id', array(':id' => $this->responseId));
$oResponse->$sAnswerColumn = ls_json_encode($aAnswer);
$oResponse->$sAnswerCountColumn = 1;
if (method_exists($oResponse, 'encryptSave')) {
$saveResult = $oResponse->encryptSave();
} else {
$saveResult = $oResponse->save();
}
if (!$saveResult) {
Yii::log($oResponse->getErrors(), 'error', 'application.plugins.pdfReport');
}
$sessionSurvey = Yii::app()->session["survey_{$this->surveyId}"];
$sessionSurvey[$sAnswerColumn] = $oResponse->$sAnswerColumn;
$sessionSurvey[$sAnswerCountColumn] = $oResponse->$sAnswerCountColumn;
Yii::app()->session["survey_{$this->surveyId}"] = $sessionSurvey;
}
/**
* Send the pdf by email
* @param
* @retuen void
*/
private function pdfReportSendByEmail($oQuestion)
{
if (version_compare(Yii::app()->getConfig('versionnumber'), "4.0.0", "<")) {
$this->pdfReportSendByEmailLegacy($oQuestion);
return;
}
$aQuestionsAttributes = QuestionAttribute::model()->getQuestionAttributes($oQuestion->qid, Yii::app()->getLanguage());
$questionAttributeEmails = trim($aQuestionsAttributes['pdfReportSendByEmailMail']);
if ($questionAttributeEmails == "") {
return;
}
$questionAttributeEmails = $this->EMProcessString($questionAttributeEmails, $oQuestion->qid);
$aValidRecipient = LimeMailer::validateAddresses($questionAttributeEmails);
if (empty($aValidRecipient)) {
return;
}
$oSurvey = Survey::model()->findByPk($this->surveyId);
$mailer = \LimeMailer::getInstance();
$mailer->mailLanguage = App()->getLanguage();
$mailer->setSurvey($this->surveyId);
$mailer->setTypeWithRaw($aQuestionsAttributes['pdfReportSendByEmailContent'], App()->getLanguage());
$sFile = $this->pdfReportGetPdfFileName($oQuestion->title);
$mailer->addAttachment(
$sFile,
$this->pdfReportGetPdfSavedFileName($oQuestion)
);
if ($aQuestionsAttributes['pdfReportSendByEmailAttachment']) {
$mailer->addAttachementsByType();
}
/* Update type */
$mailer->emailType = 'plugin_pdfReport';
foreach ($aValidRecipient as $sRecipient) {
$mailer->setTo($sRecipient);
if (!$mailer->SendMessage()) {