I'm receiving an error with the email form not going through and receiving an error message. I've checked for parse and syntax errors and didn't come across any. I think that I need to upgrade the email form from php to smtp email settings, but not sure where exactly to start. Has anyone navigated this before and any tips on troubleshooting this issue? Could it be something else that is causing the error message?
<?php
/*
=== Copyright (c) x2cms.com 2011 === BUILDER_VERSION:12
*/
if (!defined("BASE_PATH")) define('BASE_PATH', isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : substr(str_replace('\\\\','\\',$_SERVER['PATH_TRANSLATED']),0, -1*strlen($_SERVER['SCRIPT_NAME'])));
/* initialize a session. */
session_start();
require("mailer.php");
require("template-loader.php");
require("settings-loader.php");
$settings['captcha_required'] = array_key_exists('captcha',$_POST);
// disable magic quotes
// --------------------------------------------------------------------------------------------
// languages
// --------------------------------------------------------------------------------------------
// load language
read_language_xml(BASE_PATH.'/emaileverything.php.xml');
// add default language for form
add_language_def('email_message','The following information was posted from your %s form');
add_language_def('email_subject','%s form results');
add_language_def('error_required','is a required field');
add_language_def('mail_sender','Mail sender IP address:');
add_language_def('go_back','« back');
add_language_def('error_captcha','The validation code you entered was invalid');
add_language_def('error_no_email_to','You must enter an email address');
add_language_def('error_no_email_from','You must enter an email address to send to.');
add_language_def('error_no_message','You must enter a message');
add_language_def('success_message','Thank you, the form has been processed successfully.');
add_language_def('error_message','The following error(s) occured: ');
// uploader
add_language_def('error_file_size','%s file is too big, the maximum file size is (%smb)');
add_language_def('file_link','File Link');
add_language_def('error_upload','Unable to save uploaded file, please check site uploaded directory and permissions.');
add_language_def('error_file_type','allowed files are %s. Yours was %s.');
// settings
// --------------------------------------------------------------------------------------------
$settings['form_id'] = ''; // form identifier
$settings['form_name'] = $_SERVER['HTTP_HOST']; // the name of the form used, defaults to the script address
$settings['confirmation_message'] = ''; // the confirmation message used with the template
$settings['confirmation_url'] = ''; // if specified we redirect to a confirmation page
$settings['email_subject'] = ''; // the email subject
$settings['email_to'] = ''; // who do we send the email to
$settings['email_from'] = ''; // the customer's email submitting the form
$settings['copy_mail_to_sender'] = 'false'; // whether we copy the form email to the mail sender $email_from
$settings['required_fields'] = ''; // required field names seperated by |
$settings['email_template'] = ''; // the email template to use
$settings['upload_max_size'] = '20'; // size in mb per file
$settings['upload_check_extension'] = 'false';
$settings['upload_allowed_extensions'] = 'jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx|zip'; // allowed file extensions
// general functions
// --------------------------------------------------------------------------------------------
if(!function_exists('str_ireplace'))
{
function str_ireplace($needle, $str, $haystack)
{
$needle = preg_quote($needle, '/');
return preg_replace("/$needle/i", $str, $haystack);
}
}
// ensure filename is in friendly format
function safe_filename($filename)
{
$filename = trim($filename);
$filename = str_replace("/", "", $filename);
$filename = str_replace("\\", "", $filename);
$filename = str_replace(">", "", $filename);
$filename = str_replace("<", "", $filename);
return $filename;
}
// check for required fields
function isRequired($field_name)
{
global $required_fieldsarr;
if(is_array($required_fieldsarr))
{
foreach ($required_fieldsarr as $required_field_name)
{
if(strtoupper($required_field_name) == strtoupper($field_name))
{
return true;
}
}
}
return false;
}
function get_file_extension($filename)
{
return end(explode(".", $filename));
}
// uploaded files
function uploadedFiles()
{
$returnStr = '';
$returnStr .= uploadFile("userfile");
for($i = 0; $i<10; $i++)
{
$returnStr .= uploadFile("userfile".$i);
}
return $returnStr;
}
function uploadFile($fieldName)
{
global $error_message, $_FILES, $language, $settings;
if(!isset($_FILES[$fieldName]))
{
return;
}
$allowed_file_ext_arr = explode("|", $settings['upload_allowed_extensions']);
$returnStr = '';
// try array of files first
if(is_array($_FILES[$fieldName]))
{
foreach ($_FILES[$fieldName]["error"] as $key => $error)
{
if ($error == UPLOAD_ERR_OK)
{
$file_type = $_FILES[$fieldName]['type'][$key];
$file_size = $_FILES[$fieldName]['size'][$key];
$tmp_name = $_FILES[$fieldName]["tmp_name"][$key];
$name = $_FILES[$fieldName]["name"][$key];
$error = "";
// check file size
if ($file_size > ((int)$settings['upload_max_size'] * 1024 * 1024))
{
$error .= sprintf($language['error_file_size'], $name, $settings['upload_max_size']).'<br/>';
}
// check file type
if($settings['upload_check_extension'] == 'true')
{
if (!in_array(get_file_extension($name),$allowed_file_ext_arr))
{
$error .= sprintf($language['error_file_type'], $settings['upload_allowed_extensions'], $file_type).'<br/>';
}
}
if ($error == "")
{
if(is_uploaded_file($tmp_name))
{
// sanatize file name
$name = preg_replace(array("/\s+/", "/[^-\.\w]+/"), array("_", ""), trim($name));
if(move_uploaded_file($tmp_name, "uploaded/$name"))
{
$returnStr .= "<tr><td>".$language['file_name']."</td><td><a href='http://".$_SERVER['HTTP_HOST']."/uploaded/$name'>$name</a></td></tr>";
}
else
{
$error_message = $language['error_upload'].'<br/>';
}
}
}
else
{
$error_message .= $error;
}
}
}
}
else // try single file
{
if($_FILES[$fieldName]["error"] == UPLOAD_ERR_OK)
{
$file_type = $_FILES[$fieldName]['type'][$key];
$file_size = $_FILES[$fieldName]['size'][$key];
$tmp_name = $_FILES[$fieldName]["tmp_name"][$key];
$name = $_FILES[$fieldName]["name"][$key];
$error = "";
// check file size
if ($file_size > ((int)$settings['upload_max_size'] * 1024 * 1024))
{
$error .= sprintf($language['error_file_size'], $key, ($maxSize/1000)).'<br/>';
}
// check file type
if($settings['upload_check_extension'] == 'true')
{
if (!in_array(get_file_extension($name),$allowed_file_ext_arr))
{
$error .= $key." Allowed files are ".$settings['upload_allowed_extensions'].". Yours was ".$file_type."<br/>";
}
}
if ($error == "")
{
if(is_uploaded_file($tmp_name))
{
// sanatize file name
$name = preg_replace(array("/\s+/", "/[^-\.\w]+/"), array("_", ""), trim($name));
if(move_uploaded_file($tmp_name, "uploaded/$name"))
{
$returnStr .= "<tr><td>".$language['file_name']."</td><td><a href='http://".$_SERVER['HTTP_HOST']."/uploaded/$name'>$name</a></td></tr>";
}
else
{
$error_message = $language['error_upload'].'<br/>';
}
}
}
else
{
$error_message .= $error;
}
}
}
return $returnStr;
}
// read POST and GET data
// --------------------------------------------------------------------------------------------
// did we specify a form name in either GET OR POST
// get the form id
if(trim($_POST['id']) != '')
{
$settings['form_id'] = trim($_POST['id']);
}
if(trim($_GET['id']) != '')
{
$settings['form_id'] = trim($_GET['id']);
}
// 5.1 get parameters from XML
load_config('emaileverything-settings.xml');
load_config($settings['form_id'].'.xml');
// parse_settings_xml(safe_filename($settings['form_id']).'-settings.xml');
// check_referrer();
// get parameters from POST, POST overwrites settings from XML
if(trim($_POST['FormName']) != '')
{
$settings['form_name'] = trim($_POST['FormName']);
}
if(trim($_POST['EmailSubject']) != '')
$settings['email_subject'] = trim($_POST['EmailSubject']);
if(trim($_POST['EmailTo']) != '')
$settings['email_to'] = trim($_POST['EmailTo']);
if(trim($_POST['email']) != '')
$settings['email_from'] = trim($_POST['email']);
if(trim($_POST['OKMessage']) != '')
$settings['confirmation_message'] = trim($_POST['OKMessage']);
if(trim($_POST['OKURL']) != '')
$settings['confirmation_url'] = trim($_POST['OKURL']);
if(trim($_POST['CopyToSender']) != '')
$settings['copy_mail_to_sender'] = trim($_POST['CopyToSender']);
if(trim($_POST['UseTemplate']) != '')
$settings['email_template'] = trim($_POST['UseTemplate']);
if(trim($_POST['TemplateID']) != '')
$settings['template_id'] = trim($_POST['TemplateID']);
if(trim($_POST['RequiredFields']) != '')
$settings['required_fields'] = trim($_POST['RequiredFields']);
// alternative field names from trellix
if(trim($_POST['tlx_Subject']) != '')
$settings['email_subject'] = trim($_POST['tlx_Subject']);
if($_POST['tlx_EmailTo'] != '')
$settings['email_to'] = trim($_POST['tlx_EmailTo']);
if($_POST['tlx_OKMessage'] != '')
$settings['confirmation_message'] = trim($_POST['tlx_OKMessage']);
// build the email
// --------------------------------------------------------------------------------------------
// now we do some work with our required fields, split on | to get each required field name
$required_fieldsarr = explode("|", $settings['required_fields']);
$error_message = '';
// check required fields
foreach ($_POST as $key => $val)
{
// see if field is required
if(isRequired($key) && ($val == ''))
{
$error_message .= $key." ".$language['error_required'].".<br/>";
}
}
// build email message
if($settings['email_template'] != '') // are we using a email template
{
// safe file name
$settings['email_template'] = safe_filename($settings['email_template']);
// check to see if template exists
if(file_exists($settings['email_template']))
{
$email_message = file_get_contents($settings['email_template']);
// replace key with value
foreach ($_POST as $key => $val)
{
$email_message = str_ireplace('{'.$key.'}', $val, $email_message);
}
// remove remaining
$email_message = preg_replace('/\{(\w*)\}/', '', $email_message);
}
}
else
{
$email_message = sprintf($language['email_message'],$settings['form_name']);
$email_message .= '<br/><br/><table cellpadding="5" cellspacing="5" border="1"><tr><th>Field Name</th><th>Value</th></tr>';`
foreach ($_POST as $key => $val)
Related
Problem
I am trying to send push notification through PHP, to both Android and iOS, but I have lots of devices to send the notification, and you can see the code that it sends the notification to all of them in a loop. It's really not optimized as my dashboard gets stuck for more than a minute due to the running loop, also somehow it is not even sending a notification to all active accounts.
Can anyone here help me out?
Code
public function insert()
{
// Set the validation rules
$this->form_validation->set_rules('title', 'Title', 'required|trim');
// If the validation worked
if ($this->form_validation->run())
{
$get_post = $this->input->get_post(null,true);
$get_post['tags'] = is_array($this->input->get_post('tags')) ? $this->input->get_post('tags') : [];
if(count($get_post['tags']) == 0)
{
$_SESSION['msg_error'][] = "Tags is a required field";
redirect('admin/newsfeed/insert');
exit;
}
# File uploading configuration
$upload_path = './uploads/newsfeeds/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$image = '';
# Try to upload file now
if ($this->upload->do_upload('image'))
{
# Get uploading detail here
$upload_detail = $this->upload->data();
$image = $upload_detail['file_name'];
} else {
$uploaded_file_array = (isset($_FILES['image']) and $_FILES['image']['size'] > 0 and $_FILES['image']['error'] == 0) ? $_FILES['image'] : '';
# Show uploading error only when the file uploading attempt exist.
if( is_array($uploaded_file_array) )
{
$uploading_error = $this->upload->display_errors();
$_SESSION['msg_error'][] = $uploading_error;
}
}
# File uploading configuration
$upload_path = './uploads/newsfeeds/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = '*';
$config['encrypt_name'] = true;
$config['max_size'] = 51200; //KB
$this->upload->initialize($config);
$audio = '';
# Try to upload file now
if ($this->upload->do_upload('audio'))
{
# Get uploading detail here
$upload_detail = $this->upload->data();
$audio = $upload_detail['file_name'];
}
else
{
$uploaded_file_array = (isset($_FILES['audio']) and $_FILES['audio']['size'] > 0 and $_FILES['audio']['error'] == 0) ? $_FILES['audio'] : '';
# Show uploading error only when the file uploading attempt exist.
if( is_array($uploaded_file_array) )
{
$uploading_error = $this->upload->display_errors();
$_SESSION['msg_error'][] = $uploading_error;
}
}
$get_post['image'] = $image;
$get_post['audio'] = $audio;
if($id = $this->newsfeed_model->insert($get_post))
{
if($get_post['status'])
{
// send push notification to all users
$notification = $this->newsfeed_model->get_newsfeed_by_id($id);
$notification->notification_type = 'article';
$notification->title = $get_post['n_title'];
$notification->body = $get_post['n_description'];
$query = $this->db->get_where('users', ['device_id !=' => '']);
foreach ($query->result() as $row) {
if ($row->device == 'IOS') {
$this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
}
if ($row->device == 'ANDROID') {
$this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
}
}
}
$_SESSION['msg_success'][] = 'Record added successfully...';
if($image){
redirect('admin/newsfeed/crop_image?id='.$id);
} else {
redirect('admin/newsfeed/');
}
}
}
$this->data['selected_page'] = 'newsfeed';
$this->load->view('admin/newsfeed_add', $this->data);
}
Description
The method is adding a newsfeed, its checks for the validations, then it inserts the feed to the db, once thats done, it sends out the notification to all devices.
Problematic Chunk
if($id = $this->newsfeed_model->insert($get_post))
{
if($get_post['status'])
{
// send push notification to all users
$notification = $this->newsfeed_model->get_newsfeed_by_id($id);
$notification->notification_type = 'article';
$notification->title = $get_post['n_title'];
$notification->body = $get_post['n_description'];
$query = $this->db->get_where('users', ['device_id !=' => '']);
foreach ($query->result() as $row) {
if ($row->device == 'IOS') {
$this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
}
if ($row->device == 'ANDROID') {
$this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
}
}
}
$_SESSION['msg_success'][] = 'Record added successfully...';
if($image) {
redirect('admin/newsfeed/crop_image?id='.$id);
} else{
redirect('admin/newsfeed/');
}
}
Thank you in advance.
I'm having trouble figuring out why it is that when an image size is too big, I get the error 'Invalid File Type' 'Uploaded file is not an image' instead of getting 'File is too big' (The image validation/upload script I didn't completely write myself- I found the code and made it work with for my needs). Everything else seems to work fine except for this. Also I get the following warning
Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\minnow\includes\create-post.php on line 75
Here is my code
<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}
$postEmpty = 0;
$imageError = 0;
if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}
// validate post
if( $postEmpty == 0 && !empty($body) ){
$cleanBody = clean_input($body);
}
// validate image (if any)
if( $has_image == 1 ){
//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');
// Create an array to hold any output
$errors = array();
// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}
//If $check image is set as true
if ( !getimagesize($_FILES[$image]['tmp_name']) ) {
$errors[] = "Uploaded file is not a valid image";
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}
// if no errors:
// upload image (if any) and retrieve filename
if( $imageError == 1 ){
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}else{
//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {
$uploadSuccesfull = 1;
}else {
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
die();
}
}
}
// if no errors:
// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){
$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";
}else{
$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";
}
$result = $db->query($query);
// send response
//check to make sure the user was added
if( $db->affected_rows == 1 ){
$user_id = $_SESSION['user_id'];
$post_id = $db->insert_id;
$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);
if($result->num_rows == 1){
$row = $result->fetch_assoc();
}
$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}
if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }
if($row['has_image'] == 1){
$data = "<article class='post'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><img src='users/user_".$rowuser['user_id']."/posts/".$row['image']."' alt=''><div class='post-body'><div class='post-options'><a class='likes' href=''>156 likes</a></div><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}else{
$data = "<article class='post no-img'><div class='post-head cf'><a class='userpic' href=''><img src='$userpic' alt='".$rowuser['username']."'></a><a href='' class='username'>".$rowuser['username']."</a></div><div class='post-body'><p><a class='username' href=''>".$rowuser['username']."</a>".$row['body']."</p><div class='post-options'><a class='likes' href=''>1 like</a></div><hr /><div class='cf'><a class='like hide-text' href='javascript:;'>Like This Post</a><form action='' class='comment'><input type='text' placeholder='Add a comment'></form></div></div></article>";
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}
}else{
$errors[] = "Server Error!";
$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);
}
die();
It could be that the file was just not uploaded to the server.
Check $_FILES[$image]['error'] to see what may have gone wrong.
Refer to the error messages here.
Edit: After these lines:
$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];
Do this:
// check for error greater than zero
if($_FILES[$image]['error'] > 0) {
// something went wrong with the upload, handle the error
echo $_FILES[$image]['error']; exit; // as an example to find out what the error was
}
Then refer to http://php.net/manual/en/features.file-upload.errors.php to find out the reason.
I have an issue where I need to data from a RETS server and populate it on the database, I was able to get all but two tables to properly automate this data in, but I'm having issues with the last (and biggest) two. After looking at it, the issue is timeout with the server, it cannot finish in time for the database to populate.
I am working off of a godaddy server and already have the maximum time I can set for the program to run, the only thing I can do now is figure out a way to speed up my code so it finishes in time, and would like some help figuring that out.
The code (posted below) was modified to fit my needs from here: https://github.com/coreyrowell/retshelper/blob/master/rets_helper.php
While it works well and I was able to get it working, I haven't been able to figure out the best way to speed it up. Any help would be sincerely appreciated.
<?php
/*
.---------------------------------------------------------------------------.
| Software: RETSHELPER - PHP Class to interface RETS with Database |
| Version: 1.0 |
| Contact: corey#coreyrowell.com |
| Info: None |
| Support: corey#coreyrowell.com |
| ------------------------------------------------------------------------- |
| Author: Corey Rowell - corey#coreyrowell.com |
| Copyright (c) 2013, Corey Rowell. All Rights Reserved. |
| ------------------------------------------------------------------------- |
| License: This content is released under the |
| (http://opensource.org/licenses/MIT) MIT License. | |
'---------------------------------------------------------------------------'
*/
/*
.---------------------------------------------------------------------------.
| This software requires the use of the PHPRETS library |
| http://troda.com/projects/phrets/ |
'---------------------------------------------------------------------------'
*/
define("BASE_PATH",dirname(__FILE__)."/");
ini_set('mysql.connect_timeout',0);
ini_set('default_socket_timeout',0);
class RETSHELPER
{
// Defaults
private $rets, $auth, $config, $database, $mysqli, $data, $log, $scriptstart, $scriptend,
$previous_start_time, $current_start_time, $updates_log, $active_ListingRids = array();
public function __construct()
{
// Require PHRETS library
require_once("phrets.php");
// Start rets connection
$this->rets = new phRETS;
$this->scriptstart = date("m-d-y_h-i-s", time());
// RETS Server Info
$this->auth['url'] = 'redacted';//MLS_URL;//MLS_URL;
$this->auth['username'] = 'redacted'; //MLS_USERNAME;
$this->auth['password'] = 'redacted'; //MLS_PASS;
$this->auth['retsversion'] = ''; //USER Agent Version
$this->auth['useragent'] = ''; //USER Agent
// RETS Options
$this->config['property_classes'] = array("A");//,"B","C","D","E","F");
$this->config['KeyField'] = "LIST_1";
$this->config['offset_support'] = TRUE; // Enable if RETS server supports 'offset'
$this->config['useragent_support'] = FALSE;
$this->config['images_path'] = BASE_PATH."listing_photos/";
$this->config['logs_path'] = BASE_PATH."logs/";
$this->config['start_times_path'] = BASE_PATH."logs/";
$this->config['previous_start_time'] = $this->get_previous_start_time();
$this->config['create_tables'] = FALSE; // Create tables for classes (terminates program)
// Log to screen?
$this->config['to_screen'] = TRUE;
// Database Config
$this->database['host'] = 'redacted'; //DB_SERVER;
$this->database['username'] = 'redacted'; //DB_USER;
$this->database['password'] = 'redacted'; //DB_PASS;
$this->database['database'] = 'redacted'; //DB_NAME;
$this->config_init();
// Load the run function
$this->run();
}
private function config_init()
{
// Set offset support based on config
if($this->config['offset_support'])
{
$this->rets->SetParam("offset_support", true);
} else {
$this->rets->SetParam("offset_support", false);
}
if($this->config['useragent_support'])
{
$this->rets->AddHeader("RETS-Version", $this->auth['retsversion']);
$this->rets->AddHeader("User-Agent", $this->auth['useragent']);
}
}
public function run()
{
// Start Logging
$this->logging_start();
// RETS Connection
$this->connect();
// Connect to Database
$this->database_connect();
if($this->config['create_tables'])
{
$this->log_data("Creating database tables, program will exit after finishing.");
foreach ($this->config['property_classes'] as $class)
{
$this->log_data("Creating table for: " . $class);
$this->create_table_for_property_class($class);
}
$this->log_data("Exiting program.");
return;
}
// Get Properties (and images)
$this->get_properties_by_class();
// Close RETS Connection
$this->disconnect();
// Delete inactive listings
$this->database_delete_records();
// Insert new listings
$this->database_insert_records();
// Disconnect from Database
$this->database_disconnect();
// End Logging
$this->logging_end();
// Time for next scheduled update
$this->set_previous_start_time();
}
private function connect()
{
$this->log_data("Connecting to RETS...");
// Connect to RETS
$connect = $this->rets->Connect($this->auth['url'], $this->auth['username'], $this->auth['password']);
if($connect)
{
$this->log_data("Successfully connected to RETS.");
return TRUE;
} else {
$error = $this->rets->Error();
if($error['text'])
{
$error = $error['text'];
} else {
$error = "No error message returned from RETS. Check RETS debug file.";
}
$this->log_error("Failed to connect to RETS.\n".$error);
die();
}
}
private function get_properties_by_class()
{
$this->log_data("Getting Classes...");
foreach ($this->config['property_classes'] as $class)
{
$this->log_data("Getting Class: ".$class);
// Set
$fields_order = array();
$mod_timestamp_field = $this->get_timestamp_field($class);
$previous_start_time = $this->config['previous_start_time'];
$search_config = array('Format' => 'COMPACT-DECODED', 'QueryType' => 'DMQL2', 'Limit'=> 1000, 'Offset' => 1, 'Count' => 1);
/*--------------------------------------------------------------------------------.
| |
| If you're having problems, they probably lie here in the $query and/or $search. |
| |
'--------------------------------------------------------------------------------*/
// Query
$query = "({$mod_timestamp_field}=2016-09-16T00:00:00-2016-09-16T01:00:00)";//{$previous_start_time}+)";
// Run Search
$search = $this->rets->SearchQuery("Property", $class, $query, $search_config);
// Get all active listings
$query_all = "({$mod_timestamp_field}=1980-01-01T00:00:00+)";
$search_all = $this->rets->SearchQuery("Property", $class, $query_all, array('Format'=>'COMPACT', 'Select'=>$this->config['KeyField']));
$tmpArray = array();
while($active_rid = $this->rets->FetchRow($search_all)) {
array_push($tmpArray, $active_rid[$this->config['KeyField']]);
}
$this->active_ListingRids['property_'.strtolower($class)] = $tmpArray;
$data = array();
if ($this->rets->NumRows($search) > 0)
{
// Get columns
$fields_order = $this->rets->SearchGetFields($search);
$this->data['headers'] = $fields_order;
// Process results
while ($record = $this->rets->FetchRow($search))
{
$this_record = array();
// Loop it
foreach ($fields_order as $fo)
{
$this_record[$fo] = $record[$fo];
}
$ListingRid = $record[$this->config['KeyField']];
$data[] = $this_record;
}
}
// Set data
$this->data['classes'][$class] = $data;
$this->log_data("Finished Getting Class: ".$class . "\nTotal found: " .$this->rets->TotalRecordsFound());
// Free RETS Result
$this->rets->FreeResult($search);
}
}
private function get_timestamp_field($class)
{
$class = strtolower($class);
switch($class)
{
case 'a':
$field = "LIST_87";
break;
}
return $field;
}
private function disconnect()
{
$this->log_data("Disconnected from RETS.");
$this->rets->Disconnect();
}
private function database_connect()
{
$this->log_data("Connecting to database...");
$host = $this->database['host'];
$username = $this->database['username'];
$password = $this->database['password'];
$database = $this->database['database'];
// Create connection
$this->mysqli = new mysqli($host, $username, $password, $database);
// Throw error if connection fails
if ($this->mysqli->connect_error) {
$this->log_error("Database Connection Error". $this->mysqli->connect_error);
die('Connect Error (' . $this->mysqli->connect_errno . ') '
. $this->mysqli->connect_error);
}
}
private function database_delete_records()
{
$this->log_data("Updating database...");
// Loop through each table and update
foreach($this->config['property_classes'] as $class)
{
// Get Tables
$table = "rets_property_".strtolower($class);
$activeListings = $this->active_ListingRids['property_'.strtolower($class)];
$sql = "DELETE FROM {$table} WHERE {$this->config['KeyField']} NOT IN (".implode(',', $activeListings).");";
$this->mysqli->query($sql);
if($this->mysqli->affected_rows > 0)
{
$this->log_data("Deleted {$this->mysqli->affected_rows} Listings.");
// return TRUE;
} else if($this->mysqli->affected_rows == 0) {
$this->log_data("Deleted {$this->mysqli->affected_rows} Listings.");
} else {
$this->log_data("Deleting database records failed \n\n" . mysqli_error($this->mysqli));
// return FALSE;
}
}
}
private function database_insert_records()
{
$this->log_data("Inserting records...");
foreach($this->config['property_classes'] as $class)
{
// Get Tables
$table = "rets_property_".strtolower($class);
// Get data
$data_row = $this->data['classes'][$class];
// Defaults
$total_rows = 0;
$total_affected_rows = 0;
// Loop through data
foreach($data_row as $drow)
{
// Clean data
// replace empty with NULL
// and wrap data in quotes
$columns = array();
$values = array();
foreach($drow as $key => $val)
{
if($val === '')
{
$val = '""';
} else {
$val = mysqli_real_escape_string($this->mysqli ,$val);
$val = "'$val'";
}
$columns[] = $key;
$values[] = $val;
}
// Implode data rows with commas
$values = implode(', ', $values);
$columns = implode(', ', $columns);
// Build SQL
$sql = "REPLACE INTO {$table} ({$columns}) VALUES ({$values})";
// Do query
$this->mysqli->query($sql);
if($this->mysqli->affected_rows > 0)
{
$total_affected_rows++;
} else {
$this->log_error("Failed to insert the following record: ".$sql . "\n\n" . mysqli_error($this->mysqli));
}
$total_rows++;
}
$this->log_data("Done inserting data. ".$class."\nTotal Records: ".$total_rows." .\nTotal Inserted: ".$total_affected_rows);
}
}
private function database_disconnect()
{
$this->log_data("Database disconnected...");
// Close connection
$this->mysqli->close();
}
private function create_table_for_property_class($class)
{
// gets resource information. need this for the KeyField
$rets_resource_info = $this->rets->GetMetadataInfo();
$resource = "Property";
// pull field format information for this class
$rets_metadata = $this->rets->GetMetadata($resource, $class);
$table_name = "rets_".strtolower($resource)."_".strtolower($class);
// i.e. rets_property_resi
$sql = $this->create_table_sql_from_metadata($table_name, $rets_metadata, $rets_resource_info[$resource]['KeyField']);
$this->mysqli->query($sql);
}
private function create_table_sql_from_metadata($table_name, $rets_metadata, $key_field, $field_prefix = "")
{
$sql_query = "CREATE TABLE {$table_name} (\n";
foreach ($rets_metadata as $field) {
$field['SystemName'] = "`{$field_prefix}{$field['SystemName']}`";
$cleaned_comment = addslashes($field['LongName']);
$sql_make = "{$field['SystemName']} ";
if ($field['Interpretation'] == "LookupMulti") {
$sql_make .= "TEXT";
}
elseif ($field['Interpretation'] == "Lookup") {
$sql_make .= "VARCHAR(50)";
}
elseif ($field['DataType'] == "Int" || $field['DataType'] == "Small" || $field['DataType'] == "Tiny") {
$sql_make .= "INT({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "Long") {
$sql_make .= "BIGINT({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "DateTime") {
$sql_make .= "DATETIME default '0000-00-00 00:00:00' not null";
}
elseif ($field['DataType'] == "Character" && $field['MaximumLength'] <= 255) {
$sql_make .= "VARCHAR({$field['MaximumLength']})";
}
elseif ($field['DataType'] == "Character" && $field['MaximumLength'] > 255) {
$sql_make .= "TEXT";
}
elseif ($field['DataType'] == "Decimal") {
$pre_point = ($field['MaximumLength'] - $field['Precision']);
$post_point = !empty($field['Precision']) ? $field['Precision'] : 0;
$sql_make .= "DECIMAL({$field['MaximumLength']},{$post_point})";
}
elseif ($field['DataType'] == "Boolean") {
$sql_make .= "CHAR(1)";
}
elseif ($field['DataType'] == "Date") {
$sql_make .= "DATE default '0000-00-00' not null";
}
elseif ($field['DataType'] == "Time") {
$sql_make .= "TIME default '00:00:00' not null";
}
else {
$sql_make .= "VARCHAR(255)";
}
$sql_make .= " COMMENT '{$cleaned_comment}'";
$sql_make .= ",\n";
$sql_query .= $sql_make;
}
$sql_query .= "`Photos` TEXT COMMENT 'Photos Array', ";
$sql_query .= "PRIMARY KEY(`{$field_prefix}{$key_field}`) )";
return $sql_query;
}
private function get_previous_start_time()
{
$filename = "previous_start_time_A.txt";
// See if file exists
if(file_exists($this->config['start_times_path'].$filename))
{
$time=time();
$this->updates_log = fopen($this->config['start_times_path'].$filename, "r+");
$this->previous_start_time = fgets($this->updates_log);
$this->current_start_time = date("Y-m-d", $time) . 'T' . date("H:i:s", $time);
} else {
// Create file
$this->updates_log = fopen($this->config['start_times_path'].$filename, "w+");
fwrite($this->updates_log, "1980-01-01T00:00:00\n");
$this->get_previous_start_time();
}
// fgets reads up to & includes the first newline, strip it
return str_replace("\n", '', $this->previous_start_time);
}
private function set_previous_start_time()
{
$file = $this->config['start_times_path'] . "previous_start_time_A.txt";
$file_data = $this->current_start_time."\n";
$file_data .= file_get_contents($file);
file_put_contents($file, $file_data);
}
private function logging_start()
{
$filename = "Log".date("m-d-y_h-i-s", time()).".txt";
// See if file exists
if(file_exists($this->config['logs_path'].$filename))
{
$this->log = fopen($this->config['logs_path'].$filename, "a");
} else {
// Create file
$this->log = fopen($this->config['logs_path'].$filename, "w+");
}
}
private function log_data($data)
{
$write_data = "\nInfo Message: [".date("m/d/y - h:i:s", time())."]\n------------------------------------------------\n";
$write_data .= $data."\n";
$write_data .= "\n------------------------------------------------\n";
fwrite($this->log, $write_data);
if($this->config['to_screen'])
{
echo str_replace(array("\n"), array('<br />'), $write_data);
}
}
private function log_error($error)
{
$write_data = "\nError Message: [".date("m/d/y - h:i:s", time())."]\n------------------------------------------------\n";
$write_data .= $error."\n";
$write_data .= "\n------------------------------------------------\n";
fwrite($this->log, $write_data);
if($this->config['to_screen'])
{
echo str_replace(array("\n"), array('<br />'), $write_data);
}
}
private function logging_end()
{
$this->scriptend = date("m-d-y_h-i-s", time());
$this->log_data("Closing log file.\n
Start Time: {$this->scriptstart}\n
End Time: {$this->scriptend}");
fclose($this->log);
}
}
// Load the class
$retshelper = new RETSHELPER;
Sorry for the wall of code; I would shorten it down but I'm at a loss with what is still needed and what isn't. Once again, any help would or a point into the right direction would be appreciated.
hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>
You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}
Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
I have written/copied a script that reads emails from an inbox and updates a ticket and then moves the email to a proccessed folder. This all works perfectly on new emails to the inbox but when someone replys to an email and it ends up in the inbox my scrtipt reads nothing on the email.
Is there something different to the way an email is structured when its a reply? I need a way of reading whats in the email so I can update a ticket with the contents. Knowing which email it is to update is all taken care of its just purely reading the content Im struggling with.
Here is the code
class Email
{
// imap server connection
public $conn;
// inbox storage and inbox message count
public $inbox;
private $msg_cnt;
// email login credentials
private $server = '????????????';
private $user = '????????';
private $pass = '?????????????';
private $port = ??;
// connect to the server and get the inbox emails
function __construct()
{
$this->connect();
$this->inbox();
}
function getdecodevalue($message,$coding)
{
switch($coding) {
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
case 5:
$message=imap_base64($message);
break;
case 4:
$message = imap_qprint($message);
break;
}
return $message;
}
// close the server connection
function close()
{
$this->inbox = array();
$this->msg_cnt = 0;
imap_close($this->conn);
}
// open the server connection
// the imap_open function parameters will need to be changed for the particular server
// these are laid out to connect to a Dreamhost IMAP server
function connect()
{
$this->conn = imap_open("{".$this->server.":".$this->port."/imap/novalidate-cert}INBOX", $this->user, $this->pass);
}
// move the message to a new folder
function move($msg_index, $folder='Read')
{
// move on server
imap_mail_move($this->conn, $msg_index, $folder);
// re-read the inbox
//$this->inbox();
}
// get a specific message (1 = first email, 2 = second email, etc.)
function get($msg_index=NULL)
{
if(count($this->inbox) <= 0)
{
return array();
}
elseif( ! is_null($msg_index) && isset($this->inbox[$msg_index]))
{
return $this->inbox[$msg_index];
}
return $this->inbox[0];
}
// read the inbox
function inbox()
{
$this->msg_cnt = imap_num_msg($this->conn);
$in = array();
for($i = 1; $i <= $this->msg_cnt; $i++)
{
$in[] = array(
'index' => $i,
'header' => imap_headerinfo($this->conn, $i),
'body' => $this->cleanBody(imap_fetchbody($this->conn, $i,1)),
'structure' => imap_fetchstructure($this->conn, $i)
);
}
$this->inbox = $in;
}
function cleanBody($body)
{
$delimiter = '#';
$startTag = '----------START REPLY----------';
$endTag = '----------END REPLY----------';
$regex = $delimiter . preg_quote($startTag, $delimiter)
. '(.*?)'
. preg_quote($endTag, $delimiter)
. $delimiter
. 's';
preg_match($regex,$body,$matches);
$ret = trim($matches[1]);
return $ret;
}
}
$emails = new Email();
$email = array();
$emailCount = 1;
foreach($emails->inbox as $ems => $em)
{
$email[$emailCount]['subject'] = $sub = $em['header']->subject;
//echo $sub;
$subParts = explode('-',$sub);
$ticketUniqueCode = trim($subParts[1]);
$sql = "SELECT * FROM ticket_main WHERE uniquecode = '".mysql_escape_string($ticketUniqueCode)."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query))
{
$res = mysql_fetch_object($query);
$ticketBody = $em['body'];
$customerID = $res->customerID;
$sql2 = "INSERT INTO ticket_updates SET ticketID = '".$res->ticketID."' , submitted = NOW() , submittedBy = '".$res->customerID."' , message = '".mysql_escape_string($ticketBody)."' , inhouse = 0";
$query = mysql_query($sql2);
// attachment section
$message_number = $em['index'];
$attachments = array();
if(isset($em['structure']->parts) && count($em['structure']->parts))
{
//echo 'hi';
for($i = 0; $i < count($em['structure']->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($em['structure']->parts[$i]->ifdparameters) {
foreach($em['structure']->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($em['structure']->parts[$i]->ifparameters) {
foreach($em['structure']->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($emails->conn, $message_number, $i+1);
if($em['structure']->parts[$i]->encoding == 3)
{ // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($em['structure']->parts[$i]->encoding == 4)
{ // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
if(isset($em['structure']->parts[$i]->disposition) && $em['structure']->parts[$i]->disposition == "attachment")
{
$filename = $attachments[$i]['name'];
$mege="";
$data="";
$mege = imap_fetchbody($emails->conn, $message_number, $i+1);
$filename= $filename;
$fp=fopen('???????????????'.$filename,"w");
$data=$emails->getdecodevalue($mege,$em['structure']->parts[$i]->type);
fputs($fp,$data);
fclose($fp);
$email[$emailCount]['attachment'] = $attachments;
}
}
}
}
$emailCount++;
}
$emailNumbers = imap_search($emails->conn,'ALL');
if(!empty($emailNumbers))
{
foreach($emailNumbers as $a)
{
$emails->move($a);
}
imap_expunge($emails->conn);
}
$emails->close();
Hope that makes some sense and someone can actually help.
Many many thanks in advance
Jon
Well the most obvious thing is your code assumes a message is always in part 1, your line:
'body' => $this->cleanBody(imap_fetchbody($this->conn, $i,1)),
Means it's only looking at body 1. If it's a pure text email body 1 will be right, but if it's multipart/alternative (text & html) body 1 would be the base MIME message which tells you that there are sub bodies (body 1.1, 1.2) that actually contain the content.
Further if the reply includes embedded images, or includes the message it's replying to as an attachment then you could have even more bodies/locations.
So how do I find the body? (you ask)... well you can use imap_fetchstructure to learn about all the body parts, then search through it to find a piece with type=0 (text) and then download that body part. (The first found text should be the right one, but note there could be more than one text body type in an email).