Exemplo n.º 1
0
 protected function createFullQuestionIndexByGroup($LEMsessid)
 {
     echo "\n\n<!-- PRESENT THE INDEX -->\n";
     echo CHtml::openTag('div', array('id' => 'index'));
     echo CHtml::openTag('div', array('class' => 'container'));
     echo CHtml::tag('h2', array(), gT("Question index"));
     echo CHtml::openTag('ol');
     foreach ($_SESSION[$LEMsessid]['grouplist'] as $key => $group) {
         //						echo '<script>';
         //						echo 'var session = '. json_encode(LimeExpressionManager::singleton()->_ValidateGroup($key)) . ';';
         //						echo 'console.log(session);';
         //						echo '</script>';
         // Better to use tracevar /
         if (LimeExpressionManager::GroupIsRelevant($group['gid'])) {
             $group['step'] = $key + 1;
             $stepInfo = LimeExpressionManager::singleton()->_ValidateGroup($key);
             $classes = implode(' ', array('row', $stepInfo['anyUnanswered'] ? 'missing' : '', $_SESSION[$LEMsessid]['step'] == $group['step'] ? 'current' : ''));
             $sButtonSubmit = CHtml::htmlButton(gT('Go to this group'), array('type' => 'submit', 'value' => $group['step'], 'name' => 'move', 'class' => 'jshide'));
             echo CHtml::tag('li', array('data-gid' => $group['gid'], 'title' => $group['description'], 'class' => $classes), $group['group_name'] . $sButtonSubmit);
         }
     }
     echo CHtml::closeTag('ol');
     echo CHtml::closeTag('div');
     echo CHtml::closeTag('div');
     App()->getClientScript()->registerScript('manageIndex', "manageIndex()\n", CClientScript::POS_END);
 }
Exemplo n.º 2
0
 function actiontokens($surveyid, $token, $langcode = '')
 {
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     $sLanguageCode = $langcode;
     $iSurveyID = $surveyid;
     $sToken = $token;
     $sToken = sanitize_token($sToken);
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Check that there is a SID
     // Get passed language from form, so that we dont loose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = sanitize_languagecode($sLanguageCode);
     }
     Yii::app()->setLanguage($sBaseLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         throw new CHttpException(404, "This survey does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     } else {
         LimeExpressionManager::singleton()->loadTokenInformation($iSurveyID, $token, false);
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $token));
         if (!isset($oToken)) {
             $sMessage = gT('You are not a participant in this survey.');
         } else {
             if ($oToken->emailstatus == 'OptOut') {
                 $oToken->emailstatus = 'OK';
                 $oToken->save();
                 $sMessage = gT('You have been successfully added back to this survey.');
             } elseif ($oToken->emailstatus == 'OK') {
                 $sMessage = gT('You are already a part of this survey.');
             } else {
                 $sMessage = gT('You have been already removed from this survey.');
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
Exemplo n.º 3
0
 /**
  * Handle email action
  */
 function email($iSurveyId, $tokenids = null)
 {
     $clang = $this->getController()->lang;
     $iSurveyId = sanitize_int($iSurveyId);
     if (!Permission::model()->hasSurveyPermission($iSurveyId, 'tokens', 'update')) {
         Yii::app()->session['flashmessage'] = $clang->gT("You do not have sufficient rights to access this page.");
         $this->getController()->redirect(array("/admin/survey/sa/view/surveyid/{$iSurveyId}"));
     }
     // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY
     $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}');
     if (!$bTokenExists) {
         self::_newtokentable($iSurveyId);
     }
     $aTokenIds = $tokenids;
     if (empty($tokenids)) {
         $aTokenIds = Yii::app()->request->getPost('tokenids', false);
     }
     if (!empty($aTokenIds)) {
         $aTokenIds = explode('|', $aTokenIds);
         $aTokenIds = array_filter($aTokenIds);
         $aTokenIds = array_map('sanitize_int', $aTokenIds);
     }
     $aTokenIds = array_unique(array_filter((array) $aTokenIds));
     $sSubAction = Yii::app()->request->getParam('action');
     $sSubAction = !in_array($sSubAction, array('email', 'remind')) ? 'email' : $sSubAction;
     $bEmail = $sSubAction == 'email';
     Yii::app()->loadHelper('surveytranslator');
     Yii::app()->loadHelper('/admin/htmleditor');
     Yii::app()->loadHelper('replacements');
     $token = Token::model($iSurveyId)->find();
     $aExampleRow = isset($token) ? $token->attributes : array();
     $aSurveyLangs = Survey::model()->findByPk($iSurveyId)->additionalLanguages;
     $sBaseLanguage = Survey::model()->findByPk($iSurveyId)->language;
     array_unshift($aSurveyLangs, $sBaseLanguage);
     $aTokenFields = getTokenFieldsAndNames($iSurveyId, true);
     $iAttributes = 0;
     $bHtml = getEmailFormat($iSurveyId) == 'html';
     $timeadjust = Yii::app()->getConfig("timeadjust");
     $aData['thissurvey'] = getSurveyInfo($iSurveyId);
     foreach ($aSurveyLangs as $sSurveyLanguage) {
         $aData['thissurvey'][$sSurveyLanguage] = getSurveyInfo($iSurveyId, $sSurveyLanguage);
     }
     $aData['surveyid'] = $iSurveyId;
     $aData['sSubAction'] = $sSubAction;
     $aData['bEmail'] = $bEmail;
     $aData['aSurveyLangs'] = $aData['surveylangs'] = $aSurveyLangs;
     $aData['baselang'] = $sBaseLanguage;
     $aData['tokenfields'] = array_keys($aTokenFields);
     $aData['nrofattributes'] = $iAttributes;
     $aData['examplerow'] = $aExampleRow;
     $aData['tokenids'] = $aTokenIds;
     $aData['ishtml'] = $bHtml;
     $iMaxEmails = Yii::app()->getConfig('maxemails');
     if (Yii::app()->request->getPost('bypassbademails') == 'Y') {
         $SQLemailstatuscondition = "emailstatus = 'OK'";
     } else {
         $SQLemailstatuscondition = "emailstatus <> 'OptOut'";
     }
     if (!Yii::app()->request->getPost('ok')) {
         if (empty($aData['tokenids'])) {
             $aTokens = TokenDynamic::model($iSurveyId)->findUninvitedIDs($aTokenIds, 0, $bEmail, $SQLemailstatuscondition);
             foreach ($aTokens as $aToken) {
                 $aData['tokenids'][] = $aToken;
             }
         }
         $this->_renderWrappedTemplate('token', array('tokenbar', $sSubAction), $aData);
     } else {
         $SQLremindercountcondition = "";
         $SQLreminderdelaycondition = "";
         if (!$bEmail) {
             if (Yii::app()->request->getPost('maxremindercount') && Yii::app()->request->getPost('maxremindercount') != '' && intval(Yii::app()->request->getPost('maxremindercount')) != 0) {
                 $SQLremindercountcondition = "remindercount < " . intval(Yii::app()->request->getPost('maxremindercount'));
             }
             if (Yii::app()->request->getPost('minreminderdelay') && Yii::app()->request->getPost('minreminderdelay') != '' && intval(Yii::app()->request->getPost('minreminderdelay')) != 0) {
                 // Yii::app()->request->getPost('minreminderdelay') in days (86400 seconds per day)
                 $compareddate = dateShift(date("Y-m-d H:i:s", time() - 86400 * intval(Yii::app()->request->getPost('minreminderdelay'))), "Y-m-d H:i", $timeadjust);
                 $SQLreminderdelaycondition = " ( " . " (remindersent = 'N' AND sent < '" . $compareddate . "') " . " OR " . " (remindersent < '" . $compareddate . "'))";
             }
         }
         $ctresult = TokenDynamic::model($iSurveyId)->findUninvitedIDs($aTokenIds, 0, $bEmail, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
         $ctcount = count($ctresult);
         $emresult = TokenDynamic::model($iSurveyId)->findUninvited($aTokenIds, $iMaxEmails, $bEmail, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition);
         $emcount = count($emresult);
         foreach ($aSurveyLangs as $language) {
             // See #08683 : this allow use of {TOKEN:ANYTHING}, directly replaced by {ANYTHING}
             $sSubject[$language] = preg_replace("/{TOKEN:([A-Z0-9_]+)}/", "{" . "\$1" . "}", Yii::app()->request->getPost('subject_' . $language));
             $sMessage[$language] = preg_replace("/{TOKEN:([A-Z0-9_]+)}/", "{" . "\$1" . "}", Yii::app()->request->getPost('message_' . $language));
             if ($bHtml) {
                 $sMessage[$language] = html_entity_decode($sMessage[$language], ENT_QUOTES, Yii::app()->getConfig("emailcharset"));
             }
         }
         $attributes = array_keys(getTokenFieldsAndNames($iSurveyId, true));
         $tokenoutput = "";
         if ($emcount > 0) {
             foreach ($emresult as $emrow) {
                 $to = $fieldsarray = array();
                 $aEmailaddresses = explode(';', $emrow['email']);
                 foreach ($aEmailaddresses as $sEmailaddress) {
                     $to[] = $emrow['firstname'] . " " . $emrow['lastname'] . " <{$sEmailaddress}>";
                 }
                 $fieldsarray["{EMAIL}"] = $emrow['email'];
                 $fieldsarray["{FIRSTNAME}"] = $emrow['firstname'];
                 $fieldsarray["{LASTNAME}"] = $emrow['lastname'];
                 $fieldsarray["{TOKEN}"] = $emrow['token'];
                 $fieldsarray["{LANGUAGE}"] = $emrow['language'];
                 foreach ($attributes as $attributefield) {
                     $fieldsarray['{' . strtoupper($attributefield) . '}'] = $emrow[$attributefield];
                     $fieldsarray['{TOKEN:' . strtoupper($attributefield) . '}'] = $emrow[$attributefield];
                 }
                 $emrow['language'] = trim($emrow['language']);
                 $found = array_search($emrow['language'], $aSurveyLangs);
                 if ($emrow['language'] == '' || $found == false) {
                     $emrow['language'] = $sBaseLanguage;
                 }
                 $from = Yii::app()->request->getPost('from_' . $emrow['language']);
                 $fieldsarray["{OPTOUTURL}"] = $this->getController()->createAbsoluteUrl("/optout/tokens/langcode/" . trim($emrow['language']) . "/surveyid/{$iSurveyId}/token/{$emrow['token']}");
                 $fieldsarray["{OPTINURL}"] = $this->getController()->createAbsoluteUrl("/optin/tokens/langcode/" . trim($emrow['language']) . "/surveyid/{$iSurveyId}/token/{$emrow['token']}");
                 $fieldsarray["{SURVEYURL}"] = $this->getController()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}/token/{$emrow['token']}/lang/" . trim($emrow['language']) . "/");
                 foreach (array('OPTOUT', 'OPTIN', 'SURVEY') as $key) {
                     $url = $fieldsarray["{{$key}URL}"];
                     if ($bHtml) {
                         $fieldsarray["{{$key}URL}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>';
                     }
                     if ($key == 'SURVEY') {
                         $barebone_link = $url;
                     }
                 }
                 $customheaders = array('1' => "X-surveyid: " . $iSurveyId, '2' => "X-tokenid: " . $fieldsarray["{TOKEN}"]);
                 global $maildebug;
                 $modsubject = Replacefields($sSubject[$emrow['language']], $fieldsarray);
                 $modmessage = Replacefields($sMessage[$emrow['language']], $fieldsarray);
                 if (isset($barebone_link)) {
                     $modsubject = str_replace("@@SURVEYURL@@", $barebone_link, $modsubject);
                     $modmessage = str_replace("@@SURVEYURL@@", $barebone_link, $modmessage);
                 }
                 if (trim($emrow['validfrom']) != '' && convertDateTimeFormat($emrow['validfrom'], 'Y-m-d H:i:s', 'U') * 1 > date('U') * 1) {
                     $tokenoutput .= $emrow['tid'] . " " . ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) delayed: Token is not yet valid.") . "<br />", $fieldsarray);
                 } elseif (trim($emrow['validuntil']) != '' && convertDateTimeFormat($emrow['validuntil'], 'Y-m-d H:i:s', 'U') * 1 < date('U') * 1) {
                     $tokenoutput .= $emrow['tid'] . " " . ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) skipped: Token is not valid anymore.") . "<br />", $fieldsarray);
                 } else {
                     /*
                      * Get attachments.
                      */
                     if ($sSubAction == 'email') {
                         $sTemplate = 'invitation';
                     } elseif ($sSubAction == 'remind') {
                         $sTemplate = 'reminder';
                     }
                     $aRelevantAttachments = array();
                     if (isset($aData['thissurvey'][$emrow['language']]['attachments'])) {
                         $aAttachments = unserialize($aData['thissurvey'][$emrow['language']]['attachments']);
                         if (!empty($aAttachments)) {
                             if (isset($aAttachments[$sTemplate])) {
                                 LimeExpressionManager::singleton()->loadTokenInformation($aData['thissurvey']['sid'], $emrow['token']);
                                 foreach ($aAttachments[$sTemplate] as $aAttachment) {
                                     if (LimeExpressionManager::singleton()->ProcessRelevance($aAttachment['relevance'])) {
                                         $aRelevantAttachments[] = $aAttachment['url'];
                                     }
                                 }
                             }
                         }
                     }
                     /**
                      * Event for email handling.
                      * Parameter    type    description:
                      * subject      rw      Body of the email
                      * to           rw      Recipient(s)
                      * from         rw      Sender(s)
                      * type         r       "invitation" or "reminder"
                      * send         w       If true limesurvey will send the email. Setting this to false will cause limesurvey to assume the mail has been sent by the plugin.
                      * error        w       If set and "send" is true, log the error as failed email attempt.
                      * token        r       Raw token data.
                      */
                     $event = new PluginEvent('beforeTokenEmail');
                     $event->set('type', $sTemplate);
                     $event->set('subject', $modsubject);
                     $event->set('to', $to);
                     $event->set('body', $modmessage);
                     $event->set('from', $from);
                     $event->set('bounce', getBounceEmail($iSurveyId));
                     $event->set('token', $emrow);
                     App()->getPluginManager()->dispatchEvent($event);
                     $modsubject = $event->get('subject');
                     $modmessage = $event->get('body');
                     $to = $event->get('to');
                     $from = $event->get('from');
                     if ($event->get('send', true) == false) {
                         // This is some ancient global used for error reporting instead of a return value from the actual mail function..
                         $maildebug = $event->get('error', $maildebug);
                         $success = $event->get('error') == null;
                     } else {
                         $success = SendEmailMessage($modmessage, $modsubject, $to, $from, Yii::app()->getConfig("sitename"), $bHtml, getBounceEmail($iSurveyId), $aRelevantAttachments, $customheaders);
                     }
                     if ($success) {
                         // Put date into sent
                         $token = Token::model($iSurveyId)->findByPk($emrow['tid']);
                         if ($bEmail) {
                             $tokenoutput .= $clang->gT("Invitation sent to:");
                             $token->sent = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
                         } else {
                             $tokenoutput .= $clang->gT("Reminder sent to:");
                             $token->remindersent = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
                             $token->remindercount++;
                         }
                         $token->save();
                         //Update central participant survey_links
                         if (!empty($emrow['participant_id'])) {
                             $slquery = SurveyLink::model()->find('participant_id = :pid AND survey_id = :sid AND token_id = :tid', array(':pid' => $emrow['participant_id'], ':sid' => $iSurveyId, ':tid' => $emrow['tid']));
                             if (!is_null($slquery)) {
                                 $slquery->date_invited = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust"));
                                 $slquery->save();
                             }
                         }
                         $tokenoutput .= "{$emrow['tid']}: {$emrow['firstname']} {$emrow['lastname']} ({$emrow['email']})<br />\n";
                         if (Yii::app()->getConfig("emailsmtpdebug") == 2) {
                             $tokenoutput .= $maildebug;
                         }
                     } else {
                         $tokenoutput .= ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:") . " " . $maildebug . "<br />", $fieldsarray);
                     }
                 }
                 unset($fieldsarray);
             }
             $aViewUrls = array('tokenbar', 'emailpost');
             $aData['tokenoutput'] = $tokenoutput;
             if ($ctcount > $emcount) {
                 $i = 0;
                 if (isset($aTokenIds)) {
                     while ($i < $iMaxEmails) {
                         array_shift($aTokenIds);
                         $i++;
                     }
                     $aData['tids'] = implode('|', $aTokenIds);
                 }
                 $aData['lefttosend'] = $ctcount - $iMaxEmails;
                 $aViewUrls[] = 'emailwarning';
             } else {
                 $aData['tokenoutput'] .= "<strong class='result success text-success'>" . gT("All emails were sent.") . "<strong>";
             }
             $this->_renderWrappedTemplate('token', $aViewUrls, $aData);
         } else {
             $this->_renderWrappedTemplate('token', array('tokenbar', 'message' => array('title' => $clang->gT("Warning"), 'message' => $clang->gT("There were no eligible emails to send. This will be because none satisfied the criteria of:") . "<br/>&nbsp;<ul><li>" . $clang->gT("having a valid email address") . "</li>" . "<li>" . $clang->gT("not having been sent an invitation already") . "</li>" . "<li>" . $clang->gT("having already completed the survey") . "</li>" . "<li>" . $clang->gT("having a token") . "</li></ul>")), $aData);
         }
     }
 }
Exemplo n.º 4
0
 /**
  * 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, $aReplacement = array(), $sDebugSource = __CLASS__)
 {
     $LEM = LimeExpressionManager::singleton();
     $LEM::SetDirtyFlag();
     // Not sure it's needed
     $LEM::SetPreviewMode('logic');
     $aReData = array();
     if ($this->iSurveyId) {
         $LEM::StartSurvey($this->iSurveyId, 'survey', array('hyperlinkSyntaxHighlighting' => true));
         // replace QCODE
         $aReData['thissurvey'] = getSurveyInfo($this->iSurveyId, $this->sLang);
     }
     // 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();
 }
 /**
  * Returns the survey ID of the EM singleton
  */
 public static function getLEMsurveyId()
 {
     $LEM =& LimeExpressionManager::singleton();
     return $LEM->sid;
 }
Exemplo n.º 6
0
 function actionparticipants()
 {
     $iSurveyID = Yii::app()->request->getQuery('surveyid');
     $sLanguageCode = Yii::app()->request->getQuery('langcode');
     $sToken = sanitize_token(Yii::app()->request->getQuery('token'));
     Yii::app()->loadHelper('database');
     Yii::app()->loadHelper('sanitize');
     if (!$iSurveyID) {
         $this->redirect(array('/'));
     }
     $iSurveyID = (int) $iSurveyID;
     //Make sure it's an integer (protect from SQL injects)
     //Check that there is a SID
     // Get passed language from form, so that we dont lose this!
     if (!isset($sLanguageCode) || $sLanguageCode == "" || !$sLanguageCode) {
         $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language;
     } else {
         $sBaseLanguage = sanitize_languagecode($sLanguageCode);
     }
     Yii::app()->setLanguage($sBaseLanguage);
     $aSurveyInfo = getSurveyInfo($iSurveyID, $sBaseLanguage);
     if ($aSurveyInfo == false || !tableExists("{{tokens_{$iSurveyID}}}")) {
         throw new CHttpException(404, "The survey in which you are trying to participate does not seem to exist. It may have been deleted or the link you were given is outdated or incorrect.");
     } else {
         LimeExpressionManager::singleton()->loadTokenInformation($iSurveyID, $sToken, false);
         $oToken = Token::model($iSurveyID)->findByAttributes(array('token' => $sToken));
         if (!isset($oToken)) {
             $sMessage = gT('You are not a participant in this survey.');
         } else {
             if (substr($oToken->emailstatus, 0, strlen('OptOut')) !== 'OptOut') {
                 $oToken->emailstatus = 'OptOut';
                 $oToken->save();
                 $sMessage = gT('You have been successfully removed from this survey.');
             } else {
                 $sMessage = gT('You have been already removed from this survey.');
             }
             if (!empty($oToken->participant_id)) {
                 //Participant also exists in central db
                 $oParticipant = Participant::model()->findByPk($oToken->participant_id);
                 if ($oParticipant->blacklisted == "Y") {
                     $sMessage .= "<br />";
                     $sMessage .= gT("You have already been removed from the central participants list for this site");
                 } else {
                     $oParticipant->blacklisted = 'Y';
                     $oParticipant->save();
                     $sMessage .= "<br />";
                     $sMessage .= gT("You have been removed from the central participants list for this site");
                 }
             }
         }
     }
     //PRINT COMPLETED PAGE
     if (!$aSurveyInfo['templatedir']) {
         $sTemplate = getTemplatePath(Yii::app()->getConfig("defaulttemplate"));
     } else {
         $sTemplate = getTemplatePath($aSurveyInfo['templatedir']);
     }
     $this->_renderHtml($sMessage, $sTemplate, $aSurveyInfo);
 }
Exemplo n.º 7
0
    public function oldTestEvaluator()
    {
        // Syntax for $tests is
        // expectedResult~expression
        // if the expected result is an error, use NULL for the expected result
        $tests = <<<EOD
<B>Empty Vs. Empty</B>~"<B>Empty Vs. Empty</B>"
1~'' == ''
0~'' != ''
0~'' > ''
1~'' >= ''
0~'' < ''
1~'' <= ''
1~!''
~('' and '')
~('' or '')
<B>Empty Vs. Zero</B>~"<B>Empty Vs. Zero</B>"
0~'' == 0
1~'' != 0
0~'' > 0
0~'' >= 0
0~'' < 0
0~'' <= 0
1~!''
1~!0
0~('' and 0)
0~('' or 0)
<B>Empty Vs. Constant</B>~"<B>Empty Vs. Constant</B>"
0~'' == 3
1~'' != 3
0~'' > 3
0~'' >= 3
0~'' < 3
0~'' <= 3
1~!''
0~!3
0~('' and 3)
1~('' or 3)
<B>Empty Vs. Empty_Var</B>~"<B>Empty Vs. Empty_Var</B>"
1~'' == empty
0~'' != empty
0~'' > empty
1~'' >= empty
0~'' < empty
1~'' <= empty
1~!''
1~!empty
~('' and empty)
~('' or empty)
<B>Empty_Var Vs. Zero</B>~"<B>Empty_Var Vs. Zero</B>"
0~empty == 0
1~empty != 0
0~empty > 0
0~empty >= 0
0~empty < 0
0~empty <= 0
1~!empty
1~!0
0~(empty and 0)
0~(empty or 0)
<B>Empty_Var Vs. Zero</B>~"<B>Empty_Var Vs. Zero</B>"
0~empty == zero
1~empty != zero
0~empty > zero
0~empty >= zero
0~empty < zero
0~empty <= zero
1~!empty
1~!zero
0~(empty and zero)
0~(empty or zero)
<B>Empty_Var Vs. Constant</B>~"<B>Empty_Var Vs. Constant</B>"
0~empty == 3
1~empty != 3
0~empty > 3
0~empty >= 3
0~empty < 3
0~empty <= 3
1~!empty
0~!3
0~(empty and 3)
1~(empty or 3)
<B>Solution: Empty_Var Vs. Zero</B>~"<B>Solution: Empty_Var Vs. Zero</B>"
0~!is_empty(empty) && (empty == 0)
0~!is_empty(five) && (five == 0)
1~!is_empty(zero) && (zero == 0)
0~!is_empty(empty) && (empty > 0)
0~!is_empty(empty) && (empty >= 0)
0~!is_empty(empty) && (empty < 0)
0~!is_empty(empty) && (empty <= 0)
0~!is_empty(empty) && ((empty and 0))
0~!is_empty(empty) && ((empty or 0))
<B>Solution: Empty_Var Vs. Zero</B>~"<B>Solution: Empty_Var Vs. Zero</B>"
0~!is_empty(empty) && (empty == zero)
0~!is_empty(five) && (five == zero)
1~!is_empty(zero) && (zero == zero)
0~!is_empty(empty) && (empty > zero)
0~!is_empty(empty) && (empty >= zero)
0~!is_empty(empty) && (empty < zero)
0~!is_empty(empty) && (empty <= zero)
0~!is_empty(empty) && ((empty and zero))
0~!is_empty(empty) && ((empty or zero))
<B>Solution: Empty_Var Vs. Constant</B>~"<B>Solution: Empty_Var Vs. Constant</B>"
0~!is_empty(empty) && (empty < 3)
0~!is_empty(empty) && (empty <= 3)
<B>Solution: Empty_Var Vs. Variable</B>~"<B>Solution: Empty_Var Vs. Variable</B>"
0~!is_empty(empty) && (empty < five)
0~!is_empty(empty) && (empty <= five)
<B>Solution: The Hard One is Empty_Var != 0</B>~"<B>Solution: The Hard One is Empty_Var != 0</B>"
1~(empty != 0)
1~!is_empty(empty) && (empty != 0)
1~is_empty(empty) || (empty != 0)
1~is_empty(empty) || (empty != zero)
0~is_empty(zero) || (zero != 0)
1~is_empty(five) || (five != 0)
<b>SETUP</b>~'<b>SETUP</b>'
&quot;Can strings contain embedded \\&quot;quoted passages\\&quot; (and parentheses + other characters?)?&quot;~a=htmlspecialchars(ASSESSMENT_HEADING)
&quot;can single quoted strings&quot; . &#039;contain nested &#039;quoted sections&#039;?~b=htmlspecialchars(QUESTIONHELP)
Can strings have embedded &lt;tags&gt; like &lt;html&gt;, or even unbalanced &quot;quotes or entities without terminal semicolons like &amp;amp and  &amp;lt?~c=htmlspecialchars(QUESTION_HELP)
<span id="d" style="border-style: solid; border-width: 2px; border-color: green">Hi there!</span>~d='<span id="d" style="border-style: solid; border-width: 2px; border-color: green">Hi there!</span>'
<b>FUNCTIONS</b>~'<b>FUNCTIONS</b>'
5~abs(five)
5~abs(-five)
0.2~acos(cos(0.2))
0~acos(cos(pi()))-pi()
&quot;Can strings contain embedded \\&quot;quoted passages\\&quot; (and parentheses + other characters?)?&quot;~addslashes(a)
&quot;can single quoted strings&quot; . &#039;contain nested &#039;quoted sections&#039;?~addslashes(b)
Can strings have embedded &lt;tags&gt; like &lt;html&gt;, or even unbalanced &quot;quotes or entities without terminal semicolons like &amp;amp and  &amp;lt?~addslashes(c)
0.2~asin(sin(0.2))
0.2~atan(tan(0.2))
0~atan2(0,1)
1~ceil(0.3)
1~ceil(0.7)
0~ceil(-0.3)
0~ceil(-0.7)
10~ceil(9.1)
1~checkdate(1,29,1967)
0~checkdate(2,29,1967)
0.2~cos(acos(0.2))
5~count(1,2,3,4,5)
0~count()
5~count(one,two,three,four,five)
2~count(a,'',c)
NULL~date('F j, Y, g:i a',time())
April 5, 2006, 1:02 am~date('F j, Y, g:i a',mktime(1,2,3,4,5,6))
20~floor(exp(3))
0~floor(asin(sin(pi())))
9~floor(9.9)
3~floor(pi())
January 12, 2012, 5:27 pm~date('F j, Y, g:i a',1326410867)
January 12, 2012, 11:27 pm~gmdate('F j, Y, g:i a',1326410867)
"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"~html_entity_decode(a)
"can single quoted strings" . &#039;contain nested &#039;quoted sections&#039;?~html_entity_decode(b)
Can strings have embedded <tags> like <html>, or even unbalanced "quotes or entities without terminal semicolons like &amp and  &lt?~html_entity_decode(c)
&quot;Can strings contain embedded \\&quot;quoted passages\\&quot; (and parentheses + other characters?)?&quot;~htmlentities(a)
&quot;can single quoted strings&quot; . &#039;contain nested &#039;quoted sections&#039;?~htmlentities(b)
Can strings have embedded &lt;tags&gt; like &lt;html&gt;, or even unbalanced &quot;quotes or entities without terminal semicolons like &amp;amp and &amp;lt?~htmlentities(c)
1~c==htmlspecialchars(htmlspecialchars_decode(c))
1~b==htmlspecialchars(htmlspecialchars_decode(b))
1~a==htmlspecialchars(htmlspecialchars_decode(a))
"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"~htmlspecialchars_decode(a)
"can single quoted strings" . 'contain nested 'quoted sections'?~htmlspecialchars_decode(b)
Can strings have embedded like , or even unbalanced "quotes or entities without terminal semicolons like & and <?~htmlspecialchars_decode(c)
"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"~htmlspecialchars(a)
"can single quoted strings" . 'contain nested 'quoted sections'?~htmlspecialchars(b)
Can strings have embedded <tags> like <html>, or even unbalanced "quotes or entities without terminal semicolons like &amp and &lt?~htmlspecialchars(c)
9~idate('B',1326410867)
0~if('0',1,0)
0~if(0,1,0)
1~if(!0,1,0)
0~if(!(!0),1,0)
1~if('true',1,0)
1~if('false',1,0)
1~if('00',1,0)
0~if('',1,0)
1~if('A',1,0)
0~if(empty,1,0)
4~if(5 > 7,2,4)
1~if(' ',1,0)
there~if((one > two),'hi','there')
64~if((one < two),pow(2,6),pow(6,2))
H e l l o~implode(' ','H','e','l','l','o')
1|2|3|4|5~implode('|',one,two,three,four,five)
123~join(1,2,3)
123 5~join(one,2,three," ",five)
4~intval('4')
4~intval('100',2)
5~intval(5.7)
0~is_empty(four)
1~is_empty(empty)
1~is_empty('')
0~is_empty(0)
0~is_empty('0')
0~is_empty('false')
0~is_empty('NULL')
0~is_empty(1)
1~is_empty(one==two)
0~!is_empty(one==two)
1~is_float(half)
0~is_float(one)
1~is_float(pi())
0~is_float(5)
0~is_int(half)
1~is_int(one)
0~is_nan(half)
1~is_nan(WELCOME)
1~is_null(sdfjskdfj)
0~is_null(four)
0~is_numeric(empty)
1~is_numeric('1')
1~is_numeric(four)
0~is_numeric('hi')
1~is_numeric(five)
0~is_numeric(hi)
0~is_string(four)
1~is_string('hi')
1~is_string(hi)
1, 2, 3, 4, 5~list(one,two,three,min(four,five,six),max(three,four,five))
11, 12~list(eleven,twelve)
0, 1, 3, 5~list(0,one,'',three,'',five)
1~log(exp(1))
2~log(exp(2))
I was trimmed   ~ltrim('     I was trimmed   ')
10~max(5,6,10,-20)
6~max(five,(one + (two * four)- three))
6~max((one + (two * four)- three))
212~5 + max(1,(2+3),(4 + (5 + 6)),((7 + 8) + 9),((10 + 11), 12),(13 + (14 * 15) - 16))
29~five + max(one, (two + three), (four + (five + six)),((seven + eight) + nine),((ten + eleven), twelve),(one + (two * three) - four))
1024~max(one,(two*three),pow(four,five),six)
2~max(one,two)
5~max(one,two,three,four,five)
-5~min(-5,10,15,12,-3)
1~min(five,four,one,two,three)
1344765967~mktime(5,6,7,8)
1144191723~mktime(1,2,3,4,5,6)
1,000~number_format(1000)
1,000.23~number_format(1000.23)
1,234,567~number_format(1234567)
315~ceil(100*pi())
1~pi() == pi() * 2 - pi()
4~pow(2,2)
27~pow(3,3)
=~quoted_printable_decode(quoted_printable_encode('='))
\\\$~quotemeta('\$')
IGNORE THIS ERROR~rand(3,5)
0~(a=rand())-a
1~regexMatch('/embedded/',c)
1~regexMatch('/^.*embedded.*\$/',c)
0~regexMatch('/joe/',c)
1~regexMatch('/(?:dog|cat)food/','catfood stinks')
1~regexMatch('/(?:dog|cat)food/','catfood stinks')
1~regexMatch('/[0-9]{3}-[0-9]{2}-[0-9]{4}/','123-45-6789')
1~regexMatch('/\\d{3}-\\d{2}-\\d{4}/','123-45-6789')
1~regexMatch('/(?:\\(\\d{3}\\))\\s*\\d{3}-\\d{4}/','(212) 555-1212')
0~round(0.2)
1~round(.8)
0.07~0.01 + 0.06
0.07~round(0.01 + 0.06,10)
     I was trimmed~rtrim('     I was trimmed   ')
0.2~sin(asin(0.2))
1~sin(pi()/2)
1~sin(pi()/2) == sin(.5 * pi())
1~sin(0.5 * pi())
hello,5~sprintf('%s,%d','hello',5)
2~sqrt(4)
158~round(stddev(4,5,6,7,8)*100)
hello-----~str_pad('hello',10,'-')
hello     ~str_pad('hello',10)
hello~str_pad('hello',3)
testtesttest~str_repeat('test',3)
I am awesome~str_replace('You are','I am','You are awesome')
I love LimeSurvey~str_replace('like','love','I like LimeSurvey')
1~0==strcasecmp('Hello','hello')
0~0==strcasecmp('Hello','hi')
1~0==strcmp('Hello','Hello')
0~0==strcmp('Hello','hi')
Hi there!~c=strip_tags(d)
hello~strip_tags('<b>hello</b>')
5~stripos('ABCDEFGHI','f')
hi~stripslashes('\\h\\i')
FGHI~stristr('ABCDEFGHI','fg')
5~strlen('12345')
5~strlen(hi)
0~strpos('ABCDEFGHI','f')
5~strpos('ABCDEFGHI','F')
2~strpos('I like LimeSurvey','like')
54321~strrev('12345')
0~strstr('ABCDEFGHI','fg')
FGHI~strstr('ABCDEFGHI','FG')
hi there!~strtolower(c)
HI THERE!~strtoupper(c)
3600~strtotime("27 Mar 1976 8:20")-strtotime("1976/03/27 7:20")
10~(strtotime("13 Apr 2013")-strtotime("2013-04-03"))/60/60/24
1985-11-05 00:00:00~date("Y-m-d H:i:s",strtotime("05 Nov 1985"))
HOURS PASSED SINCE 1970~round(strtotime("now")/60/60)
~""
1985-11-05 00:00:00~date("Y-m-d H:i:s",strtotime("11/5/85"))
2010-08-09 00:00:00~date("Y-m-d H:i:s",strtotime("8/9/10"))
2010-08-09 00:00:00~date("Y-m-d H:i:s",strtotime("8/9/2010"))
2010-08-09 00:00:00~date("Y-m-d H:i:s",strtotime("2010/8/9"))
~""
1985-11-05 00:00:00~date("Y-m-d H:i:s",strtotime("85-11-5"))
2010-08-09 00:00:00~date("Y-m-d H:i:s",strtotime("10-8-9"))
2010-08-09 00:00:00~date("Y-m-d H:i:s",strtotime("9-8-2010"))
2010-08-09 00:00:00~date("Y-m-d H:i:s",strtotime("2010-8-9"))
~""
1985-11-05 00:53:20~date("Y-m-d H:i:s",strtotime("85-11-5 0:53:20"))
2010-08-09 00:53:20~date("Y-m-d H:i:s",strtotime("10-8-9 0:53:20"))
2010-08-09 11:12:13~date("Y-m-d H:i:s",strtotime("9-8-2010 11:12:13"))
2010-08-09 11:12:13~date("Y-m-d H:i:s",strtotime("2010-8-9 11:12:13"))
~""
Today 11:11:59~date("Y-m-d H:i:s",strtotime("11.11.59"))
Today 9:08:10~date("Y-m-d H:i:s",strtotime("9.8.10"))
2010-08-09 00:00:00~date("Y-m-d H:i:s",strtotime("9.8.2010"))
~""
1985-11-05 00:53:20~date("Y-m-d H:i:s",strtotime("5.11.85 0:53:20"))
2010-08-09 11:12:13~date("Y-m-d H:i:s",strtotime("9.8.2010 11:12:13"))
~""
1970-01-01 00:00:00~date("Y-m-d H:i:s",strtotime("70-01-01"))
1999-01-01 00:00:00~date("Y-m-d H:i:s",strtotime("99-01-01"))
2001-01-01 00:00:00~date("Y-m-d H:i:s",strtotime("01-01-01"))
1902-01-01 00:00:00~date("Y-m-d H:i:s",strtotime("1902-01-01"))
~""
today 2:15:00~date("Y-m-d H:i:s",strtotime("2:15:00"))
Some dates that are not (correctly) parsed:~"Some dates that are not (correctly) parsed:"
1969-01-19 00:00:00~date("Y-m-d H:i:s",strtotime("69-01-19"))
1985-11-05 00:00:00~date("Y-m-d H:i:s",strtotime("85/11/5"))
1985-11-05 00:00:00~date("Y-m-d H:i:s",strtotime("5-11-85"))
2010-08-09 00:00:00~date("Y-m-d H:i:s",strtotime("2010.8.9"))
1985-11-05 00:00:00~date("Y-m-d H:i:s",strtotime("85.11.5"))
1985-11-05 00:53:20~date("Y-m-d H:i:s",strtotime("85.11.5 0:53:20"))
2010-08-09 11:12:13~date("Y-m-d H:i:s",strtotime("9.8.10 11:12:13"))
678~substr('1234567890',5,3)
15~sum(1,2,3,4,5)
15~sum(one,two,three,four,five)
0.2~tan(atan(0.2))
IGNORE THIS ERROR~time()
I was trimmed~trim('     I was trimmed   ')
Hi There You~ucwords('hi there you')
<b>EXPRESSIONS</b>~'<b>EXPRESSIONS</b>'
1~!'0'
1~0 eq '0'
0~0 ne '0'
0~0 eq empty
1~0 ne empty
0~0 eq ''
1~0 ne ''
0~'' < 10
0~0 < empty
1~0 <= empty
0~0 > empty
1~0 >= empty
0~'0' eq empty
1~'0' ne empty
0~'0' < empty
1~'0' <= empty
0~'0' > empty
1~'0' >= empty
1~empty eq empty
0~empty ne empty
0~'' > 0
0~' ' > 0
1~!0
0~!' '
0~!'A'
0~!1
0~!'1'
1~!''
1~!empty
1~'0'==0
0~'A'>0
0~'A'<0
0~'A'==0
0~'A'>=0
0~'A'<=0
0~0>'A'
0~0>='B'
0~0=='C'
0~0<'D'
0~0<='E'
1~0!='F'
1~'A' or 'B'
1~'A' and 'B'
0~'A' eq 'B'
1~'A' ne 'B'
1~'A' < 'B'
1~'A' <= 'B'
0~'A' > 'B'
0~'A' >= 'B'
AB~'A' + 'B'
NAN~'A' - 'B'
NAN~'A' * 'B'
NAN~'A' / 'B'
1~'A' or empty
0~'A' and empty
0~'A' eq empty
1~'A' ne empty
0~'A' < empty
0~'A' <= empty
1~'A' > empty
1~'A' >= empty
A~'A' + empty
NAN~'A' - empty
NAN~'A' * empty
NAN~'A' / empty
0~0 or empty
0~0 and empty
0~0 + empty
0~0 - empty
0~0 * empty
NAN~0 / empty
0~(-1 > 0)
0~zero
~empty
1~five > zero
1~five > empty
1~empty < 16
1~zero == empty
3~q5pointChoice.code
5~q5pointChoice.type
(question for q5pointChoice)~q5pointChoice.question
1~q5pointChoice.relevance
4~q5pointChoice.NAOK + 1
NULL~q5pointChoice.bogus
14~q5pointChoice.qid
7~qArrayNumbers_ls1_min.code
1~(one * (two + (three - four) + five) / six)
2.4~(one  * two) + (three * four) / (five * six)
50~12X34X56 * 12X3X5lab1_ber
1~c == 'Hi there!'
1~c == "Hi there!"
3~a=three
3~c=a
12~c*=four
15~c+=a
5~c/=a
-1~c-=six
24~one * two * three * four
-4~five - four - three - two
0~two * three - two - two - two
4~two * three - two
105~5 + 1, 7 * 15
7~7
15~10 + 5
24~12 * 2
10~13 - 3
3.5~14 / 4
5~3 + 1 * 2
1~one
there~hi
6.25~one * two - three / four + five
1~one + hi
1~two > one
1~two gt one
1~three >= two
1~three ge  two
0~four < three
0~four lt three
0~four <= three
0~four le three
0~four == three
0~four eq three
1~four != three
0~four ne four
NAN~one * hi
0~a='hello',b='',c=0
hello~a
0~c
0~one && 0
0~two and 0
1~five && 6
1~seven && eight
1~one or 0
1~one || 0
1~(one and 0) || (two and three)
value for {QID}~QID
"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"~ASSESSMENT_HEADING
"can single quoted strings" . 'contain nested 'quoted sections'?~QUESTIONHELP
Can strings have embedded <tags> like <html>, or even unbalanced "quotes or entities without terminal semicolons like &amp and  &lt?~QUESTION_HELP
value for {TOKEN:FIRSTNAME}~TOKEN:FIRSTNAME
value for {THEREAREXQUESTIONS}~THEREAREXQUESTIONS
15~12X3X5lab1_ber#1
1~three == three
1~three == 3
11~eleven
144~twelve * twelve
0~!three
8~five + + three
2~five + - three
<b>SYNTAX ERRORS</b>~'<b>SYNTAX ERRORS</b>'
NULL~*
NULL~three +
NULL~four * / seven
NULL~(five - three
NULL~five + three)
NULL~seven + = four
NULL~>
NULL~five > > three
NULL~seven > = four
NULL~seven >=
NULL~three &&
NULL~three ||
NULL~three +
NULL~three >=
NULL~three +=
NULL~three !
NULL~three *
NULL~five ! three
NULL~(5 + 7) = 8
NULL~&& four
NULL~min(
NULL~max three, four, five)
NULL~three four
NULL~max(three,four,five) six
NULL~WELCOME='Good morning'
NULL~TOKEN:FIRSTNAME='Tom'
NULL~NUMBEROFQUESTIONS+=3
NULL~NUMBEROFQUESTIONS*=4
NULL~NUMBEROFQUESTIONS/=5
NULL~NUMBEROFQUESTIONS-=6
NULL~'Tom'='tired'
NULL~max()
NULL~convert_value( 10, 1, '0,5,10,15,20', '0,5,10,15') 
100~convert_value( 10, 1, '0,5,10,15,20', '0,50,100,150,200')
NULL~convert_value( 10, 0, '0,5,10,15,20', '0,50,100,150,200')
100~convert_value( 8, 0, '0,5,10,15,20', '0,50,100,150,200')
100~convert_value( 12, 0, '0,5,10,15,20', '0,50,100,150,200')
0~convert_value( 0, 0, '0,5,10,15,20', '0,50,100,150,200')
0~convert_value( -10000, 0, '0,5,10,15,20', '0,50,100,150,200')
NULL~convert_value( -10000, 1, '0,5,10,15,20', '0,50,100,150,200')
200~convert_value( 20, 0, '0,5,10,15,20', '0,50,100,150,200')
200~convert_value( 20, 1, '0,5,10,15,20', '0,50,100,150,200')
200~convert_value( 30, 0, '0,5,10,15,20', '0,50,100,150,200')
NULL~convert_value( 30, 1, '0,5,10,15,20', '0,50,100,150,200')
EOD;
        $atests = explode("\n", $tests);
        $atests[] = "1\n2\n3~BREAKS";
        $atests[] = "1<br />\n2<br />\n3~nl2br(BREAKS)";
        $atests[] = "hi<br />\nthere<br />\nhow<br />\nare<br />\nyou?~nl2br('hi\\nthere\\nhow\\nare\\nyou?')";
        $atests[] = "hi<br />\nthere,<br />\nuser!~nl2br(implode('\\n','hi','there,','user!'))";
        $LEM =& LimeExpressionManager::singleton();
        $em = new ExpressionManager();
        $LEM->setTempVars($vars);
        //$LEMsessid = 'survey_' . Yii::app()->getConfig('surveyID');
        $LEMsessid = 'survey_12345';
        // manually set relevance status
        $_SESSION[$LEMsessid]['relevanceStatus'] = array();
        foreach ($vars as $var) {
            if (isset($var['qseq'])) {
                $_SESSION[$LEMsessid]['relevanceStatus'][$var['qseq']] = 1;
            }
        }
        $allJsVarnamesUsed = array();
        $body = '';
        $body .= '<table border="1"><tr><th>Expression</th><th>PHP Result</th><th>Expected</th><th>JavaScript Result</th><th>VarNames</th><th>JavaScript Eqn</th></tr>';
        $i = 0;
        $javaScript = array();
        foreach ($atests as $test) {
            ++$i;
            $values = explode("~", $test);
            $expectedResult = array_shift($values);
            $expr = implode("~", $values);
            $resultStatus = 'ok';
            $em->groupSeq = 2;
            $em->questionSeq = 3;
            $status = $em->RDP_Evaluate($expr);
            if ($status) {
                $allJsVarnamesUsed = array_merge($allJsVarnamesUsed, $em->GetJsVarsUsed());
            }
            $result = $em->GetResult();
            $valToShow = $result;
            // htmlspecialchars($result,ENT_QUOTES,'UTF-8',false);
            $expectedToShow = $expectedResult;
            // htmlspecialchars($expectedResult,ENT_QUOTES,'UTF-8',false);
            $body .= "<tr>";
            $body .= "<td>" . $em->GetPrettyPrintString() . "</td>\n";
            if (is_null($result)) {
                $valToShow = "NULL";
            }
            if ($valToShow != $expectedToShow) {
                $resultStatus = 'error';
            }
            $body .= "<td class='" . $resultStatus . "'>" . $valToShow . "</td>\n";
            $body .= '<td>' . $expectedToShow . "</td>\n";
            $javaScript[] = $em->GetJavascriptTestforExpression($expectedToShow, $i);
            $body .= "<td id='test_" . $i . "'>&nbsp;</td>\n";
            $varsUsed = $em->GetVarsUsed();
            if (is_array($varsUsed) and count($varsUsed) > 0) {
                $varDesc = array();
                foreach ($varsUsed as $v) {
                    $varDesc[] = $v;
                }
                $body .= '<td>' . implode(',<br/>', $varDesc) . "</td>\n";
            } else {
                $body .= "<td>&nbsp;</td>\n";
            }
            $jsEqn = $em->GetJavaScriptEquivalentOfExpression();
            if ($jsEqn == '') {
                $body .= "<td>&nbsp;</td>\n";
            } else {
                $body .= '<td>' . $jsEqn . "</td>\n";
            }
            $body .= '</tr>';
        }
        $body .= '</table>';
        $body .= "<script type='text/javascript'>\n";
        $body .= "<!--\n";
        $body .= "var LEMgseq=2;\n";
        $body .= "var LEMmode='group';\n";
        $body .= "function recompute() {\n";
        $body .= implode("\n", $javaScript);
        $body .= "}\n//-->\n</script>\n";
        $allJsVarnamesUsed = array_unique($allJsVarnamesUsed);
        asort($allJsVarnamesUsed);
        $pre = '';
        $pre .= "<h3>Change some Relevance values to 0 to see how it affects computations</h3>\n";
        $pre .= '<table border="1"><tr><th>#</th><th>JsVarname</th><th>Starting Value</th><th>Relevance</th></tr>';
        $i = 0;
        $LEMvarNameAttr = array();
        $LEMalias2varName = array();
        foreach ($allJsVarnamesUsed as $jsVarName) {
            ++$i;
            $pre .= "<tr><td>" . $i . "</td><td>" . $jsVarName;
            foreach ($vars as $k => $v) {
                if ($v['jsName'] == $jsVarName) {
                    $value = $v['code'];
                }
            }
            $pre .= "</td><td>" . $value . "</td><td><input type='text' id='relevance" . $i . "' value='1' onchange='recompute()'/>\n";
            $pre .= "<input type='hidden' id='" . $jsVarName . "' name='" . $jsVarName . "' value='" . $value . "'/>\n";
            $pre .= "</td></tr>\n";
            $LEMalias2varName[] = "'" . substr($jsVarName, 5) . "':'" . $jsVarName . "'";
            $LEMalias2varName[] = "'" . $jsVarName . "':'" . $jsVarName . "'";
            $attrInfo = "'" . $jsVarName . "': {'jsName':'" . $jsVarName . "'";
            $varInfo = $vars[substr($jsVarName, 5)];
            foreach ($varInfo as $k => $v) {
                if ($k == 'code') {
                    continue;
                    // will access it from hidden node
                }
                if ($k == 'shown') {
                    $k = 'shown';
                    $v = htmlspecialchars(preg_replace("/[[:space:]]/", ' ', $v), ENT_QUOTES);
                }
                if ($k == 'jsName') {
                    continue;
                    // since already set
                }
                $attrInfo .= ", '" . $k . "':'" . $v . "'";
            }
            $attrInfo .= ",'qid':" . $i . "}";
            $LEMvarNameAttr[] = $attrInfo;
        }
        $pre .= "</table>\n";
        $pre .= "<script type='text/javascript'>\n";
        $pre .= "<!--\n";
        $pre .= "var LEMalias2varName= {" . implode(",\n", $LEMalias2varName) . "};\n";
        $pre .= "var LEMvarNameAttr= {" . implode(",\n", $LEMvarNameAttr) . "};\n";
        $pre .= "var LEMradix = '.';\n";
        $pre .= "//-->\n</script>\n";
        print $pre;
        print $body;
    }
Exemplo n.º 8
0
    /**
     * Unit test the Evaluator, allowing for passing in of extra functions, variables, and tests
     */
    static function UnitTestEvaluator()
    {
        // Some test cases for Evaluator
        $vars = array('one' => array('sgqa' => 'one', 'code' => 1, 'jsName' => 'java_one', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 4), 'two' => array('sgqa' => 'two', 'code' => 2, 'jsName' => 'java_two', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 4), 'three' => array('sgqa' => 'three', 'code' => 3, 'jsName' => 'java_three', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 4), 'four' => array('sgqa' => 'four', 'code' => 4, 'jsName' => 'java_four', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 1), 'five' => array('sgqa' => 'five', 'code' => 5, 'jsName' => 'java_five', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 1), 'six' => array('sgqa' => 'six', 'code' => 6, 'jsName' => 'java_six', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 1), 'seven' => array('sgqa' => 'seven', 'code' => 7, 'jsName' => 'java_seven', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 5), 'eight' => array('sgqa' => 'eight', 'code' => 8, 'jsName' => 'java_eight', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 5), 'nine' => array('sgqa' => 'nine', 'code' => 9, 'jsName' => 'java_nine', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 5), 'ten' => array('sgqa' => 'ten', 'code' => 10, 'jsName' => 'java_ten', 'readWrite' => 'Y', 'gseq' => 1, 'qseq' => 1), 'half' => array('sgqa' => 'half', 'code' => 0.5, 'jsName' => 'java_half', 'readWrite' => 'Y', 'gseq' => 1, 'qseq' => 1), 'hi' => array('sgqa' => 'hi', 'code' => 'there', 'jsName' => 'java_hi', 'readWrite' => 'Y', 'gseq' => 1, 'qseq' => 1), 'hello' => array('sgqa' => 'hello', 'code' => "Tom", 'jsName' => 'java_hello', 'readWrite' => 'Y', 'gseq' => 1, 'qseq' => 1), 'a' => array('sgqa' => 'a', 'code' => 0, 'jsName' => 'java_a', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 2), 'b' => array('sgqa' => 'b', 'code' => 0, 'jsName' => 'java_b', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 2), 'c' => array('sgqa' => 'c', 'code' => 0, 'jsName' => 'java_c', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 2), 'd' => array('sgqa' => 'd', 'code' => 0, 'jsName' => 'java_d', 'readWrite' => 'Y', 'gseq' => 2, 'qseq' => 2), 'eleven' => array('sgqa' => 'eleven', 'code' => 11, 'jsName' => 'java_eleven', 'readWrite' => 'Y', 'gseq' => 1, 'qseq' => 1), 'twelve' => array('sgqa' => 'twelve', 'code' => 12, 'jsName' => 'java_twelve', 'readWrite' => 'Y', 'gseq' => 1, 'qseq' => 1), 'ASSESSMENT_HEADING' => array('sgqa' => 'ASSESSMENT_HEADING', 'code' => '"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"', 'jsName' => '', 'readWrite' => 'N'), 'QID' => array('sgqa' => 'QID', 'code' => 'value for {QID}', 'jsName' => '', 'readWrite' => 'N'), 'QUESTIONHELP' => array('sgqa' => 'QUESTIONHELP', 'code' => '"can single quoted strings" . \'contain nested \'quoted sections\'?', 'jsName' => '', 'readWrite' => 'N'), 'QUESTION_HELP' => array('sgqa' => 'QUESTION_HELP', 'code' => 'Can strings have embedded <tags> like <html>, or even unbalanced "quotes or entities without terminal semicolons like &amp and  &lt?', 'jsName' => '', 'readWrite' => 'N'), 'NUMBEROFQUESTIONS' => array('sgqa' => 'NUMBEROFQUESTIONS', 'code' => 'value for {NUMBEROFQUESTIONS}', 'jsName' => '', 'readWrite' => 'N'), 'THEREAREXQUESTIONS' => array('sgqa' => 'THEREAREXQUESTIONS', 'code' => 'value for {THEREAREXQUESTIONS}', 'jsName' => '', 'readWrite' => 'N'), 'TOKEN:FIRSTNAME' => array('sgqa' => 'TOKEN:FIRSTNAME', 'code' => 'value for {TOKEN:FIRSTNAME}', 'jsName' => '', 'readWrite' => 'N'), 'WELCOME' => array('sgqa' => 'WELCOME', 'code' => 'value for {WELCOME}', 'jsName' => '', 'readWrite' => 'N'), '12X34X56' => array('sgqa' => '12X34X56', 'code' => 5, 'jsName' => '', 'readWrite' => 'N', 'gseq' => 1, 'qseq' => 1), '12X3X5lab1_ber' => array('sgqa' => '12X3X5lab1_ber', 'code' => 10, 'jsName' => '', 'readWrite' => 'N', 'gseq' => 1, 'qseq' => 1), 'q5pointChoice' => array('sgqa' => 'q5pointChoice', 'code' => 3, 'jsName' => 'java_q5pointChoice', 'readWrite' => 'N', 'shown' => 'Father', 'relevance' => 1, 'type' => '5', 'question' => '(question for q5pointChoice)', 'qid' => 14, 'gseq' => 2, 'qseq' => 14), 'qArrayNumbers_ls1_min' => array('sgqa' => 'qArrayNumbers_ls1_min', 'code' => 7, 'jsName' => 'java_qArrayNumbers_ls1_min', 'readWrite' => 'N', 'shown' => 'I love LimeSurvey', 'relevance' => 1, 'type' => 'A', 'question' => '(question for qArrayNumbers)', 'qid' => 6, 'gseq' => 2, 'qseq' => 6), '12X3X5lab1_ber#1' => array('sgqa' => '12X3X5lab1_ber#1', 'code' => 15, 'jsName' => '', 'readWrite' => 'N', 'gseq' => 1, 'qseq' => 1), 'zero' => array('sgqa' => 'zero', 'code' => 0, 'jsName' => 'java_zero', 'gseq' => 0, 'qseq' => 0), 'empty' => array('sgqa' => 'empty', 'code' => '', 'jsName' => 'java_empty', 'gseq' => 0, 'qseq' => 0), 'BREAKS' => array('sgqa' => 'BREAKS', 'code' => '1\\n2\\n3', 'jsName' => '', 'readWrite' => 'N'));
        // Syntax for $tests is
        // expectedResult~expression
        // if the expected result is an error, use NULL for the expected result
        $tests = <<<EOD
<b>SETUP</b>~'<b>SETUP</b>'
&quot;Can strings contain embedded \\&quot;quoted passages\\&quot; (and parentheses + other characters?)?&quot;~a=htmlspecialchars(ASSESSMENT_HEADING)
&quot;can single quoted strings&quot; . &#039;contain nested &#039;quoted sections&#039;?~b=htmlspecialchars(QUESTIONHELP)
Can strings have embedded &lt;tags&gt; like &lt;html&gt;, or even unbalanced &quot;quotes or entities without terminal semicolons like &amp;amp and  &amp;lt?~c=htmlspecialchars(QUESTION_HELP)
<span id="d" style="border-style: solid; border-width: 2px; border-color: green">Hi there!</span>~d='<span id="d" style="border-style: solid; border-width: 2px; border-color: green">Hi there!</span>'
<b>FUNCTIONS</b>~'<b>FUNCTIONS</b>'
5~abs(five)
5~abs(-five)
0.2~acos(cos(0.2))
0~acos(cos(pi()))-pi()
&quot;Can strings contain embedded \\&quot;quoted passages\\&quot; (and parentheses + other characters?)?&quot;~addslashes(a)
&quot;can single quoted strings&quot; . &#039;contain nested &#039;quoted sections&#039;?~addslashes(b)
Can strings have embedded &lt;tags&gt; like &lt;html&gt;, or even unbalanced &quot;quotes or entities without terminal semicolons like &amp;amp and  &amp;lt?~addslashes(c)
0.2~asin(sin(0.2))
0.2~atan(tan(0.2))
0~atan2(0,1)
1~ceil(0.3)
1~ceil(0.7)
0~ceil(-0.3)
0~ceil(-0.7)
10~ceil(9.1)
1~checkdate(1,29,1967)
0~checkdate(2,29,1967)
0.2~cos(acos(0.2))
5~count(1,2,3,4,5)
0~count()
5~count(one,two,three,four,five)
2~count(a,'',c)
NULL~date('F j, Y, g:i a',time())
April 5, 2006, 1:02 am~date('F j, Y, g:i a',mktime(1,2,3,4,5,6))
20~floor(exp(3))
0~floor(asin(sin(pi())))
9~floor(9.9)
3~floor(pi())
January 12, 2012, 5:27 pm~date('F j, Y, g:i a',1326410867)
January 12, 2012, 11:27 pm~gmdate('F j, Y, g:i a',1326410867)
"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"~html_entity_decode(a)
"can single quoted strings" . &#039;contain nested &#039;quoted sections&#039;?~html_entity_decode(b)
Can strings have embedded <tags> like <html>, or even unbalanced "quotes or entities without terminal semicolons like &amp and  &lt?~html_entity_decode(c)
&quot;Can strings contain embedded \\&quot;quoted passages\\&quot; (and parentheses + other characters?)?&quot;~htmlentities(a)
&quot;can single quoted strings&quot; . &#039;contain nested &#039;quoted sections&#039;?~htmlentities(b)
Can strings have embedded &lt;tags&gt; like &lt;html&gt;, or even unbalanced &quot;quotes or entities without terminal semicolons like &amp;amp and &amp;lt?~htmlentities(c)
1~c==htmlspecialchars(htmlspecialchars_decode(c))
1~b==htmlspecialchars(htmlspecialchars_decode(b))
1~a==htmlspecialchars(htmlspecialchars_decode(a))
"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"~htmlspecialchars_decode(a)
"can single quoted strings" . 'contain nested 'quoted sections'?~htmlspecialchars_decode(b)
Can strings have embedded like , or even unbalanced "quotes or entities without terminal semicolons like & and <?~htmlspecialchars_decode(c)
"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"~htmlspecialchars(a)
"can single quoted strings" . 'contain nested 'quoted sections'?~htmlspecialchars(b)
Can strings have embedded <tags> like <html>, or even unbalanced "quotes or entities without terminal semicolons like &amp and &lt?~htmlspecialchars(c)
9~idate('B',1326410867)
0~if('0',1,0)
0~if(0,1,0)
1~if(!0,1,0)
0~if(!(!0),1,0)
1~if('true',1,0)
1~if('false',1,0)
1~if('00',1,0)
0~if('',1,0)
1~if('A',1,0)
0~if(empty,1,0)
4~if(5 > 7,2,4)
1~if(' ',1,0)
there~if((one > two),'hi','there')
64~if((one < two),pow(2,6),pow(6,2))
H e l l o~implode(' ','H','e','l','l','o')
1|2|3|4|5~implode('|',one,two,three,four,five)
4~intval('4')
4~intval('100',2)
5~intval(5.7)
0~is_empty(four)
1~is_empty(empty)
1~is_empty('')
0~is_empty(0)
0~is_empty('0')
0~is_empty('false')
0~is_empty('NULL')
0~is_empty(1)
1~is_empty(one==two)
0~!is_empty(one==two)
1~is_float(half)
0~is_float(one)
1~is_float(pi())
0~is_float(5)
0~is_int(half)
1~is_int(one)
0~is_nan(half)
1~is_nan(WELCOME)
1~is_null(sdfjskdfj)
0~is_null(four)
0~is_numeric(empty)
1~is_numeric('1')
1~is_numeric(four)
0~is_numeric('hi')
1~is_numeric(five)
0~is_numeric(hi)
0~is_string(four)
1~is_string('hi')
1~is_string(hi)
1, 2, 3, 4, 5~list(one,two,three,min(four,five,six),max(three,four,five))
11, 12~list(eleven,twelve)
0, 1, 3, 5~list(0,one,'',three,'',five)
1~log(exp(1))
2~log(exp(2))
I was trimmed   ~ltrim('     I was trimmed   ')
10~max(5,6,10,-20)
6~max(five,(one + (two * four)- three))
6~max((one + (two * four)- three))
212~5 + max(1,(2+3),(4 + (5 + 6)),((7 + 8) + 9),((10 + 11), 12),(13 + (14 * 15) - 16))
29~five + max(one, (two + three), (four + (five + six)),((seven + eight) + nine),((ten + eleven), twelve),(one + (two * three) - four))
1024~max(one,(two*three),pow(four,five),six)
2~max(one,two)
5~max(one,two,three,four,five)
-5~min(-5,10,15,12,-3)
1~min(five,four,one,two,three)
1344765967~mktime(5,6,7,8)
1144191723~mktime(1,2,3,4,5,6)
1\\n2\\n3~nl2br(BREAKS)
1,000~number_format(1000)
1,000.23~number_format(1000.23)
1,234,567~number_format(1234567)
315~ceil(100*pi())
1~pi() == pi() * 2 - pi()
4~pow(2,2)
27~pow(3,3)
=~quoted_printable_decode(quoted_printable_encode('='))
1\\n2\\n3=~nl2br(quoted_printable_decode(quoted_printable_encode(BREAKS)+'='))
\\\$~quotemeta('\$')
IGNORE THIS ERROR~rand(3,5)
0~(a=rand())-a
1~regexMatch('/embedded/',c)
1~regexMatch('/^.*embedded.*\$/',c)
0~regexMatch('/joe/',c)
1~regexMatch('/(?:dog|cat)food/','catfood stinks')
1~regexMatch('/(?:dog|cat)food/','catfood stinks')
1~regexMatch('/[0-9]{3}-[0-9]{2}-[0-9]{4}/','123-45-6789')
1~regexMatch('/\\d{3}-\\d{2}-\\d{4}/','123-45-6789')
1~regexMatch('/(?:\\(\\d{3}\\))\\s*\\d{3}-\\d{4}/','(212) 555-1212')
0~round(0.2)
1~round(.8)
0.07~0.01 + 0.06
0.07~round(0.01 + 0.06,10)
     I was trimmed~rtrim('     I was trimmed   ')
0.2~sin(asin(0.2))
1~sin(pi()/2)
1~sin(pi()/2) == sin(.5 * pi())
1~sin(0.5 * pi())
hello,5~sprintf('%s,%d','hello',5)
2~sqrt(4)
158~round(stddev(4,5,6,7,8)*100)
hello-----~str_pad('hello',10,'-')
hello     ~str_pad('hello',10)
hello~str_pad('hello',3)
testtesttest~str_repeat('test',3)
I am awesome~str_replace('You are','I am','You are awesome')
I love LimeSurvey~str_replace('like','love','I like LimeSurvey')
1~0==strcasecmp('Hello','hello')
0~0==strcasecmp('Hello','hi')
1~0==strcmp('Hello','Hello')
0~0==strcmp('Hello','hi')
Hi there!~c=strip_tags(d)
hello~strip_tags('<b>hello</b>')
5~stripos('ABCDEFGHI','f')
hi~stripslashes('\\h\\i')
FGHI~stristr('ABCDEFGHI','fg')
5~strlen('12345')
5~strlen(hi)
0~strpos('ABCDEFGHI','f')
5~strpos('ABCDEFGHI','F')
2~strpos('I like LimeSurvey','like')
54321~strrev('12345')
0~strstr('ABCDEFGHI','fg')
FGHI~strstr('ABCDEFGHI','FG')
hi there!~strtolower(c)
HI THERE!~strtoupper(c)
678~substr('1234567890',5,3)
15~sum(1,2,3,4,5)
15~sum(one,two,three,four,five)
0.2~tan(atan(0.2))
IGNORE THIS ERROR~time()
I was trimmed~trim('     I was trimmed   ')
Hi There You~ucwords('hi there you')
<b>EXPRESSIONS</b>~'<b>EXPRESSIONS</b>'
1~!'0'
1~0 eq '0'
0~0 ne '0'
0~0 eq empty
1~0 ne empty
0~0 eq ''
1~0 ne ''
0~'' < 10
0~0 < empty
1~0 <= empty
0~0 > empty
1~0 >= empty
0~'0' eq empty
1~'0' ne empty
0~'0' < empty
1~'0' <= empty
0~'0' > empty
1~'0' >= empty
1~empty eq empty
0~empty ne empty
0~'' > 0
0~' ' > 0
1~!0
0~!' '
0~!'A'
0~!1
0~!'1'
1~!''
1~!empty
1~'0'==0
0~'A'>0
0~'A'<0
0~'A'==0
0~'A'>=0
0~'A'<=0
0~0>'A'
0~0>='B'
0~0=='C'
0~0<'D'
0~0<='E'
1~0!='F'
1~'A' or 'B'
1~'A' and 'B'
0~'A' eq 'B'
1~'A' ne 'B'
1~'A' < 'B'
1~'A' <= 'B'
0~'A' > 'B'
0~'A' >= 'B'
AB~'A' + 'B'
NAN~'A' - 'B'
NAN~'A' * 'B'
NAN~'A' / 'B'
1~'A' or empty
0~'A' and empty
0~'A' eq empty
1~'A' ne empty
0~'A' < empty
0~'A' <= empty
1~'A' > empty
1~'A' >= empty
A~'A' + empty
NAN~'A' - empty
NAN~'A' * empty
NAN~'A' / empty
0~0 or empty
0~0 and empty
0~0 + empty
0~0 - empty
0~0 * empty
NAN~0 / empty
0~(-1 > 0)
0~zero
~empty
1~five > zero
1~five > empty
1~empty < 16
1~zero == empty
3~q5pointChoice.code
5~q5pointChoice.type
(question for q5pointChoice)~q5pointChoice.question
1~q5pointChoice.relevance
4~q5pointChoice.NAOK + 1
NULL~q5pointChoice.bogus
14~q5pointChoice.qid
7~qArrayNumbers_ls1_min.code
1~(one * (two + (three - four) + five) / six)
2.4~(one  * two) + (three * four) / (five * six)
50~12X34X56 * 12X3X5lab1_ber
1~c == 'Hi there!'
1~c == "Hi there!"
3~a=three
3~c=a
12~c*=four
15~c+=a
5~c/=a
-1~c-=six
24~one * two * three * four
-4~five - four - three - two
0~two * three - two - two - two
4~two * three - two
105~5 + 1, 7 * 15
7~7
15~10 + 5
24~12 * 2
10~13 - 3
3.5~14 / 4
5~3 + 1 * 2
1~one
there~hi
6.25~one * two - three / four + five
1~one + hi
1~two > one
1~two gt one
1~three >= two
1~three ge  two
0~four < three
0~four lt three
0~four <= three
0~four le three
0~four == three
0~four eq three
1~four != three
0~four ne four
NAN~one * hi
0~a='hello',b='',c=0
hello~a
0~c
0~one && 0
0~two and 0
1~five && 6
1~seven && eight
1~one or 0
1~one || 0
1~(one and 0) || (two and three)
value for {QID}~QID
"Can strings contain embedded \\"quoted passages\\" (and parentheses + other characters?)?"~ASSESSMENT_HEADING
"can single quoted strings" . 'contain nested 'quoted sections'?~QUESTIONHELP
Can strings have embedded <tags> like <html>, or even unbalanced "quotes or entities without terminal semicolons like &amp and  &lt?~QUESTION_HELP
value for {TOKEN:FIRSTNAME}~TOKEN:FIRSTNAME
value for {THEREAREXQUESTIONS}~THEREAREXQUESTIONS
15~12X3X5lab1_ber#1
1~three == three
1~three == 3
11~eleven
144~twelve * twelve
0~!three
8~five + + three
2~five + - three
<b>SYNTAX ERRORS</b>~'<b>SYNTAX ERRORS</b>'
NULL~*
NULL~three +
NULL~four * / seven
NULL~(five - three
NULL~five + three)
NULL~seven + = four
NULL~>
NULL~five > > three
NULL~seven > = four
NULL~seven >=
NULL~three &&
NULL~three ||
NULL~three +
NULL~three >=
NULL~three +=
NULL~three !
NULL~three *
NULL~five ! three
NULL~(5 + 7) = 8
NULL~&& four
NULL~min(
NULL~max three, four, five)
NULL~three four
NULL~max(three,four,five) six
NULL~WELCOME='Good morning'
NULL~TOKEN:FIRSTNAME='Tom'
NULL~NUMBEROFQUESTIONS+=3
NULL~NUMBEROFQUESTIONS*=4
NULL~NUMBEROFQUESTIONS/=5
NULL~NUMBEROFQUESTIONS-=6
NULL~'Tom'='tired'
NULL~max()
EOD;
        $LEM =& LimeExpressionManager::singleton();
        $em = new ExpressionManager();
        $LEM->setTempVars($vars);
        // manually set relevance status
        $_SESSION['relevanceStatus'] = array();
        foreach ($vars as $var) {
            if (isset($var['qseq'])) {
                $_SESSION['relevanceStatus'][$var['qseq']] = 1;
            }
        }
        $allJsVarnamesUsed = array();
        $body = '';
        $body .= '<table border="1"><tr><th>Expression</th><th>PHP Result</th><th>Expected</th><th>JavaScript Result</th><th>VarNames</th><th>JavaScript Eqn</th></tr>';
        $i = 0;
        $javaScript = array();
        foreach (explode("\n", $tests) as $test) {
            ++$i;
            $values = explode("~", $test);
            $expectedResult = array_shift($values);
            $expr = implode("~", $values);
            $resultStatus = 'ok';
            $em->groupSeq = 2;
            $em->questionSeq = 3;
            $status = $em->RDP_Evaluate($expr);
            if ($status) {
                $allJsVarnamesUsed = array_merge($allJsVarnamesUsed, $em->GetJsVarsUsed());
            }
            $result = $em->GetResult();
            $valToShow = $result;
            // htmlspecialchars($result,ENT_QUOTES,'UTF-8',false);
            $expectedToShow = $expectedResult;
            // htmlspecialchars($expectedResult,ENT_QUOTES,'UTF-8',false);
            $body .= "<tr>";
            $body .= "<td>" . $em->GetPrettyPrintString() . "</td>\n";
            if (is_null($result)) {
                $valToShow = "NULL";
            }
            if ($valToShow != $expectedToShow) {
                $resultStatus = 'error';
            }
            $body .= "<td class='" . $resultStatus . "'>" . $valToShow . "</td>\n";
            $body .= '<td>' . $expectedToShow . "</td>\n";
            $javaScript[] = $em->GetJavascriptTestforExpression($expectedToShow, $i);
            $body .= "<td id='test_" . $i . "'>&nbsp;</td>\n";
            $varsUsed = $em->GetVarsUsed();
            if (is_array($varsUsed) and count($varsUsed) > 0) {
                $varDesc = array();
                foreach ($varsUsed as $v) {
                    $varDesc[] = $v;
                }
                $body .= '<td>' . implode(',<br/>', $varDesc) . "</td>\n";
            } else {
                $body .= "<td>&nbsp;</td>\n";
            }
            $jsEqn = $em->GetJavaScriptEquivalentOfExpression();
            if ($jsEqn == '') {
                $body .= "<td>&nbsp;</td>\n";
            } else {
                $body .= '<td>' . $jsEqn . "</td>\n";
            }
            $body .= '</tr>';
        }
        $body .= '</table>';
        $body .= "<script type='text/javascript'>\n";
        $body .= "<!--\n";
        $body .= "var LEMgid=2;\n";
        $body .= "var LEMmode='group';\n";
        $body .= "function recompute() {\n";
        $body .= implode("\n", $javaScript);
        $body .= "}\n//-->\n</script>\n";
        $allJsVarnamesUsed = array_unique($allJsVarnamesUsed);
        asort($allJsVarnamesUsed);
        $pre = '';
        $pre .= "<h3>Change some Relevance values to 0 to see how it affects computations</h3>\n";
        $pre .= '<table border="1"><tr><th>#</th><th>JsVarname</th><th>Starting Value</th><th>Relevance</th></tr>';
        $i = 0;
        $LEMvarNameAttr = array();
        $LEMalias2varName = array();
        foreach ($allJsVarnamesUsed as $jsVarName) {
            ++$i;
            $pre .= "<tr><td>" . $i . "</td><td>" . $jsVarName;
            foreach ($vars as $k => $v) {
                if ($v['jsName'] == $jsVarName) {
                    $value = $v['code'];
                }
            }
            $pre .= "</td><td>" . $value . "</td><td><input type='text' id='relevance" . $i . "' value='1' onchange='recompute()'/>\n";
            $pre .= "<input type='hidden' id='" . $jsVarName . "' name='" . $jsVarName . "' value='" . $value . "'/>\n";
            $pre .= "</td></tr>\n";
            $LEMalias2varName[] = "'" . substr($jsVarName, 5) . "':'" . $jsVarName . "'";
            $LEMalias2varName[] = "'" . $jsVarName . "':'" . $jsVarName . "'";
            $attrInfo = "'" . $jsVarName . "': {'jsName':'" . $jsVarName . "'";
            $varInfo = $vars[substr($jsVarName, 5)];
            foreach ($varInfo as $k => $v) {
                if ($k == 'code') {
                    continue;
                    // will access it from hidden node
                }
                if ($k == 'shown') {
                    $k = 'shown';
                    $v = htmlspecialchars(preg_replace("/[[:space:]]/", ' ', $v), ENT_QUOTES);
                }
                if ($k == 'jsName') {
                    continue;
                    // since already set
                }
                $attrInfo .= ", '" . $k . "':'" . $v . "'";
            }
            $attrInfo .= ",'qid':" . $i . "}";
            $LEMvarNameAttr[] = $attrInfo;
        }
        $pre .= "</table>\n";
        $pre .= "<script type='text/javascript'>\n";
        $pre .= "<!--\n";
        $pre .= "var LEMalias2varName= {" . implode(",\n", $LEMalias2varName) . "};\n";
        $pre .= "var LEMvarNameAttr= {" . implode(",\n", $LEMvarNameAttr) . "};\n";
        $pre .= "//-->\n</script>\n";
        print $pre;
        print $body;
    }
Exemplo n.º 9
0
 /**
  * Create HTML view of the survey, showing everything that uses EM
  * @param <type> $sid
  * @param <type> $gid
  * @param <type> $qid
  */
 public static function ShowSurveyLogicFile($sid, $gid = NULL, $qid = NULL, $LEMdebugLevel = 0, $assessments = false)
 {
     // Title
     // Welcome
     // G1, name, relevance, text
     // *Q1, name [type], relevance [validation], text, help, default, help_msg
     // SQ1, name [scale], relevance [validation], text
     // A1, code, assessment_value, text
     // End Message
     global $rooturl;
     $LEM =& LimeExpressionManager::singleton();
     $allErrors = array();
     $warnings = 0;
     $surveyOptions = array('assessments' => $assessments, 'hyperlinkSyntaxHighlighting' => true, 'rooturl' => $rooturl);
     $varNamesUsed = array();
     // keeps track of whether variables have been declared
     if (!is_null($qid)) {
         $surveyMode = 'question';
         LimeExpressionManager::StartSurvey($sid, 'question', $surveyOptions, false, $LEMdebugLevel);
         $qseq = LimeExpressionManager::GetQuestionSeq($qid);
         $moveResult = LimeExpressionManager::JumpTo($qseq + 1, true, false, true);
     } else {
         if (!is_null($gid)) {
             $surveyMode = 'group';
             LimeExpressionManager::StartSurvey($sid, 'group', $surveyOptions, false, $LEMdebugLevel);
             $gseq = LimeExpressionManager::GetGroupSeq($gid);
             $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true, false, true);
         } else {
             $surveyMode = 'survey';
             LimeExpressionManager::StartSurvey($sid, 'survey', $surveyOptions, false, $LEMdebugLevel);
             $moveResult = LimeExpressionManager::NavigateForwards();
         }
     }
     $qtypes = getqtypelist('', 'array');
     if (is_null($moveResult) || is_null($LEM->currentQset) || count($LEM->currentQset) == 0) {
         return array('errors' => 1, 'html' => $LEM->gT('Invalid question - probably missing sub-questions or language-specific settings for language ') . $_SESSION['LEMlang']);
     }
     $surveyname = templatereplace('{SURVEYNAME}');
     $out = '<H3>' . $LEM->gT('Logic File for Survey # ') . '[' . $LEM->sid . "]: {$surveyname}</H3>\n";
     $out .= "<table border='1'>";
     if (is_null($gid) && is_null($qid)) {
         $description = templatereplace('{SURVEYDESCRIPTION}');
         $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
         if ($description != '') {
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("Description:") . "</td><td colspan=2>" . $description . "</td></tr>";
         }
         $welcome = templatereplace('{WELCOME}');
         $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
         if ($welcome != '') {
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("Welcome:") . "</td><td colspan=2>" . $welcome . "</td></tr>";
         }
         $endmsg = templatereplace('{ENDTEXT}');
         $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
         if ($endmsg != '') {
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("End message:") . "</td><td colspan=2>" . $endmsg . "</td></tr>";
         }
         $_linkreplace = templatereplace('{URL}');
         $errClass = $LEM->em->HasErrors() ? 'LEMerror' : '';
         if ($_linkreplace != '') {
             $out .= "<tr class='LEMgroup {$errClass}'><td colspan=2>" . $LEM->gT("End URL") . ":</td><td colspan=2>" . $_linkreplace . "</td></tr>";
         }
     }
     $out .= "<tr><th>#</th><th>" . $LEM->gT('Name [ID]') . "</th><th>" . $LEM->gT('Relevance [Validation] (Default)') . "</th><th>" . $LEM->gT('Text [Help] (Tip)') . "</th></tr>\n";
     $_gseq = -1;
     foreach ($LEM->currentQset as $q) {
         $gseq = $q['info']['gseq'];
         $gid = $q['info']['gid'];
         $qid = $q['info']['qid'];
         $qseq = $q['info']['qseq'];
         $errorCount = 0;
         //////
         // SHOW GROUP-LEVEL INFO
         //////
         if ($gseq != $_gseq) {
             $LEM->ParseResultCache = array();
             // reset for each group so get proper color coding?
             $_gseq = $gseq;
             $ginfo = $LEM->gseq2info[$gseq];
             $grelevance = '{' . ($ginfo['grelevance'] == '' ? 1 : $ginfo['grelevance']) . '}';
             $gtext = trim($ginfo['description']) == '' ? '&nbsp;' : $ginfo['description'];
             $groupRow = "<tr class='LEMgroup'>" . "<td>G-{$gseq}</td>" . "<td><b>" . $ginfo['group_name'] . "</b><br/>[<a target='_blank' href='{$rooturl}/admin/admin.php?action=orderquestions&sid={$sid}&gid={$gid}'>GID " . $gid . "</a>]</td>" . "<td>" . $grelevance . "</td>" . "<td>" . $gtext . "</td>" . "</tr>\n";
             $LEM->ProcessString($groupRow, $qid, NULL, false, 1, 1, false, false);
             $out .= $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
         }
         //////
         // SHOW QUESTION-LEVEL INFO
         //////
         $mandatory = $q['info']['mandatory'] == 'Y' ? "<span style='color:red'>*</span>" : '';
         $type = $q['info']['type'];
         $typedesc = $qtypes[$type]['description'];
         $sgqas = explode('|', $q['sgqa']);
         if (count($sgqas) == 1 && !is_null($q['info']['default'])) {
             $LEM->ProcessString($q['info']['default'], $qid, NULL, false, 1, 1, false, false);
             $_default = $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
             $default = '<br/>(' . $LEM->gT('DEFAULT:') . '  ' . $_default . ')';
         } else {
             $default = '';
         }
         $qtext = $q['info']['qtext'] != '' ? $q['info']['qtext'] : '&nbsp';
         $help = $q['info']['help'] != '' ? '<hr/>[' . $LEM->gT("HELP:") . ' ' . $q['info']['help'] . ']' : '';
         $prettyValidTip = $q['prettyValidTip'] == '' ? '' : '<hr/>(' . $LEM->gT("TIP:") . ' ' . $q['prettyValidTip'] . ')';
         //////
         // SHOW QUESTION ATTRIBUTES THAT ARE PROCESSED BY EM
         //////
         $attrTable = '';
         $attrs = isset($LEM->qattr[$qid]) ? $LEM->qattr[$qid] : array();
         if (isset($LEM->q2subqInfo[$qid]['preg'])) {
             $attrs['regex_validation'] = $LEM->q2subqInfo[$qid]['preg'];
         }
         if (isset($LEM->questionSeq2relevance[$qseq]['other'])) {
             $attrs['other'] = $LEM->questionSeq2relevance[$qseq]['other'];
         }
         if (count($attrs) > 0) {
             $attrTable = "<hr/><table border='1'><tr><th>" . $LEM->gT("Question Attribute") . "</th><th>" . $LEM->gT("Value") . "</th></tr>\n";
             $count = 0;
             foreach ($attrs as $key => $value) {
                 if (is_null($value) || trim($value) == '') {
                     continue;
                 }
                 switch ($key) {
                     default:
                     case 'exclude_all_others':
                     case 'exclude_all_others_auto':
                     case 'hidden':
                         if ($value == false || $value == '0') {
                             $value = NULL;
                             // so can skip this one - just using continue here doesn't work.
                         }
                         break;
                     case 'relevance':
                         $value = NULL;
                         // means an outdate database structure
                         break;
                     case 'array_filter':
                     case 'array_filter_exclude':
                     case 'code_filter':
                     case 'em_validation_q_tip':
                     case 'em_validation_sq_tip':
                         break;
                     case 'equals_num_value':
                     case 'em_validation_q':
                     case 'em_validation_sq':
                     case 'max_answers':
                     case 'max_num_value':
                     case 'max_num_value_n':
                     case 'min_answers':
                     case 'min_num_value':
                     case 'min_num_value_n':
                     case 'min_num_of_files':
                     case 'max_num_of_files':
                     case 'multiflexible_max':
                     case 'multiflexible_min':
                         $value = '{' . $value . '}';
                         break;
                     case 'other_replace_text':
                     case 'show_totals':
                     case 'regex_validation':
                         break;
                     case 'other':
                         if ($value == 'N') {
                             $value = NULL;
                             // so can skip this one
                         }
                         break;
                 }
                 if (is_null($value)) {
                     continue;
                     // since continuing from within a switch statement doesn't work
                 }
                 ++$count;
                 $attrTable .= "<tr><td>{$key}</td><td>{$value}</td></tr>\n";
             }
             $attrTable .= "</table>\n";
             if ($count == 0) {
                 $attrTable = '';
             }
         }
         $LEM->ProcessString($qtext . $help . $prettyValidTip . $attrTable, $qid, NULL, false, 1, 1, false, false);
         $qdetails = $LEM->GetLastPrettyPrintExpression();
         if ($LEM->em->HasErrors()) {
             ++$errorCount;
         }
         //////
         // SHOW RELEVANCE
         //////
         // Must parse Relevance this way, otherwise if try to first split expressions, regex equations won't work
         $relevanceEqn = $q['info']['relevance'] == '' ? 1 : $q['info']['relevance'];
         if (!isset($LEM->ParseResultCache[$relevanceEqn])) {
             $result = $LEM->em->ProcessBooleanExpression($relevanceEqn, $gseq, $qseq);
             $prettyPrint = $LEM->em->GetPrettyPrintString();
             $hasErrors = $LEM->em->HasErrors();
             $LEM->ParseResultCache[$relevanceEqn] = array('result' => $result, 'prettyPrint' => $prettyPrint, 'hasErrors' => $hasErrors);
         }
         $relevance = $LEM->ParseResultCache[$relevanceEqn]['prettyPrint'];
         if ($LEM->ParseResultCache[$relevanceEqn]['hasErrors']) {
             ++$errorCount;
         }
         //////
         // SHOW VALIDATION EQUATION
         //////
         // Must parse Validation this way so that regex (preg) works
         $prettyValidEqn = '';
         if ($q['prettyValidEqn'] != '') {
             $validationEqn = $q['validEqn'];
             if (!isset($LEM->ParseResultCache[$validationEqn])) {
                 $result = $LEM->em->ProcessBooleanExpression($validationEqn, $gseq, $qseq);
                 $prettyPrint = $LEM->em->GetPrettyPrintString();
                 $hasErrors = $LEM->em->HasErrors();
                 $LEM->ParseResultCache[$validationEqn] = array('result' => $result, 'prettyPrint' => $prettyPrint, 'hasErrors' => $hasErrors);
             }
             $prettyValidEqn = '<hr/>(' . $LEM->gT("VALIDATION:") . ' ' . $LEM->ParseResultCache[$validationEqn]['prettyPrint'] . ')';
             if ($LEM->ParseResultCache[$validationEqn]['hasErrors']) {
                 ++$errorCount;
             }
         }
         //////
         // TEST VALIDITY OF ROOT VARIABLE NAME AND WHETHER HAS BEEN USED
         //////
         $rootVarName = $q['info']['rootVarName'];
         $varNameErrorMsg = '';
         $varNameError = NULL;
         if (isset($varNamesUsed[$rootVarName])) {
             $varNameErrorMsg .= $LEM->gT('This variable name has already been used.');
         } else {
             $varNamesUsed[$rootVarName] = array('gseq' => $gseq, 'qid' => $qid);
         }
         if (!preg_match('/^[_a-zA-Z][_0-9a-zA-Z]*$/', $rootVarName)) {
             $varNameErrorMsg .= $LEM->gT('Starting in 1.92, variable names should only contain letters, numbers, and underscores; and may not start with a number. This variable name is deprecated.');
         }
         if ($varNameErrorMsg != '') {
             $varNameError = array('message' => $varNameErrorMsg, 'gseq' => $varNamesUsed[$rootVarName]['gseq'], 'qid' => $varNamesUsed[$rootVarName]['qid'], 'gid' => $gid);
             if (!$LEM->sgqaNaming) {
                 ++$errorCount;
             } else {
                 ++$warnings;
             }
         }
         //////
         // SHOW ALL SUB-QUESTIONS
         //////
         $sqRows = '';
         $i = 0;
         $sawThis = array();
         // array of rowdivids already seen so only show them once
         foreach ($sgqas as $sgqa) {
             if ($LEM->knownVars[$sgqa]['qcode'] == $rootVarName) {
                 continue;
                 // so don't show the main question as a sub-question too
             }
             $rowdivid = $sgqa;
             $varName = $LEM->knownVars[$sgqa]['qcode'];
             switch ($q['info']['type']) {
                 case '1':
                     if (preg_match('/#1$/', $sgqa)) {
                         $rowdivid = NULL;
                         // so that doesn't show same message for second scale
                     } else {
                         $rowdivid = substr($sgqa, 0, -2);
                         // strip suffix
                         $varName = substr($LEM->knownVars[$sgqa]['qcode'], 0, -2);
                     }
                     break;
                 case 'P':
                     if (preg_match('/comment$/', $sgqa)) {
                         $rowdivid = NULL;
                     }
                     break;
                 case ':':
                 case ';':
                     $_rowdivid = $LEM->knownVars[$sgqa]['rowdivid'];
                     if (isset($sawThis[$qid . '~' . $_rowdivid])) {
                         $rowdivid = NULL;
                         // so don't show again
                     } else {
                         $sawThis[$qid . '~' . $_rowdivid] = true;
                         $rowdivid = $_rowdivid;
                         $sgqa_len = strlen($sid . 'X' . $gid . 'X' . $qid);
                         $varName = $rootVarName . '_' . substr($_rowdivid, $sgqa_len);
                     }
                     break;
             }
             if (is_null($rowdivid)) {
                 continue;
             }
             ++$i;
             $subQeqn = '&nbsp;';
             if (isset($LEM->subQrelInfo[$qid][$rowdivid])) {
                 $sq = $LEM->subQrelInfo[$qid][$rowdivid];
                 $subQeqn = $sq['prettyPrintEqn'];
                 // {' . $sq['eqn'] . '}';  // $sq['prettyPrintEqn'];
                 if ($sq['hasErrors']) {
                     ++$errorCount;
                 }
             }
             $sgqaInfo = $LEM->knownVars[$sgqa];
             $subqText = $sgqaInfo['subqtext'];
             if (isset($sgqaInfo['default']) && $sgqaInfo['default'] !== '') {
                 $LEM->ProcessString($sgqaInfo['default'], $qid, NULL, false, 1, 1, false, false);
                 $_default = $LEM->GetLastPrettyPrintExpression();
                 if ($LEM->em->HasErrors()) {
                     ++$errorCount;
                 }
                 $subQeqn .= '<br/>(' . $LEM->gT('DEFAULT:') . '  ' . $_default . ')';
             }
             $sqRows .= "<tr class='LEMsubq'>" . "<td>SQ-{$i}</td>" . "<td><b>" . $varName . "</b></td>" . "<td>{$subQeqn}</td>" . "<td>" . $subqText . "</td>" . "</tr>";
         }
         $LEM->ProcessString($sqRows, $qid, NULL, false, 1, 1, false, false);
         $sqRows = $LEM->GetLastPrettyPrintExpression();
         if ($LEM->em->HasErrors()) {
             ++$errorCount;
         }
         //////
         // SHOW ANSWER OPTIONS FOR ENUMERATED LISTS, AND FOR MULTIFLEXI
         //////
         $answerRows = '';
         if (isset($LEM->qans[$qid]) || isset($LEM->multiflexiAnswers[$qid])) {
             $_scale = -1;
             if (isset($LEM->multiflexiAnswers[$qid])) {
                 $ansList = $LEM->multiflexiAnswers[$qid];
             } else {
                 $ansList = $LEM->qans[$qid];
             }
             foreach ($ansList as $ans => $value) {
                 $ansInfo = explode('~', $ans);
                 $valParts = explode('|', $value);
                 $valInfo[0] = array_shift($valParts);
                 $valInfo[1] = implode('|', $valParts);
                 if ($_scale != $ansInfo[0]) {
                     $i = 1;
                     $_scale = $ansInfo[0];
                 }
                 $subQeqn = '';
                 $rowdivid = $sgqas[0] . $ansInfo[1];
                 if ($q['info']['type'] == 'R') {
                     $rowdivid = $LEM->sid . 'X' . $gid . 'X' . $qid . $ansInfo[1];
                 }
                 if (isset($LEM->subQrelInfo[$qid][$rowdivid])) {
                     $sq = $LEM->subQrelInfo[$qid][$rowdivid];
                     $subQeqn = ' ' . $sq['prettyPrintEqn'];
                     if ($sq['hasErrors']) {
                         ++$errorCount;
                     }
                 }
                 $answerRows .= "<tr class='LEManswer'>" . "<td>A[" . $ansInfo[0] . "]-" . $i++ . "</td>" . "<td><b>" . $ansInfo[1] . "</b></td>" . "<td>[VALUE: " . $valInfo[0] . "]" . $subQeqn . "</td>" . "<td>" . $valInfo[1] . "</td>" . "</tr>\n";
             }
             $LEM->ProcessString($answerRows, $qid, NULL, false, 1, 1, false, false);
             $answerRows = $LEM->GetLastPrettyPrintExpression();
             if ($LEM->em->HasErrors()) {
                 ++$errorCount;
             }
         }
         //////
         // FINALLY, SHOW THE QUESTION ROW(S), COLOR-CODING QUESTIONS THAT CONTAIN ERRORS
         //////
         $errclass = $errorCount > 0 ? "class='LEMerror' title='" . sprintf($LEM->gT("This question has at least %s error(s)"), $errorCount) . "'" : '';
         $questionRow = "<tr class='LEMquestion'>" . "<td {$errclass}>Q-" . $q['info']['qseq'] . "</td>" . "<td><b>" . $mandatory;
         if ($varNameErrorMsg == '') {
             $questionRow .= $rootVarName;
         } else {
             $editlink = $LEM->surveyOptions['rooturl'] . '/admin/admin.php?sid=' . $LEM->sid . '&gid=' . $varNameError['gid'] . '&qid=' . $varNameError['qid'];
             $questionRow .= "<span style='border-style: solid; border-width: 2px; border-color: #FF00FF; color: red;' title='" . $varNameError['message'] . "' " . "onclick='window.open(\"{$editlink}\",\"_blank\")'>" . $rootVarName . "</span>";
         }
         $questionRow .= "</b><br/>[<a target='_blank' href='{$rooturl}/admin/admin.php?action=editquestion&sid={$sid}&gid={$gid}&qid={$qid}'>QID {$qid}</a>]<br/>{$typedesc} [{$type}]</td>" . "<td>" . $relevance . $prettyValidEqn . $default . "</td>" . "<td>" . $qdetails . "</td>" . "</tr>\n";
         $out .= $questionRow;
         $out .= $sqRows;
         $out .= $answerRows;
         if ($errorCount > 0) {
             $allErrors[$gid . '~' . $qid] = $errorCount;
         }
     }
     $out .= "</table>";
     LimeExpressionManager::FinishProcessingPage();
     if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
         $out .= LimeExpressionManager::GetDebugTimingMessage();
     }
     if (count($allErrors) > 0) {
         $out = "<p class='LEMerror'>" . sprintf($LEM->gT("%s question(s) contain errors that need to be corrected"), count($allErrors)) . "</p>\n" . $out;
     } else {
         switch ($surveyMode) {
             case 'survey':
                 $message = $LEM->gT('No syntax errors detected in this survey');
                 break;
             case 'group':
                 $message = $LEM->gT('This group, by itself, does not contain any syntax errors');
                 break;
             case 'question':
                 $message = $LEM->gT('This question, by itself, does not contain any syntax errors');
                 break;
         }
         $out = "<p class='LEMerror'>{$message}</p>\n" . $out;
     }
     return array('errors' => $allErrors, 'html' => $out);
 }
Exemplo n.º 10
0
 /**
  * Send the register email with $_POST value
  * @param $iSurveyId Survey Id to register
  * @return boolean : if email is set to sent (before SMTP problem)
  */
 public function sendRegistrationEmail($iSurveyId, $iTokenId)
 {
     $sLanguage = App()->language;
     $aSurveyInfo = getSurveyInfo($iSurveyId, $sLanguage);
     $aMail['subject'] = $aSurveyInfo['email_register_subj'];
     $aMail['message'] = $aSurveyInfo['email_register'];
     $aReplacementFields = array();
     $aReplacementFields["{ADMINNAME}"] = $aSurveyInfo['adminname'];
     $aReplacementFields["{ADMINEMAIL}"] = $aSurveyInfo['adminemail'];
     $aReplacementFields["{SURVEYNAME}"] = $aSurveyInfo['name'];
     $aReplacementFields["{SURVEYDESCRIPTION}"] = $aSurveyInfo['description'];
     $aReplacementFields["{EXPIRY}"] = $aSurveyInfo["expiry"];
     $oToken = Token::model($iSurveyId)->findByPk($iTokenId);
     // Reload the token (needed if just created)
     foreach ($oToken->attributes as $attribute => $value) {
         $aReplacementFields["{" . strtoupper($attribute) . "}"] = $value;
     }
     $sToken = $oToken->token;
     $useHtmlEmail = getEmailFormat($iSurveyId) == 'html';
     $aMail['subject'] = preg_replace("/{TOKEN:([A-Z0-9_]+)}/", "{" . "\$1" . "}", $aMail['subject']);
     $aMail['message'] = preg_replace("/{TOKEN:([A-Z0-9_]+)}/", "{" . "\$1" . "}", $aMail['message']);
     $aReplacementFields["{SURVEYURL}"] = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}", array('lang' => $sLanguage, 'token' => $sToken));
     $aReplacementFields["{OPTOUTURL}"] = App()->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyId}", array('langcode' => $sLanguage, 'token' => $sToken));
     $aReplacementFields["{OPTINURL}"] = App()->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyId}", array('langcode' => $sLanguage, 'token' => $sToken));
     foreach (array('OPTOUT', 'OPTIN', 'SURVEY') as $key) {
         $url = $aReplacementFields["{{$key}URL}"];
         if ($useHtmlEmail) {
             $aReplacementFields["{{$key}URL}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>';
         }
         $aMail['subject'] = str_replace("@@{$key}URL@@", $url, $aMail['subject']);
         $aMail['message'] = str_replace("@@{$key}URL@@", $url, $aMail['message']);
     }
     // Replace the fields
     $aMail['subject'] = ReplaceFields($aMail['subject'], $aReplacementFields);
     $aMail['message'] = ReplaceFields($aMail['message'], $aReplacementFields);
     $sFrom = "{$aSurveyInfo['adminname']} <{$aSurveyInfo['adminemail']}>";
     $sBounce = getBounceEmail($iSurveyId);
     $sTo = $oToken->email;
     $sitename = Yii::app()->getConfig('sitename');
     // Plugin event for email handling (Same than admin token but with register type)
     $event = new PluginEvent('beforeTokenEmail');
     $event->set('survey', $iSurveyId);
     $event->set('type', 'register');
     $event->set('model', 'register');
     $event->set('subject', $aMail['subject']);
     $event->set('to', $sTo);
     $event->set('body', $aMail['message']);
     $event->set('from', $sFrom);
     $event->set('bounce', $sBounce);
     $event->set('token', $oToken->attributes);
     App()->getPluginManager()->dispatchEvent($event);
     $aMail['subject'] = $event->get('subject');
     $aMail['message'] = $event->get('body');
     $sTo = $event->get('to');
     $sFrom = $event->get('from');
     $sBounce = $event->get('bounce');
     $aRelevantAttachments = array();
     if (isset($aSurveyInfo['attachments'])) {
         $aAttachments = unserialize($aSurveyInfo['attachments']);
         if (!empty($aAttachments)) {
             if (isset($aAttachments['registration'])) {
                 LimeExpressionManager::singleton()->loadTokenInformation($aSurveyInfo['sid'], $sToken);
                 foreach ($aAttachments['registration'] as $aAttachment) {
                     if (LimeExpressionManager::singleton()->ProcessRelevance($aAttachment['relevance'])) {
                         $aRelevantAttachments[] = $aAttachment['url'];
                     }
                 }
             }
         }
     }
     if ($event->get('send', true) == false) {
         $this->sMessage = $event->get('message', $this->sMailMessage);
         // event can send is own message
         if ($event->get('error') == null) {
             $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
             $oToken->sent = $today;
             $oToken->save();
         }
     } elseif (SendEmailMessage($aMail['message'], $aMail['subject'], $sTo, $sFrom, $sitename, $useHtmlEmail, $sBounce, $aRelevantAttachments)) {
         // TLR change to put date into sent
         $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig('timeadjust'));
         $oToken->sent = $today;
         $oToken->save();
         $this->sMessage = "<div id='wrapper' class='message tokenmessage'>" . "<p>" . gT("Thank you for registering to participate in this survey.") . "</p>\n" . "<p>{$this->sMailMessage}</p>\n" . "<p>" . sprintf(gT("Survey administrator %s (%s)"), $aSurveyInfo['adminname'], $aSurveyInfo['adminemail']) . "</p>" . "</div>\n";
     } else {
         $this->sMessage = "<div id='wrapper' class='message tokenmessage'>" . "<p>" . gT("Thank you for registering to participate in this survey.") . "</p>\n" . "<p>" . gT("You are registered but an error happened when trying to send the email - please contact the survey administrator.") . "</p>\n" . "<p>" . sprintf(gT("Survey administrator %s (%s)"), $aSurveyInfo['adminname'], $aSurveyInfo['adminemail']) . "</p>" . "</div>\n";
     }
     // Allways return true : if we come here, we allways trye to send an email
     return true;
 }