Commit 308288a0 authored by Denis Chenu's avatar Denis Chenu
Browse files

[feature] Update token table after survey is submitted

parents
<?php
/**
* updateTokenByResponse
*
* @author Denis Chenu <denis@sondages.pro>
* @copyright 2016 Denis Chenu <http://www.sondages.pro>
* @copyright 2016 Yxplora AG <https://www.yxplora.ch/>
* @license GPL v3
* @version 0.0.1
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 updateTokenByResponse extends \ls\pluginmanager\PluginBase
{
protected $storage = 'DbStorage';
static protected $description = 'Update token after survey is submitted';
static protected $name = 'updateTokenByResponse';
protected $settings = array(
'information' => array(
'type' => 'info',
'class' => "alert alert-info",
'content' => '<p>Set the default value for each token, you can use Expression Manager, <strong>remind to use {} to activate expression manager</strong>. Expression is not validated, if there are error : this is not fixed. If the result of the expression is empty (trimmed) : attribute is not updated</p>',
),
'em_token_firstname'=>array(
'type'=>"string",
'label'=>"Value for firstname",
'default'=>"",
),
'em_token_lastname'=>array(
'type'=>"string",
'label'=>"Value for lastname",
'default'=>"",
),
'em_token_email'=>array(
'type'=>"string",
'label'=>"Value for email",
'default'=>"",
),
);
public function init()
{
$this->subscribe('afterSurveyComplete');
$this->subscribe('beforeSurveySettings');
$this->subscribe('newSurveySettings');
}
public function afterSurveyComplete()
{
$aTokenAttributes=$this->getTokensAttributes();
if(!empty($aTokenAttributes))
{
$iSurveyId = $this->event->get('surveyId');
$aResponse = $this->pluginManager->getAPI()->getResponse($iSurveyId, $this->event->get('responseId'));
if($aResponse && isset($aResponse['token']) && $aResponse['token'])// OK for anonymous token : no issue
{
$aAttributeUpdate=array();
foreach($aTokenAttributes as $attribute=>$description)
{
//~ $sEmValue=$this->get("token_{$attribute}","Survey",$iSurveyId,null);
//~ if(empty($sEmValue))
//~ {
$sEmValue=$this->get("em_token_{$attribute}","Survey",$iSurveyId,"");
if($sEmValue==="")
{
$sEmValue=$this->get("em_token_{$attribute}",null,null,"");
}
//~ }
if($sEmValue)
{
$sValue= trim(LimeExpressionManager::ProcessString($sEmValue,0,array(),0,1,1,false,false,true));// force static
if(!empty($sValue))
{
$aAttributeUpdate[$attribute]=$sValue;
}
}
}
if(!empty($aAttributeUpdate))
{
$oToken=Token::model($iSurveyId)->find("token=:token",array(":token"=>$aResponse['token']));
if($oToken)
{
foreach($aAttributeUpdate as $attribute=>$value)
{
$oToken->$attribute=$value;
}
if(!$oToken->save())
{
tracevar($oToken->getErrors());
}
}
}
}
}
}
public function newSurveySettings()
{
/* save it direclty : maybe use array for setting token_ ? */
foreach ($this->event->get('settings') as $name => $value)
{
$this->set($name, $value, 'Survey', $this->event->get('survey'),"");
}
}
public function beforeSurveySettings()
{
$oEvent=$this->event;
/* Token attribute */
$aTokenAttributes=$this->getTokensAttributes();
if(!empty($aTokenAttributes))
{
$oSurvey=Survey::model()->findByPk($oEvent->get('survey'));
//~ $oCriteria=new CdbCriteria();
//~ $oCriteria->condition="parent_qid=0 and t.sid=:sid and t.language=:language";
//~ $oCriteria->params[':sid'] = $oSurvey->sid;
//~ $oCriteria->params[':language'] = $oSurvey->language;
//~ $oCriteria->addInCondition("type",array("L","!","S","T","U","Q","N","*"));
//~ $oCriteria->order='group_order ASC, question_order ASC';
//~ $aoPossibleQuestions=Question::model()->with('groups')->findAll($oCriteria);
//~ $aPossibleQuestions=array(); // Array with : value as EM and some text : actually we use EM only if not empty (or error ?)
//~ foreach($aoPossibleQuestions as $oQuestion)
//~ {
//~ switch($oQuestion->type)
//~ {
//~ case "Q":
//~ $oSubQuestions=Question::model()->findAll(array("condition"=>"parent_qid=:qid AND language=:language","order"=>"question_order","params"=>array(":qid"=>$oQuestion->qid,":language"=>$oSurvey->language)));
//~ foreach($oSubQuestions as $oSubQuestion)
//~ {
//~ $aPossibleQuestions["{{$oQuestion->title}_{$oSubQuestion->title}.shown}"]="[{$oQuestion->title}_{$oSubQuestion->title}] ".viewHelper::flatEllipsizeText($oQuestion->question,1,40,"...",0.6)." : ".viewHelper::flatEllipsizeText($oSubQuestion->question,1,40,"...",0.6);
//~ }
//~ break;
//~ default:
//~ $aPossibleQuestions["{{$oQuestion->title}.shown}"]="[{$oQuestion->title}] ".viewHelper::flatEllipsizeText($oQuestion->question,1,80,"...",0.6);
//~ break;
//~ }
//~ }
foreach($aTokenAttributes as $attribute=>$description)
{
/* Value by question (shown) */
//~ $aSettings["token_{$attribute}"]=array(
//~ 'type'=>'select',
//~ 'label'=>"<span class='label label-info'>".(empty($description) ? $attribute : $description)."</span>, updated with question",
//~ 'options'=>$aPossibleQuestions,
//~ 'htmlOptions'=>array(
//~ 'empty'=>gT('Use Expression if exist'),
//~ ),
//~ 'current'=>$this->get("token_{$attribute}","Survey",$oEvent->get('survey')),
//~ );
/* Value by EM */
$default=$this->get("em_token_{$attribute}",null,null,"");
$aSettings["em_token_{$attribute}"]=array(
'type'=>'string',
'label'=>"<span class='label'>".(empty($description) ? $attribute : $description)."</span>, updated with value (you can use Expression Manager (remind to add thee { and } for expression)).",
'current'=>$this->get("em_token_{$attribute}","Survey",$oEvent->get('survey'),""),
);
$actualValue=$this->get("em_token_{$attribute}","Survey",$oEvent->get('survey'),$default);
if($actualValue)
{
$aSettings["em_token_{$attribute}"]['help']="Actual value: ".$this->getHtmlExpression($actualValue,$oEvent->get('survey'));
}
elseif(!empty($default))
{
$aSettings["em_token_{$attribute}"]['help']="Actual value (by default): ".$this->getHtmlExpression($default,$oEvent->get('survey'));
}
}
}
if(!empty($aSettings))
{
$oEvent->set("surveysettings.{$this->id}", array(
'name' => get_class($this),
'settings' => $aSettings,
));
}
}
/**
* get the token attributes array
* @return array
*/
private function getTokensAttributes()
{
$aTokenAttributes=array();
$iSurveyId=$this->event->get('survey',$this->event->get('surveyId'));
if($iSurveyId && tableExists("{{tokens_{$iSurveyId}}}")){
$aRealTokenAttributes=array_keys(Yii::app()->db->schema->getTable("{{tokens_{$iSurveyId}}}")->columns);
$aRealTokenAttributes=array_combine($aRealTokenAttributes,$aRealTokenAttributes);
$aTokenAttributes=array_filter(Token::model($iSurveyId)->attributeLabels());
$aTokenAttributes=array_diff_key(
array_replace($aRealTokenAttributes,$aTokenAttributes),
array(
'tid' => 'tid',
'partcipant' => 'partcipant',
'participant' => 'participant',
'participant_id' => 'participant_id',
//~ 'firstname' => 'firstname',
//~ 'lastname' => 'lastname',
//~ 'email' => 'email',
'emailstatus' => 'emailstatus',
'token' => 'token',
'language' => 'language',
'blacklisted' => 'blacklisted',
'sent' => 'sent',
'remindersent' => 'remindersent',
'remindercount' => 'remindercount',
'completed' => 'completed',
'usesleft' => 'usesleft',
'validfrom' => 'validfrom',
'validuntil' => 'validuntil',
'mpid' => 'mpid'
)
);
}
return $aTokenAttributes;
}
/**
* update the plugin settings when loaded
*/
public function getPluginSettings($getValues=true)
{
for ($cnt = 1; $cnt <= 100; $cnt++) {
$this->settings["em_token_attribute_{$cnt}"]=array(
'type'=>"string",
'label'=>"Value for attribute {$cnt}",
'default'=>"",
);
}
return parent::getPluginSettings($getValues);
}
/**
* Get the complete HTML from a string
* @param string $sExpression : the string to parse
* @param array $aReplacement : optionnal array of replacemement
* @param string $sDebugSource : optionnal debug source (for templatereplace)
* @uses ExpressionValidate::$iSurveyId
* @uses ExpressionValidate::$sLang
*
* @author Denis Chenu
* @version 1.0
*/
private function getHtmlExpression($sExpression,$iSurveyId,$aReplacement=array(),$sDebugSource=__CLASS__)
{
$LEM =LimeExpressionManager::singleton();
$LEM::SetDirtyFlag();// Not sure it's needed
$LEM::SetPreviewMode('logic');
$aReData=array();
if($iSurveyId)
{
$LEM::StartSurvey($iSurveyId, 'survey', array('hyperlinkSyntaxHighlighting'=>true));// replace QCODE
$aReData['thissurvey']=getSurveyInfo($iSurveyId);
}
// TODO : Find error in class name, style etc ....
// need: templatereplace without any filter and find if there are error but $bHaveError=$LEM->em->HasErrors() is Private
$oFilter = new CHtmlPurifier();
templatereplace($oFilter->purify(viewHelper::filterScript($sExpression)), $aReplacement,$aReData,$sDebugSource,false,null,array(),true);
return $LEM::GetLastPrettyPrintExpression();
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment