I would like to let the form send a copy to the email address which the visitor entered into 'label' => 'Email'.
3 php files are handling the whole thing and are as fallows:
This is the PHP Form which handles the input of the HTML
<?php
require_once('form_process.php');
$form = array(
'subject' => 'Contact Form',
'heading' => 'Submission',
'success_redirect' => '',
'resources' => array(
'checkbox_checked' => 'Checked',
'checkbox_unchecked' => 'Unchecked',
'submitted_from' => 'Form submitted from website: %s',
'submitted_by' => 'Visitor IP address: %s',
'too_many_submissions' => 'Too many recent submissions from this IP',
'failed_to_send_email' => 'Failed to send email',
'invalid_reCAPTCHA_private_key' => 'Invalid reCAPTCHA private key.',
'invalid_field_type' => 'Unknown field type \'%s\'.',
'invalid_form_config' => 'Field \'%s\' has an invalid configuration.',
'unknown_method' => 'Unknown server request method'
),
'email' => array(
'from' => 'info#myurl.com',
'to' => 'info#myurl.com'
),
'fields' => array(
'custom_U8149' => array(
'order' => 1,
'type' => 'string',
'label' => 'Name',
'required' => true,
'errors' => array(
'required' => 'Field \'Name\' is required.'
)
),
'Email' => array(
'order' => 2,
'type' => 'email',
'label' => 'Email',
'required' => true,
'errors' => array(
'required' => 'Field \'Email\' is required.',
'format' => 'Field \'Email\' has an invalid email.'
)
),
'custom_U8139' => array(
'order' => 3,
'type' => 'string',
'label' => 'Message',
'required' => false,
'errors' => array(
)
)
)
);
process_form($form);
?>
This is the form_process.php
<?php
require_once('form_throttle.php');
function process_form($form) {
if ($_SERVER['REQUEST_METHOD'] != 'POST')
die(get_form_error_response($form['resources']['unknown_method']));
if (formthrottle_too_many_submissions($_SERVER['REMOTE_ADDR']))
die(get_form_error_response($form['resources']['too_many_submissions']));
// will die() if there are any errors
check_required_fields($form);
// will die() if there is a send email problem
email_form_submission($form);
}
function get_form_error_response($error) {
return get_form_response(false, array('error' => $error));
}
function get_form_response($success, $data) {
if (!is_array($data))
die('data must be array');
$status = array();
$status[$success ? 'FormResponse' : 'MusePHPFormResponse'] = array_merge(array('success' => $success), $data);
return json_serialize($status);
}
function check_required_fields($form) {
$errors = array();
foreach ($form['fields'] as $field => $properties) {
if (!$properties['required'])
continue;
if (!array_key_exists($field, $_REQUEST) || empty($_REQUEST[$field]))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['required']));
else if (!check_field_value_format($form, $field, $properties))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['format']));
}
if (!empty($errors))
die(get_form_error_response(array('fields' => $errors)));
}
function check_field_value_format($form, $field, $properties) {
$value = get_form_field_value($field, $properties, $form['resources'], false);
switch($properties['type']) {
case 'checkbox':
case 'string':
case 'captcha':
// no format to validate for those fields
return true;
case 'checkboxgroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
// If the value received is not an array, treat it as invalid format
if (!isset($value))
return false;
// Check each option to see if it is a valid value
foreach($value as $checkboxValue) {
if (!in_array($checkboxValue, $properties['optionItems']))
return false;
}
return true;
case 'radiogroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
//check list of real radio values
return in_array($value, $properties['optionItems']);
case 'recaptcha':
if (!array_key_exists('recaptcha', $form) || !array_key_exists('private_key', $form['recaptcha']) || empty($form['recaptcha']['private_key']))
die(get_form_error_response($form['resources']['invalid_reCAPTCHA_private_key']));
$resp = recaptcha_check_answer($form['recaptcha']['private_key'], $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
return $resp->is_valid;
case 'email':
return 1 == preg_match('/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i', $value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($form['resources']['invalid_field_type'], $properties['type'])));
}
}
function email_form_submission($form) {
if(!defined('PHP_EOL'))
define('PHP_EOL', '\r\n');
$form_email = ((array_key_exists('Email', $_REQUEST) && !empty($_REQUEST['Email'])) ? cleanup_email($_REQUEST['Email']) : '');
$to = $form['email']['to'];
$subject = $form['subject'];
$message = get_email_body($subject, $form['heading'], $form['fields'], $form['resources']);
$headers = get_email_headers($to, $form_email);
$sent = #mail($to, $subject, $message, $headers);
if(!$sent)
die(get_form_error_response($form['resources']['failed_to_send_email']));
$success_data = array(
'redirect' => $form['success_redirect']
);
echo get_form_response(true, $success_data);
}
function get_email_headers($to_email, $form_email) {
$headers = 'From: ' . $to_email . PHP_EOL;
$headers .= 'Reply-To: ' . $form_email . PHP_EOL;
$headers .= 'X-Mailer: Adobe Muse CC 2015.0.2.310 with PHP' . PHP_EOL;
$headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
return $headers;
}
function get_email_body($subject, $heading, $fields, $resources) {
$message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
$message .= '<html xmlns="http://www.w3.org/1999/xhtml">';
$message .= '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><title>' . encode_for_form($subject) . '</title></head>';
$message .= '<body style="background-color: #ffffff; color: #000000; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: 18px; font-family: helvetica, arial, verdana, sans-serif;">';
$message .= '<h2 style="background-color: #eeeeee;">' . $heading . '</h2>';
$message .= '<table cellspacing="0" cellpadding="0" width="100%" style="background-color: #ffffff;">';
$sorted_fields = array();
foreach ($fields as $field => $properties) {
// Skip reCAPTCHA from email submission
if ('recaptcha' == $properties['type'])
continue;
array_push($sorted_fields, array('field' => $field, 'properties' => $properties));
}
// sort fields
usort($sorted_fields, 'field_comparer');
foreach ($sorted_fields as $field_wrapper)
$message .= '<tr><td valign="top" style="background-color: #ffffff;"><b>' . encode_for_form($field_wrapper['properties']['label']) . ':</b></td><td>' . get_form_field_value($field_wrapper['field'], $field_wrapper['properties'], $resources, true) . '</td></tr>';
$message .= '</table>';
$message .= '<br/><br/>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_from'], encode_for_form($_SERVER['SERVER_NAME'])) . '</div>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_by'], encode_for_form($_SERVER['REMOTE_ADDR'])) . '</div>';
$message .= '</body></html>';
return cleanup_message($message);
}
function field_comparer($field1, $field2) {
if ($field1['properties']['order'] == $field2['properties']['order'])
return 0;
return (($field1['properties']['order'] < $field2['properties']['order']) ? -1 : 1);
}
function is_assoc_array($arr) {
if (!is_array($arr))
return false;
$keys = array_keys($arr);
foreach (array_keys($arr) as $key)
if (is_string($key)) return true;
return false;
}
function json_serialize($data) {
if (is_assoc_array($data)) {
$json = array();
foreach ($data as $key => $value)
array_push($json, '"' . $key . '": ' . json_serialize($value));
return '{' . implode(', ', $json) . '}';
}
if (is_array($data)) {
$json = array();
foreach ($data as $value)
array_push($json, json_serialize($value));
return '[' . implode(', ', $json) . ']';
}
if (is_int($data) || is_float($data))
return $data;
if (is_bool($data))
return $data ? 'true' : 'false';
return '"' . encode_for_json($data) . '"';
}
function encode_for_json($value) {
return preg_replace(array('/([\'"\\t\\\\])/i', '/\\r/i', '/\\n/i'), array('\\\\$1', '\\r', '\\n'), $value);
}
function encode_for_form($text) {
$text = stripslashes($text);
return htmlentities($text, ENT_QUOTES, 'UTF-8');// need ENT_QUOTES or webpro.js jQuery.parseJSON fails
}
function get_form_field_value($field, $properties, $resources, $forOutput) {
$value = $_REQUEST[$field];
switch($properties['type']) {
case 'checkbox':
return (($value == '1' || $value == 'true') ? $resources['checkbox_checked'] : $resources['checkbox_unchecked']);
case 'checkboxgroup':
if (!is_array($value))
return NULL;
$outputValue = array();
foreach ($value as $checkboxValue)
array_push($outputValue, $forOutput ? encode_for_form($checkboxValue) : stripslashes($checkboxValue));
if ($forOutput)
$outputValue = implode(', ', $outputValue);
return $outputValue;
case 'radiogroup':
return ($forOutput ? encode_for_form($value) : stripslashes($value));
case 'string':
case 'captcha':
case 'recaptcha':
case 'email':
return encode_for_form($value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($resources['invalid_field_type'], $properties['type'])));
}
}
function cleanup_email($email) {
$email = encode_for_form($email);
$email = preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $email);
return $email;
}
function cleanup_message($message) {
$message = wordwrap($message, 70, "\r\n");
return $message;
}
?>
This is the form_throttle.php
<?php
function formthrottle_check()
{
if (!is_writable('.'))
{
return '8';
}
try
{
if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE))
{
$db = new PDO('sqlite:muse-throttle-db.sqlite3');
if ( file_exists('muse-throttle-db') )
{
unlink('muse-throttle-db');
}
}
else if (function_exists("sqlite_open"))
{
$db = new PDO('sqlite2:muse-throttle-db');
if ( file_exists('muse-throttle-db.sqlite3') )
{
unlink('muse-throttle-db.sqlite3');
}
}
}
catch( PDOException $Exception ) {
return '9';
}
$retCode ='5';
if ($db)
{
$res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
if (!$res or $res->fetchColumn() == 0)
{
$created = $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
if($created == 0)
{
$created = $db->exec("INSERT INTO Submission_History (IP,Submission_Date) VALUES ('256.256.256.256', DATETIME('now'))");
}
if ($created != 1)
{
$retCode = '2';
}
}
if($retCode == '5')
{
$res = $db->query("SELECT COUNT(1) FROM Submission_History;");
if ($res && $res->fetchColumn() > 0)
{
$retCode = '0';
}
else
$retCode = '3';
}
// Close file db connection
$db = null;
}
else
$retCode = '4';
return $retCode;
}
function formthrottle_too_many_submissions($ip)
{
$tooManySubmissions = false;
try
{
if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE))
{
$db = new PDO('sqlite:muse-throttle-db.sqlite3');
}
else if (function_exists("sqlite_open"))
{
$db = new PDO('sqlite2:muse-throttle-db');
}
}
catch( PDOException $Exception ) {
return $tooManySubmissions;
}
if ($db)
{
$res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
if (!$res or $res->fetchColumn() == 0)
{
$db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
}
$db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')");
$stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
$stmt->closeCursor();
$stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
if ($stmt->fetchColumn() > 25)
$tooManySubmissions = true;
// Close file db connection
$db = null;
}
return $tooManySubmissions;
}
?>
Related
I was working on another person's code and when I deployed the laravel app the login page works but when I input the testing credentials it spits out this error
Trying to get property 'id' of non-object
in helpers.php line 159
at HandleExceptions->handleError(8, 'Trying to get property \'id\' of non-object', '/var/www/html/first-project/app/Helpers/helpers.php', 159, array('fields' => object(Collection), 'fieldsValues' => object(Collection), 'htmlFields' => array(), 'startSeparator' => '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">', 'endSeparator' => '</div>', 'field' => object(CustomField), 'dynamicVars' => array('$RANDOM_VARIABLE$' => 'var15931958241638660037ble', '$FIELD_NAME$' => 'phone', '$DISABLED$' => '', '$REQUIRED$' => '"required" => "required",', '$MODEL_NAME_SNAKE$' => 'user', '$FIELD_VALUE$' => '\'+136 226 5660\'', '$INPUT_ARR_SELECTED$' => '+136 226 5660'), 'gf' => object(GeneratorField), 'value' => object(CustomFieldValue)))
in helpers.php line 159
The actual function referred to is the following
function generateCustomField($fields, $fieldsValues = null)
{
$htmlFields = [];
$startSeparator = '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">';
$endSeparator = '</div>';
foreach ($fields as $field) {
$dynamicVars = [
'$RANDOM_VARIABLE$' => 'var' . time() . rand() . 'ble',
'$FIELD_NAME$' => $field->name,
'$DISABLED$' => $field->disabled === true ? '"disabled" => "disabled",' : '',
'$REQUIRED$' => $field->required === true ? '"required" => "required",' : '',
'$MODEL_NAME_SNAKE$' => getOnlyClassName($field->custom_field_model),
'$FIELD_VALUE$' => 'null',
'$INPUT_ARR_SELECTED$' => '[]',
];
$gf = new GeneratorField();
if ($fieldsValues) {
foreach ($fieldsValues as $value) {
if ($field->id === $value->customField->id) {
$dynamicVars['$INPUT_ARR_SELECTED$'] = $value->value ? $value->value : '[]';
$dynamicVars['$FIELD_VALUE$'] = '\'' . addslashes($value->value) . '\'';
$gf->validations[] = $value->value;
continue;
}
}
}
// dd($gf->validations);
$gf->htmlType = $field['type'];
$gf->htmlValues = $field['values'];
$gf->dbInput = '';
if ($field['type'] === 'selects') {
$gf->htmlType = 'select';
$gf->dbInput = 'hidden,mtm';
}
$fieldTemplate = HTMLFieldGenerator::generateCustomFieldHTML($gf, config('infyom.laravel_generator.templates', 'adminlte-templates'));
if (!empty($fieldTemplate)) {
foreach ($dynamicVars as $variable => $value) {
$fieldTemplate = str_replace($variable, $value, $fieldTemplate);
}
$htmlFields[] = $fieldTemplate;
}
// dd($fieldTemplate);
}
foreach ($htmlFields as $index => $field) {
if (round(count($htmlFields) / 2) == $index + 1) {
$htmlFields[$index] = $htmlFields[$index] . "\n" . $endSeparator . "\n" . $startSeparator;
}
}
$htmlFieldsString = implode("\n\n", $htmlFields);
$htmlFieldsString = $startSeparator . "\n" . $htmlFieldsString . "\n" . $endSeparator;
// dd($htmlFieldsString);
$renderedHtml = "";
try {
$renderedHtml = render(Blade::compileString($htmlFieldsString));
// dd($renderedHtml);
} catch (FatalThrowableError $e) {
}
return $renderedHtml;
}
its usage is as follows in the controllers. It is used many times in almost all controllers for example in the UserController.php file I think this is the calling method. I am not that well versed in laravel sorry for any noob mistakes in advance.
public function profile()
{
$user = $this->userRepository->findWithoutFail(auth()->id());
unset($user->password);
$customFields = false;
$role = $this->roleRepository->pluck('name', 'name');
$rolesSelected = $user->getRoleNames()->toArray();
$customFieldsValues = $user->customFieldsValues()->with('customField')->get();
$hasCustomField = in_array($this->userRepository->model(), setting('custom_field_models', []));
if ($hasCustomField) {
$customFields = $this->customFieldRepository->findByField('custom_field_model', $this->userRepository->model());
$customFields = generateCustomField($customFields, $customFieldsValues);
}
return view('settings.users.profile', compact(['user', 'role', 'rolesSelected', 'customFields', 'customFieldsValues']));
}
You have to change this line
From
$user = $this->userRepository->findWithoutFail(auth()->id());
To
$user = $this->userRepository->findWithoutFail(auth()->user()->id());
My first guess, change this $user = $this->userRepository->findWithoutFail(auth()->id()); to $user = $this->userRepository->findWithoutFail(auth()->user()->id);
Added auth()->user()->id;
Fatal Error: call to a member function uploadFile() on a non-object
Getting this error of upload file function on Uploading File to dropbox using PHP API On live Server. Same Code Working fine on localhost and doing it in codeigniter. start of code is**
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(1);
require_once(APPPATH . 'libraries/dropbox/vendor/autoload.php');
use \Dropbox as dbx;
class Knowledge extends CI_Controller
{
public $appInfoFile;
public $requestPath; **
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->database();
$this->load->library('form_validation');
//load the models
$this->load->model('knowledge_model');
//$this->load->helper('messages');
//$this->load->model('messages_model');
$this->load->model('messages_model', 'send_messages');
// custom library in codeigniter
$this->appInfoFile = APPPATH.'libraries/dropbox/app-info.json';
$redirect_uri ='https://www.domainname.com/knowledge/add/';
$requestPath = $this->init();
session_start();
validate_user();
}
public function index($msg = NULL)
{
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['records'] = $this->knowledge_model->get_all_rec();
// echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function tag($msg = NULL)
{
$tagname = $this->uri->segment("3");
$tagnamehits = $this->uri->segment("4");
$session_data = $this->session->all_userdata();
$data['msg'] = $msg;
if (isset($session_data["validated"]) && $session_data["validated"] == '1') {
$data['title'] = 'Knowledge Center';
$data['update_rec'] = $this->knowledge_model->update_hits($tagnamehits);
$data['records'] = $this->knowledge_model->get_notifyrec_bytags($tagname);
//echo "<pre>".print_r($data['records'],true)."</pre>";exit;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('knowledge', $data);
$this->load->view('includes/footer');
} else {
redirect(base_url());
}
}
public function add()
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$seralizedtags = serialize($this->input->post('tagsar'));
//echo "<pre>".print_r($seralizedArray,true)."</pre>";exit;
// drop box upload filess
if (isset($_FILES['attached_file']['name']) && !empty($_FILES['attached_file']['name'])) {
$file_name= $_FILES['attached_file']['name'];
$return_result=$this->upload_to_dropbox($file_name);
$rev=$return_result['rev'];
$mime_type=$return_result['mime_type'];
$path=$return_result['path'];
$size=$return_result['size'];
$revision=$return_result['revision'];
}
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'user_id' => $user_id,
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description'),
'dropbox_rev'=>$rev,
'dropbox_mim_type'=>$mime_type,
'dropbox_path'=>$path,
'dropbox_filesize'=>$size,
'dropbox_revision'=>$revision,
);
$message=$this->input->post('subject');
//for slack call
if(isset($message)){
$message=$message;
$messageType = "Knowledge_center";
$this->send_messages->send_message_on_slack($messageType);
}
//echo "<pre>" . print_r($data, true) . "</pre>";
$insert_res = $this->knowledge_model->insert_rec($data);
if ($insert_res != "conf") {
if ($insert_res == "subject") {
$this->session->set_flashdata('message', "<p>Subject Name already exist.Please change Subject</p>");
} else {
$this->session->set_flashdata('message', "<p>Error in Insertion.</p>");
}
echo '<script>window.location.href = "' . base_url() . 'knowledge/add";</script>';
} else {
$this->session->set_flashdata('message', "<p>Record added successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $this->form_validation->set_value('subject'),
);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $this->form_validation->set_value('tagsar'),
);
$data['desc'] = $this->form_validation->set_value('description');
// $data['dropbox']=$this->dropbox->dp();
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('add_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function view($id)
{
$update_rec = $this->knowledge_model->get_rec_byid($id);
$data['dropbox_detail']=array(
"dropbox_rev"=> $update_rec[0]->dropbox_rev,
"dropbox_mim_type"=> $update_rec[0]->dropbox_mim_type,
"dropbox_path"=> $update_rec[0]->dropbox_path,
"dropbox_filesize"=> $update_rec[0]->dropbox_filesize,
"dropbox_revision"=> $update_rec[0]->dropbox_revision,
);
$data['subject_data'] = $update_rec[0]->subject;
$data['tags_data'] = unserialize($update_rec[0]->tags);
$data['desc'] = $update_rec[0]->description;
$data['title'] = 'Knowledge Center';
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('view_knowledge', $this->data);
$this->load->view('includes/footer');
}
public function manage_notify()
{
$notifyid = $_POST["elid"];
$notifytext = $_POST["notifytext"];
$notify_rec = $this->knowledge_model->get_notifyrec_byid($notifytext);
$ret_res = "<ul>";
foreach ($notify_rec as $notify_record) {
$ret_res .= "<li>" . $notify_record->subject . "</li>";
}
$ret_res .= "</ul>";
echo $ret_res;
exit;
}
public function update($id)
{
//validate form input
$this->form_validation->set_rules('subject', 'subject', 'required');
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
$update_rec = $this->knowledge_model->get_rec_byid($id);
//echo "<pre>".print_r($update_rec[0],true)."</pre>";exit;
$seralizedtags = serialize($this->input->post('tagsar'));
if ($this->form_validation->run() == true) {
$session_data = $this->session->all_userdata();
$user_id = $session_data["userid"];
$data = array(
'edit_by_userid' => $user_id,
'subject' => $this->input->post('subject'),
'tags' => $seralizedtags,
'description' => $this->input->post('description')
);
$recid = $this->input->post('recid');
// echo "<pre>".print_r($data,true)."</pre>";exit;
$update_res = $this->knowledge_model->update_rec($recid, $data);
if ($update_res > 0) {
$this->session->set_flashdata('message', "<p>Record Updated successfully.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
} else {
$this->session->set_flashdata('message', "<p>Error in Updation.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge/update/' . $recid . '";</script>';
}
} else {
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : $this->session->flashdata('message'));
if (isset($update_rec)) {
$this->data['recid'] = array(
'name' => 'recid',
'class' => 'form-control',
'id' => 'recid',
'type' => 'hidden',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->id,
);
$this->data['subject'] = array(
'name' => 'subject',
'class' => 'form-control round-input',
'id' => 'subject',
'placeholder' => 'Subject',
'type' => 'text',
'autofocus' => 'true',
'data-required' => '1',
'value' => $update_rec[0]->subject,
);
$tags_data = unserialize($update_rec[0]->tags);
$this->data['tagdata'] = array(
'name' => 'tagsar',
'class' => 'form-control tags tags-input',
'id' => 'tagsar',
'type' => 'text',
'autofocus' => 'true',
'data-type' => 'tags',
'value' => $tags_data,
);
$data['desc'] = $update_rec[0]->description;
} else {
$this->session->set_flashdata('message', "<p>Update Record not found.</p>");
echo '<script>window.location.href = "' . base_url() . 'knowledge";</script>';
}
$msg = "";
$data['title'] = 'Knowledge Center';
$data['msg'] = $msg;
$this->load->view('includes/header', $data);
$this->load->view('includes/sidebar', $data);
$this->load->view('edit_knowledge', $this->data);
$this->load->view('includes/footer');
}
}
public function download_dbx_file(){
$file_path = $_POST['dropbox_path'];
$mime_type = $_POST['dropbox_mim_type'];
$this->download_file($file_path,$mime_type);
}
public function del($id)
{
$this->knowledge_model->del_rec($id);
$this->session->set_flashdata('message', "<p>Record Deleted successfully.</p>");
redirect(base_url() . 'knowledge');
}
// for upload to dropbox //
function getAppConfig()
{
global $appInfoFile;
try {
$appInfo = dbx\AppInfo::loadFromJsonFile($this->appInfoFile);
}
catch (dbx\AppInfoLoadException $ex) {
throw new Exception("Unable to load \"$this->appInfoFile\": " . $ex->getMessage());
}
$clientIdentifier = "examples-web-file-browser";
$userLocale = null;
return array($appInfo, $clientIdentifier, $userLocale);
}
function getClient()
{
if (!isset($_SESSION['access-token'])) {
return false;
}
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$accessToken = $_SESSION['access-token'];
return new dbx\Client($accessToken, $clientIdentifier, $userLocale,$appInfo->getHost());
}
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = $this->getAppConfig();
$redirectUri = getUrl("dropbox-auth-finish");
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
function respondWithError($code, $title, $body = "")
{
$proto = $_SERVER['SERVER_PROTOCOL'];
header("$proto $code $title", true, $code);
echo renderHtmlPage($title, $body);
}
function getUrl($relative_path)
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
$scheme = "https";
} else {
$scheme = "http";
}
$host = $_SERVER['HTTP_HOST'];
$path = getPath($relative_path);
return $scheme."://".$host.$path;
}
function getPath($relative_path)
{
if (PHP_SAPI === 'cli-server') {
return "/".$relative_path;
} else {
return $_SERVER["SCRIPT_NAME"]."/".$relative_path;
}
}
function init()
{
global $argv;
// If we were run as a command-line script, launch the PHP built-in web server.
if (PHP_SAPI === 'cli') {
launchBuiltInWebServer($argv);
assert(false);
}
if (PHP_SAPI === 'cli-server') {
// For when we're running under PHP's built-in web server, do the routing here.
return $_SERVER['SCRIPT_NAME'];
}
else {
// For when we're running under CGI or mod_php.
if (isset($_SERVER['PATH_INFO'])) {
return $_SERVER['PATH_INFO'];
} else {
return "/";
}
}
}
function launchBuiltInWebServer($argv)
{
// The built-in web server is only available in PHP 5.4+.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
fprintf(STDERR,
"Unable to run example. The version of PHP you used to run this script (".PHP_VERSION.")\n".
"doesn't have a built-in web server. You need PHP 5.4 or newer.\n".
"\n".
"You can still run this example if you have a web server that supports PHP 5.3.\n".
"Copy the Dropbox PHP SDK into your web server's document path and access it there.\n");
exit(2);
}
$php_file = $argv[0];
if (count($argv) === 1) {
$port = 5000;
} else if (count($argv) === 2) {
$port = intval($argv[1]);
} else {
fprintf(STDERR,
"Too many arguments.\n".
"Usage: php $argv[0] [server-port]\n");
exit(1);
}
$host = "localhost:$port";
$cmd = escapeshellarg(PHP_BINARY)." -S ".$host." ".escapeshellarg($php_file);
$descriptors = array(
0 => array("pipe", "r"), // Process' stdin. We'll just close this right away.
1 => STDOUT, // Relay process' stdout to ours.
2 => STDERR, // Relay process' stderr to ours.
);
$proc = proc_open($cmd, $descriptors, $pipes);
if ($proc === false) {
fprintf(STDERR,
"Unable to launch PHP's built-in web server. Used command:\n".
" $cmd\n");
exit(2);
}
fclose($pipes[0]); // Close the process' stdin.
$exitCode = proc_close($proc); // Wait for process to exit.
exit($exitCode);
}
public function upload_to_dropbox($filename){
if($filename != ''){
try {
$dbxClient = $this->getClient();
$remoteDir = "/";
if (isset($_POST['folder'])) $remoteDir = $_POST['folder'];
$remotePath = rtrim($remoteDir, "/")."/".$filename;
$fp = fopen($_FILES['attached_file']['tmp_name'], "rb");
$result = $dbxClient->uploadFile($remotePath, dbx\WriteMode::add(), $fp);
fclose($fp);
//$str = print_r($result, true);
return $result;
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "File does not exists";
exit;
}
}
public function download_file($file_path,$file_mime_type){
if($file_path != '' && $file_mime_type != '' ) {
try {
$dbxClient = $this->getClient();
$path = $file_path;
$fd = tmpfile();
$metadata = $dbxClient->getFile($path, $fd);
header("Content-Type: $metadata[mime_type]");
fseek($fd, 0);
fpassthru($fd);
fclose($fd);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
else{
echo "Invalid Request";
exit;
}
}
}
Pingback wasn't successful. Reason: Response body does not match the
expected pattern: OK
Signature base string
uid=currency=type=0ref=369e67e903ca0b2261cd342575b8979e
Signature = MD5(Signature base string)
2aa9f1c847d1492b18cd017cdf78290b
this is model.donate.php
<?php
in_file();
class Mdonate{
protected $registry, $db, $config;
private $vars = array();
protected $hash_item = '';
protected $paypal_ipn_url = 'https://www.paypal.com/cgi-bin/webscr';
protected $paypal_ipn_url_ssl = 'www.paypal.com';
protected $req = 'cmd=_notify-validate';
protected $post = array();
protected $paypal_response;
public $order_details = array();
protected $pw_ip_white_list = array('174.36.92.186', '66.220.10.3', '174.36.92.186', '174.36.96.66', '174.36.92.187', '174.36.92.192', '174.37.14.28');
protected $pw_reason_list = array(0 => 'Invalid Reason',
1 => 'Chargeback',
2 => 'Credit Card fraud',
3 => 'Order fraud',
4 => 'Bad data entry',
5 => 'Fake / proxy user',
6 => 'Rejected by advertiser',
7 => 'Duplicate conversions',
8 => 'Goodwill credit taken back',
9 => 'Cancelled order',
10 => 'Partially reversed transaction');
public function __construct(){
$this->registry = registry::getInstance();
$this->db = $this->registry->db;
$this->config = $this->registry->config;
}
public function __set($key, $val){
$this->vars[$key] = $val;
}
public function __get($name){
return $this->vars[$name];
}
public function __isset($name){
return isset($this->vars[$name]);
}
public function get_paypal_packages(){
return $this->db->query('SELECT id, package, reward, price, currency FROM dmncms_donate_paypal_packages WHERE status = 1 ORDER BY orders ASC')->fetch_all();
}
public function check_package($id){
$count = $this->db->snumrows('SELECT COUNT(id) as count FROM dmncms_donate_paypal_packages WHERE id = '.$this->db->escape($id).' AND status = 1');
return ($count == 1);
}
public function insert_paypal_order($reward, $price, $currency){
$this->hash_item = md5($_SESSION['name'].$price.$currency.uniqid(microtime(),1));
$stmt = $this->db->prepare('INSERT INTO dmncms_donate_paypal_orders (amount, currency, credits, account, hash) VALUES(:amount, :currency, :credits, :account, :hash)');
return $stmt->execute(array(':amount' => $price, ':currency' => $currency, ':credits' => $reward, ':account' => $_SESSION['name'], ':hash' => $this->hash_item));
}
public function get_paypal_data(){
return array('email' => $this->config->load_xml_config('donate|pp_email'), 'item' => $this->hash_item, 'user' => $_SESSION['name']);
}
public function gen_post_fields($data){
$data_array = explode('&', $data);
foreach($data_array as $value){
$value = explode ('=', $value);
if(count($value) == 2)
$this->post[$value[0]] = urldecode($value[1]);
}
foreach($this->post as $key => $value) {
$this->req .= "&".$key."=".urlencode($value);
}
}
public function post_back_paypal_fsock(){
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: ".$this->paypal_ipn_url_ssl."\r\n";
$header .= "Content-Length: " . strlen($this->req) . "\r\n";
$header .= "Connection: close\r\n\r\n";
$fp = fsockopen('ssl://'.$this->paypal_ipn_url_ssl, 443, $errno, $errstr, 30);
if(!$fp){
$this->writelog('PayPal sent fsockopen error no. '.$errno.': '.$errstr.'','Paypal');
return false;
}
else{
fputs($fp, $header.$this->req);
while(!feof($fp)){
$this->paypal_response = fgets($fp, 1024);
}
fclose($fp);
}
return true;
}
public function post_back_paypal_curl(){
$request = curl_init();
curl_setopt_array($request, array(CURLOPT_URL => $this->paypal_ipn_url,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $this->req,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array('Connection: Close'),
CURLOPT_SSL_VERIFYPEER => TRUE,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_FORBID_REUSE => TRUE,
CURLOPT_CAINFO => APP_PATH.DS.'data'.DS.'cacert.pem'));
$this->paypal_response = curl_exec($request);
if(curl_errno($request)){
$this->writelog(curl_error($request), 'Paypal');
return false;
}
curl_close($request);
return true;
}
public function validate_paypal_payment(){
if(stripos($this->paypal_response, "VERIFIED") !== false){
if(!$this->check_email()){
return false;
}
if(!$this->check_order_number()){
return false;
}
switch($this->vars['payment_status']){
case 'Completed':
if($this->vars['tax'] > 0){
$this->vars['mc_gross'] -= $this->vars['tax'];
}
if($this->vars['mc_gross'] == $this->order_details['amount']){
if($this->vars['mc_currency'] == $this->order_details['currency']){
if($this->check_completed_transaction()){
return false;
}
if($this->check_pending_transaction()){
if($this->update_transaction_status()){
return true;
}
}
else{
if($this->insert_transaction_status()){
return true;
}
}
}
}
break;
case 'Pending':
if($this->vars['tax'] > 0){
$this->vars['mc_gross'] -= $this->vars['tax'];
}
if(!$this->check_completed_transaction() && !$this->check_pending_transaction()){
$this->insert_transaction_status();
}
break;
case 'Reversed': case 'Refunded':
$this->decrease_credits($this->order_details['account'], $this->order_details['credits']);
$this->update_transaction_status();
if($this->config->load_xml_config('donate|pp_punish_player') == 1){
$this->block_user($this->order_details['account']);
}
break;
}
}
if(stripos($this->paypal_response, "INVALID") !== false){
$this->writelog('PayPal sent [status: INVALID] [transaction id: '.$this->vars['txn_id'], 'Paypal');
}
}
private function check_email(){
if(strtolower($this->vars['receiver_email']) != strtolower($this->config->load_xml_config('donate|pp_email'))){
$this->writelog('PayPal sent invalid reciever email: '.$this->vars['receiver_email'].'', 'Paypal');
return false;
}
return true;
}
private function check_order_number(){
$count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_orders where hash = '.$this->db->escape($this->vars['item_number']));
if($count == 1){
$this->order_details = $this->db->query('SELECT amount, currency, account, credits FROM dmncms_donate_paypal_orders where hash = '.$this->db->escape($this->vars['item_number']))->fetch();
return true;
}
else{
$this->writelog('PayPal sent invalid order [transaction id: '.$this->vars['txn_id'].']', 'Paypal');
return false;
}
}
private function check_completed_transaction(){
$count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_transactions where transaction_id = '.$this->db->escape($this->vars['txn_id']).' and status = \'Completed\'');
if($count > 0){
return true;
}
return false;
}
private function check_pending_transaction(){
$count = $this->db->snumrows('SELECT COUNT(id) AS count FROM dmncms_donate_paypal_transactions where transaction_id = '.$this->db->escape($this->vars['txn_id']).' and status = \'Pending\'');
if($count > 0){
return true;
}
return false;
}
private function update_transaction_status(){
$stmt = $this->db->prepare('UPDATE dmncms_donate_paypal_transactions SET status = :status WHERE transaction_id = :trans_id');
return $stmt->execute(array(':status' => $this->vars['payment_status'], ':trans_id' => $this->vars['txn_id']));
}
private function insert_transaction_status(){
$stmt = $this->db1->prepare('INSERT INTO dmncms_donate_paypal_transactions (transaction_id, amount, currency, acc, credits, order_date, status, payer_email) VALUES (:trans_id, :gross, :currency, :account, :credits, :time, :payment_status, :payer_email)');
return $stmt->execute(array(':trans_id' => $this->vars['txn_id'], ':gross' => $this->vars['mc_gross'], ':currency' => $this->vars['mc_currency'], ':account' => $this->order_details['account'], ':credits' => $this->order_details['credits'], ':time' => time(), ':payment_status' => $this->vars['payment_status'], ':payer_email' => $this->vars['payer_email']));
}
public function reward_user($acc, $credits){
$stmt = $this->db->prepare('UPDATE bg_user SET cash = cash + :credits WHERE bg_user = :account');
$stmt->execute(array(':account' => $acc, ':credits' => str_replace('-', '', $credits)));
}
private function decrease_credits($acc, $credits){
$stmt = $this->db1->prepare('UPDATE bg_user SET cash = cash - :credits WHERE bg_user = :account');
$stmt->execute(array(':credits' => str_replace('-', '', $credits), ':account' => $acc));
}
private function block_user($acc){
return;
}
public function validate_ip_list(){
return (in_array($_SERVER['REMOTE_ADDR'], $this->pw_ip_white_list));
}
public function validate_pw_signature(){
return (md5('uid='.$this->vars['uid'].'currency='.$this->vars['currency'].'type='.$this->vars['type'].'ref='.$this->vars['ref'].$this->config->load_xml_config('donate|pw_secretkey')) == $this->vars['sig']);
}
public function validate_pw_payment(){
if(!$this->check_reference()){
if($this->log_pw_transaction()){
return true;
}
}
else{
if($this->vars['type'] == 2){
$this->change_pw_transaction_status();
if($this->vars['reason'] == 2 || $this->vars['reason'] == 3){
$this->block_user($this->vars['uid']);
}
$this->decrease_credits($this->vars['uid'], $this->vars['currency']);
}
}
}
private function check_reference(){
$count = $this->db->snumrows('SELECT COUNT(uid) AS count FROM dmncms_donate_paymentwall WHERE uid = '.$this->db->escape($this->vars['uid']).' AND ref = '.$this->db->escape($this->vars['ref']).'');
if($count > 0){
return true;
}
return false;
}
private function log_pw_transaction(){
$prepare = $this->db->prepare('INSERT INTO dmncms_donate_paymentwall (uid, currency, type, ref, reason, order_date) VALUES (:uid, :currency, :type, :ref, :reason, :time)');
return $prepare->execute(array(':uid' => $this->vars['uid'], ':currency' => $this->vars['currency'], ':type' => $this->vars['type'], ':ref' => $this->vars['ref'], ':reason' => 'Complete', ':time' => time()));
}
private function change_pw_transaction_status(){
$stmt = $this->db->prepare('UPDATE dmncms_donate_paymentwall SET currency = :currency, reason = :reason, order_date = :order_date WHERE uid =:uid AND ref = :ref');
$stmt->execute(array(':currency' => $this->vars['currency'], ':reason' => $this->pw_reason_list[$this->vars['reason']], ':order_date' => time(), ':uid' => $this->vars['uid'], ':ref' => $this->vars['ref']));
}
public function writelog($logentry, $lgname) {
$log = '['.$_SERVER['REMOTE_ADDR'].'] ['.(isset($_SESSION['name']) ? $_SESSION['name'] : 'Unknown').'] '.$logentry.'';
$log_name = APP_PATH.DS.'logs'.DS.$lgname.'_'.date("m-d-y").'.txt';
$logfile = #fopen($log_name, "a+");
if($logfile){
fwrite($logfile, "[".date ("h:iA")."] $log\r\n");
fclose($logfile);
}
}
}
This is view.paymentwall.php / http://domain.com/donate/paymentwall - im using it for pingback adress
<?php
if(load::get('errors') != false){
foreach(load::get('errors') as $errors){
echo '<div class="notification-box notification-box-error">'.$errors.'</div>';
}
}
if(load::get('pw') == false || load::get('pw') == 0){
echo '<div class="notification-box notification-box-error">This donation method is disabled.</div>';
}
else{
echo '<div style="/* border: 1px dotted black; *//* -webkit-border-radius: 5px; */-moz-border-radius: 5px;/* border-radius: 5px; */margin-top: 10px; padding: 10px; height: auto; background: rgba(55, 52, 55, 1); box-shadow: 0 0 4px rgba(0,0,0,.6), 0 1px 1px rgba(0,0,0,.5), inset 0 0 0 1px rgba(255,255,255,.015), inset 0 1px 0 rgba(255,255,255,.05); -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; /* margin-left: -38px; */ z-index: 1;">
<div style="padding: 2px; text-align: center;"><iframe src="http://wallapi.com/api/ps/?key='.load::get('pw_apikey').'&uid='.$_SESSION['name'].'&widget='.load::get('pw_widget').'" width="'.load::get('pw_w_width').'" height="'.load::get('pw_w_height').'" frameborder="0"></iframe></div>
</div>';
}
?>
When Paymentwall sends a Pingback, it expects your server to respond with HTTP Status Code 200 and with response body only containing OK https://www.paymentwall.com/en/documentation/Virtual-Currency-API/711#http_pingback_return_value
It looks like currently your script returns HTML code of the payment page as a response to Paymentwall's Pingback, so the problem is that the response body doesn't only contain OK.
I recommend splitting the payment page and the pingback processing script and move the pingback processing script to something like domain/paymentwall-pingback
On a separate note, to validate Paymentwal pingbacks easier, please feel free to use Paymentwall PHP Library.
With Paymentwall PHP Library, validating the pingback signature, pingback origin and the parameters can be done with just a few lines:
require_once('/path/to/paymentwall-php/lib/paymentwall.php');
Paymentwall_Config::getInstance()->set(array(
'api_type' => Paymentwall_Config::API_VC, //OR API_GOODS or API_CART
'public_key' => 'YOUR_PUBLIC_KEY',
'private_key' => 'YOUR_PRIVATE_KEY'
));
$pingback = new Paymentwall_Pingback($_GET, $_SERVER['REMOTE_ADDR']);
if ($pingback->validate()) {
//product delivery logic
}
It is necessary to use appropriate algorithm and parameters for signature calculation based on version you would like to use :
https://www.paymentwall.com/en/documentation/Signature-Calculation/2313
If the version is 2 or 3 your parameters should be sorted alphabetically.
For pingback you have to return only string "OK" from your server in case of successful pingback/negative pingback.
I have this class for show error with session method using PHP.
class Messages {
//-----------------------------------------------------------------------------------------------
// Class Variables
//-----------------------------------------------------------------------------------------------
var $msgId;
var $msgTypes = array( 'help', 'info', 'warning', 'success', 'danger' );
var $msgClass = 'alert';
var $msgWrapper = " <div class='alert %s-%s flashit'>
<button class='close' aria-hidden='true' data-dismiss='alert' type='button'>×</button>
<p><i style='vertical-align: middle;' class='%s icon-2x'></i> %s</p>
</div>";
var $msgBefore = '';
var $msgAfter = "";
public function __construct() {
// Generate a unique ID for this user and session
$this->msgId = md5(uniqid());
// Create the session array if it doesnt already exist
if( !array_key_exists('flash_messages', $_SESSION) ) $_SESSION['flash_messages'] = array();
}
public function add($type, $message, $redirect_to=null) {
if( !isset($_SESSION['flash_messages']) ) return false;
if( !isset($type) || !isset($message[0]) ) return false;
// Replace any shorthand codes with their full version
if( strlen(trim($type)) == 1 ) {
$type = str_replace( array('h', 'i', 'w', 'e', 's'), array('help', 'info', 'warning', 'danger', 'success'), $type );
$icon = str_replace( array('h', 'i', 'w', 'e', 's'), array('fa-help', 'fa-info', 'fa-warning', 'fa-danger', 'fa-success'), $type );
// Backwards compatibility...
} elseif( $type == 'information' ) {
$type = 'info';
$icon = 'fa-info';
}
// Make sure it's a valid message type
if( !in_array($type, $this->msgTypes) ) die('"' . strip_tags($type) . '" is not a valid message type!' );
// If the session array doesn't exist, create it
if( !array_key_exists( $type, $_SESSION['flash_messages'] ) ) $_SESSION['flash_messages'][$type] = array();
$_SESSION['flash_messages'][$type][] = $message;
if( !is_null($redirect_to) ) {
header("Location: $redirect_to");
exit();
}
return true;
}
//-----------------------------------------------------------------------------------------------
// display()
// print queued messages to the screen
//-----------------------------------------------------------------------------------------------
public function display($type='all', $print=true) {
$messages = '';
$data = '';
if( !isset($_SESSION['flash_messages']) ) return false;
if( $type == 'g' || $type == 'growl' ) {
$this->displayGrowlMessages();
return true;
}
// Print a certain type of message?
if( in_array($type, $this->msgTypes) ) {
foreach( $_SESSION['flash_messages'][$type] as $msg ) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $type,$icon,$messages);
// Clear the viewed messages
$this->clear($type);
// Print ALL queued messages
} elseif( $type == 'all' ) {
foreach( $_SESSION['flash_messages'] as $type => $msgArray ) {
$messages = '';
foreach( $msgArray as $msg ) {
$messages .= $this->msgBefore . $msg . $this->msgAfter;
}
$data .= sprintf($this->msgWrapper, $this->msgClass, $type,$icon,$messages);
}
// Clear ALL of the messages
$this->clear();
// Invalid Message Type?
} else {
return false;
}
// Print everything to the screen or return the data
if( $print ) {
echo $data;
} else {
return $data;
}
}
//..... more
}
Call:
$msg = new Messages();
$msg->add('i', 'This is a Information message!');
echo $msg->display();
Now in Output:
<i style="vertical-align: middle;" class=" icon-2x"></i>
Icon class not printed and empty: class=" icon-2x". how do can i fix this ?
EDit: Indeed i need to print for each type One class name.
I'm relatively new to WordPress and PHP, however I am trying to create my own shortcode plugin, which I have completed and is working.
However if I add more than 1 on the same page in WP, both forms submit and are not exclusive of each other.
I have search around the web, but can't find out how to easily separate the form id's, below is my plugin code:
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to '
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
If someone can help that would be appreciated.
Thanks,
Steve
I am pretty sure you've forgotten the last attribute in the function shortcode_atts, even if it's optionnal, you need to call it.
Also, is there some code missing ?
edit : you need to id your forms otherwise the function will pick up the datas twice. call the second shortcode giving the value 'second' to teh variable $num_f like so [wptuts_contact_form_sc -your bunch of vars here- num_f="second"]
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"num_f" => 'first'
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $num_f == 'second') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
To have more than two forms, you can either do it manually by calling the third block 'trird' and so on, but that's not very good practice to be honest...
If I were you I would change your code at the core, create a function that would return the form with a hidden field like so : <input type"hidden" name="hidden" value=" . $nf . "> and then instead of controling $_SERVER['REQUEST_METHOD'], you'd control the value of $_POST['n'] after checking if it's set ofc.
Here's the code I came up with :
<?php
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"nf" => '1'
), $atts));
if (isset($_POST['hidden'])) {
$hidden = $_POST['hidden'];
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
} else {
$hidden = $_POST['hidden'];
}
for ($i = 1; $i <= $nf; $i++) {
if($result != "" && $i == $hidden) {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="hidden" name="hidden" value="' . $nf . '">
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info . $email_form;
}
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
?>
Let me know if it works, (or does not) I obviously couldnt test it so there might be somehting wrong, in which case I just hope you got the whole idea behind it.