/** * Run the handler. Move the elements specified in the element map to their * set paths. */ public function run() { if (count($this->_elementMap) > 0) { foreach ($this->_elementMap as $name => $path) { if (!is_writable($path)) { throw new Exception('File upload path is not writable'); } if (array_key_exists($name, $_FILES) && is_array($_FILES[$name])) { $file = $_FILES[$name]; if (is_array($file['error'])) { // Process multiple upload field foreach ($file['error'] as $key => $error) { if ($error === UPLOAD_ERR_OK) { $pathInfo = pathinfo($file['name'][$key]); $extension = strtolower($pathInfo['extension']); $filenameFilter = new iPhorm_Filter_Filename(); $filename = $filenameFilter->filter($pathInfo['filename']) . '.' . $extension; if (file_exists($path . $filename)) { $filename = $this->_generateFilename($path, $filename); } move_uploaded_file($file['tmp_name'][$key], $path . $filename); } } } else { // Process single upload field if ($file['error'] === UPLOAD_ERR_OK) { $pathInfo = pathinfo($file['name']); $extension = strtolower($pathInfo['extension']); $filenameFilter = new iPhorm_Filter_Filename(); $filename = $filenameFilter->filter($pathInfo['filename']) . '.' . $extension; if (file_exists($path . $filename)) { $filename = $this->_generateFilename($path, $filename); } move_uploaded_file($file['tmp_name'], $path . $filename); } } } } } }
/** * Process the form and returns the response * * @return string */ function iphorm_process_form() { $ajax = isset($_POST['iphorm_ajax']) && $_POST['iphorm_ajax'] == 1; $swfu = isset($_POST['iphorm_swfu']) && $_POST['iphorm_swfu'] == 1; if (isset($_POST['iphorm_id']) && isset($_POST['iphorm_uid']) && ($form = iphorm_get_form($_POST['iphorm_id'], $_POST['iphorm_uid'])) instanceof iPhorm && $form->getActive()) { // Strip slashes from the submitted data (WP adds them automatically) $_POST = stripslashes_deep($_POST); // Pre-process action hooks do_action('iphorm_pre_process', $form); do_action('iphorm_pre_process_' . $form->getId(), $form); $response = ''; // If we have files uploaded via SWFUpload, merge them into $_FILES if ($swfu && isset($_SESSION['iphorm-' . $form->getUniqId()])) { $_FILES = array_merge($_FILES, $_SESSION['iphorm-' . $form->getUniqId()]); } // Set the form element values $form->setValues($_POST); // Calculate which elements are hidden by conditional logic and which groups are empty $form->calculateElementStatus(); // Pre-validate action hooks do_action('iphorm_pre_validate', $form); do_action('iphorm_pre_validate_' . $form->getId(), $form); if ($form->isValid()) { // Post-validate action hooks do_action('iphorm_post_validate', $form); do_action('iphorm_post_validate_' . $form->getId(), $form); // Process any uploads first $attachments = array(); $elements = $form->getElements(); foreach ($elements as $element) { if ($element instanceof iPhorm_Element_File) { $elementName = $element->getName(); if (array_key_exists($elementName, $_FILES) && is_array($_FILES[$elementName])) { $file = $_FILES[$elementName]; if (is_array($file['error'])) { // Process multiple upload field foreach ($file['error'] as $key => $error) { if ($error === UPLOAD_ERR_OK) { $pathInfo = pathinfo($file['name'][$key]); $extension = isset($pathInfo['extension']) ? $pathInfo['extension'] : ''; $filenameFilter = new iPhorm_Filter_Filename(); $filename = strlen($extension) ? str_replace(".{$extension}", '', $pathInfo['basename']) : $pathInfo['basename']; $filename = $filenameFilter->filter($filename); $filename = apply_filters('iphorm_filename_' . $element->getName(), $filename, $element, $form); if (strlen($extension)) { $filename = strlen($filename) ? "{$filename}.{$extension}" : "upload.{$extension}"; } else { $filename = strlen($filename) ? $filename : 'upload'; } $fullPath = $file['tmp_name'][$key]; $value = array('text' => $filename); if ($element->getSaveToServer()) { $result = iphorm_save_uploaded_file($fullPath, $filename, $element, $form->getId()); if ($result !== false) { $fullPath = $result['fullPath']; $filename = $result['filename']; $value = array('url' => iphorm_get_wp_uploads_url() . '/' . $result['path'] . $filename, 'text' => $filename, 'fullPath' => $fullPath); } } if ($element->getAddAsAttachment()) { $attachments[] = array('fullPath' => $fullPath, 'type' => $file['type'][$key], 'filename' => $filename); } $element->addFile($value); } } } else { // Process single upload field if ($file['error'] === UPLOAD_ERR_OK) { $pathInfo = pathinfo($file['name']); $extension = isset($pathInfo['extension']) ? $pathInfo['extension'] : ''; $filenameFilter = new iPhorm_Filter_Filename(); $filename = strlen($extension) ? str_replace(".{$extension}", '', $pathInfo['basename']) : $pathInfo['basename']; $filename = $filenameFilter->filter($filename); $filename = apply_filters('iphorm_filename_' . $element->getName(), $filename, $element, $form); if (strlen($extension)) { $filename = strlen($filename) ? "{$filename}.{$extension}" : "upload.{$extension}"; } else { $filename = strlen($filename) ? $filename : 'upload'; } $fullPath = $file['tmp_name']; $value = array('text' => $filename); if ($element->getSaveToServer()) { $result = iphorm_save_uploaded_file($fullPath, $filename, $element, $form->getId()); if (is_array($result)) { $fullPath = $result['fullPath']; $filename = $result['filename']; $value = array('url' => iphorm_get_wp_uploads_url() . '/' . $result['path'] . $filename, 'text' => $filename, 'fullPath' => $fullPath); } } if ($element->getAddAsAttachment()) { $attachments[] = array('fullPath' => $fullPath, 'type' => $file['type'], 'filename' => $filename); } $element->addFile($value); } } } // end in $_FILES } // end instanceof file } // end foreach element // Save the entry to the database if ($form->getSaveToDatabase()) { global $wpdb; $currentUser = wp_get_current_user(); $entry = array('form_id' => $form->getId(), 'date_added' => gmdate('Y-m-d H:i:s'), 'ip' => mb_substr(iphorm_get_user_ip(), 0, 32), 'form_url' => isset($_POST['form_url']) ? mb_substr($_POST['form_url'], 0, 512) : '', 'referring_url' => isset($_POST['referring_url']) ? mb_substr($_POST['referring_url'], 0, 512) : '', 'post_id' => isset($_POST['post_id']) ? mb_substr($_POST['post_id'], 0, 32) : '', 'post_title' => isset($_POST['post_title']) ? mb_substr($_POST['post_title'], 0, 128) : '', 'user_display_name' => mb_substr(iphorm_get_current_userinfo('display_name'), 0, 128), 'user_email' => mb_substr(iphorm_get_current_userinfo('user_email'), 0, 128), 'user_login' => mb_substr(iphorm_get_current_userinfo('user_login'), 0, 128)); $wpdb->insert(iphorm_get_form_entries_table_name(), $entry); $entryId = $wpdb->insert_id; $form->setEntryId($entryId); $entryDataTableName = iphorm_get_form_entry_data_table_name(); foreach ($elements as $element) { if ($element->getSaveToDatabase() && !$element->isConditionallyHidden()) { $entryData = array('entry_id' => $entryId, 'element_id' => $element->getId(), 'value' => $element->getValueHtml()); $wpdb->insert($entryDataTableName, $entryData); } } } // Check if we need to send any emails if ($form->getSendNotification() || $form->getSendAutoreply()) { // Get a new PHP mailer instance $mailer = iphorm_new_phpmailer($form); // Create an email address validator, we'll need to use it later $emailValidator = new iPhorm_Validator_Email(); // Check if we should send the notification email if ($form->getSendNotification() && count($form->getRecipients())) { // Set the from address $notificationFromInfo = $form->getNotificationFromInfo(); $mailer->From = $notificationFromInfo['email']; $mailer->FromName = $notificationFromInfo['name']; // Set the BCC if (count($bcc = $form->getBcc())) { foreach ($bcc as $bccEmail) { $mailer->AddBCC($bccEmail); } } // Set the Reply-To header if (($replyToElement = $form->getNotificationReplyToElement()) instanceof iPhorm_Element_Email && $emailValidator->isValid($replyToEmail = $replyToElement->getValue())) { $mailer->AddReplyTo($replyToEmail); } // Set the subject $mailer->Subject = $form->replacePlaceholderValues($form->getSubject()); // Check for conditional recipient rules if (count($form->getConditionalRecipients())) { $recipients = array(); foreach ($form->getConditionalRecipients() as $rule) { if (isset($rule['element'], $rule['value'], $rule['operator'], $rule['recipient']) && ($rElement = $form->getElementById($rule['element'])) instanceof iPhorm_Element_Multi) { if ($rule['operator'] == 'eq') { if ($rElement->getValue() == $rule['value']) { $recipients[] = $rule['recipient']; } } else { if ($rElement->getValue() != $rule['value']) { $recipients[] = $rule['recipient']; } } } } if (count($recipients)) { foreach ($recipients as $recipient) { $mailer->AddAddress($form->replacePlaceholderValues($recipient)); } } else { // No conditional recipient rules were matched, use default recipients foreach ($form->getRecipients() as $recipient) { $mailer->AddAddress($form->replacePlaceholderValues($recipient)); } } } else { // Set the recipients foreach ($form->getRecipients() as $recipient) { $mailer->AddAddress($form->replacePlaceholderValues($recipient)); } } // Set the message content $emailHTML = ''; $emailPlain = ''; if ($form->getCustomiseEmailContent()) { if ($form->getNotificationFormat() == 'html') { $emailHTML = $form->getNotificationEmailContent(); } else { $emailPlain = $form->getNotificationEmailContent(); } // Replace any placeholder values $emailHTML = $form->replacePlaceholderValues($emailHTML, 'html', '<br />'); $emailPlain = $form->replacePlaceholderValues($emailPlain, 'plain', iphorm_get_email_newline()); } else { ob_start(); include IPHORM_INCLUDES_DIR . '/emails/email-html.php'; $emailHTML = ob_get_clean(); ob_start(); include IPHORM_INCLUDES_DIR . '/emails/email-plain.php'; $emailPlain = ob_get_clean(); } if (strlen($emailHTML)) { $mailer->MsgHTML($emailHTML); if (strlen($emailPlain)) { $mailer->AltBody = $emailPlain; } } else { $mailer->Body = $emailPlain; } // Attachments foreach ($attachments as $file) { $mailer->AddAttachment($file['fullPath'], $file['filename'], 'base64', $file['type']); } $mailer = apply_filters('iphorm_pre_send_notification_email', $mailer, $form, $attachments); $mailer = apply_filters('iphorm_pre_send_notification_email_' . $form->getId(), $mailer, $form, $attachments); try { // Send the message $mailer->Send(); } catch (Exception $e) { if (WP_DEBUG) { throw $e; } } } // Check if we should send the autoreply email if ($form->getSendAutoreply() && ($recipientElement = $form->getAutoreplyRecipientElement()) instanceof iPhorm_Element_Email && strlen($recipientEmailAddress = $recipientElement->getValue()) && $emailValidator->isValid($recipientEmailAddress)) { // Get a new PHP mailer instance $mailer = iphorm_new_phpmailer($form); // Set the subject $mailer->Subject = $form->replacePlaceholderValues($form->getAutoreplySubject()); // Set the from name/email $autoreplyFromInfo = $form->getAutoreplyFromInfo(); $mailer->From = $autoreplyFromInfo['email']; $mailer->FromName = $autoreplyFromInfo['name']; // Add the recipient address $mailer->AddAddress($recipientEmailAddress); // Build the email content $emailHTML = ''; $emailPlain = ''; if (strlen($autoreplyEmailContent = $form->getAutoreplyEmailContent())) { if ($form->getAutoreplyFormat() == 'html') { $emailHTML = $form->replacePlaceholderValues($autoreplyEmailContent, 'html', '<br />'); } else { $emailPlain = $form->replacePlaceholderValues($autoreplyEmailContent, 'plain', iphorm_get_email_newline()); } } if (strlen($emailHTML)) { $mailer->MsgHTML($emailHTML); } else { $mailer->Body = $emailPlain; } $mailer = apply_filters('iphorm_pre_send_autoreply_email', $mailer, $form, $attachments); $mailer = apply_filters('iphorm_pre_send_autoreply_email_' . $form->getId(), $mailer, $form, $attachments); try { // Send the autoreply $mailer->Send(); } catch (Exception $e) { if (WP_DEBUG) { throw $e; } } } } // Okay, so now we can save form data to the custom database table if configured if (count($fields = $form->getDbFields())) { foreach ($fields as $key => $value) { $fields[$key] = $form->replacePlaceholderValues($value); } if ($form->getUseWpDb()) { global $wpdb; $wpdb->insert($form->getDbTable(), $fields); } else { $cwpdb = new wpdb($form->getDbUsername(), $form->getDbPassword(), $form->getDbName(), $form->getDbHost()); $cwpdb->insert($form->getDbTable(), $fields); } } // Delete uploaded files and unset file upload info from session if (isset($_SESSION['iphorm-' . $form->getUniqId()])) { if (is_array($_SESSION['iphorm-' . $form->getUniqId()])) { foreach ($_SESSION['iphorm-' . $form->getUniqId()] as $file) { if (isset($file['tmp_name'])) { if (is_array($file['tmp_name'])) { foreach ($file['tmp_name'] as $multiFile) { if (is_string($multiFile) && strlen($multiFile) && file_exists($multiFile)) { unlink($multiFile); } } } else { if (is_string($file['tmp_name']) && strlen($file['tmp_name']) && file_exists($file['tmp_name'])) { unlink($file['tmp_name']); } } } } } unset($_SESSION['iphorm-' . $form->getUniqId()]); } // Unset CAPTCHA info from session if (isset($_SESSION['iphorm-captcha-' . $form->getUniqId()])) { unset($_SESSION['iphorm-captcha-' . $form->getUniqId()]); } // Post-process action hooks do_action('iphorm_post_process', $form); do_action('iphorm_post_process_' . $form->getId(), $form); $result = array('type' => 'success', 'data' => $form->getSuccessMessage()); if ($form->getSuccessType() == 'redirect') { $result['redirect'] = $form->getSuccessRedirectURL(); } if (!$ajax) { // Reset the form for non-JavaScript submit $successMessage = $form->getSuccessMessage(); $form->setSubmitted(true); $form->reset(); } else { // This counteracts the fact that wrapping the JSON response in a textarea decodes HTML entities if (isset($result['redirect'])) { $result['redirect'] = htmlspecialchars($result['redirect'], ENT_NOQUOTES); } $result['data'] = htmlspecialchars($result['data'], ENT_NOQUOTES); } } else { $result = array('type' => 'error', 'data' => $form->getErrors()); } if ($ajax) { $response = '<textarea>' . iphorm_json_encode($result) . '</textarea>'; } else { // Redirect if successful if (isset($result['type'], $result['redirect']) && $result['type'] == 'success') { return '<meta http-equiv="refresh" content="0;URL=\'' . esc_url($result['redirect']) . '\'">'; } // Displays the form again do_action('iphorm_pre_display', $form); do_action('iphorm_pre_display_' . $form->getId(), $form); ob_start(); include IPHORM_INCLUDES_DIR . '/form.php'; $response = ob_get_clean(); } return $response; } }
/** * Export form entries */ function iphorm_export_entries() { if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['iphorm_do_entries_export']) && $_POST['iphorm_do_entries_export'] == 1) { if (isset($_POST['form_id']) && iphorm_form_exists($_POST['form_id'])) { $config = iphorm_get_form_config($_POST['form_id']); $id = $config['id']; $filenameFilter = new iPhorm_Filter_Filename(); $filename = $filenameFilter->filter($config['name']); // Send headers header('Content-Type: text/csv'); header('Content-Disposition: attachment;filename=' . $filename . '-' . date('Y-m-d') . '.csv'); global $wpdb; $elementsCache = array(); // Build the query $sql = "SELECT `entries`.*"; if (isset($config['elements']) && is_array($config['elements'])) { foreach ($config['elements'] as $element) { if (isset($element['save_to_database']) && $element['save_to_database']) { $elementId = absint($element['id']); $sql .= ", GROUP_CONCAT(if (`data`.`element_id` = {$elementId}, value, NULL)) AS `element_{$elementId}`"; $elementsCache[$elementId] = iphorm_get_element_config($elementId, $config); } } } if (isset($_POST['from'], $_POST['to'])) { $pattern = '/^\\d{4}-\\d{2}-\\d{2}$/'; if (preg_match($pattern, $_POST['from']) && preg_match($pattern, $_POST['to'])) { $from = iphorm_local_to_utc($_POST['from'] . ' 00:00:00'); $to = iphorm_local_to_utc($_POST['to'] . ' 23:59:59'); $dateSql = $wpdb->prepare(' AND (`entries`.`date_added` >= %s AND `entries`.`date_added` <= %s)', array($from, $to)); } } $sql .= "\r\n FROM `" . iphorm_get_form_entries_table_name() . "` `entries`\r\n LEFT JOIN `" . iphorm_get_form_entry_data_table_name() . "` `data` ON `data`.`entry_id` = `entries`.`id`\r\n WHERE `entries`.`form_id` = {$id}"; if (isset($dateSql)) { $sql .= $dateSql; } $sql .= "\r\n GROUP BY `entries`.`id`;"; $wpdb->query('SET @@GROUP_CONCAT_MAX_LEN = 65535'); $entries = $wpdb->get_results($sql, ARRAY_A); $validFields = array('id' => 'Entry ID', 'date_added' => 'Date', 'ip' => 'IP address', 'form_url' => 'Form URL', 'referring_url' => 'Referring URL', 'post_id' => 'Post / page ID', 'post_title' => 'Post / page title', 'user_display_name' => 'User WordPress display name', 'user_email' => 'User WordPress email', 'user_login' => 'User WordPress login'); // Sanitize chosen fields $validFields = iphorm_get_valid_entry_fields(); $fields = array(); if (isset($_POST['export_fields']) && is_array($_POST['export_fields'])) { // Check which fields have been chosen for export and get their labels foreach ($_POST['export_fields'] as $field) { if (array_key_exists($field, $validFields)) { // It's a default column, get the label $fields[$field] = $validFields[$field]; } elseif (preg_match('/element_(\\d+)/', $field, $matches)) { // It's an element column, so get the element label $elementId = absint($matches[1]); if (isset($elementsCache[$elementId])) { $label = iphorm_get_element_admin_label($elementsCache[$elementId]); } else { $label = ''; } $fields[$field] = $label; } } } $fh = fopen('php://output', 'w'); // Write column headings row fputcsv($fh, $fields); // Write each entry if (is_array($entries)) { foreach ($entries as $entry) { $row = array(); foreach ($fields as $field => $label) { $row[$field] = isset($entry[$field]) ? $entry[$field] : ''; if (strlen($row[$field]) && strpos($field, 'element_') !== false) { $elementId = absint(str_replace('element_', '', $field)); if (isset($elementsCache[$elementId])) { // Per element modifications to the output if (isset($elementsCache[$elementId]['type'])) { switch ($elementsCache[$elementId]['type']) { // Remove <br /> from textarea newlines case 'text': case 'textarea': case 'password': case 'hidden': $row[$field] = htmlspecialchars_decode(preg_replace('/<br\\s*?\\/>/', '', $row[$field]), ENT_QUOTES); break; case 'email': // Email elements: remove <a> tag $row[$field] = trim(strip_tags($row[$field])); break; case 'checkbox': case 'radio': // Multiple elements: replace <br /> with new line $row[$field] = trim(preg_replace('/<br\\s*?\\/>/', "\n", $row[$field])); break; case 'file': // File uploads: replace <br /> with newline, remove anchor tag, use href attr as value $result = preg_match_all('/href=([\'"])?((?(1).+?|[^\\s>]+))(?(1)\\1)/is', $row[$field], $uploads); if ($result > 0) { $row[$field] = join("\n", $uploads[2]); } else { $row[$field] = trim(preg_replace('/<br\\s*?\\/>/', "\n", $row[$field])); } break; } } } } // Format the date to include the WordPress Timezone offset if ($field === 'date_added') { $row[$field] = iphorm_format_date($row[$field]); } } fputcsv($fh, $row); } } fclose($fh); exit; } } }
/** * Sends the email to the set recipients */ public function run() { // Create new transport to use PHP's mail() function $transport = Swift_MailTransport::newInstance(); // You could use an SMTP server here instead //$transport = Swift_SmtpTransport::newInstance('yoursmtpserver.com', 25)->setUsername('yourusername')->setPassword('yourpassword'); // Create the mailer instance $mailer = Swift_Mailer::newInstance($transport); // Create a new mail message $message = Swift_Message::newInstance(); // Set the from address if ($this->getFromAddress() !== null) { $message->setFrom($this->getFromAddress()); } elseif ($this->_form->getValue('email') !== null) { $message->setFrom($this->_form->getValue('email')); } else { $message->setFrom('*****@*****.**'); } // Set the subject $message->setSubject($this->getSubject()); // Set the to addresses foreach ($this->getRecipients() as $recipient) { $message->addTo($recipient); } // Set the message content $message->setBody($this->_getEmailBodyHtml(), 'text/html'); $message->addPart($this->_getEmailBodyPlain(), 'text/plain'); // Add any attachments, validation is done by the FileUpload validator automatically registered with the element if (count($this->_attachmentElements) > 0) { // Check file uploads for each file element foreach ($this->_attachmentElements as $element) { if (array_key_exists($element->getName(), $_FILES) && is_array($_FILES[$element->getName()])) { $file = $_FILES[$element->getName()]; if (is_array($file['error'])) { // Process multiple upload field foreach ($file['error'] as $key => $error) { if ($error === UPLOAD_ERR_OK) { $pathInfo = pathinfo($file['name'][$key]); $extension = strtolower($pathInfo['extension']); $filenameFilter = new iPhorm_Filter_Filename(); $filename = $filenameFilter->filter($pathInfo['filename']) . '.' . $extension; $attachment = Swift_Attachment::fromPath($file['tmp_name'][$key], $file['type'][$key])->setFilename($filename); $message->attach($attachment); } } } else { // Process single upload field if ($file['error'] === UPLOAD_ERR_OK) { $pathInfo = pathinfo($file['name']); $extension = strtolower($pathInfo['extension']); $filenameFilter = new iPhorm_Filter_Filename(); $filename = $filenameFilter->filter($pathInfo['filename']) . '.' . $extension; $attachment = Swift_Attachment::fromPath($file['tmp_name'], $file['type'])->setFilename($filename); $message->attach($attachment); } } } } } // Send the message $mailer->send($message); // Send the autoreply if (!empty($this->_autoReply) && array_key_exists('subject', $this->_autoReply)) { $userMessage = Swift_Message::newInstance(); $userMessage->setFrom($this->_form->getValue('email')); $userMessage->setTo($this->_form->getValue('email')); $userMessage->setSubject($this->_replacePlaceholderValues($this->_autoReply['subject'])); ob_start(); require_once IPHORM_ROOT . '/emails/' . $this->_autoReply['htmlFile']; $html = ob_get_clean(); $userMessage->setBody($html, 'text/html'); ob_start(); require_once IPHORM_ROOT . '/emails/' . $this->_autoReply['plainTextFile']; $body = ob_get_clean(); $userMessage->addPart($body, 'text/plain'); $mailer->send($userMessage); } }