Guest User

Untitled

a guest
May 18th, 2019
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.75 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Survey page
  4.  *
  5.  * @author Fredrick Gabelmann <fredrick.gabelmann@interspire.com>
  6.  *
  7.  * To render out a survey for the link provided for the user..
  8.  */
  9.  
  10. // Make sure that the IEM controller does NOT redirect request.
  11. if (!defined('IEM_NO_CONTROLLER')) {
  12.     define('IEM_NO_CONTROLLER', true);
  13. }
  14.  
  15. /**
  16. * Require base sendstudio functionality. This connects to the database, sets up our base paths and so on.
  17. */
  18. require_once dirname(__FILE__) . '/admin/index.php';
  19. require_once SENDSTUDIO_FUNCTION_DIRECTORY . '/sendstudio_functions.php';
  20. require_once SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/api/surveys.php';
  21. require_once SENDSTUDIO_BASE_DIRECTORY . '/addons/interspire_addons.php';
  22. require_once SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/language/language.php';
  23.  
  24. class surveySubmit extends Interspire_Addons {
  25.  
  26.     /**
  27.      * api
  28.      * Holds reference to surveys api
  29.      */
  30.     static public $api;
  31.  
  32.     public function __construct() {
  33.         $this->_handleSubmitAction();
  34.     }
  35.  
  36.     public function getApi()
  37.     {
  38.         if (!self::$api instanceof Addons_survey_api) {
  39.             if (!class_exists('Addons_survey_api', false)) {
  40.                 require(SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/api/surveys.php');
  41.             }
  42.             self::$api = new Addons_survey_api();
  43.         }
  44.  
  45.         return self::$api;
  46.     }
  47.  
  48.     /**
  49.      * Redirects back to the http referer.s
  50.      *
  51.      * @return Void
  52.      */
  53.     private function redirectToReferer()
  54.     {
  55.         header('Location: ' . $_SERVER['HTTP_REFERER']);
  56.         exit;
  57.     }
  58.  
  59.     /**
  60.      * getSpecificApi
  61.      *
  62.      * @param $api string apiname
  63.      * Will call the specific api specified in the parametersthe files
  64.      * need to exist under the addon directory
  65.      * Will return false if no file is found.
  66.      *
  67.      * @return the API object
  68.      */
  69.  
  70.     public function getSpecificApi($api)
  71.     {
  72.         $className = 'Addons_survey_' . $api . '_api';
  73.         if (!class_exists($className, false)) {
  74.                 if (file_exists(SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/api/' . $api . '.php')) {
  75.                     require_once(SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/api/' . $api . '.php');
  76.                 } else {
  77.                     return false;
  78.                 }
  79.         }
  80.         $instance = new $className;
  81.         return $instance;
  82.     }
  83.  
  84.     /**
  85.      * _validateIsBlank
  86.      * @param $str the string
  87.      * @param $trim whether or not to trim the str
  88.      *
  89.      * Handles the form submission from all feedback forms on the front end.
  90.      *
  91.      * @return boolean true when its blank, false otherwise
  92.      **/
  93.     private function _validateIsBlank($str,$trim=true)
  94.     {
  95.         if ($trim) { $str = trim($str); }
  96.         if(strlen($str) === 0 || $str === null || strtolower($str) == "null" || $str === "0" || $str === 0){
  97.             return true;
  98.         }else{
  99.             return false;
  100.         }
  101.     }
  102.  
  103.     private function _handleSubmitAction()
  104.     {
  105.         // don't escape
  106.         $template_dir = SENDSTUDIO_BASE_DIRECTORY . '/addons/surveys/templates';
  107.         $this->_template =   GetTemplateSystem($template_dir);
  108.  
  109.         $this->_template->DefaultHtmlEscape = false;
  110.  
  111.         $formId      = (int) IEM::requestGetGET('formId');
  112.         $postWidgets = IEM::requestGetPOST('widget');
  113.  
  114.         // If there are files, take the values and place them in the $postWidgets array so they can
  115.         // get validated and entered into the response values in the same manner. Uploads will be
  116.         // handled separately.
  117.  
  118.         if (isset($_FILES['widget'])) {
  119.             foreach ($_FILES['widget']['name'] as $widgetId => $widget) {
  120.                 foreach ($widget as $fields) {
  121.                     foreach ($fields as $fieldId => $field) {
  122.                         $postWidgets[$widgetId]['field'][$fieldId]['value'] = 'file_' . $field['value'];
  123.                     }
  124.                 }
  125.             }
  126.         }
  127.  
  128.         // If the form and widgets weren't posted in the format we require then redirect back
  129.         if (!$formId) {
  130.             $this->redirectToReferer();
  131.         }
  132.  
  133.         $surveyApi = $this->getApi();
  134.         $surveyApi->Load($formId);
  135.         $surveyData = $surveyApi->GetData();
  136.  
  137.         $errors       = 0;
  138.         $widgets      = $surveyApi->getWidgets($formId);
  139.         $widgetErrors = array();
  140.  
  141.  
  142.         /****  START OF ERROR VALIDATION ****/
  143.  
  144.         // compile a list of widget ids so we can check the posted widgets against a list of
  145.         // valid widget ids
  146.  
  147.  
  148.         foreach ($widgets as $widgetKey => $widget) {
  149.  
  150.             if (!isset($widgetErrors[$widget['id']])) {
  151.                 $widgetErrors[$widget['id']] = array();
  152.             }
  153.  
  154.             // validate required fields
  155.             if ($widget['is_required']) {
  156.                 // the widget is assumed blank until one of it's fields is found not blank
  157.                 $isBlank = true;
  158.                 $isOther = false;
  159.  
  160.  
  161.                 // make sure the required widget was even posted
  162.  
  163.                 if (isset($postWidgets[$widget['id']])) {
  164.                     foreach ($postWidgets[$widget['id']]['field'] as $field) {
  165.                         if (isset($field['value'])) {
  166.                             $values = (array) $field['value'];
  167.  
  168.                             foreach ($values as $value) {
  169.  
  170.                                 // get the value of an "other" field if it is one, otherwise just grab
  171.                                 // the normal value
  172.                                 if ($value == '__other__') {
  173.                                     $isOther = true;
  174.                                     $value   = $field['other'];
  175.                                 }
  176.  
  177.                                 // make sure the value isn't blank
  178.                                 if ($this->_validateIsBlank($value) !== true) {
  179.                                     $isBlank = false;
  180.                                 }
  181.                             }
  182.                         }
  183.                     }
  184.                 }
  185.  
  186.                 // if the widget is blank, flag an error
  187.                 if ($isBlank) {
  188.                     if ($isOther) {
  189.                         $error = GetLang('Addon_Surveys_ErrorRequiredOther');
  190.                     } else {
  191.                         $error = GetLang('Addon_Surveys_ErrorRequired');
  192.                     }
  193.                     $widgetErrors[$widget['id']][] = $error;
  194.                     $errors++;
  195.                 }
  196.  
  197.                 if ($widget['type'] == 'file') {
  198.                     foreach ($postWidgets[$widget['id']]['field'] as $fieldid) {
  199.                         if (isset($fieldid['value'])) {$uploaded_file = $fieldid['value'];break;}
  200.                     }
  201.                     if (empty($uploaded_file) || $uploaded_file == "file_") {
  202.                         $error = GetLang('Addon_Surveys_ErrorRequired');
  203.                         $widgetErrors[$widget['id']][] = $error;
  204.                         $errors++;
  205.                     }
  206.                 }
  207.             }
  208.  
  209.  
  210.  
  211.  
  212.             // validate file types
  213.             if ($widget['type'] == 'file') {
  214.  
  215.                 if (!empty($widget['allowed_file_types'])) {
  216.                     $typeArr     = preg_split('/\s*,\s*/', strtolower($widget['allowed_file_types']));
  217.                     $invalidType = false;
  218.  
  219.  
  220.                     // foreach of the passed fields (most likely 1) check and see if they are valid file types
  221.                     foreach ($postWidgets[$widget['id']]['field'] as $field) {
  222.                         $parts = explode('.', $field['value']);
  223.                         $ext   = strtolower(end($parts));
  224.  
  225.  
  226.  
  227.                         // only if the field has a value we will test its file type
  228.                         if (trim($field['value']) != '' && !in_array($ext, $typeArr)) {
  229.                             $invalidType = true;
  230.                         }
  231.                     }
  232.  
  233.                     // if the a file is not a valid file type, then the whole widget fails validation
  234.                     if ($invalidType) {
  235.                         $lastFileType   = '<em>.' . array_pop($typeArr) . '</em>';
  236.                         $firstFileTypes = '<em>.' . implode('</em>, <em>.', $typeArr) . '</em>';
  237.                         $widgetErrors[$widget['id']][] = sprintf(GetLang('Addon_Surveys_ErrorInvalidFileType'), $lastFileType, $firstFileTypes);
  238.                         $errors++;
  239.                     }
  240.                 }
  241.             }
  242.  
  243.             if (isset($postWidgets[$widget['id']])) {
  244.                 // add a value to the values array so it can be passed to the email feedback template
  245.                 @$widgets[$widgetKey]['values'] = $postWidgets[$widget['id']]['field'];
  246.             }
  247.         }
  248.  
  249.         // if there were errors, redirect back and display the errors
  250.         if ($errors) {
  251.             // set a global error message to alert the user to the specific errors
  252.             IEM::sessionSet('survey.addon.' . $formId . '.errorMessage', $surveyData['error_message']);
  253.             // set the widget errors so we can retrieve them for the user
  254.             IEM::sessionSet('survey.addon.' . $formId . '.widgetErrors', $widgetErrors);
  255.             $this->redirectToReferer();
  256.         }
  257.  
  258.         /****  END OF ERROR VALIDATION ****/
  259.  
  260.         // isntantiate a new response object
  261.         $response = $this->getSpecificApi('responses');
  262.  
  263.         // associate the response to a particular form
  264.         $response->surveys_id = $formId;
  265.  
  266.         // if the response was saved, then associate values to the response
  267.         if ($response->Save()) {
  268.             // foreach of the posted widgets, check to see if it belongs in this form and save it if it does
  269.  
  270.             foreach ($postWidgets as $postWidgetId => $postWidget) {
  271.                 // iterate through each field and enter it in the feedback
  272.  
  273.                 foreach ($postWidget['field'] as $field) {
  274.                     // make sure it has a value first
  275.  
  276.                     if (isset($field['value'])) {
  277.                         // since multiple values can be given, we treat them as an array
  278.                         $values = (array) $field['value'];
  279.  
  280.                         foreach ($values as $value) {
  281.  
  282.                             $responseValue = $this->getSpecificApi('responsesvalue');
  283.                             // foreign key for the response id
  284.                             $responseValue->surveys_response_id = $response->GetId();
  285.  
  286.                             // set the widget id foreign key; widgets can have multiple field values and
  287.                             // should be treated as such
  288.                             $responseValue->surveys_widgets_id =  $postWidgetId;
  289.  
  290.                             // set the value of the feedback; this should be a single value since widgets
  291.                             // can have multiple feed back values
  292.                             if ($value == '__other__') {
  293.                                 $responseValue->value =  $field['other'];
  294.                                 $responseValue->is_othervalue = 1;
  295.                             } else {
  296.                                 // if file value exist we need to save the md5 name of the file in the database
  297.                                 $responseValue->file_value = "";
  298.                                 if (substr($value, 0, 5) == "file_") {
  299.                                     $value = str_replace("file_", "", $value);
  300.                                     $responseValue->file_value = md5($value);
  301.                                 }
  302.  
  303.                                 $responseValue->value = $value;
  304.                                 $responseValue->is_othervalue = 0;
  305.                             }
  306.  
  307.                             // save it
  308.                             $responseValue->Save();
  309.                         }
  310.  
  311.                     }
  312.                 }
  313.             }
  314.  
  315.             // send an email if desired
  316.             /**
  317.              *  Prepare for sending the email..
  318.              */
  319.  
  320.             $widget_api = $this->getSpecificApi('widgets');
  321.  
  322.             if ($surveyData['email_feedback']) {
  323.                 foreach ($widgets as &$widget) {
  324.                     $widget_api->populateFormData($widget);
  325.  
  326.                     // set the values (normally 1, unless it's a list of checkboxes)
  327.                     $widget['values'] = $widget_api->getResponseValues($response->id);
  328.  
  329.                     // get the other value
  330.                     $other = $widget_api->getOtherField();
  331.  
  332.                     // add the full url to the file
  333.                     if ($widget['type'] == 'file') {
  334.                         $attachment_url = "admin/index.php?Page=Addons&Addon=surveys&Action=DownloadAttach&ajax=1&formId=" . $formId . "&responseId=" . $response->id . "&value=" . base64_encode($widget['values'][0]['value']);
  335.                         $attachment_tag =  SENDSTUDIO_APPLICATION_URL . "/" .  $attachment_url;
  336.                         // . "'>" . $widget['values'][0]['value'];
  337.                         $widget['values'][0]['value'] = $attachment_tag;
  338.                     }
  339.  
  340.                     if ($other) {
  341.                         // the other value will be the last one
  342.                         $otherValueIndex = count($widget['values']) - 1;
  343.                         $widget['values'][$otherValueIndex]['value'] = $other['other_label_text'] . ' ' . $widget['values'][$otherValueIndex]['value'];
  344.                     }
  345.                 }
  346.  
  347.  
  348.                 $viewUri = SENDSTUDIO_APPLICATION_URL
  349.                      . '/admin/index.php?Page=Addons&Addon=surveys&Action=viewresponses&surveyId='
  350.                      . $surveyApi->id
  351.                      . '&responseId='
  352.                      . $response->id;
  353.                 $editUri = SENDSTUDIO_APPLICATION_URL
  354.                      . '/admin/index.php?Page=Addons&Addon=surveys&Action=editresponse&surveyId='
  355.                      . $surveyApi->id
  356.                      . '&responseId='
  357.                      . $response->id;
  358.  
  359.                 $this->_template->Assign('form', $surveyApi->GetData());
  360.                 $this->_template->Assign('widgets', $widgets);
  361.                 $this->_template->Assign('emailBodyStart', sprintf(GetLang('Addon_Surveys_emailBodyStart'), $surveyApi->Get('name')));
  362.                 $this->_template->Assign('emailViewLink', sprintf(GetLang('Addon_Surveys_emailViewLink'), $viewUri));
  363.                 $this->_template->Assign('emailEditLink', sprintf(GetLang('Addon_Surveys_emailEditLink'), $editUri));
  364.  
  365.                 // parse the email template for its content
  366.                 $emailTemplate = $this->_template->ParseTemplate('email', true);
  367.  
  368.                 require_once(IEM_PATH . '/ext/interspire_email/email.php');
  369.                 $emailapi = new Email_API();
  370.  
  371.                 $emailapi->SetSmtp(SENDSTUDIO_SMTP_SERVER, SENDSTUDIO_SMTP_USERNAME, @base64_decode(SENDSTUDIO_SMTP_PASSWORD), SENDSTUDIO_SMTP_PORT);
  372.                 //if ($this->smtpserver) {
  373.                 //  $emailapi->SetSmtp($this->smtpserver, $this->smtpusername, $this->smtppassword, $this->smtpport);
  374.                 //}
  375.  
  376.                 $emailapi->ClearRecipients();
  377.                 $emailapi->ForgetEmail();
  378.                 $emailapi->Set('forcechecks', false);
  379.  
  380.                 $to = ($surveyApi->Get('email'));
  381.                 $emailapi->AddRecipient($to);
  382.  
  383.                 $emailapi->Set('FromAddress', (defined('SENDSTUDIO_EMAIL_ADDRESS') ? SENDSTUDIO_EMAIL_ADDRESS : $userobject->emailaddress));
  384.                 $emailapi->Set('BounceAddress', SENDSTUDIO_EMAIL_ADDRESS);
  385.                 $emailapi->Set('CharSet', SENDSTUDIO_CHARSET);
  386.  
  387.                 $subject = sprintf(GetLang('Addon_Surveys_emailSubject'), $surveyApi->Get('name'));
  388.                 $emailapi->Set('Subject', $subject);
  389.  
  390.  
  391.                 //email body
  392.                 $emailapi->AddBody('text', $emailTemplate);
  393.                 $status = $emailapi->Send();
  394.                 if ($status['success'] != 1) {
  395.                     trigger_error(__CLASS__ . '::' . __METHOD__ . ' -- Was not able to send email: ' . serialize($status['failed']), E_USER_NOTICE);
  396.                     return false;
  397.                 }
  398.             }
  399.  
  400.             // perform file uploading
  401.  
  402.             if (isset($_FILES['widget']['name'])) {
  403.                 $files = $_FILES['widget']['name'];
  404.  
  405.                 foreach ($files as $widgetId => $widget) {
  406.                     foreach ($widget as $widgetKey => $fields) {
  407.                         foreach ($fields as $fieldId => $field) {
  408.                             // gather file information
  409.                             $name    = $_FILES['widget']['name'][$widgetId]['field'][$fieldId]['value'];
  410.                             $type    = $_FILES['widget']['type'][$widgetId]['field'][$fieldId]['value'];
  411.                             $tmpName = $_FILES['widget']['tmp_name'][$widgetId]['field'][$fieldId]['value'];
  412.                             $error   = $_FILES['widget']['error'][$widgetId]['field'][$fieldId]['value'];
  413.                             $size    = $_FILES['widget']['size'][$widgetId]['field'][$fieldId]['value'];
  414.  
  415.                             // if the upload was successful to the temporary folder, move it
  416.                             if ($error == UPLOAD_ERR_OK) {
  417.                                 $tempdir   = TEMP_DIRECTORY;
  418.                                 $upBaseDir = $tempdir . DIRECTORY_SEPARATOR . 'surveys';
  419.                                 $upSurveyDir = $upBaseDir . DIRECTORY_SEPARATOR . $formId;
  420.                                 $upDir     = $upSurveyDir . DIRECTORY_SEPARATOR . $response->GetId();
  421.  
  422.                                 // if the base upload directory doesn't exist create it
  423.                                 if (!is_dir($upBaseDir)) {
  424.                                     mkdir($upBaseDir, 0755);
  425.                                 }
  426.  
  427.                                 if (!is_dir($upSurveyDir)) {
  428.                                     mkdir($upSurveyDir, 0755);
  429.                                 }
  430.  
  431.                                 // if the upload directory doesn't exist create it
  432.                                 if (!is_dir($upDir)) {
  433.                                     mkdir($upDir, 0755);
  434.                                 }
  435.  
  436.                                 // upload the file
  437.                                 move_uploaded_file($tmpName, $upDir . DIRECTORY_SEPARATOR . $name);
  438.                             }
  439.                         }
  440.                     }
  441.                 }
  442.             }
  443.         }
  444.  
  445.         // if we are redirecting to a url, redirect them
  446.         switch ($surveyData['after_submit']) {
  447.             case 'show_uri':
  448.                 header('Location: ' . $surveyApi->show_uri);
  449.                 exit;
  450.             break;
  451.  
  452.             case 'show_message':
  453.                 IEM::sessionSet('survey.addon.' . $formId . '.successMessage', $surveyApi->show_message);
  454.  
  455.             default:
  456.                 // redirect back
  457.                 $this->redirectToReferer();
  458.         }
  459.     }
  460. }
  461.  
  462.  
  463. $submit = new surveySubmit();
  464.  
  465. ?>
Add Comment
Please, Sign In to add comment