pdfReport.php 34.6 KB
Newer Older
Denis Chenu's avatar
Denis Chenu committed
1
<?php
2
/**
Denis Chenu's avatar
Denis Chenu committed
3
 * pdfReport Plugin for LimeSurvey
Denis Chenu's avatar
Denis Chenu committed
4
 * Use question settings to create a report and send it by email.
Denis Chenu's avatar
Denis Chenu committed
5
 *
6 7 8
 * @author Denis Chenu <https://sondages.pro>
 * @copyright 2015-2017 Denis Chenu <https://sondages.pro>
 * @copyright 2017 Réseau en scène Languedoc-Roussillon <https://www.reseauenscene.fr/>
Denis Chenu's avatar
Denis Chenu committed
9 10
 * @copyright 2015 Ingeus <http://www.ingeus.fr/>
 * @license AGPL v3
11
 * @version 1.2.1
Denis Chenu's avatar
Denis Chenu committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 *
 * 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 \ls\pluginmanager\PluginBase {
    protected $storage = 'DbStorage';
    static protected $description = 'Do a PDF report for question.';
    static protected $name = 'pdfReport';

29 30 31 32 33 34 35 36
    /**
     * @var integer $_iSurveyId
     */
    private $_iSurveyId;
    /**
     * @var integer $_iResponseId
     */
    private $_iResponseId;
Denis Chenu's avatar
Denis Chenu committed
37

38 39 40
    /**
     * Register to needed event
     */
Denis Chenu's avatar
Denis Chenu committed
41
    public function init()
Denis Chenu's avatar
Denis Chenu committed
42
    {
43 44 45 46
        /* Add the attribute */
        $this->subscribe('newQuestionAttributes','addPdfReportAttribute');
        /* Generate and save pdfReport when submit */
        $this->subscribe('afterSurveyComplete', 'afterSurveyComplete');
47 48
        /* Remove answers (and help) part */
        $this->subscribe('beforeQuestionRender', 'removeAnswersPart');
49 50
        /* To add own translation message source */
        $this->subscribe('afterPluginLoad');
51 52
        /* To replace if needed printanswer */
        $this->subscribe('beforeControllerAction', 'setPrintAnswer');
Denis Chenu's avatar
Denis Chenu committed
53
    }
54 55 56 57

    /**
     * @see ls\pluginmanager\PluginBase->seetings
     */
Denis Chenu's avatar
Denis Chenu committed
58
    protected $settings = array(
59
        'basesavedirectory'=> array(
Denis Chenu's avatar
Denis Chenu committed
60
            'type'=>'string',
Denis Chenu's avatar
Denis Chenu committed
61
            'label'=>'[WIP] Directory on the server to move the file (if question settings is set)',
62
            'help'=>'You can use {SID} for survey id. Plugin didn`t create directory.',
Denis Chenu's avatar
Denis Chenu committed
63 64
            'default'=>'',
        ),
65 66 67 68 69 70 71 72 73 74 75
        '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',
        ),
Denis Chenu's avatar
Denis Chenu committed
76 77 78 79
        '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>',
        ),
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        /* 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',
        //~ ),
Denis Chenu's avatar
Denis Chenu committed
98 99
    );

100 101 102 103 104 105 106
    /**
     * @see getPluginSettings
     */
    public function getPluginSettings($getValues=true)
    {
        $dowloadurl=$this->api->createUrl('plugins/direct', array('plugin' => $this->getName(), 'surveyid' => 'SID','qid'=>'QID'));
        $dowloadurl=str_replace(array("SID","QID"),array("{SID}","{QID}"),$dowloadurl);
Denis Chenu's avatar
Denis Chenu committed
107
        $helpString=sprintf($this->_translate("[WIP] 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}");
108 109 110 111 112
        $this->settings['basicDocumentation']['content']="<div class='well'>{$helpString}</div>";

        return parent::getPluginSettings($getValues);
    }

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

    /**
     * @see ls\helpers\questionHelper->getAttributesDefinitions()
     */
    public function addPdfReportAttribute()
    {
        $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'=>'',
                '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'=>'',
                'caption'=>$this->_translate('Sub title for the pdf.'),
            ),
151
            'pdfReportPrintAnswer'=>array(
152 153 154
                'types'=>'|', /* upload question type */
                'category'=>$this->_translate('pdf report'),
                'sortorder'=>20,
155 156 157
                'inputtype'=>'singleselect',
                'options'=>array(
                    0=>gT('No'),
158
                    1=>$this->_translate('Allow public download (with the link).'),
159 160 161
                    2=>$this->_translate('Replace public print answer.'),
                ),
                'default'=>0,
162
                '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.'),
163 164 165 166 167 168
                'caption'=>$this->_translate('Replace public print answer.'),
            ),
            'pdfReportSavedFileName'=>array(
                'types'=>'|', /* upload question type */
                'category'=>$this->_translate('pdf report'),
                'sortorder'=>30,
169
                'inputtype'=>'text',
170
                'default'=>'',
171
                'i18n'=>true,
Denis Chenu's avatar
Denis Chenu committed
172 173 174
                'htmlOptions'=>array(
                    'placeholder'=>'questioncode_{SAVEDID}',
                ),
175
                'expression'=>1,
Denis Chenu's avatar
Denis Chenu committed
176
                'help'=>$this->_translate('By default usage of questioncode_{SAVEDID}. You don\'t have to put the .pdf part.'),
177 178
                'caption'=>$this->_translate('Name of saved PDF file.'),
            ),
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
            '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.'),
                '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.'),
                'caption'=>$this->_translate('Content and subject of the email'),
            ),
206 207 208 209 210 211 212 213 214
            'pdfReportSendByEmailAttachment'=>array(
                'types'=>'|', /* upload question type */
                'category'=>$this->_translate('pdf report'),
                'sortorder'=>50,
                'inputtype'=>'switch',
                'default'=>1,
                'help'=>$this->_translate('Add attachements on same way than default.'),
                'caption'=>$this->_translate('Add attachements of email'),
            ),
215 216 217 218 219 220 221 222 223 224
        );
        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);
        }
    }

225 226 227
    /**
     * Do all the pdf after survey is submitted, and each action if needed
     */
228 229 230 231 232 233
    public function afterSurveyComplete()
    {
        $this->_iSurveyId=$this->getEvent()->get('surveyId');
        $this->_iResponseId=$this->getEvent()->get('responseId');
        $this->doPdfReports();
    }
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

    /**
     * Do all the pdf after survey is submitted, and each action if needed
     */
    public function removeAnswersPart()
    {
        if($this->getEvent()->get('type')=='|') {
            $oEvent=$this->getEvent();
            $oQuestionPdfReport = intval(QuestionAttribute::model()->count(
                "attribute=:attribute and qid=:qid and value=:value",
                array(':attribute'=>'pdfReport',':qid'=>$oEvent->get('qid'),':value'=>1)
            ));
            if($oQuestionPdfReport) {
                $inputName="{$oEvent->get('surveyId')}X{$oEvent->get('gid')}X{$oEvent->get('qid')}";
                $answers = \CHtml::hiddenField($inputName , '', array('id' => $inputName)) // LS bug : must fix (id starting by number)
                         . \CHtml::hiddenField("{$inputName}_filecount" , '', array('id' => "{$inputName}_filecount"));
                $oEvent->set('answers',$answers);
                $oEvent->set('file_valid_message','');
                $oEvent->set('valid_message','');
                $oEvent->set('class', $oEvent->get('class')." pdfreport-question");
            }
        }
    }

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    /**
     * Do all reports needed
     */
    public function doPdfReports()
    {
        // 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->join='LEFT JOIN {{questions}} as question ON question.qid=t.qid';
        $criteria->condition='question.sid = :sid and question.language=:language and attribute=:attribute and value=:value';
        $criteria->params=array(':sid'=>$this->_iSurveyId,':language'=>Yii::app()->getLanguage(),':attribute'=>'pdfReport',':value'=>1);
        $oQuestionAttribute = QuestionAttribute::model()->findAll($criteria);
        if($oQuestionAttribute){
            foreach($oQuestionAttribute as $questionAttribute){
                $pdfFile=$this->_getPdfFile($questionAttribute->qid);
                if($pdfFile){
                    $oQuestion=Question::model()->findByPk(array('qid'=>$questionAttribute->qid,'language'=>Yii::app()->getLanguage()));
                    if($oQuestion->type=="|"){
                        $this->_saveInFileUpload($oQuestion);
277
                        $this->_setSessionPrintAnswer($oQuestion);
278
                    }
279
                    $this->_sendByEMail($oQuestion);
280
                    $this->_saveInDirectory($oQuestion);
281 282 283 284 285
                    unlink($pdfFile);
                }
            }
        }
    }
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

    /**
     * Replace print answer by own donwload
     * @see beforeControllerAction
     */
    public function setPrintAnswer()
    {
        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);
            }
        }
    }

    /**
     * Pdf download of a upload question type
     * @param int $surveyid
     * @param int $qid
     * @param int $srid : responseId
     * @return void
     */
    public 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 */
        $aSessionPrintRigth=Yii::app()->session["pdfReportPrintRight"];
        $aSurveyPrintRigth=$aSessionPrintRigth[$surveyid];
        if(empty($aSurveyPrintRigth)){
            throw new CHttpException(401, 'You are not allowed to print answers.');
        }
Denis Chenu's avatar
Denis Chenu committed
323
        if(!$srid) {
324 325
            $srid=$aSurveyPrintRigth['srid'];
        }
Denis Chenu's avatar
Denis Chenu committed
326
        if(!$qid) {
327 328 329 330 331 332 333 334 335 336
            $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];
Denis Chenu's avatar
Denis Chenu committed
337
        $sFileRealName = Yii::app()->getConfig('uploaddir') . "/surveys/" . $surveyid . "/files/" . $aFile['filename'];
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
        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 and value>0",
Denis Chenu's avatar
Denis Chenu committed
366
            array(':attribute'=>'pdfReportPrintAnswer',':qid'=>$oQuestion->qid)
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        );
        if(!$oQuestionAttribute){
            return;
        }
        $aSessionPrintRigth=Yii::app()->session["pdfReportPrintRight"];
        if(empty($aSessionPrintRigth)) {
            $aSessionPrintRigth=array();
        }
        if(empty($aSessionPrintRigth)) {
            $aSessionPrintRigth[$oQuestion->sid]=array(
                'srid'=>$this->_iResponseId,
                '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;
    }
389 390 391 392
    /**
     * Get a pdf file from a string
     * @param integer $iQid
     * @return string : URI for pdf file
Denis Chenu's avatar
Denis Chenu committed
393
     */
394
    private function _getPdfFile($iQid)
395
    {
396
        $oQuestion=Question::model()->findByPk(array('qid'=>$iQid,'language'=>Yii::app()->getLanguage()));
397 398 399
        if(!$oQuestion){
            Yii::log("Question number {$iQid} invalid",'error','application.plugins.sendPdfReport');
            return null;
Denis Chenu's avatar
Denis Chenu committed
400
        }
401 402 403
        $iSurveyId=$this->_iSurveyId;
        $iResponseId=$this->_iResponseId;

Denis Chenu's avatar
Denis Chenu committed
404

405 406 407 408 409 410 411 412
        $sText=$oQuestion->question;
        $aQuestionsAttributes=QuestionAttribute::model()->getQuestionAttributes($iQid,Yii::app()->getLanguage());
        $sHeader=trim($aQuestionsAttributes['pdfReportTitle'][Yii::app()->getLanguage()]);
        $sSubHeader=trim($aQuestionsAttributes['pdfReportSubTitle'][Yii::app()->getLanguage()]);

        $sText=$this->_EMProcessString($sText);
        $sHeader=$this->_EMProcessString($sHeader);
        $sSubHeader=$this->_EMProcessString($sSubHeader);
Denis Chenu's avatar
Denis Chenu committed
413 414

        //~ return;
415
        $sCssContent=$this->_getCss();
Denis Chenu's avatar
Denis Chenu committed
416 417 418
        $sHeader=strip_tags($sHeader);
        $sSubHeader=strip_tags($sSubHeader);

419
        $aSurvey=getSurveyInfo($this->_iSurveyId,Yii::app()->getLanguage());
Denis Chenu's avatar
Denis Chenu committed
420
        $sSurveyName = $aSurvey['surveyls_title'];
421 422 423
        if (!defined('K_PATH_IMAGES')) {
            define('K_PATH_IMAGES', '');
        }
Denis Chenu's avatar
Denis Chenu committed
424 425 426 427 428
        Yii::setPathOfAlias('sendPdfReport', dirname(__FILE__));
        //define('K_PATH_IMAGES', Yii::app()->getConfig("homedir").DIRECTORY_SEPARATOR);

        Yii::import('application.libraries.admin.pdf', true);
        Yii::import('application.helpers.pdfHelper');
429
        Yii::import("sendPdfReport.helpers.pdfReportHelper");
Denis Chenu's avatar
Denis Chenu committed
430

431
        $aPdfLanguageSettings=pdfHelper::getPdfLanguageSettings(Yii::app()->getLanguage());
Denis Chenu's avatar
Denis Chenu committed
432

433
        $oPDF = new pdfReportHelper();
Denis Chenu's avatar
Denis Chenu committed
434
        $oPDF->sImageBlank = realpath(dirname(__FILE__))."/blank.png";
435 436 437
        $oPDF->sAbsoluteUrl = App()->request->getHostInfo();
        $oPDF->sAbsolutePath = dirname(Yii::app()->request->scriptFile);

Denis Chenu's avatar
Denis Chenu committed
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
        $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);
        if(function_exists ("tidy_parse_string")) // Call to undefined function tidy_parse_string() in ./application/third_party/tcpdf/include/tcpdf_static.php on line 2099
        {
            $tidy_options = array (
                'clean' => 1,
                'drop-empty-paras' => 0,
                'drop-proprietary-attributes' => 0,
                'fix-backslash' => 1,
                'hide-comments' => 1,
                'join-styles' => 1,
                'lower-literals' => 1,
                'merge-divs' => 1,
                'merge-spans' => 1,
                'output-xhtml' => 1,
                'word-2000' => 0,
                'wrap' => 0,
                'output-bom' => 0,
                'char-encoding' => 'utf8',
                'input-encoding' => 'utf8',
                'output-encoding' => 'utf8'
            );// Fix UTF8 and <br preakpage="true" />
            $sText=$oPDF->fixHTMLCode($sText,$sCssContent,'',$tidy_options);
        }
        else
        {
            // TODO : Find the good way to use pagebreak="true", verify if page is used in tcpdf
            // ALT : explode/implode
            $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,
                    )
            );
            $sText=$oPurifier->purify($sText);

        }
        $sText=str_replace($pdfReplaced, $pdfSpecific, $sText);
        $sText="<style>\n{$sCssContent}\n</style>\n$sText\n";
        //~ $this->event->getContent($this)
              //~ ->addContent(htmlentities($sText));
492
        $aLogo=$this->_getLogoPaths($this->_iSurveyId);
493
        if(!empty($aLogo['path'])){
Denis Chenu's avatar
Denis Chenu committed
494
           $oPDF->sLogoFile=$aLogo['path'];
495
        }
Denis Chenu's avatar
Denis Chenu committed
496 497 498 499 500
        $oPDF->initAnswerPDF($aSurvey, $aPdfLanguageSettings, $sHeader, $sSubHeader);
        // output the HTML content
        $oPDF->writeHTML($sText, true, false, true, false, '');

        $oPDF->lastPage();
501
        $sFilePdfName=$this->_getPdfFileName($oQuestion->title);
Denis Chenu's avatar
Denis Chenu committed
502 503

        $oPDF->Output($sFilePdfName, 'F');
504
        Yii::log("getPdfFile done for {$iQid} in {$this->_iSurveyId}",'trace','application.plugins.sendPdfReport');
Denis Chenu's avatar
Denis Chenu committed
505
        return $sFilePdfName;
506
    }
507

508 509 510 511
    /**
     * Get the logo file name
     * @return string : URI for pdf file
     */
512
    private function _getLogoPaths()
Denis Chenu's avatar
Denis Chenu committed
513
    {
514
        $aLogoNames=array(
515 516 517
            'pdflogo.png',
            'pdflogo.jpg',
            'pdflogo.gif',
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
        $surveyUploadDir=Yii::app()->getConfig('uploaddir')."/surveys/".$this->_iSurveyId;
        $surveyUploadUrl=Yii::app()->getConfig('uploadurl')."/surveys/".$this->_iSurveyId;
        $oTemplate = \Template::model()->getInstance(null, $this->_iSurveyId);
        $oSurvey=Survey::model()->findByPk($this->_iSurveyId);
        $templateUploadDir=$oTemplate->filesPath;
        $templateUploadUrl = Template::getTemplateURL($oSurvey->template)."/";
        $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,
                    );
                }
            }
Denis Chenu's avatar
Denis Chenu committed
550
        }
551

Denis Chenu's avatar
Denis Chenu committed
552
        return array('error'=>"File not found in your survey.");
553
    }
554

555 556 557 558 559 560
    /**
     * Save the generated file in file upload
     * @todo
     * @param object question object
     * @return void
     */
Denis Chenu's avatar
Denis Chenu committed
561
    private function _saveInDirectory($oQuestion) {
562 563

    }
564 565 566 567 568 569 570
    /**
     * Save the generated file in file upload
     * @param object question object
     * @return void
     */
    private function _saveInFileUpload($oQuestion)
    {
571 572 573
        if($oQuestion->type!='|'){
            return;
        }
574 575 576 577 578 579 580 581 582 583 584 585 586
        $oSurvey=Survey::model()->findByPk($this->_iSurveyId);
        if(!$oSurvey || $oSurvey->active!='Y'){
            return;
        }
        $sAnswerColumn="{$this->_iSurveyId}X{$oQuestion->gid}X{$oQuestion->qid}";
        $sAnswerCountColumn= "{$sAnswerColumn}_filecount";
        $uploadSurveyDir=App()->getConfig("uploaddir").DIRECTORY_SEPARATOR."surveys".DIRECTORY_SEPARATOR.$this->_iSurveyId.DIRECTORY_SEPARATOR."files".DIRECTORY_SEPARATOR;
        if(!is_dir($uploadSurveyDir)) {
            mkdir($uploadSurveyDir, 0777, true);
        }
        $fileName=$this->_getPdfFileName($oQuestion->title);
        $fileSize=0.001 * filesize($fileName); // Same than controller
        $oQuestionAttribute = QuestionAttribute::model()->find(
587 588
            "attribute=:attribute and qid=:qid",
            array(':attribute'=>'pdfReportSavedFileName',':qid'=>$oQuestion->qid)
589 590 591 592
        );
        if($oQuestionAttribute && trim($oQuestionAttribute->value)) {
            $reportSavedFileName=$this->_EMProcessString(trim($oQuestionAttribute->value)).".pdf";
        } else {
593
            $reportSavedFileName="{$oQuestion->title}.pdf";
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
        }
        $sDestinationFileName = 'fu_' . hexdec(crc32($this->_iResponseId.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->_iSurveyId)->find('id=:id',array(':id'=>$this->_iResponseId));
        $oResponse->$sAnswerColumn=ls_json_encode($aAnswer);
        $oResponse->$sAnswerCountColumn=1;
613 614 615
        if(!$oResponse->save()){
            Yii::log($oResponse->getErrors(),'error','application.plugins.pdfReport');
        }
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

    /**
     * Save the pdf by email
     * @param
     * @retuen void
     */
    private function _sendByEmail($oQuestion)
    {
        $aQuestionsAttributes=QuestionAttribute::model()->getQuestionAttributes($oQuestion->qid,Yii::app()->getLanguage());
        $questionAttributeEmails=trim($aQuestionsAttributes['pdfReportSendByEmailMail']);
        if($questionAttributeEmails==""){
            return;
        }
        $questionAttributeEmails=$this->_EMProcessString($questionAttributeEmails);
        $aRecipient=explode(";", $questionAttributeEmails);
        $aValidRecipient=array();
        foreach($aRecipient as $sRecipient)
        {
            $sRecipient=trim($sRecipient);
            if(validateEmailAddress($sRecipient))
            {
                $aValidRecipient[]=$sRecipient;
            }
        }
        $oSurvey=Survey::model()->findByPk($this->_iSurveyId);
        $aMessage=$this->_getEmailContent($aQuestionsAttributes['pdfReportSendByEmailContent']);
        $sFile=$this->_getPdfFileName($oQuestion->title);
        $aAttachments = array($this->_getPdfFileName($oQuestion->title));
645 646 647 648
        /* Add LS attachments */
        if($aQuestionsAttributes['pdfReportSendByEmailAttachment']) {
            $aAttachments = array_merge($this->_getEmailAttachements($aQuestionsAttributes['pdfReportSendByEmailContent']),$aAttachments);
        }
649 650 651 652 653 654 655 656 657 658 659 660 661
        foreach ($aValidRecipient as $sRecipient)
        {
            if (!SendEmailMessage($aMessage['message'], $aMessage['subject'],$sRecipient,"{$oSurvey->admin} <{$oSurvey->adminemail}>" , Yii::app()->getConfig("sitename"), true, getBounceEmail($this->_iSurveyId), $aAttachments))
            {
                Yii::log("Email with ".$sFile." can not be sent due to a mail error",'error','application.plugins.pdfReport');
            }
            else
            {
                Yii::log("Email with ".$sFile." sent",'info','application.plugins.pdfReport');
            }
        }

    }
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
    /**
     * Generate unique pdf filename
     * @param string $qCode question code
     * @param boolean $onlyFile return only the file name
     * @return string URI
     */
    private function _getPdfFileName($qCode,$onlyFile=false)
    {
        $aFilePdfName=array(
            $qCode,
            $this->_iSurveyId,
        );
        /* For unicity : make an unique responseId big number : only for testing or deactivated survey*/
        if(empty($this->_iResponseId)){
            $this->_iResponseId=hexdec(crc32(time().rand ( 1 , 1000 )));
        }
        if(!empty($_SESSION["survey_{$this->_iSurveyId}"]['token']) && $this->get("usetokenfilename",null,null,$this->settings['usetokenfilename']['default'])!=='none') {
            $aFilePdfName[]=$_SESSION["survey_{$this->_iSurveyId}"]['token'];
            if($this->get("usetokenfilename",null,null,$this->settings['usetokenfilename']['default'])==!'alone'){
                $aFilePdfName[]=$this->_iResponseId;
            }
        } else {
             $aFilePdfName[]=$this->_iResponseId;
        }
        $sPdfFileName=implode("_",$aFilePdfName);
687
        $sPdfFileName.=".pdf";
688 689 690 691 692 693
        if($onlyFile) {
            return $sPdfFileName;
        } else {
            return Yii::app()->getRuntimePath()."/".$sPdfFileName;
        }
    }
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713

    /**
     * Get fixed content by email
     */
    private function _getEmailContent($sType)
    {
        $aReplacementVars=$this->_getReplacementVars($sType=='confirm');
        $aSurvey=getSurveyInfo($this->_iSurveyId,Yii::app()->language);
        $aReData=array(
            'saved_id'=>$this->_iResponseId,
            'thissurvey'=>$aSurvey,
        );
        $sSubject=templatereplace($aSurvey["email_{$sType}_subj"],$aReplacementVars,$aReData,'',false,null,array(),true);
        $sMessage=templatereplace($aSurvey["email_{$sType}"],$aReplacementVars,$aReData,'',false,null,array(),true);

        return array(
            'subject'=>$sSubject,
            'message'=>$sMessage,
        );
    }
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
    /**
     * Get attachement content by email
     */
    private function _getEmailAttachements($sType)
    {
        /* @todo : search the for needed other replace (invite and remind) */
        switch ($sType) {
            case 'confirm':
                $sType = 'confirmation';
            default :
        }
        $aRelevantAttachments = array();
        $aSurvey=getSurveyInfo($this->_iSurveyId,Yii::app()->language);
        $aAttachments = unserialize($aSurvey['attachments']);
        /*
         * Iterate through attachments and check them for relevance.
         */
        if (!empty($aAttachments[$sType])) {
            foreach ($aAttachments[$sType] as $aAttachment) {
                // If the attachment is relevant it will be added to the mail.
                if (LimeExpressionManager::ProcessRelevance($aAttachment['relevance']) && @file_exists($aAttachment['url'])) {
                    $aRelevantAttachments[] = $aAttachment['url'];
                }
            }
        }
        return $aRelevantAttachments;
    }
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
    /**
     * Get the replacement var for email
     * @param boolean : wit or wothout token value
     * @return string[]
     */
    private function _getReplacementVars()
    {
        $thissurvey=$aSurvey=getSurveyInfo($this->_iSurveyId,Yii::app()->language);
        $aReplacementVars=array();
        $aReplacementVars['RELOADURL']='';
        $aReplacementVars['ADMINNAME'] = $aSurvey['adminname'];
        $aReplacementVars['ADMINEMAIL'] = $aSurvey['adminemail'];
        $aReplacementVars['VIEWRESPONSEURL']=Yii::app()->createAbsoluteUrl("/admin/responses/sa/view/surveyid/{$this->_iSurveyId}/id/{$this->_iResponseId}");
        $aReplacementVars['EDITRESPONSEURL']=Yii::app()->createAbsoluteUrl("/admin/dataentry/sa/editdata/subaction/edit/surveyid/{$this->_iSurveyId}/id/{$this->_iResponseId}");
        $aReplacementVars['STATISTICSURL']=Yii::app()->createAbsoluteUrl("/admin/statistics/sa/index/surveyid/{$this->_iSurveyId}");
        // Always HTML, TODO : fix it
        if (true)
        {
            $aReplacementVars['VIEWRESPONSEURL']="<a href='{$aReplacementVars['VIEWRESPONSEURL']}'>{$aReplacementVars['VIEWRESPONSEURL']}</a>";
            $aReplacementVars['EDITRESPONSEURL']="<a href='{$aReplacementVars['EDITRESPONSEURL']}'>{$aReplacementVars['EDITRESPONSEURL']}</a>";
            $aReplacementVars['STATISTICSURL']="<a href='{$aReplacementVars['STATISTICSURL']}'>{$aReplacementVars['STATISTICSURL']}</a>";
        }
        $aReplacementVars['ANSWERTABLE']='';
        $oSessionSurvey=Yii::app()->session["survey_{$this->_iSurveyId}"];
        if($thissurvey['anonymized'] != 'Y' && !empty($oSessionSurvey['token']) && tableExists('{{tokens_' . $this->_iSurveyId . '}}'))
        {
            $oToken=Token::model($this->_iSurveyId)->find("token=:token",array('token' => $oSessionSurvey['token']));
            if($oToken)
            {
                foreach($oToken->attributes as $attribute=>$value)
                {
                    $aReplacementVars[strtoupper($attribute)]=$value;
                }
            }
        }
        return $aReplacementVars;
    }
778 779 780 781 782 783 784 785 786 787 788 789 790

    /**
     * get css for this survey
     * @return string : css
     */
    private function _getCss()
    {
        $oTemplate = \Template::model()->getInstance(null, $this->_iSurveyId);
        if(is_file($oTemplate->filesPath.'pdfreport.css')){
            return file_get_contents($oTemplate->filesPath.'/pdfreport.css');
        }
        return file_get_contents(dirname(__FILE__).'/base.css');
    }
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
    /**
     * Translate a plugin string
     * @param string $string to translate
     * @return string
     */
    private function _translate($string){
        return Yii::t('',$string,array(),'pdfReport');
    }

    /**
     * Add this translation just after loaded all plugins
     * @see event afterPluginLoad
     */
    public function afterPluginLoad(){
        // messageSource for this plugin:
        $pdfReportLang=array(
            'class' => 'CGettextMessageSource',
            'cacheID' => 'pdfReportLang',
            'cachingDuration'=>3600,
            'forceTranslation' => true,
            'useMoFile' => true,
            'basePath' => __DIR__ . DIRECTORY_SEPARATOR.'locale',
            'catalog'=>'messages',// default from Yii
        );
        Yii::app()->setComponent('pdfReport',$pdfReportLang);
    }

    /**
     * Process a string via expression manager (static way)
     * @param string $string
     * @return string
     */
    private function _EMProcessString($string)
    {
        Yii::app()->setConfig('surveyID',$this->_iSurveyId);
        $oSurvey=Survey::model()->findByPk($this->_iSurveyId);
        $replacementFields=array(
            'SAVEDID'=>$this->_iResponseId,
            'SITENAME'=>App()->getConfig('sitename'),
            'SURVEYNAME'=>$oSurvey->getLocalizedTitle(),
Denis Chenu's avatar
Denis Chenu committed
831
            'SURVEYRESOURCESURL'=> Yii::app()->getConfig("uploadurl").'/surveys/'.$this->_iSurveyId.'/'
832 833 834
        );
        return \LimeExpressionManager::ProcessString($string, null, $replacementFields, false, 3, 0, false, false, true);
    }
Denis Chenu's avatar
Denis Chenu committed
835
}