} $msgsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray); $sendmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray); $customheaders = array( '1' => "X-surveyid: ".$surveyid, '2' => "X-tokenid: ".$fieldsarray["{TOKEN}"]); 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); } elseif (SendEmailMessage($sendmessage, $msgsubject, $to, $from, $sitename,$ishtml,getBounceEmail($surveyid),null,$customheaders)) { // Put date into remindersent $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n" ."SET remindersent='$today',remindercount = remindercount+1 WHERE tid={$emrow['tid']}"; // $uderesult = $connect->Execute($udequery) or safe_die ("Could not update tokens<br />$udequery<br />".$connect->ErrorMsg()); //orig: $tokenoutput .= "({$emrow['tid']})[".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]<br />\n"; $tokenoutput .= "({$emrow['tid']}) [".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)]<br />\n"; } else { $tokenoutput .= $emrow['tid'] ." ".ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."<br />", $fieldsarray); if ($debug>0)
/** * submitfailed : used in em_manager_helper.php */ function submitfailed($errormsg = '') { global $debug; global $thissurvey; global $subquery, $surveyid; $clang = Yii::app()->lang; $completed = "<br /><strong><font size='2' color='red'>" . $clang->gT("Did Not Save") . "</strong></font><br /><br />\n\n" . $clang->gT("An unexpected error has occurred and your responses cannot be saved.") . "<br /><br />\n"; if ($thissurvey['adminemail']) { $completed .= $clang->gT("Your responses have not been lost and have been emailed to the survey administrator and will be entered into our database at a later point.") . "<br /><br />\n"; if ($debug > 0) { $completed .= 'Error message: ' . htmlspecialchars($errormsg) . '<br />'; } $email = $clang->gT("An error occurred saving a response to survey id", "unescaped") . " " . $thissurvey['name'] . " - {$surveyid}\n\n"; $email .= $clang->gT("DATA TO BE ENTERED", "unescaped") . ":\n"; foreach ($_SESSION['survey_' . $surveyid]['insertarray'] as $value) { $email .= "{$value}: {$_SESSION['survey_' . $surveyid][$value]}\n"; } $email .= "\n" . $clang->gT("SQL CODE THAT FAILED", "unescaped") . ":\n" . "{$subquery}\n\n" . $clang->gT("ERROR MESSAGE", "unescaped") . ":\n" . $errormsg . "\n\n"; SendEmailMessage($email, $clang->gT("Error saving results", "unescaped"), $thissurvey['adminemail'], $thissurvey['adminemail'], "LimeSurvey", false, getBounceEmail($surveyid)); //echo "<!-- EMAIL CONTENTS:\n$email -->\n"; //An email has been sent, so we can kill off this session. killSurveySession($surveyid); } else { $completed .= "<a href='javascript:location.reload()'>" . $clang->gT("Try to submit again") . "</a><br /><br />\n"; $completed .= $subquery; } return $completed; }
} if ($saver['email']) { //Send email if (validate_email($saver['email']) && !returnglobal('redo')) { $subject = $clang->gT("Saved Survey Details"); $message = $clang->gT("Thank you for saving your survey in progress. The following details can be used to return to this survey and continue where you left off. Please keep this e-mail for your reference - we cannot retrieve the password for you."); $message .= "\n\n" . $thissurvey['name'] . "\n\n"; $message .= $clang->gT("Name") . ": " . $saver['identifier'] . "\n"; $message .= $clang->gT("Password") . ": " . $saver['password'] . "\n\n"; $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n"; $message .= $publicurl . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&lang=" . urlencode($saver['language']) . "&loadname=" . urlencode($saver['identifier']) . "&loadpass="******"&token=" . $tokendata['token']; } $from = $thissurvey['adminemail']; if (SendEmailMessage(null, $message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent = "Y"; $dataentryoutput .= "<font class='successtitle'>" . $clang->gT("An email has been sent with details about your saved survey") . "</font><br />\n"; } } } } else { safe_die("Unable to insert record into saved_control table.<br /><br />" . $connect->ErrorMsg()); } } $dataentryoutput .= "\t<div class='successheader'>" . $clang->gT("Success") . "</div>\n"; $thisid = $connect->Insert_ID(); $dataentryoutput .= "\t" . $clang->gT("The entry was assigned the following record id: ") . " {$thisid}<br /><br />\n"; } $dataentryoutput .= $errormsg; $dataentryoutput .= "\t<input type='submit' value='" . $clang->gT("Add Another Record") . "' onclick=\"window.open('{$scriptname}?action=dataentry&sid={$surveyid}&language=" . $_POST['language'] . "', '_top')\" /><br /><br />\n";
/** * * Function to send reminder, invitation or custom mails to participants of a specific survey * @param $sUser * @param $sPass * @param $iVid * @param $type * @param $maxLsrcEmails * @param $subject * @param $emailText * @return unknown_type */ function sSendEmail($sUser, $sPass, $iVid, $type, $maxLsrcEmails = '', $subject = '', $emailText = '') { global $sitename, $siteadminemail; include "lsrc.config.php"; $lsrcHelper = new lsrcHelper(); $lsrcHelper->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", START OK "); // wenn maxmails ber den lsrc gegeben wird das nurtzen, ansonsten die default werte aus der config.php if ($maxLsrcEmails != '') { $maxemails = $maxLsrcEmails; } if (!$lsrcHelper->checkUser($sUser, $sPass)) { throw new SoapFault("Authentication: ", "User or password wrong"); exit; } // Check if all mandatory parameters are present, else abort... if (!is_int($iVid) || $iVid == 0 || $type == '') { throw new SoapFault("Server: ", "Mandatory Parameters missing"); exit; } if ($type == 'custom' && $subject != '' && $emailText != '') { //GET SURVEY DETAILS not working here... don't know why... //$thissurvey=getSurveyInfo($iVid); $from = $siteadminemail; $lsrcHelper->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", Admin Email: {$from} ; survey: {$iVid} ; dump: " . print_r($thissurvey) . ""); $emquery = "SELECT firstname, lastname, email, token, tid, language"; //if ($ctfieldcount > 7) {$emquery .= ", attribute_1, attribute_2";} $emquery .= " FROM " . db_table_name("tokens_{$iVid}") . " WHERE email != '' "; if (isset($tokenid)) { $emquery .= " and tid='{$tokenid}'"; } $tokenoutput .= "\n\n<!-- emquery: {$emquery} -->\n\n"; //$emresult = db_select_limit_assoc($emquery,$maxemails); $emresult = db_execute_assoc($emquery); $emcount = $emresult->RecordCount(); if ($emcount > 0) { $mailsSend = 0; while ($emrow = $emresult->FetchRow()) { if (SendEmailMessage($emailText, $subject, $emrow['email'], $from, $sitename, $ishtml = false, getBounceEmail($iVid))) { $mailsSend++; } else { //$tokenoutput .= ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."<br />", $fieldsarray); if ($n == 1) { $failedAddresses .= "," . $emrow['email']; } else { $failedAddresses = $emrow['email']; $n = 1; } } } } else { return "No Mails to send"; } // if ($ctcount > $emcount) // { // $lefttosend = $ctcount-$maxemails; // // }else{$lefttosend = 0;} // if($maxemails>0) // { // $returnValue = "".$mailsSend." Mails send. ".$lefttosend." Mails left to send"; // if(isset($failedAddresses)) // $returnValue .= "\nCould not send to: ".$failedAddresses; // return $returnValue; // } if (isset($mailsSend)) { $returnValue = "" . $mailsSend . " Mails send. "; if (isset($failedAddresses)) { $returnValue .= "\nCould not send to: " . $failedAddresses; } return $returnValue; } } if ($type == 'invite' || $type == 'remind') { $emailSenderReturn = $lsrcHelper->emailSender($iVid, $type, $maxLsrcEmails); return $emailSenderReturn; } else { throw new SoapFault("Type: ", "Wrong send Type given. Possible types are: custom, invite or remind"); exit; } }
function savedcontrol() { //This data will be saved to the "saved_control" table with one row per response. // - a unique "saved_id" value (autoincremented) // - the "sid" for this survey // - the "srid" for the survey_x row id // - "saved_thisstep" which is the step the user is up to in this survey // - "saved_ip" which is the ip address of the submitter // - "saved_date" which is the date ofthe saved response // - an "identifier" which is like a username // - a "password" // - "fieldname" which is the fieldname of the saved response // - "value" which is the value of the response //We start by generating the first 5 values which are consistent for all rows. global $connect, $surveyid, $dbprefix, $thissurvey, $errormsg, $publicurl, $sitename, $timeadjust, $clang, $clienttoken, $thisstep; //Check that the required fields have been completed. $errormsg = ""; if (!isset($_POST['savename']) || !$_POST['savename']) { $errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n"; } if (!isset($_POST['savepass']) || !$_POST['savepass']) { $errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n"; } if (isset($_POST['savepass']) && !isset($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) { $errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n"; } // if security question asnwer is incorrect if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) { if (!isset($_POST['loadsecurity']) || !isset($_SESSION['secanswer']) || $_POST['loadsecurity'] != $_SESSION['secanswer']) { $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n"; } } if ($errormsg) { return; } //All the fields are correct. Now make sure there's not already a matching saved item $query = "SELECT COUNT(*) FROM {$dbprefix}saved_control\n" . "WHERE sid={$surveyid}\n" . "AND identifier=" . db_quoteall($_POST['savename'], true); $result = db_execute_num($query) or safe_die("Error checking for duplicates!<br />{$query}<br />" . $connect->ErrorMsg()); // Checked list($count) = $result->FetchRow(); if ($count > 0) { $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n"; return; } else { //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist if (!isset($_SESSION['srid'])) { $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); $sdata = array("datestamp" => $today, "ipaddr" => $_SERVER['REMOTE_ADDR'], "startlanguage" => $_SESSION['s_lang'], "refurl" => getenv("HTTP_REFERER")); //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated if ($connect->AutoExecute($thissurvey['tablename'], $sdata, 'INSERT')) { $srid = $connect->Insert_ID($thissurvey['tablename'], "sid"); $_SESSION['srid'] = $srid; } else { safe_die("Unable to insert record into survey table.<br /><br />" . $connect->ErrorMsg()); } } //CREATE ENTRY INTO "saved_control" $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); $scdata = array("sid" => $surveyid, "srid" => $_SESSION['srid'], "identifier" => $_POST['savename'], "access_code" => md5($_POST['savepass']), "email" => $_POST['saveemail'], "ip" => $_SERVER['REMOTE_ADDR'], "refurl" => getenv("HTTP_REFERER"), "saved_thisstep" => $thisstep, "status" => "S", "saved_date" => $today); if ($connect->AutoExecute("{$dbprefix}saved_control", $scdata, 'INSERT')) { $scid = $connect->Insert_ID("{$dbprefix}saved_control", 'scid'); $_SESSION['scid'] = $scid; } else { safe_die("Unable to insert record into saved_control table.<br /><br />" . $connect->ErrorMsg()); } $_SESSION['holdname'] = $_POST['savename']; //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output $_SESSION['holdpass'] = $_POST['savepass']; //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output //Email if needed if (isset($_POST['saveemail'])) { if (validate_email($_POST['saveemail'])) { $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name']; $message = $clang->gT("Thank you for saving your survey in progress. The following details can be used to return to this survey and continue where you left off. Please keep this e-mail for your reference - we cannot retrieve the password for you.", "unescaped"); $message .= "\n\n" . $thissurvey['name'] . "\n\n"; $message .= $clang->gT("Name", "unescaped") . ": " . $_POST['savename'] . "\n"; $message .= $clang->gT("Password", "unescaped") . ": " . $_POST['savepass'] . "\n\n"; $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):", "unescaped") . ":\n"; $message .= $publicurl . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&loadname=" . urlencode($_POST['savename']) . "&loadpass="******"&token=" . $clienttoken; } $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent = "Y"; } else { echo "Error: Email failed, this may indicate a PHP Mail Setup problem on your server. Your survey details have still been saved, however you will not get an email with the details. You should note the \"name\" and \"password\" you just used for future reference."; } } } return $clang->gT('Your survey was successfully saved.'); } }
/** * Sends email to tokens - invitation and reminders * * @param mixed $iSurveyID * @param array $aResultTokens * @param string $sType type of notification invite|register|remind * @return array of results */ function emailTokens($iSurveyID, $aResultTokens, $sType) { Yii::app()->loadHelper('common'); $oSurvey = Survey::model()->findByPk($iSurveyID); if (getEmailFormat($iSurveyID) == 'html') { $bHtml = true; } else { $bHtml = false; } $attributes = array_keys(getTokenFieldsAndNames($iSurveyID)); $oSurveyLocale = SurveyLanguageSetting::model()->findAllByAttributes(array('surveyls_survey_id' => $iSurveyID)); $oTokens = Token::model($iSurveyID); $aSurveyLangs = $oSurvey->additionalLanguages; array_unshift($aSurveyLangs, $oSurvey->language); //Convert result to associative array to minimize SurveyLocale access attempts foreach ($oSurveyLocale as $rows) { $oTempObject = array(); foreach ($rows as $k => $v) { $oTempObject[$k] = $v; } $aSurveyLocaleData[$rows['surveyls_language']] = $oTempObject; } foreach ($aResultTokens as $aTokenRow) { //Select language $aTokenRow['language'] = trim($aTokenRow['language']); $found = array_search($aTokenRow['language'], $aSurveyLangs); if ($aTokenRow['language'] == '' || $found == false) { $aTokenRow['language'] = $oSurvey['language']; } $sTokenLanguage = $aTokenRow['language']; //Build recipient $to = array(); $aEmailaddresses = explode(';', $aTokenRow['email']); foreach ($aEmailaddresses as $sEmailaddress) { $to[] = $aTokenRow['firstname'] . " " . $aTokenRow['lastname'] . " <{$sEmailaddress}>"; } //Populate attributes $fieldsarray["{SURVEYNAME}"] = $aSurveyLocaleData[$sTokenLanguage]['surveyls_title']; if ($fieldsarray["{SURVEYNAME}"] == '') { $fieldsarray["{SURVEYNAME}"] = $aSurveyLocaleData[$oSurvey['language']]['surveyls_title']; } $fieldsarray["{SURVEYDESCRIPTION}"] = $aSurveyLocaleData[$sTokenLanguage]['surveyls_description']; if ($fieldsarray["{SURVEYDESCRIPTION}"] == '') { $fieldsarray["{SURVEYDESCRIPTION}"] = $aSurveyLocaleData[$oSurvey['language']]['surveyls_description']; } $fieldsarray["{ADMINNAME}"] = $oSurvey['admin']; $fieldsarray["{ADMINEMAIL}"] = $oSurvey['adminemail']; $from = $fieldsarray["{ADMINNAME}"] . ' <' . $fieldsarray["{ADMINEMAIL}"] . '>'; if ($from == '') { $from = Yii::app()->getConfig('siteadminemail'); } foreach ($attributes as $attributefield) { $fieldsarray['{' . strtoupper($attributefield) . '}'] = $aTokenRow[$attributefield]; $fieldsarray['{TOKEN:' . strtoupper($attributefield) . '}'] = $aTokenRow[$attributefield]; } //create urls $fieldsarray["{OPTOUTURL}"] = Yii::app()->getController()->createAbsoluteUrl("/optout/tokens/langcode/" . trim($aTokenRow['language']) . "/surveyid/{$iSurveyID}/token/{$aTokenRow['token']}"); $fieldsarray["{OPTINURL}"] = Yii::app()->getController()->createAbsoluteUrl("/optin/tokens/langcode/" . trim($aTokenRow['language']) . "/surveyid/{$iSurveyID}/token/{$aTokenRow['token']}"); $fieldsarray["{SURVEYURL}"] = Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}/token/{$aTokenRow['token']}/lang/" . trim($aTokenRow['language']) . "/"); if ($bHtml) { foreach (array('OPTOUT', 'OPTIN', 'SURVEY') as $key) { $url = $fieldsarray["{{$key}URL}"]; $fieldsarray["{{$key}URL}"] = "<a href='{$url}'>" . htmlspecialchars($url) . '</a>'; if ($key == 'SURVEY') { $barebone_link = $url; } } } //mail headers $customheaders = array('1' => "X-surveyid: " . $iSurveyID, '2' => "X-tokenid: " . $fieldsarray["{TOKEN}"]); global $maildebug; //choose appriopriate email message if ($sType == 'invite') { $sSubject = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_invite_subj']; $sMessage = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_invite']; } else { if ($sType == 'register') { $sSubject = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_register_subj']; $sMessage = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_register']; } else { $sSubject = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_remind_subj']; $sMessage = $aSurveyLocaleData[$sTokenLanguage]['surveyls_email_remind']; } } $modsubject = Replacefields($sSubject, $fieldsarray); $modmessage = Replacefields($sMessage, $fieldsarray); if (isset($barebone_link)) { $modsubject = str_replace("@@SURVEYURL@@", $barebone_link, $modsubject); $modmessage = str_replace("@@SURVEYURL@@", $barebone_link, $modmessage); } if (isset($aTokenRow['validfrom']) && trim($aTokenRow['validfrom']) != '' && convertDateTimeFormat($aTokenRow['validfrom'], 'Y-m-d H:i:s', 'U') * 1 > date('U') * 1) { $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => 'Token not valid yet'); } elseif (isset($aTokenRow['validuntil']) && trim($aTokenRow['validuntil']) != '' && convertDateTimeFormat($aTokenRow['validuntil'], 'Y-m-d H:i:s', 'U') * 1 < date('U') * 1) { $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => 'Token not valid anymore'); } else { if (SendEmailMessage($modmessage, $modsubject, $to, $from, Yii::app()->getConfig("sitename"), $bHtml, getBounceEmail($iSurveyID), null, $customheaders)) { $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'OK'); if ($sType == 'invite' || $sType == 'register') { $oTokens->updateByPk($aTokenRow['tid'], array('sent' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust")))); } if ($sType == 'remind') { $iRCount = $oTokens->findByPk($aTokenRow['tid'])->remindercount + 1; $oTokens->updateByPk($aTokenRow['tid'], array('remindersent' => dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust")))); $oTokens->updateByPk($aTokenRow['tid'], array('remindercount' => $iRCount)); } } else { $aResult[$aTokenRow['tid']] = array('name' => $fieldsarray["{FIRSTNAME}"] . " " . $fieldsarray["{LASTNAME}"], 'email' => $fieldsarray["{EMAIL}"], 'status' => 'fail', 'error' => $maildebug); } } unset($fieldsarray); } return $aResult; }
/** * register::index() * Process register form data and take appropriate action * @return */ function actionIndex($iSurveyID = null) { Yii::app()->loadHelper('database'); Yii::app()->loadHelper('replacements'); $sLanguage = Yii::app()->request->getParam('lang', ''); if ($iSurveyID == null) { $iSurveyID = Yii::app()->request->getPost('sid'); } if (!$iSurveyID) { $this->redirect(Yii::app()->baseUrl); } if ($sLanguage == "") { $sBaseLanguage = Survey::model()->findByPk($iSurveyID)->language; } else { $sBaseLanguage = $sLanguage; } Yii::import('application.libraries.Limesurvey_lang'); Yii::app()->lang = new Limesurvey_lang($sBaseLanguage); $clang = Yii::app()->lang; $thissurvey = getSurveyInfo($iSurveyID, $sBaseLanguage); $register_errormsg = ""; // Check the security question's answer if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) { if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $iSurveyID]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $iSurveyID]['secanswer']) { $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n"; } } //Check that the email is a valid style address if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) { $register_errormsg .= $clang->gT("The email you used is not valid. Please try again."); } // Check for additional fields $attributeinsertdata = array(); foreach (GetParticipantAttributes($iSurveyID) as $field => $data) { if (empty($data['show_register']) || $data['show_register'] != 'Y') { continue; } $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field)); if (trim($value) == '' && $data['mandatory'] == 'Y') { $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]); } $attributeinsertdata[$field] = $value; } if ($register_errormsg != "") { $_SESSION['survey_' . $iSurveyID]['register_errormsg'] = $register_errormsg; $this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage))); } //Check if this email already exists in token database $oToken = TokenDynamic::model($iSurveyID)->find('email=:email', array(':email' => Yii::app()->request->getPost('register_email'))); if ($oToken) { $register_errormsg = $clang->gT("The email you used has already been registered."); $_SESSION['survey_' . $iSurveyID]['register_errormsg'] = $register_errormsg; $this->redirect($this->createUrl("survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage))); //include "index.php"; //exit; } $mayinsert = false; // Get the survey settings for token length $tokenlength = $thissurvey['tokenlength']; //if tokenlength is not set or there are other problems use the default value (15) if (!isset($tokenlength) || $tokenlength == '') { $tokenlength = 15; } while ($mayinsert != true) { $newtoken = randomChars($tokenlength); $oTokenExist = TokenDynamic::model($iSurveyID)->find('token=:token', array(':token' => $newtoken)); if (!$oTokenExist) { $mayinsert = true; } } $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname'))); $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname'))); $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate')); $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate')); /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1'))); $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2'))); */ // Insert new entry into tokens db $oToken = Token::create($thissurvey['sid']); $oToken->firstname = $postfirstname; $oToken->lastname = $postlastname; $oToken->email = Yii::app()->request->getPost('register_email'); $oToken->emailstatus = 'OK'; $oToken->token = $newtoken; if ($starttime && $endtime) { $oToken->validfrom = $starttime; $oToken->validuntil = $endtime; } $oToken->setAttributes($attributeinsertdata, false); $result = $oToken->save(); //$tid = $oToken->tid;// Not needed any more $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname']; $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail']; $fieldsarray["{SURVEYNAME}"] = $thissurvey['name']; $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description']; $fieldsarray["{FIRSTNAME}"] = $postfirstname; $fieldsarray["{LASTNAME}"] = $postlastname; $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"]; $fieldsarray["{TOKEN}"] = $oToken->token; $fieldsarray["{EMAIL}"] = $oToken->email; $token = $oToken->token; $message = $thissurvey['email_register']; $subject = $thissurvey['email_register_subj']; $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; $surveylink = $this->createAbsoluteUrl("/survey/index/sid/{$iSurveyID}", array('lang' => $sBaseLanguage, 'token' => $newtoken)); $optoutlink = $this->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyID}", array('langcode' => $sBaseLanguage, 'token' => $newtoken)); $optinlink = $this->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyID}", array('langcode' => $sBaseLanguage, 'token' => $newtoken)); if (getEmailFormat($iSurveyID) == 'html') { $useHtmlEmail = true; $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>"; $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>"; $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>"; } else { $useHtmlEmail = false; $fieldsarray["{SURVEYURL}"] = $surveylink; $fieldsarray["{OPTOUTURL}"] = $optoutlink; $fieldsarray["{OPTINURL}"] = $optinlink; } $message = ReplaceFields($message, $fieldsarray); $subject = ReplaceFields($subject, $fieldsarray); $html = ""; //Set variable $sitename = Yii::app()->getConfig('sitename'); if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($iSurveyID))) { // 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(); $html = "<div id='wrapper' class='message tokenmessage'>" . "<p>" . $clang->gT("Thank you for registering to participate in this survey.") . "</p>\n" . "<p>" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "</p>\n" . "<p>" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n"; $html = ReplaceFields($html, $fieldsarray); } else { $html = "Email Error"; } //PRINT COMPLETED PAGE if (!$thissurvey['template']) { $thistpl = getTemplatePath(validateTemplateDir('default')); } else { $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template'])); } // Same fix than http://bugs.limesurvey.org/view.php?id=8441 ob_start(function ($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); Yii::app()->lang = $clang; // fetch the defined variables and pass it to the header footer templates. $redata = compact(array_keys(get_defined_vars())); $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__); $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__); echo $html; $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__); doFooter(); ob_flush(); }
/** * submitfailed : used in em_manager_helper.php * * "Unexpected error" * * Will send e-mail to adminemail if defined. * * @param string $errormsg * @param string $query Will be included in sent email * @return string Error message */ function submitfailed($errormsg = '', $query = null) { global $debug; global $thissurvey; global $subquery, $surveyid; $completed = "<p><span class='fa fa-exclamation-triangle'></span> <strong>" . gT("Did Not Save") . "</strong></p>" . "<p>" . gT("An unexpected error has occurred and your responses cannot be saved.") . "</p>"; if ($thissurvey['adminemail']) { $completed .= "<p>"; $completed .= gT("Your responses have not been lost and have been emailed to the survey administrator and will be entered into our database at a later point."); $completed .= "</p>"; if ($debug > 0) { $completed .= 'Error message: ' . htmlspecialchars($errormsg) . '<br />'; } $email = gT("An error occurred saving a response to survey id", "unescaped") . " " . $thissurvey['name'] . " - {$surveyid}\n\n"; $email .= gT("DATA TO BE ENTERED", "unescaped") . ":\n"; foreach ($_SESSION['survey_' . $surveyid]['insertarray'] as $value) { if (isset($_SESSION['survey_' . $surveyid][$value])) { $email .= "{$value}: {$_SESSION['survey_' . $surveyid][$value]}\n"; } else { $email .= "{$value}: N/A\n"; } } $email .= "\n" . gT("SQL CODE THAT FAILED", "unescaped") . ":\n" . "{$subquery}\n\n" . ($query ? $query : '') . "\n\n" . gT("ERROR MESSAGE", "unescaped") . ":\n" . $errormsg . "\n\n"; SendEmailMessage($email, gT("Error saving results", "unescaped"), $thissurvey['adminemail'], $thissurvey['adminemail'], "LimeSurvey", false, getBounceEmail($surveyid)); } else { $completed .= "<a href='javascript:location.reload()'>" . gT("Try to submit again") . "</a><br /><br />\n"; $completed .= $subquery; } return $completed; }
function sendStatistic($surveyid, $to, $tempFile, $html = null) { include "lsrc.config.php"; global $sitename; global $clang; if ($tempFile == null && isset($html)) { $css = "<style type='text/css'>" . "table.statisticstable, table.statisticssummary {\r\n\t\t\t\t background-color:#EEF6FF;\r\n\t\t\t\t border-collapse:collapse;\r\n\t\t\t\t border-width: 0px;\r\n\t\t\t\t border-style: none;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t.statisticssummary thead th\r\n\t\t\t\t{\r\n\t\t\t\t background:#D2E0F2;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t.statisticssummary th:first-child,\r\n\t\t\t\t.statisticstable td:first-child {\r\n\t\t\t\t text-align:right;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t.statisticssummary thead th:first-child\r\n\t\t\t\t{\r\n\t\t\t\t text-align:center;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t.statisticssummary th, .statisticssummary td, .statisticstable td {\r\n\t\t\t\t padding:3px 10px;\r\n\t\t\t\t \r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t.statisticstable tr {\r\n\t\t\t\t border-color: #fff;\r\n\t\t\t\t border-style: solid;\r\n\t\t\t\t border-width: 1px;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t.statisticstable thead th\r\n\t\t\t\t{\r\n\t\t\t\t background:#D2E0F2;\r\n\t\t\t\t text-align:center;\r\n\t\t\t\t color:#1D2D45;\r\n\t\t\t\t padding:4 10px;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t.statisticstable tfoot tr {\r\n\t\t\t\t background:#D2E0F2;\r\n\t\t\t\t text-align:center;\r\n\t\t\t\t}" . "</style>"; $message = sprintf($clang->gT("This is your personal statistic sheet for survey #%s"), $css . "<center>" . $message . $surveyid . "<br/>" . $html . "</center>"); return SendEmailMessage($message, sprintf($clang->gT("Statistics Survey #%s"), $surveyid), $to, getBounceEmail($surveyid), $sitename, true); } else { $message = sprintf($clang->gT("This is your personal statistic sheet for survey #%s"), $surveyid); return SendEmailMessage($message, sprintf($clang->gT("Statistics Survey #%s"), $surveyid), $to, getBounceEmail($surveyid), $sitename, $ishtml, getBounceEmail($surveyid), $tempFile); } }
/** * savesilent() saves survey responses when the "Resume later" button * is press but has no interaction. i.e. it does not ask for email, * username or password or capture. * * @return string confirming successful save. */ function savedsilent() { global $connect, $surveyid, $dbprefix, $thissurvey, $errormsg, $publicurl, $sitename, $timeadjust, $clang, $clienttoken, $thisstep, $modrewrite; submitanswer(); // Prepare email $tokenentryquery = 'SELECT * from '.$dbprefix.'tokens_'.$surveyid.' WHERE token=\''.sanitize_paranoid_string($clienttoken).'\';'; $tokenentryresult = db_execute_assoc($tokenentryquery); $tokenentryarray = $tokenentryresult->FetchRow(); $from = $thissurvey['adminname'].' <'.$thissurvey['adminemail'].'>'; $to = $tokenentryarray['firstname'].' '.$tokenentryarray['lastname'].' <'.$tokenentryarray['email'].'>'; $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name']; $message = $clang->gT("Thank you for saving your survey in progress. You can return to the survey at the same point you saved it at any time using the link from this or any previous email sent to regarding this survey.","unescaped")."\n\n"; $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):","unescaped")."\n"; $language = $tokenentryarray['language']; if($modrewrite) { $message .= "\n\n$publicurl/$surveyid/lang-$language/tk-$clienttoken"; } else { $message .= "\n\n$publicurl/index.php?lang=$language&sid=$surveyid&token=$clienttoken"; }; if (SendEmailMessage($message, $subject, $to, $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent="Y"; } else { echo "Error: Email failed, this may indicate a PHP Mail Setup problem on your server. Your survey details have still been saved, however you will not get an email with the details. You should note the \"name\" and \"password\" you just used for future reference."; }; return $clang->gT('Your survey was successfully saved.'); };
public function beforeSurveyPage() { $oEvent = $this->event; $iSurveyId = $oEvent->get('surveyId'); self::__init(); $bUse=$this->get('bUse', 'Survey', $iSurveyId); if(is_null($bUse)) $bUse=$this->bUse; if(!$bUse) return; $sToken= Yii::app()->request->getParam('token'); if($iSurveyId && !$sToken)// Test invalid token ? { // Get the survey model $oSurvey=Survey::model()->find("sid=:sid",array(':sid'=>$iSurveyId)); if($oSurvey && $oSurvey->active=="Y" && $oSurvey->allowregister=="Y" && tableExists("tokens_{$iSurveyId}")) { // Fill parameters $bShowTokenForm=$this->get('bShowTokenForm', 'Survey', $iSurveyId); if(is_null($bShowTokenForm)) $bShowTokenForm=$this->bShowTokenForm; $bShowTokenForm=$this->get('use', 'Survey', $iSurveyId); if(is_null($bShowTokenForm)) $bShowTokenForm=$this->bUse; Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicurl')."plugins/replaceRegister/css/register.css"); // We can go $sLanguage = Yii::app()->request->getParam('lang',''); if ($sLanguage=="" ) { $sLanguage = Survey::model()->findByPk($iSurveyId)->language; } $aSurveyInfo=getSurveyInfo($iSurveyId,$sLanguage); $sAction= Yii::app()->request->getParam('action','view') ; $sHtmlRegistererror=""; $sHtmlRegistermessage1=gT("You must be registered to complete this survey");; $sHtmlRegistermessage2=gT("You may register for this survey if you wish to take part.")."<br />\n".gT("Enter your details below, and an email containing the link to participate in this survey will be sent immediately."); $sHtmlRegisterform=""; $sHtml=""; $bShowForm=true; $bValidMail=false; $bTokenCreate=true; $aExtraParams=array(); $aRegisterError=array(); $sR_email= Yii::app()->request->getPost('register_email'); $sR_firstname= sanitize_xss_string(Yii::app()->request->getPost('register_firstname',"")); $sR_lastname= sanitize_xss_string(Yii::app()->request->getPost('register_lastname',"")); $sR_lastname= sanitize_xss_string(Yii::app()->request->getPost('register_lastname',"")); $aR_attribute=array(); $aR_attributeGet=array(); $aExtraParams=array(); $aMail=array(); foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute) { if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y') { $aR_attribute[$field]= sanitize_xss_string(Yii::app()->request->getPost('register_'.$field),"");// Need to be filtered ? } elseif($aAttribute['description']==sanitize_paranoid_string($aAttribute['description']) && trim(Yii::app()->request->getQuery($aAttribute['description'],"")) ) { $aR_attributeGet[$field]= sanitize_xss_string(trim(Yii::app()->request->getQuery($aAttribute['description'],"")));// Allow prefill with URL (TODO: add an option) $aExtraParams[$aAttribute['description']]=sanitize_xss_string(trim(Yii::app()->request->getParam($aAttribute['description'],""))); } } if($sAction=='register' && !is_null($sR_email) && Yii::app()->request->getPost('changelang')!='changelang') { $bShowForm=false; // captcha $sLoadsecurity=Yii::app()->request->getPost('loadsecurity'); $sSecAnswer=(isset($_SESSION['survey_'.$iSurveyId]['secanswer']))?$_SESSION['survey_'.$iSurveyId]['secanswer']:""; $bShowForm=false; $bNoError=true; // Copy paste RegisterController if($sR_email) { //Check that the email is a valid style addressattribute_2 if (!validateEmailAddress($sR_email)) { $aRegisterError[]= gT("The email you used is not valid. Please try again."); } } else { $aRegisterError[]= gT("The email you used is not valid. Please try again.");// Empty email } // Fill and validate mandatory extra attribute foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute) { if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y' && $aAttribute['mandatory'] == 'Y' && ($aR_attribute[$field]=="" || is_null($aR_attribute[$field])) ) { $aRegisterError[]= sprintf(gT("%s cannot be left empty").".", $aSurveyInfo['attributecaptions'][$field]); } } // Check the security question's answer : at end because the security question is the last one if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen',$aSurveyInfo['usecaptcha']) ) { if (!$sLoadsecurity || !$sSecAnswer || $sLoadsecurity != $sSecAnswer) { $aRegisterError[]= gT("The answer to the security question is incorrect."); } } if(count($aRegisterError)==0) { //Check if this email already exists in token database $oToken=TokenDynamic::model($iSurveyId)->find('email=:email',array(':email'=>$sR_email)); if ($oToken) { if($oToken->usesleft<1 && $aSurveyInfo['alloweditaftercompletion']!='Y') { $aRegisterError="The e-mail address you have entered is already registered an the questionnaire has been completed."; } elseif(strtolower(substr(trim($oToken->emailstatus),0,6))==="optout")// And global blacklisting ? { $aRegisterError="This email address is already registered but someone ask to don't receive new email again."; } elseif(!$oToken->emailstatus && $oToken->emailstatus!="OK") { $aRegisterError="This email address is already registered but the email adress was bounced."; } else { $iTokenId=$oToken->tid; $aMail['subject']=$aSurveyInfo['email_register_subj']; $aMail['message']=$aSurveyInfo['email_register']; $aMail['information']="The address you have entered is already registered. An email has been sent to this address with a link that gives you access to the survey."; // Did we update the token ? Setting ? } } else { $oToken= Token::create($iSurveyId); $oToken->firstname = $sR_firstname; $oToken->lastname = $sR_lastname; $oToken->email = $sR_email; $oToken->emailstatus = 'OK'; $oToken->language = $sLanguage; $oToken->setAttributes($aR_attribute); $oToken->setAttributes($aR_attributeGet);// Need an option if ($aSurveyInfo['startdate']) { $oToken->validfrom = $aSurveyInfo['startdate']; } if ($aSurveyInfo['expires']) { $oToken->validuntil = $aSurveyInfo['expires']; } $oToken->save(); $iTokenId=$oToken->tid; TokenDynamic::model($iSurveyId)->createToken($iTokenId);// Review if really create a token $aMail['subject']=$aSurveyInfo['email_register_subj']; $aMail['message']=$aSurveyInfo['email_register']; $aMail['information']=gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed."); } } } if($aMail && $oToken) { $aReplacementFields=array(); $aReplacementFields["{ADMINNAME}"]=$aSurveyInfo['adminname']; $aReplacementFields["{ADMINEMAIL}"]=$aSurveyInfo['adminemail']; $aReplacementFields["{SURVEYNAME}"]=$aSurveyInfo['name']; $aReplacementFields["{SURVEYDESCRIPTION}"]=$aSurveyInfo['description']; $aReplacementFields["{EXPIRY}"]=$aSurveyInfo["expiry"]; $oToken=TokenDynamic::model($iSurveyId)->findByPk($iTokenId); foreach($oToken->attributes as $attribute=>$value){ $aReplacementFields["{".strtoupper($attribute)."}"]=$value; } $sToken=$oToken->token; $aMail['subject']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['subject']); $aMail['message']=preg_replace("/{TOKEN:([A-Z0-9_]+)}/","{"."$1"."}",$aMail['message']); $surveylink = App()->createAbsoluteUrl("/survey/index/sid/{$iSurveyId}",array('lang'=>$sLanguage,'token'=>$sToken)); $optoutlink = App()->createAbsoluteUrl("/optout/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=>$sToken)); $optinlink = App()->createAbsoluteUrl("/optin/tokens/surveyid/{$iSurveyId}",array('langcode'=>$sLanguage,'token'=>$sToken)); if (getEmailFormat($iSurveyId) == 'html') { $useHtmlEmail = true; $aReplacementFields["{SURVEYURL}"]="<a href='$surveylink'>".$surveylink."</a>"; $aReplacementFields["{OPTOUTURL}"]="<a href='$optoutlink'>".$optoutlink."</a>"; $aReplacementFields["{OPTINURL}"]="<a href='$optinlink'>".$optinlink."</a>"; } else { $useHtmlEmail = false; $aReplacementFields["{SURVEYURL}"]= $surveylink; $aReplacementFields["{OPTOUTURL}"]= $optoutlink; $aReplacementFields["{OPTINURL}"]= $optinlink; } // Allow barebone link for all URL $aMail['message'] = str_replace("@@SURVEYURL@@", $surveylink, $aMail['message']); $aMail['message'] = str_replace("@@OPTOUTURL@@", $optoutlink, $aMail['message']); $aMail['message'] = str_replace("@@OPTINURL@@", $optinlink, $aMail['message']); // Replace the fields $aMail['subject']=ReplaceFields($aMail['subject'], $aReplacementFields); $aMail['message']=ReplaceFields($aMail['message'], $aReplacementFields); // We have it, then try to send the mail. $from = "{$aSurveyInfo['adminname']} <{$aSurveyInfo['adminemail']}>"; $sitename = Yii::app()->getConfig('sitename'); if (SendEmailMessage($aMail['message'], $aMail['subject'], $sR_email, $from, $sitename,$useHtmlEmail,getBounceEmail($iSurveyId))) { // 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(); $sReturnHtml="<div id='wrapper' class='message tokenmessage'>" . "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n" . "<p>".$aMail['information']."</p>\n" . "<p>".gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n"; } else { $sReturnHtml="<div id='wrapper' class='message tokenmessage'>" . "<p>".gT("Thank you for registering to participate in this survey.")."</p>\n" . "<p>"."We can not sent you an email actually, please contact the survey administrator"."</p>\n" . "<p>".gT("Survey administrator")." {ADMINNAME} ({ADMINEMAIL})</p>" . "</div>\n"; } $sReturnHtml=ReplaceFields($sReturnHtml, $aReplacementFields); $sTemplatePath=$aData['templatedir'] = getTemplatePath($aSurveyInfo['template']); ob_start(function($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); $aData['thissurvey'] = $aSurveyInfo; $aData['thissurvey'] = $aSurveyInfo; echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData); echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData); echo $sReturnHtml; echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData); doFooter(); ob_flush(); App()->end(); } if($bShowForm || count($aRegisterError)) { // Language ? if(count($aRegisterError)==1){ $sHtmlRegistererror="<p class='error error-register'><strong>{$aRegisterError[0]}</strong></p>"; }elseif(count($aRegisterError)>1){ $sHtmlRegistererror="<ul class='error error-register error-list'>"; foreach ($aRegisterError as $sRegisterError) $sHtmlRegistererror.="<li><strong>{$sRegisterError}</strong></li>"; $sHtmlRegistererror.="</ul>"; } $aExtraParams['action']='register'; $aExtraParams['lang']=$sLanguage; $sHtmlRegisterform = CHtml::form(Yii::app()->createUrl("/survey/index/sid/{$iSurveyId}",$aExtraParams), 'post'); $sHtmlRegisterform.="<table class='register'><tbody>\n"; $sHtmlRegisterform.= "<tr><th><label for='register_firstname'>".gT("First name") . "</label></th><td>".CHtml::textField('register_firstname',htmlentities($sR_firstname, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n"; $sHtmlRegisterform.= "<tr><th><label for='register_lastname'>".gT("Last name") . "</label></th><td>".CHtml::textField('register_lastname',htmlentities($sR_lastname, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n"; $sHtmlRegisterform.= "<tr class='mandatory'><th><label for='register_email'>".gT("Email address") . "</label></th><td>".CHtml::textField('register_email',htmlentities($sR_email, ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n"; // Extra attribute foreach ($aSurveyInfo['attributedescriptions'] as $field => $aAttribute) { if (!empty($aAttribute['show_register']) && $aAttribute['show_register'] == 'Y') { $sHtmlRegisterform.= "<tr".($aAttribute['mandatory'] == 'Y' ? " class='mandatory'" : '')."><th><label for='register_{$field}'>".$aSurveyInfo['attributecaptions'][$field].($aAttribute['mandatory'] == 'Y' ? ' *' : '')."</label></th><td>".CHtml::textField('register_'.$field,htmlentities($aR_attribute[$field], ENT_QUOTES, 'UTF-8'),array('class'=>'text'))."</td></tr>\n"; } } if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $aSurveyInfo['usecaptcha'])) $sHtmlRegisterform.= "<tr><th><label for='loadsecurity'>" . gT("Security question") . "</label></th><td><img src='".Yii::app()->getController()->createUrl("/verification/image/sid/{$iSurveyId}")."' alt='' /><input type='text' size='5' maxlength='3' name='loadsecurity' id='loadsecurity' value='' /></td></tr>\n"; $sHtmlRegisterform.= "<tr><td></td><td>".CHtml::submitButton(gT("Continue"))."</td></tr>"; $sHtmlRegisterform.= "</tbody></table>\n"; $sHtmlRegisterform.= makeLanguageChangerSurvey($sLanguage);// Need to be inside the form $sHtmlRegisterform.= CHtml::endForm(); } $sTemplatePath=$aData['templatedir'] = getTemplatePath($aSurveyInfo['template']); ob_start(function($buffer, $phase) { App()->getClientScript()->render($buffer); App()->getClientScript()->reset(); return $buffer; }); ob_implicit_flush(false); sendCacheHeaders(); doHeader(); // Get the register.pstpl file content, but remplace default by own string $sHtmlRegister=file_get_contents($sTemplatePath.'/register.pstpl'); $sHtmlRegister= str_replace("{REGISTERERROR}",$sHtmlRegistererror,$sHtmlRegister); $sHtmlRegister= str_replace("{REGISTERMESSAGE1}",$sHtmlRegistermessage1,$sHtmlRegister); $sHtmlRegister= str_replace("{REGISTERMESSAGE2}",$sHtmlRegistermessage2,$sHtmlRegister); $sHtmlRegister= str_replace("{REGISTERFORM}",$sHtmlRegisterform,$sHtmlRegister); $aData['thissurvey'] = $aSurveyInfo; echo templatereplace(file_get_contents($sTemplatePath.'/startpage.pstpl'),array(), $aData); echo templatereplace(file_get_contents($sTemplatePath.'/survey.pstpl'),array(), $aData); echo templatereplace($sHtmlRegister); echo templatereplace(file_get_contents($sTemplatePath.'/endpage.pstpl'),array(), $aData); doFooter(); ob_flush(); App()->end(); } } }
/** * savesilent() saves survey responses when the "Resume later" button * is press but has no interaction. i.e. it does not ask for email, * username or password or capture. * * @return string confirming successful save. */ function savedsilent() { global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $timeadjust, $clang, $clienttoken, $thisstep; submitanswer(); // Prepare email $tokenentryquery = 'SELECT * from {{tokens_' . $surveyid . '}} WHERE token=\'' . sanitize_paranoid_string($clienttoken) . '\';'; $tokenentryresult = dbExecuteAssoc($tokenentryquery); $tokenentryarray = $tokenentryresult->read(); $from = $thissurvey['adminname'] . ' <' . $thissurvey['adminemail'] . '>'; $to = $tokenentryarray['firstname'] . ' ' . $tokenentryarray['lastname'] . ' <' . $tokenentryarray['email'] . '>'; $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name']; $message = $clang->gT("Thank you for saving your survey in progress. You can return to the survey at the same point you saved it at any time using the link from this or any previous email sent to regarding this survey.") . "\n\n"; $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . ":\n"; $language = $tokenentryarray['language']; //$message .= "\n\n$publicurl/$surveyid/lang-$language/tk-$clienttoken"; $message .= "\n\n" . Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/lang/{$language}/token/{$clienttoken}"); if (SendEmailMessage($message, $subject, $to, $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent = "Y"; } else { $clang->eT('Error: Email failed, this may indicate a PHP Mail Setup problem on your server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.'); if (trim($thissurvey['adminemail']) == '') { $clang->eT('(Reason: Admin email address empty)'); } } return $clang->gT('Your survey was successfully saved.'); }
/** * Handle email action */ function email($iSurveyId, $tokenids = null) { /* Check permissions */ if (!hasSurveyPermission($iSurveyId, 'tokens', 'read')) { die("You do not have permission to view this page"); // TODO Replace } $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)); // CHECK TO SEE IF A TOKEN TABLE EXISTS FOR THIS SURVEY $bTokenExists = tableExists('{{tokens_' . $iSurveyId . '}}'); if (!$bTokenExists) { self::_newtokentable($iSurveyId); } $clang = $this->getController()->lang; $iSurveyId = sanitize_int($iSurveyId); if (!hasSurveyPermission($iSurveyId, 'tokens', 'update')) { die("no permissions"); // TODO Replace } $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'); $query = Tokens_dynamic::model($iSurveyId)->find(); $aExampleRow = empty($query) ? array() : $query->attributes; $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); $aData['surveyid'] = $iSurveyId; $aData['sSubAction'] = $sSubAction; $aData['bEmail'] = $bEmail; $aData['aSurveyLangs'] = $aData['surveylangs'] = $aSurveyLangs; $aData['baselang'] = $sBaseLanguage; $aData['tokenfields'] = $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 = Tokens_dynamic::model($iSurveyId)->findUninvited($aTokenIds, 0, $bEmail, $SQLemailstatuscondition); foreach ($aTokens as $aToken) { $aData['tokenids'][] = $aToken['tid']; } } $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 = Tokens_dynamic::model($iSurveyId)->findUninvited($aTokenIds, 0, $bEmail, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition); $ctcount = count($ctresult); $emresult = Tokens_dynamic::model($iSurveyId)->findUninvited($aTokenIds, $iMaxEmails, $bEmail, $SQLemailstatuscondition, $SQLremindercountcondition, $SQLreminderdelaycondition); $emcount = count($emresult); foreach ($aSurveyLangs as $language) { $_POST['message_' . $language] = autoUnescape(Yii::app()->request->getPost('message_' . $language)); $_POST['subject_' . $language] = autoUnescape(Yii::app()->request->getPost('subject_' . $language)); if ($bHtml) { $_POST['message_' . $language] = html_entity_decode(Yii::app()->request->getPost('message_' . $language), ENT_QUOTES, Yii::app()->getConfig("emailcharset")); } } $attributes = getTokenFieldsAndNames($iSurveyId); $tokenoutput = ""; if ($emcount > 0) { foreach ($emresult as $emrow) { $to = 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 => $attributedescription) { $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']}/langcode/" . 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(Yii::app()->request->getPost('subject_' . $emrow['language']), $fieldsarray); $modmessage = Replacefields(Yii::app()->request->getPost('message_' . $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 { if (SendEmailMessage($modmessage, $modsubject, $to, $from, Yii::app()->getConfig("sitename"), $bHtml, getBounceEmail($iSurveyId), null, $customheaders)) { // Put date into sent $udequery = Tokens_dynamic::model($iSurveyId)->findByPk($emrow['tid']); if ($bEmail) { $tokenoutput .= $clang->gT("Invitation sent to:"); $udequery->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:"); $udequery->remindersent = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", Yii::app()->getConfig("timeadjust")); $udequery->remindercount = $udequery->remindercount + 1; } $udequery->save(); //Update central participant survey_links if (!empty($emrow['participant_id'])) { $slquery = Survey_links::model()->find('participant_id = "' . $emrow['participant_id'] . '" AND survey_id = ' . $iSurveyId . ' AND token_id = ' . $emrow['tid']); $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'; } $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/> <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); } } }
/** * 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('type', '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); $aMail['subject'] = $event->get('subject'); $aMail['message'] = $event->get('body'); $sTo = $event->get('to'); $sFrom = $event->get('from'); if ($event->get('send', true) == false) { $this->sMessage = $event->get('message', ''); if ($event->get('error') == null) { // mimic token system, set send to today $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)) { // 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; }
/** * register::index() * Process register form data and take appropriate action * @return */ function actionIndex($surveyid = null) { Yii::app()->loadHelper('database'); Yii::app()->loadHelper('replacements'); $postlang = Yii::app()->request->getPost('lang'); if ($surveyid == null) { $surveyid = Yii::app()->request->getPost('sid'); } if (!$surveyid) { Yii::app()->request->redirect(Yii::app()->baseUrl); } // Get passed language from form, so that we dont loose this! if (!isset($postlang) || $postlang == "" || !$postlang) { $baselang = Survey::model()->findByPk($surveyid)->language; Yii::import('application.libraries.Limesurvey_lang'); Yii::app()->lang = new Limesurvey_lang($baselang); $clang = Yii::app()->lang; } else { Yii::import('application.libraries.Limesurvey_lang'); Yii::app()->lang = new Limesurvey_lang($postlang); $clang = Yii::app()->lang; $baselang = $postlang; } $thissurvey = getSurveyInfo($surveyid, $baselang); $register_errormsg = ""; // Check the security question's answer if (function_exists("ImageCreate") && isCaptchaEnabled('registrationscreen', $thissurvey['usecaptcha'])) { if (!isset($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || Yii::app()->request->getPost('loadsecurity') != $_SESSION['survey_' . $surveyid]['secanswer']) { $register_errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n"; } } //Check that the email is a valid style address if (!validateEmailAddress(Yii::app()->request->getPost('register_email'))) { $register_errormsg .= $clang->gT("The email you used is not valid. Please try again."); } // Check for additional fields $attributeinsertdata = array(); foreach (GetParticipantAttributes($surveyid) as $field => $data) { if (empty($data['show_register']) || $data['show_register'] != 'Y') { continue; } $value = sanitize_xss_string(Yii::app()->request->getPost('register_' . $field)); if (trim($value) == '' && $data['mandatory'] == 'Y') { $register_errormsg .= sprintf($clang->gT("%s cannot be left empty"), $thissurvey['attributecaptions'][$field]); } $attributeinsertdata[$field] = $value; } if ($register_errormsg != "") { $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg; Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid)); } //Check if this email already exists in token database $query = "SELECT email FROM {{tokens_{$surveyid}}}\n" . "WHERE email = '" . sanitize_email(Yii::app()->request->getPost('register_email')) . "'"; $usrow = Yii::app()->db->createCommand($query)->queryRow(); if ($usrow) { $register_errormsg = $clang->gT("The email you used has already been registered."); $_SESSION['survey_' . $surveyid]['register_errormsg'] = $register_errormsg; Yii::app()->request->redirect(Yii::app()->createUrl('survey/index/sid/' . $surveyid)); //include "index.php"; //exit; } $mayinsert = false; // Get the survey settings for token length //$this->load->model("surveys_model"); $tlresult = Survey::model()->findAllByAttributes(array("sid" => $surveyid)); if (isset($tlresult[0])) { $tlrow = $tlresult[0]; } else { $tlrow = $tlresult; } $tokenlength = $tlrow['tokenlength']; //if tokenlength is not set or there are other problems use the default value (15) if (!isset($tokenlength) || $tokenlength == '') { $tokenlength = 15; } while ($mayinsert != true) { $newtoken = randomChars($tokenlength); $ntquery = "SELECT * FROM {{tokens_{$surveyid}}} WHERE token='{$newtoken}'"; $usrow = Yii::app()->db->createCommand($ntquery)->queryRow(); if (!$usrow) { $mayinsert = true; } } $postfirstname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_firstname'))); $postlastname = sanitize_xss_string(strip_tags(Yii::app()->request->getPost('register_lastname'))); $starttime = sanitize_xss_string(Yii::app()->request->getPost('startdate')); $endtime = sanitize_xss_string(Yii::app()->request->getPost('enddate')); /*$postattribute1=sanitize_xss_string(strip_tags(returnGlobal('register_attribute1'))); $postattribute2=sanitize_xss_string(strip_tags(returnGlobal('register_attribute2'))); */ // Insert new entry into tokens db Tokens_dynamic::sid($thissurvey['sid']); $token = new Tokens_dynamic(); $token->firstname = $postfirstname; $token->lastname = $postlastname; $token->email = Yii::app()->request->getPost('register_email'); $token->emailstatus = 'OK'; $token->token = $newtoken; if ($starttime && $endtime) { $token->validfrom = $starttime; $token->validuntil = $endtime; } foreach ($attributeinsertdata as $k => $v) { $token->{$k} = $v; } $result = $token->save(); /** $result = $connect->Execute($query, array($postfirstname, $postlastname, returnGlobal('register_email'), 'OK', $newtoken) // $postattribute1, $postattribute2) ) or safeDie ($query."<br />".$connect->ErrorMsg()); //Checked - According to adodb docs the bound variables are quoted automatically */ $tid = getLastInsertID($token->tableName()); $fieldsarray["{ADMINNAME}"] = $thissurvey['adminname']; $fieldsarray["{ADMINEMAIL}"] = $thissurvey['adminemail']; $fieldsarray["{SURVEYNAME}"] = $thissurvey['name']; $fieldsarray["{SURVEYDESCRIPTION}"] = $thissurvey['description']; $fieldsarray["{FIRSTNAME}"] = $postfirstname; $fieldsarray["{LASTNAME}"] = $postlastname; $fieldsarray["{EXPIRY}"] = $thissurvey["expiry"]; $message = $thissurvey['email_register']; $subject = $thissurvey['email_register_subj']; $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; if (getEmailFormat($surveyid) == 'html') { $useHtmlEmail = true; $surveylink = $this->createAbsoluteUrl($surveyid . '/lang-' . $baselang . '/tk-' . $newtoken); $optoutlink = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken); $optinlink = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken); $fieldsarray["{SURVEYURL}"] = "<a href='{$surveylink}'>" . $surveylink . "</a>"; $fieldsarray["{OPTOUTURL}"] = "<a href='{$optoutlink}'>" . $optoutlink . "</a>"; $fieldsarray["{OPTINURL}"] = "<a href='{$optinlink}'>" . $optinlink . "</a>"; } else { $useHtmlEmail = false; $fieldsarray["{SURVEYURL}"] = $this->createAbsoluteUrl('' . $surveyid . '/lang-' . $baselang . '/tk-' . $newtoken); $fieldsarray["{OPTOUTURL}"] = $this->createAbsoluteUrl('optout/local/' . $surveyid . '/' . $baselang . '/' . $newtoken); $fieldsarray["{OPTINURL}"] = $this->createAbsoluteUrl('optin/local/' . $surveyid . '/' . $baselang . '/' . $newtoken); } $message = ReplaceFields($message, $fieldsarray); $subject = ReplaceFields($subject, $fieldsarray); $html = ""; //Set variable $sitename = Yii::app()->getConfig('sitename'); if (SendEmailMessage($message, $subject, Yii::app()->request->getPost('register_email'), $from, $sitename, $useHtmlEmail, getBounceEmail($surveyid))) { // 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')); $query = "UPDATE {{tokens_{$surveyid}}}\n" . "SET sent='{$today}' WHERE tid={$tid}"; $result = dbExecuteAssoc($query) or show_error("Unable to execute this query : {$query}<br />"); //Checked $html = "<center>" . $clang->gT("Thank you for registering to participate in this survey.") . "<br /><br />\n" . $clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.") . "<br /><br />\n" . $clang->gT("Survey administrator") . " {ADMINNAME} ({ADMINEMAIL})"; $html = ReplaceFields($html, $fieldsarray); $html .= "<br /><br /></center>\n"; } else { $html = "Email Error"; } //PRINT COMPLETED PAGE if (!$thissurvey['template']) { $thistpl = getTemplatePath(validateTemplateDir('default')); } else { $thistpl = getTemplatePath(validateTemplateDir($thissurvey['template'])); } sendCacheHeaders(); doHeader(); Yii::app()->lang = $clang; // fetch the defined variables and pass it to the header footer templates. $redata = compact(array_keys(get_defined_vars())); $this->_printTemplateContent($thistpl . '/startpage.pstpl', $redata, __LINE__); $this->_printTemplateContent($thistpl . '/survey.pstpl', $redata, __LINE__); echo $html; $this->_printTemplateContent($thistpl . '/endpage.pstpl', $redata, __LINE__); doFooter(); }
function savedcontrol() { //This data will be saved to the "saved_control" table with one row per response. // - a unique "saved_id" value (autoincremented) // - the "sid" for this survey // - the "srid" for the survey_x row id // - "saved_thisstep" which is the step the user is up to in this survey // - "saved_ip" which is the ip address of the submitter // - "saved_date" which is the date ofthe saved response // - an "identifier" which is like a username // - a "password" // - "fieldname" which is the fieldname of the saved response // - "value" which is the value of the response //We start by generating the first 5 values which are consistent for all rows. global $surveyid, $thissurvey, $errormsg, $publicurl, $sitename, $clang, $clienttoken, $thisstep; $timeadjust = getGlobalSetting('timeadjust'); //Check that the required fields have been completed. $errormsg = ''; if (empty($_POST['savename'])) { $errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n"; } if (empty($_POST['savepass'])) { $errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n"; } if (empty($_POST['savepass']) || empty($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) { $errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n"; } // if security question asnwer is incorrect if (function_exists("ImageCreate") && isCaptchaEnabled('saveandloadscreen', $thissurvey['usecaptcha'])) { if (empty($_POST['loadsecurity']) || !isset($_SESSION['survey_' . $surveyid]['secanswer']) || $_POST['loadsecurity'] != $_SESSION['survey_' . $surveyid]['secanswer']) { $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n"; } } if (!empty($errormsg)) { return; } $duplicate = SavedControl::model()->findByAttributes(array('sid' => $surveyid, 'identifier' => $_POST['savename'])); if (!empty($duplicate) && $duplicate->count() > 0) { $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n"; return; } else { //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist if (!isset($_SESSION['survey_' . $surveyid]['srid'])) { $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); $sdata = array("datestamp" => $today, "ipaddr" => getIPAddress(), "startlanguage" => $_SESSION['survey_' . $surveyid]['s_lang'], "refurl" => getenv("HTTP_REFERER")); if (SurveyDynamic::model($thissurvey['sid'])->insert($sdata)) { $srid = getLastInsertID('{{survey_' . $surveyid . '}}'); $_SESSION['survey_' . $surveyid]['srid'] = $srid; } else { safeDie("Unable to insert record into survey table.<br /><br />"); } } //CREATE ENTRY INTO "saved_control" $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); $saved_control = new SavedControl(); $saved_control->sid = $surveyid; $saved_control->srid = $_SESSION['survey_' . $surveyid]['srid']; $saved_control->identifier = $_POST['savename']; // Binding does escape, so no quoting/escaping necessary $saved_control->access_code = md5($_POST['savepass']); $saved_control->email = $_POST['saveemail']; $saved_control->ip = getIPAddress(); $saved_control->saved_thisstep = $thisstep; $saved_control->status = 'S'; $saved_control->saved_date = $today; $saved_control->refurl = getenv('HTTP_REFERER'); if ($saved_control->save()) { $scid = getLastInsertID('{{saved_control}}'); $_SESSION['survey_' . $surveyid]['scid'] = $scid; } else { safeDie("Unable to insert record into saved_control table.<br /><br />"); } $_SESSION['survey_' . $surveyid]['holdname'] = $_POST['savename']; //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output $_SESSION['survey_' . $surveyid]['holdpass'] = $_POST['savepass']; //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output //Email if needed if (isset($_POST['saveemail']) && validateEmailAddress($_POST['saveemail'])) { $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name']; $message = $clang->gT("Thank you for saving your survey in progress. The following details can be used to return to this survey and continue where you left off. Please keep this e-mail for your reference - we cannot retrieve the password for you."); $message .= "\n\n" . $thissurvey['name'] . "\n\n"; $message .= $clang->gT("Name") . ": " . $_POST['savename'] . "\n"; $message .= $clang->gT("Password") . ": " . $_POST['savepass'] . "\n\n"; $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . "\n"; $message .= Yii::app()->getController()->createAbsoluteUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/{$scid}/loadname/" . rawurlencode($_POST['savename']) . "/loadpass/" . rawurlencode($_POST['savepass']) . "/lang/" . rawurlencode($clang->langcode)); if ($clienttoken) { $message .= "/token/" . rawurlencode($clienttoken); } $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent = "Y"; } else { $errormsg .= $clang->gT('Error: Email failed, this may indicate a PHP Mail Setup problem on the server. Your survey details have still been saved, however you will not get an email with the details. You should note the "name" and "password" you just used for future reference.'); if (trim($thissurvey['adminemail']) == '') { $errormsg .= $clang->gT('(Reason: Admin email address empty)'); } } } return $clang->gT('Your survey was successfully saved.'); } }
/** * 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/> <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); } } }
$fieldsarray["{SURVEYURL}"]="<a href='$publicurl/index.php?lang=".$baselang."&sid=$surveyid&token=$newtoken'>".htmlspecialchars("$publicurl/index.php?lang=".$baselang."&sid=$surveyid&token=$newtoken")."</a>"; $fieldsarray["{OPTOUTURL}"]="<a href='$publicurl/optout.php?lang=".$baselang."&sid=$surveyid&token=$newtoken'>".htmlspecialchars("$publicurl/optout.php?lang=".$baselang."&sid=$surveyid&token=$newtoken")."</a>"; } else { $useHtmlEmail = false; $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".$baselang."&sid=$surveyid&token=$newtoken"; $fieldsarray["{OPTOUTURL}"]="$publicurl/optout.phplang=".$baselang."&sid=$surveyid&token=$newtoken"; } $message=ReplaceFields($message, $fieldsarray); $subject=ReplaceFields($subject, $fieldsarray); $html=""; //Set variable if (SendEmailMessage($message, $subject, returnglobal('register_email'), $from, $sitename,$useHtmlEmail,getBounceEmail($surveyid))) { // TLR change to put date into sent // $query = "UPDATE {$dbprefix}tokens_$surveyid\n" // ."SET sent='Y' WHERE tid=$tid"; $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); $query = "UPDATE {$dbprefix}tokens_$surveyid\n" ."SET sent='$today' WHERE tid=$tid"; $result=$connect->Execute($query) or safe_die ("$query<br />".$connect->ErrorMsg()); //Checked $html="<center>".$clang->gT("Thank you for registering to participate in this survey.")."<br /><br />\n".$clang->gT("An email has been sent to the address you provided with access details for this survey. Please follow the link in that email to proceed.")."<br /><br />\n".$clang->gT("Survey Administrator")." {ADMINNAME} ({ADMINEMAIL})"; $html=ReplaceFields($html, $fieldsarray); $html .= "<br /><br /></center>\n"; } else { $html="Email Error";
/** * dataentry::insert() * insert new dataentry * @return */ public function insert() { $clang = Yii::app()->lang; $subaction = Yii::app()->request->getPost('subaction'); $surveyid = Yii::app()->request->getPost('sid'); $lang = isset($_POST['lang']) ? Yii::app()->request->getPost('lang') : NULL; $aData = array('surveyid' => $surveyid, 'lang' => $lang, 'clang' => $clang); if (hasSurveyPermission($surveyid, 'responses', 'read')) { if ($subaction == "insert" && hasSurveyPermission($surveyid, 'responses', 'create')) { $surveytable = "{{survey_{$surveyid}}}"; $thissurvey = getSurveyInfo($surveyid); $errormsg = ""; Yii::app()->loadHelper("database"); $aViewUrls['display']['menu_bars']['browse'] = $clang->gT("Data entry"); $aDataentryoutput = ''; $aDataentrymsgs = array(); $hiddenfields = ''; $lastanswfortoken = ''; // check if a previous answer has been submitted or saved $rlanguage = ''; if (isset($_POST['token'])) { $tokencompleted = ""; $tcquery = "SELECT completed from {{tokens_{$surveyid}}} WHERE token='{$_POST['token']}'"; //dbQuoteAll($_POST['token'],true); $tcresult = dbExecuteAssoc($tcquery); $tcresult = $tcresult->readAll(); $tccount = count($tcresult); foreach ($tcresult as $tcrow) { $tokencompleted = $tcrow['completed']; } if ($tccount < 1) { // token doesn't exist in token table $lastanswfortoken = 'UnknownToken'; } elseif ($thissurvey['anonymized'] == "Y") { // token exist but survey is anonymous, check completed state if ($tokencompleted != "" && $tokencompleted != "N") { // token is completed $lastanswfortoken = 'PrivacyProtected'; } } else { // token is valid, survey not anonymous, try to get last recorded response id $aquery = "SELECT id,startlanguage FROM {$surveytable} WHERE token='" . $_POST['token'] . "'"; //dbQuoteAll($_POST['token'],true); $aresult = dbExecuteAssoc($aquery); foreach ($aresult->readAll() as $arow) { if ($tokencompleted != "N") { $lastanswfortoken = $arow['id']; } $rlanguage = $arow['startlanguage']; } } } // First Check if the survey uses tokens and if a token has been provided if (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && !$_POST['token']) { $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error")); $errormsg .= CHtml::tag('p', array(), $clang->gT("This is a closed-access survey, so you must supply a valid token. Please contact the administrator for assistance.")); } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken == 'UnknownToken') { $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error")); $errormsg .= CHtml::tag('p', array(), $clang->gT("The token you have provided is not valid or has already been used.")); } elseif (tableExists('{{tokens_' . $thissurvey['sid'] . '}}') && $lastanswfortoken != '') { $errormsg = CHtml::tag('div', array('class' => 'warningheader'), $clang->gT("Error")); $errormsg .= CHtml::tag('p', array(), $clang->gT("There is already a recorded answer for this token")); if ($lastanswfortoken != 'PrivacyProtected') { $errormsg .= "<br /><br />" . $clang->gT("Follow the following link to update it") . ":\n"; $errormsg .= CHtml::link("[id:{$lastanswfortoken}]", Yii::app()->baseUrl . ('/admin/dataentry/editdata/subaction/edit/id/' . $lastanswfortoken . '/surveyid/' . $surveyid . '/lang/' . $rlanguage), array('title' => $clang->gT("Edit this entry"))); } else { $errormsg .= "<br /><br />" . $clang->gT("This surveys uses anonymized responses, so you can't update your response.") . "\n"; } } else { $last_db_id = 0; if (isset($_POST['save']) && $_POST['save'] == "on") { $aData['save'] = TRUE; $saver['identifier'] = $_POST['save_identifier']; $saver['language'] = $_POST['save_language']; $saver['password'] = $_POST['save_password']; $saver['passwordconfirm'] = $_POST['save_confirmpassword']; $saver['email'] = $_POST['save_email']; if (!returnGlobal('redo')) { $password = md5($saver['password']); } else { $password = $saver['password']; } $errormsg = ""; if (!$saver['identifier']) { $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a name for this saved session."); } if (!$saver['password']) { $errormsg .= $clang->gT("Error") . ": " . $clang->gT("You must supply a password for this saved session."); } if ($saver['password'] != $saver['passwordconfirm']) { $errormsg .= $clang->gT("Error") . ": " . $clang->gT("Your passwords do not match."); } $aData['errormsg'] = $errormsg; if ($errormsg) { foreach ($_POST as $key => $val) { if (substr($key, 0, 4) != "save" && $key != "action" && $key != "sid" && $key != "datestamp" && $key != "ipaddr") { $hiddenfields .= CHtml::hiddenField($key, $val); //$aDataentryoutput .= "<input type='hidden' name='$key' value='$val' />\n"; } } } } //BUILD THE SQL TO INSERT RESPONSES $baselang = Survey::model()->findByPk($surveyid)->language; $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid)); $insert_data = array(); $_POST['startlanguage'] = $baselang; if ($thissurvey['datestamp'] == "Y") { $_POST['startdate'] = $_POST['datestamp']; } if (isset($_POST['closerecord'])) { if ($thissurvey['datestamp'] == "Y") { $_POST['submitdate'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust')); } else { $_POST['submitdate'] = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980)); } } foreach ($fieldmap as $irow) { $fieldname = $irow['fieldname']; if (isset($_POST[$fieldname])) { if ($_POST[$fieldname] == "" && ($irow['type'] == 'D' || $irow['type'] == 'N' || $irow['type'] == 'K')) { // can't add '' in Date column // Do nothing } else { if ($irow['type'] == '|') { if (!strpos($irow['fieldname'], "_filecount")) { $json = $_POST[$fieldname]; $phparray = json_decode(stripslashes($json)); $filecount = 0; for ($i = 0; $filecount < count($phparray); $i++) { if ($_FILES[$fieldname . "_file_" . $i]['error'] != 4) { $target = Yii::app()->getConfig('uploaddir') . "/surveys/" . $thissurvey['sid'] . "/files/" . randomChars(20); $size = 0.001 * $_FILES[$fieldname . "_file_" . $i]['size']; $name = rawurlencode($_FILES[$fieldname . "_file_" . $i]['name']); if (move_uploaded_file($_FILES[$fieldname . "_file_" . $i]['tmp_name'], $target)) { $phparray[$filecount]->filename = basename($target); $phparray[$filecount]->name = $name; $phparray[$filecount]->size = $size; $pathinfo = pathinfo($_FILES[$fieldname . "_file_" . $i]['name']); $phparray[$filecount]->ext = $pathinfo['extension']; $filecount++; } } } $insert_data[$fieldname] = ls_json_encode($phparray); } else { $insert_data[$fieldname] = count($phparray); } } elseif ($irow['type'] == 'D') { Yii::app()->loadLibrary('Date_Time_Converter'); $qidattributes = getQuestionAttributeValues($irow['qid'], $irow['type']); $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey); $datetimeobj = new Date_Time_Converter($_POST[$fieldname], $dateformatdetails['phpdate']); $insert_data[$fieldname] = $datetimeobj->convert("Y-m-d H:i:s"); } else { $insert_data[$fieldname] = $_POST[$fieldname]; } } } } Survey_dynamic::sid($surveyid); $new_response = new Survey_dynamic(); foreach ($insert_data as $column => $value) { $new_response->{$column} = $value; } $new_response->save(); $last_db_id = $new_response->getPrimaryKey(); if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') { // get submit date if (isset($_POST['closedate'])) { $submitdate = $_POST['closedate']; } else { $submitdate = dateShift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust); } // check how many uses the token has left $usesquery = "SELECT usesleft FROM {{tokens_}}{$surveyid} WHERE token='" . $_POST['token'] . "'"; $usesresult = dbExecuteAssoc($usesquery); $usesrow = $usesresult->readAll(); //$usesresult->row_array() if (isset($usesrow)) { $usesleft = $usesrow[0]['usesleft']; } // query for updating tokens $utquery = "UPDATE {{tokens_{$surveyid}}}\n"; if (isTokenCompletedDatestamped($thissurvey)) { if (isset($usesleft) && $usesleft <= 1) { $utquery .= "SET usesleft=usesleft-1, completed='{$submitdate}'\n"; } else { $utquery .= "SET usesleft=usesleft-1\n"; } } else { if (isset($usesleft) && $usesleft <= 1) { $utquery .= "SET usesleft=usesleft-1, completed='Y'\n"; } else { $utquery .= "SET usesleft=usesleft-1\n"; } } $utquery .= "WHERE token='" . $_POST['token'] . "'"; $utresult = dbExecuteAssoc($utquery); //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!<br />\n$utquery<br />\n".Yii::app()->db->ErrorMsg()); // save submitdate into survey table $srid = Yii::app()->db->getLastInsertID(); // Yii::app()->db->getLastInsertID(); $sdquery = "UPDATE {{survey_{$surveyid}}} SET submitdate='" . $submitdate . "' WHERE id={$srid}\n"; $sdresult = dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!<br />\n{$sdquery}<br />\n"); $last_db_id = Yii::app()->db->getLastInsertID(); } if (isset($_POST['save']) && $_POST['save'] == "on") { $srid = Yii::app()->db->getLastInsertID(); //Yii::app()->db->getLastInsertID(); $aUserData = Yii::app()->session; //CREATE ENTRY INTO "saved_control" $saved_control_table = '{{saved_control}}'; $columns = array("sid", "srid", "identifier", "access_code", "email", "ip", "refurl", 'saved_thisstep', "status", "saved_date"); $values = array("'" . $surveyid . "'", "'" . $srid . "'", "'" . $saver['identifier'] . "'", "'" . $password . "'", "'" . $saver['email'] . "'", "'" . $aUserData['ip_address'] . "'", "'" . getenv("HTTP_REFERER") . "'", 0, "'" . "S" . "'", "'" . dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", "'" . Yii::app()->getConfig('timeadjust')) . "'"); $SQL = "INSERT INTO {$saved_control_table}\n (" . implode(',', $columns) . ")\n VALUES\n (" . implode(',', $values) . ")"; /*$scdata = array("sid"=>$surveyid, "srid"=>$srid, "identifier"=>$saver['identifier'], "access_code"=>$password, "email"=>$saver['email'], "ip"=>$aUserData['ip_address'], "refurl"=>getenv("HTTP_REFERER"), 'saved_thisstep' => 0, "status"=>"S", "saved_date"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", Yii::app()->getConfig('timeadjust'))); $this->load->model('saved_control_model');*/ if (dbExecuteAssoc($SQL)) { $scid = Yii::app()->db->getLastInsertID(); // Yii::app()->db->getLastInsertID("{{saved_control}}","scid"); $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("Your survey responses have been saved successfully. You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you.")); //$aDataentryoutput .= "<font class='successtitle'></font><br />\n"; $tokens_table = "{{tokens_{$surveyid}}}"; $last_db_id = Yii::app()->db->getLastInsertID(); if (tableExists($tokens_table)) { $tkquery = "SELECT * FROM {$tokens_table}"; $tkresult = dbExecuteAssoc($tkquery); /*$tokendata = array ( "firstname"=> $saver['identifier'], "lastname"=> $saver['identifier'], "email"=>$saver['email'], "token"=>randomChars(15), "language"=>$saver['language'], "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust), "completed"=>"N");*/ $columns = array("firstname", "lastname", "email", "token", "language", "sent", "completed"); $values = array("'" . $saver['identifier'] . "'", "'" . $saver['identifier'] . "'", "'" . $saver['email'] . "'", "'" . $password . "'", "'" . randomChars(15) . "'", "'" . $saver['language'] . "'", "'" . "N" . "'"); $SQL = "INSERT INTO {$token_table}\n (" . implode(',', $columns) . ")\n VALUES\n (" . implode(',', $values) . ")"; //$this->tokens_dynamic_model->insertToken($surveyid,$tokendata); dbExecuteAssoc($SQL); //Yii::app()->db->AutoExecute(db_table_name("tokens_".$surveyid), $tokendata,'INSERT'); $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("A token entry for the saved survey has been created too.")); //$aDataentryoutput .= "<font class='successtitle'></font><br />\n"; $last_db_id = Yii::app()->db->getLastInsertID(); } if ($saver['email']) { //Send email if (validateEmailAddress($saver['email']) && !returnGlobal('redo')) { $subject = $clang->gT("Saved Survey Details"); $message = $clang->gT("Thank you for saving your survey in progress. The following details can be used to return to this survey and continue where you left off. Please keep this e-mail for your reference - we cannot retrieve the password for you."); $message .= "\n\n" . $thissurvey['name'] . "\n\n"; $message .= $clang->gT("Name") . ": " . $saver['identifier'] . "\n"; $message .= $clang->gT("Password") . ": " . $saver['password'] . "\n\n"; $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):") . ":\n"; $message .= Yii::app()->getConfig('publicurl') . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&lang=" . urlencode($saver['language']) . "&loadname=" . urlencode($saver['identifier']) . "&loadpass="******"&token=" . $tokendata['token']; } $from = $thissurvey['adminemail']; if (SendEmailMessage($message, $subject, $saver['email'], $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent = "Y"; $aDataentrymsgs[] = CHtml::tag('font', array('class' => 'successtitle'), $clang->gT("An email has been sent with details about your saved survey")); } } } } else { safeDie("Unable to insert record into saved_control table.<br /><br />"); } } $aData['thisid'] = $last_db_id; } $aData['errormsg'] = $errormsg; $aData['dataentrymsgs'] = $aDataentrymsgs; $this->_renderWrappedTemplate('dataentry', 'insert', $aData); } } }
if ($modrewrite) { $fieldsarray["{SURVEYURL}"] = "<a href='{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}'>" . htmlspecialchars("{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}") . "</a>"; $fieldsarray["@@SURVEYURL@@"] = "{$publicurl}/{$surveyid}/lang-" . trim($emrow['language']) . "/tk-{$emrow['token']}"; } else { $fieldsarray["{SURVEYURL}"] = "<a href='{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}'>" . htmlspecialchars("{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}") . "</a>"; $fieldsarray["@@SURVEYURL@@"] = "{$publicurl}/index.php?lang=" . trim($emrow['language']) . "&sid={$surveyid}&token={$emrow['token']}"; $_POST['message_' . $emrow['language']] = html_entity_decode($_POST['message_' . $emrow['language']], ENT_QUOTES, $emailcharset); } } $msgsubject = Replacefields($_POST['subject_' . $emrow['language']], $fieldsarray); $sendmessage = Replacefields($_POST['message_' . $emrow['language']], $fieldsarray); 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); } elseif (SendEmailMessage($sendmessage, $msgsubject, $to, $from, $sitename, $ishtml, getBounceEmail($surveyid))) { // Put date into remindersent $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust); $udequery = "UPDATE " . db_table_name("tokens_{$surveyid}") . "\n" . "SET remindersent='{$today}',remindercount = remindercount+1 WHERE tid={$emrow['tid']}"; // $uderesult = $connect->Execute($udequery) or safe_die("Could not update tokens<br />{$udequery}<br />" . $connect->ErrorMsg()); //orig: $tokenoutput .= "({$emrow['tid']})[".$clang->gT("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]<br />\n"; $tokenoutput .= "({$emrow['tid']}) [" . $clang->gT("Reminder sent to:") . " {$emrow['firstname']} {$emrow['lastname']} ({$to})]<br />\n"; } else { $tokenoutput .= $emrow['tid'] . " " . ReplaceFields($clang->gT("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:") . " " . $maildebug . "<br />", $fieldsarray); if ($debug > 0) { $tokenoutput .= "<pre>Subject : {$msgsubject}<br /><br />" . htmlspecialchars($maildebugbody) . "<br /></pre>"; } } $lasttid = $emrow['tid']; }