sendMailCron.php 64.3 KB
Newer Older
1 2 3 4 5 6
<?php
/**
 * sendMailCron : allow to send token email by cron or sheduled task
 * Need activate cron system in the server : php yourlimesurveydir/application/commands/console.php plugin cron --interval=X where X is interval in minutes
 *
 * @author Denis Chenu <denis@sondages.pro>
7
 * @copyright 2016-2018 Denis Chenu <https://www.sondages.pro>
8 9
 * @copyright 2016 AXA Insurance (Gulf) B.S.C. <http://www.axa-gulf.com> 
 * @copyright 2016-2018 Extract Recherche Marketing <https://dialogs.ca>
10
 * @license AGPL v3
11
 * @version 3.1.0
12 13
 *
 * This program is free software: you can redistribute it and/or modify
14
 * it under the terms of the GNU Affero General Public License as published by
15 16 17 18 19 20 21 22 23
 * 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.
 */

24
class sendMailCron extends PluginBase
25 26 27 28 29
{
    protected $storage = 'DbStorage';
    static protected $description = 'Allow to send token email by cron or sheduled task';
    static protected $name = 'sendMailCron';

30
    /**
Chenu Denis's avatar
Chenu Denis committed
31
     * @var int debug (for echoing on terminal) 0=>ERROR, 1=>WARNING+BASICINFORMATION, 2=>INFO, 3=>DEBUG/TRACE
32
     */
33
    private $debug= 1;
34
    /**
35
     * @var boolean simulate sending (for log)
36 37
     */
    private $simulate=false;
38 39 40 41
    /**
     * @var boolean disable plugin (via command line)
     */
    private $disable=false;
42 43 44 45
    /**
     * @var string actual cron type
     */
    private $cronType;
46

47 48 49 50
    /**
     * @var int currentBatchSize Count for this batch
     */
    private $currentBatchSize=0;
51 52 53 54
    /**
     * @var int SurveyBatchSize Count for this batch of actual survey
     */
    private $currentSurveyBatchSize;
55

56 57 58 59 60 61 62
    /**
     * @var string|null final attributes to be used (for this survey)
     */
    private $surveyMaxEmailAttributes;
    private $surveyDelayInvitationAttribute;
    private $surveyDelayReminderAttribute;

Chenu Denis's avatar
Chenu Denis committed
63 64 65
    /**
     * @var array[] the settings
     */
66 67 68
    protected $settings = array(
        'information' => array(
            'type' => 'info',
69
            'content' => 'You need activate cron system in the server : <code>php yourlimesurveydir/application/commands/console.php plugin cron --interval=1</code>. This plugin don\'t use interval, all email of all surveys are tested when cron happen.',
70
        ),
71 72 73 74 75 76 77 78 79 80
        //~ 'enableInCron' => array(
            //~ 'type'=>'checkbox',
            //~ 'value'=>1,
            //~ 'htmlOption'=>array(
                //~ 'uncheckValue'=>0
            //~ ),
            //~ 'label'=>"Enable in cron event.",
            //~ 'help'=>"Enable sendMailCron in cron event, you can use direct event for sending email.",
            //~ 'default'=>1,
        //~ ),
81 82 83 84 85 86 87 88 89
        'maxBatchSize' => array(
            'type'=>'int',
            'htmlOptions'=>array(
                'min'=>1,
            ),
            'label'=>"Max email to send globally (max batch size).",
            'help'=>'Leave empty to send all available email on each cron',
            'default'=>'',
        ),
90 91 92 93 94 95 96 97 98 99 100 101
        'hostInfo' => array(
            'type' => 'string',
            'label' => 'Host info for url',
        ),
        'baseUrl' => array(
            'type' => 'string',
            'label' => 'baseUrl',
        ),
        'scriptUrl' => array(
            'type' => 'string',
            'label' => 'scriptUrl',
        ),
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        'maxEmail' => array(
            'type'=>'int',
            'htmlOptions'=>array(
                'min'=>0,
            ),
            'label'=>"Max email to send (invitation + remind), set it to 0 to deactivate sending of email.",
            'default'=>2,
        ),
        'delayInvitation' => array(
            'type'=>'int',
            'htmlOptions'=>array(
                'min'=>1,
            ),
            'label'=>"Min delay between invitation and first reminder.",
            'default'=>7,
        ),
        'delayReminder' => array(
            'type'=>'int',
            'htmlOptions'=>array(
                'min'=>1,
            ),
123
            'label'=>"Min delay between each reminders.",
124 125
            'default'=>7,
        ),
126 127 128 129 130 131 132 133 134
        'validateEmail' => array(
            'type'=>'checkbox',
            'value'=>1,
            'htmlOption'=>array(
                'uncheckValue'=>0
            ),
            'label'=>"Validate email before try to send it.",
            'default'=>0,
        ),
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
        'maxEmailAttribute' => array(
            'type'=>'int',
            'htmlOptions'=>array(
                'min'=>1,
            ),
            'label'=>"Default token attribute to use for max email to send (invitation + remind).",
            'default'=>"",
        ),
        'delayInvitationAttribute' => array (
            'type'=>'int',
            'htmlOptions'=>array(
                'min'=>1,
            ),
            'label'=>"Default token attribute to use for minimum delay between invitation and first reminder.",
            'help'=>"If this attribute exist : tested just before sending, then final delay is minimum between global and this attribute",
            'default'=>"",
        ),
        'delayReminderAttribute' => array (
            'type'=>'int',
            'htmlOptions'=>array(
                'min'=>1,
            ),
            'label'=>"Default token attribute to use for minimum delay between each reminders.",
            'help'=>"If this attribute exist : tested just before sending, then final delay is minimum between global and this attribute",
            'default'=>"",
        ),
161 162
        'cronTypes' => array(
            'type'=>'text',
163 164
            'label'=>"Cron moment type.",
            'help'=>"One moment by line, use only alphanumeric caracter, you can use <code>,</code> or <code>;</code> as separator.",
165 166 167 168 169 170 171 172
            'default'=>'',
        ),
        'cronTypeNone' => array(
            'type'=>'checkbox',
            'value'=>1,
            'htmlOption'=>array(
                'uncheckValue'=>0
            ),
173 174
            'label'=>"Survey without moment use empty moment or moment not set only.",
            'help'=>"If a survey don't have type: you can choose if it sended for each cron or only if no moment is set",
175 176
            'default'=>1,
        ),
177 178 179
    );
    /**
    * Add function to be used in cron event
Chenu Denis's avatar
Chenu Denis committed
180
    * @see parent::init()
181 182 183
    */
    public function init()
    {
Chenu Denis's avatar
Chenu Denis committed
184
        /* Action on cron */
185
        $this->subscribe('cron','sendMailByCron');
186
        /* Needed config */
187
        $this->subscribe('beforeActivate');
188

189 190
        /* Add the link in menu */
        $this->subscribe('beforeToolsMenuRender');
Chenu Denis's avatar
Chenu Denis committed
191
        /* The survey seeting */
192
        $this->subscribe('beforeSurveySettings');
193 194 195

        /* Update Yii config */
        $this->subscribe('afterPluginLoad');
196 197
    }

Chenu Denis's avatar
Chenu Denis committed
198 199 200 201
    /**
    * set actual url when activate
    * @see parent::saveSettings()
    */
202 203 204 205 206 207
    public function saveSettings($settings)
    {
        if(isset($settings['cronTypes']))
        {
            $cronTypes = preg_split('/\r\n|\r|\n|,|;/', $settings['cronTypes']);
            $cronTypes = array_map(
Chenu Denis's avatar
Chenu Denis committed
208 209
                function($cronType) { return preg_replace("/[^0-9a-zA-Z]/i", '', $cronType); },
                $cronTypes
210 211 212 213 214 215
            );
            $cronTypes = array_filter($cronTypes);
            $settings['cronTypes']=implode( "|",$cronTypes);
        }
        parent::saveSettings($settings);
    }
216 217
    /**
    * set actual url when activate
Chenu Denis's avatar
Chenu Denis committed
218
    * @see parent::beforeActivate()
219 220 221 222 223 224
    */
    public function beforeActivate()
    {
        $event = $this->getEvent();
        if(is_null($this->getSetting('hostInfo')))
        {
Chenu Denis's avatar
Chenu Denis committed
225
            if(Yii::app() instanceof CConsoleApplication) {
226 227 228 229 230 231 232 233 234 235 236 237 238
                $event->set('success', false);
                $event->set('message', 'This plugin need to be configurated before activate.');
                return;
            }
            $settings=array(
                'hostInfo'=>Yii::app()->request->getHostInfo(),
                'baseUrl'=>Yii::app()->request->getBaseUrl(),
                'scriptUrl'=>Yii::app()->request->getScriptUrl(),
            );
            $this->saveSettings($settings);
            $event->set('message', 'Default configuration for url is used.');
            App()->setFlashMessage('Default configuration for url is used.');
        }
239 240
    }

Chenu Denis's avatar
Chenu Denis committed
241 242 243
    /**
     * @see parent::beforeSurveySettings()
     */
244 245 246 247 248
    public function beforeSurveySettings()
    {
        $event = $this->event;
        // Must control if token table exist
        $iSurveyId=$event->get('survey');
249
        if($this->_surveyHasTokens($iSurveyId)) {
250 251 252 253 254
            $event->set("surveysettings.{$this->id}", array(
                'name' => get_class($this),
                'settings' => array(
                    'gotosettings'=>array(
                    'type'=>'link',
255
                    'label'=>$this->_translate('Mail by cron settings'),
256
                    'htmlOptions'=>array(
257
                        'title'=>$this->_translate('This open another page'),
258
                    ),
259
                    'help'=>$this->_translate('This open a new page remind to save your settings.'),
260
                    'text'=>$this->_translate('Edit email by cron settings'),
261 262
                    'class'=>'btn btn-link',
                    'link'=>Yii::app()->createUrl('admin/pluginhelper',array('sa' => 'sidebody','plugin' => get_class($this),'method' => 'actionSettings','surveyId' => $iSurveyId)),
263
                    ),
264
                )
265 266 267 268
            ));
        }
    }

Chenu Denis's avatar
Chenu Denis committed
269
    /**
270
     * The action in direct event
Chenu Denis's avatar
Chenu Denis committed
271 272
     * @return void
     */
273 274 275 276
    public function sendMailByCli() {
        if($this->event->get("target") != get_class()) {
            return;
        }
277
        $this->_LsCommandFix();
278
        $this->_setConfigs();
279
        $this->setArgs();
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        /* @todo replace by option (in json array ?) */
    }

    /**
     * The action in cron event
     * @return void
     */
    public function sendMailByCron() {
        if($this->get('enableInCron',null,null,1) ) {
            $this->_LsCommandFix();
            $this->_setConfigs();
            $this->setArgs();
            if(!$this->disable) {
                $this->sendTokenMessages();
            }
295
        }
296 297 298 299 300 301 302
    }
    /**
     * The action of sending token emails for all survey
     * @return void
     */
    public function sendTokenMessages()
    {
303
        $maxBatchSize=$this->getSetting('maxBatchSize',null,null,'');
304 305 306

        $oSurveys=Survey::model()->findAll(
            "active = 'Y' AND (startdate <= :now1 OR startdate IS NULL) AND (expires >= :now2 OR expires IS NULL)",
307 308 309 310 311
            array(
                ':now1' => self::_dateShifted(date("Y-m-d H:i:s")),
                ':now2' => self::_dateShifted(date("Y-m-d H:i:s"))
            )
        );
312
        // Unsure we need whole ... to be fixed
313 314 315 316
        Yii::import('application.helpers.common_helper', true);
        Yii::import('application.helpers.surveytranslator_helper', true);
        Yii::import('application.helpers.replacements_helper', true);
        Yii::import('application.helpers.expressions.em_manager_helper', true);
317
        // Fix the url @todo parse url and validate
318 319 320
        Yii::app()->request->hostInfo=$this->getSetting("hostInfo");
        Yii::app()->request->baseUrl=$this->getSetting("baseUrl");
        Yii::app()->request->scriptUrl=$this->getSetting("scriptUrl");
321 322 323 324 325
        if($oSurveys)
        {
            foreach ($oSurveys as $oSurvey)
            {
                $iSurvey=$oSurvey->sid;
326
                if($this->_surveyHasTokens($iSurvey))
327
                {
328
                    /* By maxEmail */
329 330 331 332 333 334
                    $maxEmail=$this->getSetting('maxEmail','survey',$iSurvey,"");
                    if($maxEmail===""){
                        $maxEmail=$this->getSetting('maxEmail',null,null,$this->settings['maxEmail']['default']);
                    }
                    if($maxEmail < 1){
                        $this->sendMailCronLog("sendMailByCron for {$iSurvey} deactivated",2);
335
                        continue;
336
                    }
337
                    /* By day of week */
338 339 340 341 342
                    $aDayOfWeekToSend=array();
                    $dayOfWeekToSend=$this->getSetting('dayOfWeekToSend','Survey', $iSurvey);
                    if(!empty($dayOfWeekToSend) && !empty(json_decode($dayOfWeekToSend))) {
                        $aDayOfWeekToSend=array_filter(json_decode($dayOfWeekToSend));
                    }
343
                    $todayNum=(string)self::_dateShifted(date("Y-m-d H:i:s"),"N");
344
                    if(!empty($aDayOfWeekToSend) && !in_array($todayNum,$aDayOfWeekToSend)){
Chenu Denis's avatar
Chenu Denis committed
345
                        $this->sendMailCronLog("sendMailByCron deactivated for {$iSurvey} for today",2);
346
                        continue;
347
                    }
348 349 350 351 352
                    /* By cron type */
                    $availCronTypes=$this->getSetting('cronTypes',null,null,"");
                    $availCronTypes=explode('|', $availCronTypes);
                    if(!empty($availCronTypes)){
                        $surveyCronTypes=$this->getSetting('cronTypes','Survey',$iSurvey,"");
353
                        if(!empty($surveyCronTypes) && !empty(json_decode($surveyCronTypes))){
354 355 356 357 358 359 360 361 362 363 364 365
                            $surveyCronTypes=json_decode($surveyCronTypes);
                        } else {
                            $surveyCronTypes=array();
                            if(!$this->getSetting('cronTypeNone',null,null,$this->settings['cronTypeNone']['default']) && $this->cronType){
                                $surveyCronTypes=array($this->cronType);
                            } else {
                                $surveyCronTypes=array();
                            }
                        }
                        $surveyCronTypes=array_intersect($surveyCronTypes,$availCronTypes);
                        if($this->cronType){
                            if(!in_array($this->cronType,$surveyCronTypes)){
Chenu Denis's avatar
Chenu Denis committed
366
                                $this->sendMailCronLog("sendMailByCron deactivated for {$iSurvey} for this cron type ({$this->cronType})",2);
367 368 369 370
                                continue;
                            }
                        } else {
                            if(!empty($surveyCronTypes)){
Chenu Denis's avatar
Chenu Denis committed
371
                                $this->sendMailCronLog("sendMailByCron deactivated for {$iSurvey} for no cron type",2);
372 373 374 375 376
                                continue;
                            }
                        }

                    }
Chenu Denis's avatar
Chenu Denis committed
377
                    $this->sendMailCronLog("Start sendMailByCron for {$iSurvey}",1);
378 379 380 381
                    if($maxBatchSize && $maxBatchSize<=$this->currentBatchSize){
                        $this->sendMailCronLog("sendMailByCron deactivated for {$iSurvey} due to batch size",1);
                        continue;
                    }
382

383 384 385
                    Yii::app()->setConfig('surveyID',$iSurvey);
                    // Fill some information for this
                    $this->currentSurveyBatchSize=0;
386
                    $this->setAttributeValue($iSurvey);
387
                    $this->sendEmails($iSurvey,'invite');
388 389
                    if($maxEmail < 2){
                        $this->sendMailCronLog("sendMailByCron reminder for {$iSurvey} deactivated",2);
390
                    } else if(!$maxBatchSize || $maxBatchSize>=$this->currentBatchSize){
391 392
                        if(!$this->getSetting('maxSurveyBatchSize','Survey', $iSurvey) || $this->getSetting('maxSurveyBatchSize','Survey', $iSurvey)>=$this->currentBatchSize){
                            $this->sendEmails($iSurvey,'remind');
393
                        }else{
394
                            $this->sendMailCronLog("sendMailByCron reminder deactivated for {$iSurvey} due to survey batch size",1);
395 396
                        }
                    }else{
397
                        $this->sendMailCronLog("sendMailByCron reminder deactivated for {$iSurvey} due to batch size",1);
398
                    }
399 400 401 402

                    $event = new PluginEvent('finishSendEmailForSurveyCron');
                    $event->set('survey_id', $iSurvey);
                    App()->getPluginManager()->dispatchEvent($event);
403 404 405 406 407
                }
            }
        }
    }

Chenu Denis's avatar
Chenu Denis committed
408 409 410 411 412 413
    /**
     * Return the date fixed by config (SQL format)
     * @param string $date in SQL format
     * @param string $dformat in SQL format
     * @return string
     */
414
    private static function _dateShifted($date, $dformat="Y-m-d H:i:s")
415 416 417 418
    {
        if(Yii::app()->getConfig("timeadjust",false)===false)
        {
            $oTimeAdjust=SettingGlobal::model()->find("stg_name=:stg_name",array(":stg_name"=>'timeadjust'));
419
            if($oTimeAdjust) {
420
                Yii::app()->setConfig("timeadjust",$oTimeAdjust->stg_value);
421
            } else {
422
                Yii::app()->setConfig("timeadjust",0);
423
            }
424 425 426 427
        }
        return date($dformat, strtotime(Yii::app()->getConfig("timeadjust"), strtotime($date)));
    }

Chenu Denis's avatar
Chenu Denis committed
428
    /**
429
     * Set whole LimeSurvey config (not needed in new LS version)
Chenu Denis's avatar
Chenu Denis committed
430 431
     * @return void
     */
432
    private function _setConfigs()
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
    {
        $aDefaultConfigs = require(Yii::app()->basePath. DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config-defaults.php');
        foreach($aDefaultConfigs as $sConfig=>$defaultConfig)
            Yii::app()->setConfig($sConfig,$defaultConfig);
        //~ $ls_config = require(Yii::app()->basePath. DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config-defaults.php');
        //~ $this->config = array_merge($this->config, $ls_config);
        // Fix rootdir .....
        if(!is_dir(Yii::app()->getConfig('usertemplaterootdir')))
        {
            $sRootDir=realpath(Yii::app()->basePath. DIRECTORY_SEPARATOR . "..") ;
            Yii::app()->setConfig('rootdir',$sRootDir);
            Yii::app()->setConfig('publicdir',$sRootDir);
            Yii::app()->setConfig('homedir',$sRootDir);
            Yii::app()->setConfig('tempdir',$sRootDir.DIRECTORY_SEPARATOR."tmp");
            Yii::app()->setConfig('imagedir',$sRootDir.DIRECTORY_SEPARATOR."images");
            Yii::app()->setConfig('uploaddir',$sRootDir.DIRECTORY_SEPARATOR."upload");
            Yii::app()->setConfig('standardtemplaterootdir',$sRootDir.DIRECTORY_SEPARATOR."templates");
            Yii::app()->setConfig('usertemplaterootdir',$sRootDir.DIRECTORY_SEPARATOR."upload".DIRECTORY_SEPARATOR."templates");
            Yii::app()->setConfig('styledir',$sRootDir.DIRECTORY_SEPARATOR."styledir");
        }
        if(file_exists(Yii::app()->basePath. DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php'))
        {
            $config = require(Yii::app()->basePath. DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php');
            if(is_array($config['config']) && !empty($config['config']))
            {
                foreach($config['config'] as $key=>$value)
                    Yii::app()->setConfig($key,$value);
            }
        }
        $oSettings=SettingGlobal::model()->findAll();
        if (count($oSettings) > 0)
        {
            foreach ($oSettings as $oSetting)
            {
                Yii::app()->setConfig($oSetting->getAttribute('stg_name'), $oSetting->getAttribute('stg_value'));
            }
        }
    }
Chenu Denis's avatar
Chenu Denis committed
471

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    /**
     * Dispatch event after email sent and final log
     * @param int[] $aCountMail array for email count
     * @param int $iSurvey
     * @param string $sType
     * @return void
     */
    private function afterSendEmail($aCountMail, $iSurvey, $sType)
    {
        $event = new PluginEvent('finishSendEmailsForSurveyTypeCron');
        $event->set('info', $aCountMail);
        $event->set('type', $sType);
        $event->set('survey_id', $iSurvey);
        App()->getPluginManager()->dispatchEvent($event);

        $this->sendMailCronFinalLog($aCountMail);
    }

Chenu Denis's avatar
Chenu Denis committed
490
    /**
Chenu Denis's avatar
Chenu Denis committed
491
     * Send emails for a survey and a type
Chenu Denis's avatar
Chenu Denis committed
492 493 494 495
     * @param int $iSurvey
     * @param string $sType
     * @return void
     */
496 497 498
    private function sendEmails($iSurvey,$sType='invite')
    {
        // For the log
Chenu Denis's avatar
Chenu Denis committed
499 500 501 502 503 504
        $aCountMail=array(
            'total'=>0,
            'sent'=>0,
            'invalid'=>0,
            'error'=>0,
            'started'=>0,
505
            'notstarted'=>0,
506
            'attributedisabled'=>0,
Chenu Denis's avatar
Chenu Denis committed
507
        );
508
        /* Get information */
509 510 511 512 513
        $bHtml = (getEmailFormat($iSurvey) == 'html');
        $oSurvey=Survey::model()->findByPk($iSurvey);
        $aSurveyLangs = Survey::model()->findByPk($iSurvey)->additionalLanguages;
        $sBaseLanguage = Survey::model()->findByPk($iSurvey)->language;
        array_unshift($aSurveyLangs, $sBaseLanguage);
514
        foreach($aSurveyLangs as $sSurveyLanguage) {
515 516
            $aSurveys[$sSurveyLanguage] = getSurveyInfo($iSurvey, $sSurveyLanguage);
        }
517
        foreach ($aSurveyLangs as $language) {
518 519 520 521 522
            $sSubject[$language]=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aSurveys[$language]["surveyls_email_{$sType}_subj"]);
            $sMessage[$language]=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aSurveys[$language]["surveyls_email_{$sType}"]);
            if ($bHtml)
                $sMessage[$language] = html_entity_decode($sMessage[$language], ENT_QUOTES, Yii::app()->getConfig("emailcharset"));
        }
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
        /* Get the attchements */
        switch($sType) {
            case 'invite':
                $attachementTemplate = 'invitation';
                break;
            case 'remind':
                $attachementTemplate = 'reminder';
                break;
            default:
                $attachementTemplate = null;
        }
        $aAttachments = array();
        foreach ($aSurveyLangs as $language) {
            $aLangAttachments = array();
            if (isset($aSurveys[$sSurveyLanguage]['attachments'])) {
                $aCurrentAttachments = unserialize($aSurveys[$sSurveyLanguage]['attachments']);
                //$aLangAttachments = array();
                if(isset($aCurrentAttachments[$attachementTemplate]) && is_array($aCurrentAttachments[$attachementTemplate])) {
                    $aLangAttachments[$language] = $aCurrentAttachments[$attachementTemplate];
                }
            }
        }

546 547 548 549
        $dToday=dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
        $dYesterday=dateShift(date("Y-m-d H:i:s", time() - 86400), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
        $dTomorrow=dateShift(date("Y-m-d H:i:s", time() + 86400), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
        // Test si survey actif et avec bonne date $aSurveys[$sBaseLanguage]
550

551 552 553 554
        $sFrom = "{$aSurveys[$sBaseLanguage]['admin']} <{$aSurveys[$sBaseLanguage]['adminemail']}>";
        $sBounce=getBounceEmail($iSurvey);
        $dtToday=strtotime($dToday);
        $dFrom=$dToday;
555
        $maxReminder=$this->getSetting('maxEmail','survey',$iSurvey,"");
556
        if($maxReminder==="") {
557
            $maxReminder=$this->getSetting('maxEmail',null,null,$this->settings['maxEmail']['default']);
558
        }
559
        $maxReminder=intval($maxReminder);
560
        $maxReminder--;
561
        if($sType=='invite' && $maxReminder < 0) {
562
            $this->sendMailCronLog("Survey {$iSurvey}, {$sType} deactivated",2);
563 564
            return;
        }
565
        if($sType=='remind' && $maxReminder < 1) {
566
            $this->sendMailCronLog("Survey {$iSurvey}, {$sType} deactivated",2);
567 568
            return;
        }
569
        $delayInvitation=$this->getSetting('delayInvitation','survey',$iSurvey,"");
570
        if($delayInvitation=="") {
571
            $delayInvitation=$this->getSetting('delayInvitation',null,null,$this->settings['delayInvitation']['default']);
572
        }
573 574
        $delayInvitation=intval($delayInvitation);
        $dayDelayReminder=$this->getSetting('delayReminder','survey',$iSurvey,"");
575
        if($dayDelayReminder=="") {
576
            $dayDelayReminder=$this->getSetting('delayReminder',null,null,$this->settings['delayReminder']['default']);
577
        }
578
        $dayDelayReminder=intval($dayDelayReminder);
579
        if($sType=='remind' && ($delayInvitation < 1|| $dayDelayReminder < 1)) {
Chenu Denis's avatar
Chenu Denis committed
580
            $this->sendMailCronLog("Survey {$iSurvey}, {$sType} deactivated due to bad value in delays",1);
581 582
            return;
        }
583
        $isNotAnonymous=$oSurvey->anonymized!="Y";
584 585 586
        $reminderOnlyTo=$this->getSetting('reminderOnlyTo', 'Survey', $iSurvey,'');
        if($reminderOnlyTo && $isNotAnonymous){
            $controlResponse=$reminderOnlyTo;
587
        }else{
588
            $controlResponse='';
589 590 591
        }
        //~ if($sType=='invite')
            //~ $dFrom=date("Y-m-d H:i",strtotime("-".intval($this->config['inviteafter'])." days",$dtToday));// valid is 3 day before and up
592
        if($sType=='remind') {
593 594
            $dAfterSentRemind=date("Y-m-d H:i",strtotime("-".intval($dayDelayReminder)." days",$dtToday));// sent is X day before and up
            $dAfterSent=date("Y-m-d H:i",strtotime("-".intval($delayInvitation)." days",$dtToday));// sent is X day before and up
595 596
        }
        $dTomorrow=dateShift(date("Y-m-d H:i", time() + 86400 ), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));// Tomorrow for validuntil
597
        $this->sendMailCronLog("Survey {$iSurvey}, {$sType} Valid from {$dFrom} And Valid until {$dTomorrow} (or NULL)",3);
598 599
        $oCriteria = new CDbCriteria;
        $oCriteria->select = "tid";
600
        /* Always needed condition */
601
        $oCriteria->addCondition("emailstatus = 'OK'");
602
        $oCriteria->addCondition("email != '' and email IS NOT NULL");
603 604
        $oCriteria->addCondition("token != ''");
        $oCriteria->addCondition("(completed = 'N' OR completed = '' OR completed  IS NULL)");
605
        $oCriteria->addCondition("usesleft>0 OR usesleft IS NULL");
606 607
        $oCriteria->addCondition("(validfrom < :validfrom OR validfrom IS NULL)");
        $oCriteria->addCondition("(validuntil > :validuntil OR validuntil IS NULL)");
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
        $aParams=array(
            ':validfrom'=>$dFrom,
            ':validuntil'=>$dTomorrow,
        );
        switch ($sType) {
            case 'invite':
                /* Not sent condition */
                $oCriteria->addCondition("(sent = 'N' OR sent = '' OR sent IS NULL)");
                break;
            case 'remind':
                /* sent condition */
                $oCriteria->addCondition("(sent != 'N' AND sent != '' AND sent IS NOT NULL)");
                /* Delay by settings condition */
                $oCriteria->addCondition("(
                    remindersent < :remindersent AND (remindercount != '' AND remindercount IS NOT NULL AND remindercount > 0)
                ) OR (
                    sent < :sent AND (remindercount = '' OR remindercount IS NULL OR remindercount < 1)
                )");
                /* Max by settings condition */
                $oCriteria->addCondition("remindercount < :remindercount  OR remindercount = '' OR remindercount IS NULL");
                $aParams=array_merge($aParams,array(
                    ':remindersent'=>strval($dAfterSentRemind),
                    ':sent'=>strval($dAfterSent),
                    ':remindercount'=>$maxReminder,
                ));
                break;
            default:
                /* Break for invalid */
                throw new Exception("Invalid email type {$sType} in sendMailCron.");
                return 1;
638
        }
639 640
        $oCriteria->params=$aParams;
        # Send email
641
        // Find all token
642
        $oTokens=Token::model($iSurvey)->findAll($oCriteria);
Chenu Denis's avatar
Chenu Denis committed
643
        $aCountMail['total']=count($oTokens);
Chenu Denis's avatar
Chenu Denis committed
644
        $this->sendMailCronLog("Start sending $sType",2);
645
        foreach ($oTokens as $iToken) {
646
            /* Test actual sended */
647
            if($this->stopSendMailAction($aCountMail,$iSurvey,$sType)){
648
                $this->afterSendEmail($aCountMail, $iSurvey, $sType);
649 650
                return;
            }
651
            $oToken=Token::model($iSurvey)->findByPk($iToken->tid);
652 653 654
            /* Find if need to already started or not */
            if($controlResponse){
                $oResponse=SurveyDynamic::model($iSurvey)->find("token=:token",array(":token"=>$oToken->token));
655 656 657 658 659 660 661
                if(!$oResponse && $controlResponse=='notstarted'){
                    $this->sendMailCronLog("Not started survey : {$oToken->email} ({$oToken->tid}) for {$iSurvey}",3);
                    $aCountMail['notstarted']++;
                    continue;
                }
                if($oResponse && $controlResponse=='started'){
                    $this->sendMailCronLog("Already started survey : {$oToken->email} ({$oToken->tid}) for {$iSurvey}",3);
Chenu Denis's avatar
Chenu Denis committed
662
                    $aCountMail['started']++;
663 664
                    continue;
                }
665 666 667 668
            }
            if(!$this->allowSendMailByAttribute($oToken,$sType,$iSurvey)) {
                $aCountMail['attributedisabled']++;
                continue;
669 670 671 672 673 674 675 676 677 678 679 680 681 682
            }
            if ($this->getSetting('validateEmail',null,null,$this->settings['validateEmail']['default']) && !filter_var(trim($oToken->email), FILTER_VALIDATE_EMAIL)) {
                $this->sendMailCronLog("invalid email : '{$oToken->email}' ({$oToken->tid}) for {$iSurvey}",2);
                $aCountMail['invalid']++;
                $oCommand=Yii::app()->db->createCommand();
                $oCommand->update(
                    "{{tokens_{$iSurvey}}}",
                    array(
                        'emailstatus'=>'invalid',
                    ),
                    "tid=:tid",
                    array(":tid"=>$iToken->tid)
                );
                continue;
683
            }
684
            $this->sendMailCronLog("Send : {$oToken->email} ({$oToken->tid}) for {$iSurvey}",3);
685
            $sLanguage = trim($oToken->language);
686
            if (!in_array($sLanguage,$aSurveyLangs)) {
687 688
                $sLanguage = $sBaseLanguage;
            }
689

690 691 692 693 694 695 696 697 698 699
            $sToken=$oToken->token;
            /* Array of email adresses */
            $aTo=array();
            $aEmailaddresses = preg_split( "/(,|;)/", $oToken->email );
            foreach ($aEmailaddresses as $sEmailaddress)
            {
                $aTo[] = "{$oToken->firstname} {$oToken->lastname} <{$sEmailaddress}>";
            }
            /* Construct the mail content */
            $aFieldsArray=array();
700

701 702 703 704 705
            $aFieldsArray["{SURVEYNAME}"]=$aSurveys[$sLanguage]['surveyls_title'];
            $aFieldsArray["{SURVEYDESCRIPTION}"]=$aSurveys[$sLanguage]['surveyls_description'];
            $aFieldsArray["{SURVEYWELCOMETEXT}"]=$aSurveys[$sLanguage]['surveyls_welcometext'];
            $aFieldsArray["{ADMINNAME}"]=$aSurveys[$sLanguage]['admin'];
            $aFieldsArray["{ADMINEMAIL}"]=$aSurveys[$sLanguage]['adminemail'];
706 707
	    $aFieldsArray["{EXPIRY}"]=$aSurveys[$sLanguage]['expiry'];

708 709 710 711 712 713 714 715
            foreach ($oToken->attributes as $attribute=>$value)
            {
                $aFieldsArray['{' . strtoupper($attribute) . '}'] =$value;
            }
            // Url Links
            $aUrlsArray["OPTOUTURL"] = App()->createAbsoluteUrl("/optout/tokens",array('langcode'=>$sLanguage,'surveyid'=>$iSurvey,'token'=>$sToken));
            $aUrlsArray["OPTINURL"] = App()->createAbsoluteUrl("/optin/tokens",array('langcode'=>$sLanguage,'surveyid'=>$iSurvey,'token'=>$sToken));
            $aUrlsArray["SURVEYURL"] = App()->createAbsoluteUrl("/survey/index",array('sid'=>$iSurvey,'token'=>$sToken,'lang'=>$sLanguage));
716 717
            foreach($aUrlsArray as $key=>$url) {
                if ($bHtml) {
718
                    $aFieldsArray["{{$key}}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>';
719
                } else {
720
                    $aFieldsArray["{{$key}}"] = $url;
721
                }
722
            }
723

724 725 726 727 728 729 730 731 732 733 734 735 736
            $aCustomHeaders = array(
                '1' => "X-surveyid: " . $iSurvey,
                '2' => "X-tokenid: " . $sToken
            );
            $subject = Replacefields($sSubject[$sLanguage], $aFieldsArray);
            $message = Replacefields($sMessage[$sLanguage], $aFieldsArray);
            foreach($aUrlsArray as $key=>$url)
            {
                $message = str_replace("@@{$key}@@", $url, $message);
            }
            if($this->simulate){
                $success=true;
            }else{
737 738 739 740 741 742 743 744 745 746
                /* Evaluate attachement */
                $aRelevantAttachments = array();
                if(!empty($aLangAttachments[$sLanguage])) {
                    LimeExpressionManager::singleton()->loadTokenInformation($iSurvey, $sToken);
                    foreach ($aLangAttachments[$sLanguage] as $aAttachment) {
                        if (LimeExpressionManager::singleton()->ProcessRelevance($aAttachment['relevance'])) {
                            $aRelevantAttachments[] = $aAttachment['url'];
                        }
                    }
                }
747

748 749 750 751 752 753 754 755 756 757 758 759
                /* Add the event 'beforeSendEmail */
                $beforeTokenEmailEvent = new PluginEvent('beforeTokenEmail');
                $beforeTokenEmailEvent->set('survey', $iSurvey);
                $beforeTokenEmailEvent->set('type', $sType);
                $beforeTokenEmailEvent->set('model', ($sType=='remind'?'reminder':'invitation'));
                $beforeTokenEmailEvent->set('subject', $subject);
                $beforeTokenEmailEvent->set('to',$aTo);
                $beforeTokenEmailEvent->set('body', $message);
                $beforeTokenEmailEvent->set('from', $sFrom);
                $beforeTokenEmailEvent->set('bounce', $sBounce);
                $beforeTokenEmailEvent->set('token', $oToken->attributes);
                App()->getPluginManager()->dispatchEvent($beforeTokenEmailEvent);
760 761
                $subject = $beforeTokenEmailEvent->get('subject');
                $message = $beforeTokenEmailEvent->get('body');
762 763 764 765 766
                $aTo = $beforeTokenEmailEvent->get('to');
                $sFrom = $beforeTokenEmailEvent->get('from');
                $sBounce = $beforeTokenEmailEvent->get('bounce');
                /* send the email */
                global $maildebug;
767
                if ($beforeTokenEmailEvent->get('send', true) == false) {
768 769
                    $maildebug = $beforeTokenEmailEvent->get('error', $maildebug);
                    $success = $beforeTokenEmailEvent->get('error') == null;
770 771
                } else {
                    $success = SendEmailMessage($message, $subject, $aTo, $sFrom, Yii::app()->getConfig("sitename"), $bHtml, $sBounce, $aRelevantAttachments, $aCustomHeaders);
Chenu Denis's avatar
Chenu Denis committed
772
                }
773 774 775 776 777 778 779 780
            }
            /* action if email is sent */
            if ($success){
                $aCountMail['sent']++;
                $this->currentBatchSize++;
                $this->currentSurveyBatchSize++;
                if(!$this->simulate){
                    if($sType=='invite'){
781
                        $oToken->sent=dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
782
                        $txtLog="sent set to ".$oToken->sent;
783
                    }
784
                    if($sType=='remind'){
785 786
                        $oToken->remindersent=dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
                        $oToken->remindercount++;
787 788 789 790 791 792
                        $txtLog="remindersent set to ".$oToken->remindersent." count:".$oToken->remindercount;
                    }
                    if($oToken->save()) {
                        $this->sendMailCronLog("Email {$oToken->email} : $txtLog",3);
                    } else {
                        $error=CVarDumper::dumpAsString($oToken->getErrors(), 3, false);
Chenu Denis's avatar
Chenu Denis committed
793
                        $this->sendMailCronLog("Email {$oToken->email} error: $error",1);
Chenu Denis's avatar
Chenu Denis committed
794
                    }
795
                }
796 797
            } else {
                if($maildebug) {
Chenu Denis's avatar
Chenu Denis committed
798
                    $this->sendMailCronLog("Unknow error when send email to {$oToken->email} ({$iSurvey}) : ".$maildebug,0);
799
                } else {
Chenu Denis's avatar
Chenu Denis committed
800
                    $this->sendMailCronLog("Unknow error when send email to {$oToken->email} ({$iSurvey})",0);
801
                }
802
                $aCountMail['error']++;
803 804
            }
        }
805 806

        $this->afterSendEmail($aCountMail, $iSurvey, $sType);
807
    }
808

809
    /**
Chenu Denis's avatar
Chenu Denis committed
810 811 812 813
    * log an event
    * @param string $sLog
    * @param int $state
    * retrun @void
814
    */
Chenu Denis's avatar
Chenu Denis committed
815
    private function sendMailCronLog($sLog,$state=0){
816 817
        // Play with DEBUG : ERROR/LOG/DEBUG
        $sNow=date(DATE_ATOM);
Chenu Denis's avatar
Chenu Denis committed
818
        switch ($state){
819 820 821 822 823 824 825 826
            case 0:
                $sLevel='error';
                $sLogLog="[ERROR] $sLog";
                break;
            case 1:
                $sLevel='info';
                $sLogLog="[INFO] $sLog";
                break;
827 828 829 830
            case 2:
                $sLevel='info';
                $sLogLog="[DEBUG] $sLog";
                break;
831 832
            default:
                $sLevel='trace';
833
                $sLogLog="[TRACE] $sLog";
834 835 836
                break;
        }
        Yii::log($sLog, $sLevel,'application.plugins.sendMailCron');
Chenu Denis's avatar
Chenu Denis committed
837
        if($state <= $this->debug || $state==0)
838
        {
839 840 841 842 843
            echo "[{$sNow}] {$sLogLog}\n";
        }
    }

    /**
Chenu Denis's avatar
Chenu Denis committed
844 845 846 847 848 849 850 851
     * LimeSurvey 2.06 have issue with getPluginSettings->getPluginSettings (autoloader is broken) with command
     * Then use own function
     * @param string $sSetting
     * @param string $sObject
     * @param string $sObjectId
     * @param string $default
     * @return string
     */
852 853 854 855 856 857 858 859 860 861 862 863 864
    private function getSetting($sSetting,$sObject=null,$sObjectId=null,$default=null)
    {
        if($sObject && $sObjectId){
            $oSetting=PluginSetting::model()->find(
                "plugin_id=:plugin_id AND model=:model AND model_id=:model_id AND ".Yii::app()->db->quoteColumnName("key")."=:ssetting",
                array(
                    ":plugin_id"=>$this->id,
                    ":model"=>$sObject,
                    ":model_id"=>$sObjectId,
                    ":ssetting"=>$sSetting
                )
            );
        }else{
865 866
            $oSetting=PluginSetting::model()->find("plugin_id=:plugin_id AND model IS NULL AND ".Yii::app()->db->quoteColumnName("key")."=:ssetting",array(":plugin_id"=>$this->id,":ssetting"=>$sSetting));
        }
867
        if($oSetting && !is_null($oSetting->value))
868
        {
869
            return trim(stripslashes($oSetting->value),'"');
870
        }
871 872 873
        else
            return $default;
    }
Chenu Denis's avatar
Chenu Denis committed
874 875 876
    /**
     * @see parent:getPluginSettings
     */
877 878 879 880 881 882 883 884
    public function getPluginSettings($getValues=true)
    {
        if(!Yii::app() instanceof CConsoleApplication)
        {
            $this->settings['hostInfo']['default']= Yii::app()->request->getHostInfo();
            $this->settings['baseUrl']['default']= Yii::app()->request->getBaseUrl();
            $this->settings['scriptUrl']['default']= Yii::app()->request->getScriptUrl();
        }
885 886 887 888 889 890 891
        $pluginSettings= parent::getPluginSettings($getValues);
        if($getValues){
            if($pluginSettings['cronTypes']){
                $pluginSettings['cronTypes']['current']=implode("\n",explode("|",$pluginSettings['cronTypes']['current']));
            }
        }
        return $pluginSettings;
892
    }
893

894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
    /**
     * Set args by argument parameters, can not use named options (broke command console, then use anonymous with fixed string)
     * @use $_SERVER
     * @return void
     */
    private function setArgs()
    {
        $args=isset($_SERVER['argv']) ? $_SERVER['argv']:array();
        foreach($args as $arg){
            if(substr($arg, 0, strlen("sendMailCronDebug="))=="sendMailCronDebug="){
                $this->debug=intval(substr($arg,strlen("sendMailCronDebug=")));
            }
            if(substr($arg, 0, strlen("sendMailCronSimulate="))=="sendMailCronSimulate="){
                $this->simulate=boolval(substr($arg,strlen("sendMailCronSimulate=")));
            }
909 910 911
            if(substr($arg, 0, strlen("sendMailCronDisable="))=="sendMailCronDisable="){
                $this->disable=boolval(substr($arg,strlen("sendMailCronDisable=")));
            }
912 913 914 915 916 917

            if(substr($arg, 0, strlen("sendMailCronType="))=="sendMailCronType="){
                $cronType=trim(substr($arg,strlen("sendMailCronType=")));
                $availCronTypes=$this->getSetting('cronTypes',null,null,"");
                $availCronTypes=explode('|', $availCronTypes);
                if($cronType && !in_array($cronType,$availCronTypes)){
Chenu Denis's avatar
Chenu Denis committed
918
                    $this->sendMailCronLog("invalid cronType : $cronType, plugin is disable",1);
919 920 921 922 923
                    $this->disable=true;
                } else {
                    $this->cronType=$cronType;
                }
            }
924 925
        }
    }
926

Chenu Denis's avatar
Chenu Denis committed
927
    /**
928
     * Validate a send action : dis we must stop action
Chenu Denis's avatar
Chenu Denis committed
929 930 931 932
     * @param int[] $aCountMail array for email count
     * @param int $iSurvey survey id
     * @param string $sType
     * @return boolean
Chenu Denis's avatar
Chenu Denis committed
933 934 935 936 937
     *
     */
    private function stopSendMailAction($aCountMail,$iSurvey,$sType)
    {
        $maxThisType=$this->getSetting('maxSurveyBatchSize_'.$sType,'survey',$iSurvey,"");
938
        if( $maxThisType!=='' && $aCountMail['sent'] >= $maxThisType){
Chenu Denis's avatar
Chenu Denis committed
939 940
            $stillToSend=$aCountMail['total']*2-array_sum($aCountMail);
            $this->sendMailCronLog("Survey {$iSurvey}, {$sType} survey batch size achieved. {$stillToSend} email to send at next batch.",1);
941
            $this->sendMailCronFinalLog($aCountMail);
Chenu Denis's avatar
Chenu Denis committed
942 943 944 945 946 947 948 949 950
            return true;
        }

        if($this->getSetting('maxBatchSize') && $this->getSetting('maxBatchSize') <= $this->currentBatchSize){
            $stillToSend=$aCountMail['total']*2-array_sum($aCountMail);
            $this->sendMailCronLog("Batch size achieved for {$iSurvey} during {$sType}. {$stillToSend} email to send at next batch.",1);
            $this->sendMailCronFinalLog($aCountMail);
            return true;
        }
951

Chenu Denis's avatar
Chenu Denis committed
952 953 954 955 956 957
        if($this->getSetting('maxSurveyBatchSize','Survey', $iSurvey) && $this->getSetting('maxSurveyBatchSize','Survey', $iSurvey) <= $this->currentSurveyBatchSize){
            $stillToSend=$aCountMail['total']*2-array_sum($aCountMail);
            $this->sendMailCronLog("Batch survey size achieved for {$iSurvey} during {$sType}. {$stillToSend} email to send at next batch.",1);
            $this->sendMailCronFinalLog($aCountMail);
            return true;
        }
Chenu Denis's avatar
Chenu Denis committed
958
        return false;
Chenu Denis's avatar
Chenu Denis committed
959 960
    }

961 962 963 964 965 966 967 968 969 970 971 972 973
    /**
     * Get the attribute for testing
     * @param integer $surveyId
     * @return array
     *
     */
    public function getAttributesList($surveyId) {
        $oSurvey=Survey::model()->findByPk($surveyId);
        $aAvailableAttribute=array();
        $aTokensAttribute=$oSurvey->getTokenAttributes();
        foreach($aTokensAttribute as $key=>$aTokenAttribute) {
            $aAvailableAttribute[$key]=empty($aTokenAttribute['description']) ? $key : $aTokenAttribute['description'];
        }
974 975 976 977 978
        if($this->_surveyHasTokens($surveyId)) {
            $allAttributes=TokenDynamic::model($surveyId)->getCustom_attributes();
            foreach($allAttributes as $key=>$value) {
                if(!array_key_exists($key,$aAvailableAttribute)) {
                    $aAvailableAttribute[$key] = $key;
979 980 981 982 983
                }
            }
        }
        return $aAvailableAttribute;
    }
984

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    /**
     * Fill value for attribute token test
     * @param \Token token to be tested
     * @param string $sType
     * @return void
     *
     */
    public function setAttributeValue($surveyId) {
        $allAttributes=TokenDynamic::model($surveyId)->getCustom_attributes();

        $this->surveyMaxEmailAttributes = null;
        $attributes=$this->get('maxEmailAttribute', 'Survey', $surveyId,null);
        if(empty($attributes)) {
            if(!empty($this->get('maxEmailAttribute'))) {
                $attributes="attribute_".$this->get('maxEmailAttribute');
            }
        }
        if(!empty($attributes) && $attributes!="none" && array_key_exists($attributes,$allAttributes)) {
            $this->surveyMaxEmailAttributes = $attributes;
        }

        $this->surveyDelayInvitationAttribute = null;
        $attributes=$this->get('delayInvitationAttribute', 'Survey', $surveyId,null);
        if(empty($attributes)) {
            if(!empty($this->get('delayInvitationAttribute'))) {
                $attributes="attribute_".$this->get('delayInvitationAttribute');
            }
        }
        if(!empty($attributes) && $attributes!="none" && array_key_exists($attributes,$allAttributes)) {
            $this->surveyDelayInvitationAttribute = $attributes;
        }

        $this->surveyDelayReminderAttribute = null;
        $attributes=$this->get('delayReminderAttribute', 'Survey', $surveyId,null);
        if(empty($attributes)) {
            if(!empty($this->get('delayReminderAttribute'))) {
                $attributes="attribute_".$this->get('delayReminderAttribute');
            }
        }
        if(!empty($attributes) && $attributes!="none" && array_key_exists($attributes,$allAttributes)) {
            $this->surveyDelayReminderAttribute = $attributes;
        }
    }
1028

1029 1030 1031 1032
    /**
     * Test a token attributes for disable sending email
     * @param \Token token to be tested
     * @param string $sType
1033
     * @return boolean true if disable send mail
1034 1035 1036 1037 1038 1039 1040 1041
     */
    public function allowSendMailByAttribute($oToken,$sType='invite',$iSurvey)
    {
        $sended=$oToken->remindercount + 1;
        if($this->surveyMaxEmailAttributes) {
            $attribute=$this->surveyMaxEmailAttributes;
            $value = trim($oToken->$attribute);
            if($value && !ctype_digit($value)) {
Chenu Denis's avatar
Chenu Denis committed
1042
                $this->sendMailCronLog("Max email by attribute {$attribute} (disabled): {$oToken->email} ({$oToken->$attribute}) for {$iSurvey}",3);
1043 1044
                return false;
            }
1045 1046
            if(strval(intval($value))==strval($value)) {
                if(intval($value) <= $sended ) {
Chenu Denis's avatar
Chenu Denis committed
1047
                    $this->sendMailCronLog("Max email by attribute {$attribute} (done): {$oToken->email} ({$oToken->$attribute}) for {$iSurvey}",3);
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
                    return false;
                }
            }
        }
        if($sType=='invite') {
            return true;
        }
        $dateToday=dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig("timeadjust"));
        $lastSend=$oToken->sent;
        if($oToken->remindersent && $oToken->remindersent!="N") {
            $lastSend=$oToken->remindersent;
        }
        $lastSend = new DateTime($lastSend);
        $dateToday = new DateTime($dateToday);
        $interval = $lastSend->diff($dateToday);
        $dayDiff= $interval->days;
        if($sended == 1 && $this->surveyDelayInvitationAttribute) {
            $attribute=$this->surveyDelayInvitationAttribute;
            $value = trim($oToken->$attribute);
            if($value && !ctype_digit($value)) {
Chenu Denis's avatar
Chenu Denis committed
1068
                $this->sendMailCronLog("Delay after invitation by attribute {$attribute} (disabled): {$oToken->email} ({$oToken->$attribute}) for {$iSurvey}",3);
1069 1070
                return false;
            }
1071
            if(strval(intval($value))==strval($value)) {
1072 1073 1074
                $value=intval($value);
                if($value > $dayDiff ) {
                    $waiting= $value - $dayDiff;
Chenu Denis's avatar
Chenu Denis committed
1075
                    $this->sendMailCronLog("Delay after invitation by attribute {$attribute} (wait $waiting day(s)): {$oToken->email} ({$oToken->$attribute}) for {$iSurvey}",3);
1076 1077 1078 1079 1080 1081 1082 1083
                    return false;
                }
            }
        }
        if($sended > 1 && $this->surveyDelayReminderAttribute) {
            $attribute=$this->surveyDelayReminderAttribute;
            $value = trim($oToken->$attribute);
            if($value && !ctype_digit($value)) {
Chenu Denis's avatar
Chenu Denis committed
1084
                $this->sendMailCronLog("Delay between reminders by attribute {$attribute} (disabled): {$oToken->email} ({$oToken->$attribute}) for {$iSurvey}",3);
1085 1086
                return false;
            }
1087
            if(strval(intval($value))==strval($value)) {
1088 1089 1090
                $value=intval($value);
                if($value > $dayDiff ) {
                    $waiting= $value - $dayDiff;
Chenu Denis's avatar
Chenu Denis committed
1091
                    $this->sendMailCronLog("Delay between reminders by attribute {$attribute} (wait $waiting day(s)): {$oToken->email} ({$oToken->$attribute}) for {$iSurvey}",3);
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * get diff in days$
     * @param string date YYYY-MM-DD Format for example
     * @param string date YYYY-MM-DD Format for example
     * @param string format
     * @link http://php.net/manual/en/function.date-diff.php#115065
     * @return integer
     */
    private function _getDateDiffDay($dateStart,$dateEnd , $differenceFormat = '%a' ) {
        $dateStart = date_create($dateStart);
        $dateEnd = date_create($dateEnd);
        $interval = date_diff($dateStart, $dateEnd);
        return $interval->format($differenceFormat);
    }
1113

Chenu Denis's avatar
Chenu Denis committed
1114 1115
    /**
     * Ending and return information according to sended after a send session
Chenu Denis's avatar
Chenu Denis committed
1116 1117
     * @param int[] $aCountMail array for email count
     * @return @void
Chenu Denis's avatar
Chenu Denis committed
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
     */
    private function sendMailCronFinalLog($aCountMail)
    {
        if((array_sum($aCountMail)-$aCountMail['total'])==0){
            $this->sendMailCronLog("No message to sent",1);
        }else{
            if($aCountMail['sent']){
                $this->sendMailCronLog("{$aCountMail['sent']} messages sent",1);
            }
            if($aCountMail['invalid']){
Chenu Denis's avatar
Chenu Denis committed
1128
                $this->sendMailCronLog("{$aCountMail['invalid']} invalid email address",1);
Chenu Denis's avatar
Chenu Denis committed
1129 1130
            }
            if($aCountMail['started']){
Chenu Denis's avatar
Chenu Denis committed
1131
                $this->sendMailCronLog("{$aCountMail['started']} already started survey",1);
1132 1133
            }
            if($aCountMail['notstarted']){
Chenu Denis's avatar
Chenu Denis committed
1134
                $this->sendMailCronLog("{$aCountMail['started']} not started survey",1);
Chenu Denis's avatar
Chenu Denis committed
1135
            }
1136
            if($aCountMail['attributedisabled']){
Chenu Denis's avatar
Chenu Denis committed
1137
                $this->sendMailCronLog("{$aCountMail['attributedisabled']} disable by attribute",1);
1138
            }
Chenu Denis's avatar
Chenu Denis committed
1139
            if($aCountMail['error']){
Chenu Denis's avatar
Chenu Denis committed
1140
                $this->sendMailCronLog("{$aCountMail['error']} messages with error",1);
Chenu Denis's avatar
Chenu Denis committed
1141 1142 1143
            }
        }
    }
Chenu Denis's avatar
Chenu Denis committed
1144

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
    /** Menu and settings part */
    /**
     * see beforeToolsMenuRender event
     *
     * @return void
     */
    public function beforeToolsMenuRender()
    {
        $event = $this->getEvent();
        $surveyId = $event->get('surveyId');
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
        $aMenuItem = array(
            'label' => $this->_translate('Mail cron'),
            'iconClass' => 'fa fa-envelope-square',
            'href' => Yii::app()->createUrl(
                'admin/pluginhelper',
                array(
                    'sa' => 'sidebody',
                    'plugin' => get_class($this),
                    'method' => 'actionSettings',
                    'surveyId' => $surveyId
                )
            ),
1167
        );
1168 1169 1170 1171 1172
        if (class_exists("\LimeSurvey\Menu\MenuItem")) {
            $menuItem = new \LimeSurvey\Menu\MenuItem($aMenuItem);
        } else {
            $menuItem = new \ls\menu\MenuItem($aMenuItem);
        }
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
        $event->append('menuItems', array($menuItem));
    }

    /**
     * Main function
     * @param int $surveyId Survey id
     *
     * @return string
     */
    public function actionSettings($surveyId)
    {
        $oSurvey=Survey::model()->findByPk($surveyId);
        if(!$oSurvey) {
            throw new CHttpException(404,$this->translate("This survey does not seem to exist."));
        }
        if(!Permission::model()->hasSurveyPermission($surveyId,'surveysettings','update')){
            throw new CHttpException(401);
        }
        if(App()->getRequest()->getPost('save'.get_class($this))) {
            $this->set('maxEmail', App()->getRequest()->getPost('maxEmail'), 'Survey', $surveyId);
            $this->set('delayInvitation', App()->getRequest()->getPost('delayInvitation'), 'Survey', $surveyId);
            $this->set('delayReminder', App()->getRequest()->getPost('delayReminder'), 'Survey', $surveyId);
            $this->set('maxSurveyBatchSize', App()->getRequest()->getPost('maxSurveyBatchSize'), 'Survey', $surveyId);
            $this->set('maxSurveyBatchSize_invite', App()->getRequest()->getPost('maxSurveyBatchSize_invite'), 'Survey', $surveyId);
            $this->set('maxSurveyBatchSize_remind', App()->getRequest()->getPost('maxSurveyBatchSize_remind'), 'Survey', $surveyId);
            $this->set('dayOfWeekToSend', App()->getRequest()->getPost('dayOfWeekToSend'), 'Survey', $surveyId);
            $this->set('cronTypes', App()->getRequest()->getPost('cronTypes'), 'Survey', $surveyId);
            $this->set('maxEmailAttribute', App()->getRequest()->getPost('maxEmailAttribute'), 'Survey', $surveyId);
            $this->set('delayInvitationAttribute', App()->getRequest()->getPost('delayInvitationAttribute'), 'Survey', $surveyId);
            $this->set('delayReminderAttribute', App()->getRequest()->getPost('delayReminderAttribute'), 'Survey', $surveyId);
            if(App()->getRequest()->getPost('save'.get_class($this)=='redirect')) {
                Yii::app()->getController()->redirect(Yii::app()->getController()->createUrl('admin/survey',array('sa'=>'view','surveyid'=>$surveyId)));
            }
        }
        /* get the default settings */
        $defaultMaxEmail=$this->get('maxEmail', null,null,$this->settings['maxEmail']['default']);
        if(!$defaultMaxEmail){
            $defaultMaxEmail=$this->_translate("disabled");
        }
        $defaultDelayInvitation=$this->get('delayInvitation', null,null,$this->settings['delayInvitation']['default']);
        $defaultDelayReminder=$this->get('delayReminder', null,null,$this->settings['delayReminder']['default']);
        $defaultDelayInvitationAttribute=$this->get('delayInvitationAttribute', null,null,$this->settings['delayInvitationAttribute']['default']);
        $defaultDelayReminderAttribute=$this->get('delayReminderAttribute', null,null,$this->settings['delayReminderAttribute']['default']);
        $maxBatchSize=$this->get('maxBatchSize', null,null,$this->settings['maxBatchSize']['default']);
        if(!$maxBatchSize){
            $maxBatchHelp=$this->_translate("Leave empty to send all available emails.");
        }else{
            $maxBatchHelp=sprintf($this->_translate("Leave empty to send all available emails,only limited by global batch size (%s) for all surveys."),$maxBatchSize);
        }

        $aData=array();
        /* An alert if survey don't have token */
1225
        $aData['warningString'] = !$this->_surveyHasTokens($surveyId) ? $this->_translate("This survey didn't have token currently, this settings are not used until participant are not activated.") : null;
1226 1227

        $aSettings=array();
1228

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
        $aSettings[$this->_translate('Basic settings')]=array(
            'maxEmail' => array(
                'type'=>'int',
                'htmlOptions'=>array(
                    'min'=>0,
                ),
                'label'=>$this->_translate("Max email to send (invitation + remind) to each participant."),
                'help'=>sprintf($this->_translate("0 to deactivate sending of email, empty to use default (%s)"),$defaultMaxEmail),
                'current'=>$this->get('maxEmail', 'Survey', $surveyId,""),
            ),
            'delayInvitation' => array(
                'type'=>'int',
                'htmlOptions'=>array(
                    'min'=>1,
                ),
                'label'=>$this->_translate("Min delay between invitation and first reminder."),
                'help'=>sprintf($this->_translate("In days, empty for default (%s)"),$defaultDelayInvitation),
                'current'=>$this->get('delayInvitation', 'Survey', $surveyId,""),
            ),
            'delayReminder' => array(
                'type'=>'int',
                'htmlOptions'=>array(
                    'min'=>1,
                ),
                'label'=>$this->_translate("Min delay between reminders."),
                'help'=>sprintf($this->_translate("In days, empty for default (%s)"),$defaultDelayReminder),
                'current'=>$this->get('delayReminder', 'Survey', $surveyId,""),
            ),
        );
        $aSettings[$this->_translate('Batch size')]=array(
            'maxSurveyBatchSize'=>array(
                'type'=>'int',
                'htmlOptions'=>array(
                    'min'=>1,
                ),
                'label'=>$this->_translate("Max email to send (invitation + remind) in one batch for this survey."),
                'help'=>$maxBatchHelp,
                'current'=>$this->get('maxSurveyBatchSize', 'Survey', $surveyId,""),
            ),
            'maxSurveyBatchSize_invite'=>array(
                'type'=>'int',
                'htmlOptions'=>array(
                    'min'=>0,
                ),
                'label'=>$this->_translate("Max email to send for invitation in one batch for this survey."),
                'help'=>$this->_translate("The max email setting can not be exceeded."),
                'current'=>$this->get('maxSurveyBatchSize_invite', 'Survey', $surveyId,""),
            ),
            'maxSurveyBatchSize_remind'=>array(
                'type'=>'int',
                'htmlOptions'=>array(
                    'min'=>0,
                ),
                'label'=>$this->_translate("Max email to send for reminder in one batch for this survey."),
                'help'=>$this->_translate("The max email setting can not be exceeded. Reminders are sent after invitation."),
                'current'=>$this->get('maxSurveyBatchSize_remind', 'Survey', $surveyId,""),
            ),
        );
        $whenSettings=array(
            'dayOfWeekToSend'=>array(
                'type'=>'select',
                'htmlOptions'=>array(
                    'multiple'=>'multiple',
                    'empty'=>$this->_translate("All week days"),
                ),
                'selectOptions'=>array(
                    'placeholder' =>$this->_translate("All week days"),
                    'allowClear'=> true,
                    'width'=>'100%',
                ),
                'controlOptions'=>array(
                    'class'=>'search-100',
                ),
                'label'=>$this->_translate("Day of week for sending email"),
                'options'=>array(
                    1=>$this->_translate("Monday"),
                    2=>$this->_translate("Thursday"),
                    3=>$this->_translate("Wednesday"),
                    4=>$this->_translate("Thuesday"),
                    5=>$this->_translate("Friday"),
                    6=>$this->_translate("Saturday"),
                    7=>$this->_translate("Sunday"),
                ),
                'current'=>$this->get('dayOfWeekToSend', 'Survey', $surveyId,array()),
            ),
        );
        if($this->get('cronTypes', null, null)){
            $availCronTypes=$this->get('cronTypes',null,null,$this->settings['cronTypes']['default']);
            $availCronTypes=explode('|', $availCronTypes);
            $cronTypesOtions=array();
            foreach($availCronTypes as $cronType){
                $cronTypesOtions[$cronType]=$cronType;
            }
            if(!empty($cronTypesOtions)) {
                $emptyLabel=$this->get('cronTypeNone',null,null,$this->settings['cronTypeNone']['default']) ? $this->_translate("Only if no moment is set") : $this->_translate("At all moment");
                $whenSettings['cronTypes']=array(
                    'type'=>'select',
                    'htmlOptions'=>array(
                        'multiple'=>'multiple',
                        'empty'=>$emptyLabel,
                    ),
                    'selectOptions'=>array(
                        'placeholder' =>$emptyLabel,
                        'allowClear'=> true,
                        'width'=>'100%',
                    ),
                    'controlOptions'=>array(
                        'class'=>'search-100',
                    ),
                    'label'=>$this->_translate("Moment for emailing"),
                    'options'=>$cronTypesOtions,
                    'current'=>$this->get('cronTypes', 'Survey', $surveyId,array()),
                );
            }
        }
        $aSettings[$this->_translate('When email must be sent')]=$whenSettings;

        /* Get available attributes for options */
        $aAvailableAttribute=$this->getAttributesList($surveyId);
        $aAvailableAttribute['none'] = $this->_translate("None");

        $defaultMax=$this->_translate("None");
        if(!empty($this->get('maxEmailAttribute'))) {
            if(array_key_exists("attribute_".$this->get('maxEmailAttribute'),$aAvailableAttribute)) {
                $defaultMax=$aAvailableAttribute["attribute_".$this->get('maxEmailAttribute')];
            } else {
                $defaultMax = sprintf($this->_translate("None - %s"),"attribute_".$this->get('maxEmailAttribute'));
            }
        }
        $defaultInvitation=$this->_translate("None");
        if(!empty($this->get('delayInvitationAttribute'))) {
            if(array_key_exists("attribute_".$this->get('delayInvitationAttribute'),$aAvailableAttribute)) {
                $defaultInvitation=$aAvailableAttribute["attribute_".$this->get('delayInvitationAttribute')];
            } else {
                $defaultInvitation = sprintf($this->_translate("None - %s"),"attribute_".$this->get('delayInvitationAttribute'));
            }
        }
        $defaultReminder=$this->_translate("None");
        if(!empty($this->get('delayReminderAttribute'))) {
            if(array_key_exists("attribute_".$this->get('delayReminderAttribute'),$aAvailableAttribute)) {
                $defaultReminder=$aAvailableAttribute["attribute_".$this->get('delayReminderAttribute')];
            } else {
                $defaultReminder = sprintf($this->_translate("None - %s"),"attribute_".$this->get('delayReminderAttribute'));
            }
        }
        $tokenAttributeSettings=array(
            'maxEmailAttribute'=>array(
                'type'=>'select',
                'htmlOptions'=>array(
                    'empty'=>sprintf($this->_translate("Leave default (%s)"),$defaultMax),
                ),
                'label'=>$this->_translate("Attribute used for maximum number of emails."),
                'options'=>$aAvailableAttribute,
                'current'=>$this->get('maxEmailAttribute', 'Survey', $surveyId,null),
            ),
            'delayInvitationAttribute'=>array(
                'type'=>'select',
                'htmlOptions'=>array(
                    'empty'=>sprintf($this->_translate("Leave default (%s)"),$defaultInvitation),
                ),
                'label'=>$this->_translate("Attribute used for min delay between inviation and 1st reminder."),
                'options'=>$aAvailableAttribute,
                'current'=>$this->get('delayInvitationAttribute', 'Survey', $surveyId,null),
            ),
            'delayReminderAttribute'=>array(
                'type'=>'select',
                'htmlOptions'=>array(
                    'empty'=>sprintf($this->_translate("Leave default (%s)"),$defaultReminder),
                ),
                'label'=>$this->_translate("Attribute used for min delay between each reminders."),
                'options'=>$aAvailableAttribute,
                'current'=>$this->get('delayReminderAttribute', 'Survey', $surveyId,null),
            ),
        );
        $aSettings[$this->_translate('Token attribute usage')]=$tokenAttributeSettings;

        $aData['pluginClass']=get_class($this);
        $aData['surveyId']=$surveyId;
1407
        $aData['title']=$this->_translate("Send email by cron settings");
1408 1409 1410 1411 1412
        $aData['aSettings']=$aSettings;
        $aData['assetUrl']=Yii::app()->assetManager->publish(dirname(__FILE__) . '/assets/');
        $content = $this->renderPartial('settings', $aData, true);
        return $content;
    }
1413

1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    /**
     * Fix LimeSurvey command function
     * @todo : find way to control API
     * OR if another plugin already fix it
     */
    private function _LsCommandFix()
    {
        /* Bad autoloading in command */
        include_once(dirname(__FILE__)."/DbStorage.php");
        // These take care of dynamically creating a class for each token / response table.
        Yii::import('application.helpers.ClassFactory');
        ClassFactory::registerClass('Token_', 'Token');
        ClassFactory::registerClass('Response_', 'Response');
    }
1428

1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
    /**
     * Some compatibility function
     * Survey::model()->hasTokens
     * @param integer $iSurveyId
     * @return boolean;
     */
    private function _surveyHasTokens($iSurveyId) {
        Yii::import('application.helpers.common_helper', true);
        return tableExists("{{tokens_".$iSurveyId."}}");
    }
1439

Chenu Denis's avatar
Chenu Denis committed
1440 1441 1442 1443 1444 1445 1446 1447
    /**
     * get translation
     * @param string
     * @return string
     */
    private function _translate($string){
        return Yii::t('',$string,array(),get_class($this));
    }
1448

Chenu Denis's avatar
Chenu Denis committed
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
    /**
     * Add this translation just after loaded all plugins
     * @see event afterPluginLoad
     */
    public function afterPluginLoad(){
        // messageSource for this plugin:
        $messageSource=array(
            'class' => 'CGettextMessageSource',
            'cacheID' => get_class($this).'Lang',
            'cachingDuration'=>3600,
            'forceTranslation' => true,
            'useMoFile' => true,
            'basePath' => __DIR__ . DIRECTORY_SEPARATOR.'locale',
            'catalog'=>'messages',// default from Yii
        );
        Yii::app()->setComponent(get_class($this),$messageSource);
    }

1467
}