I'm new so please bear with me.
I am trying to add a BCC recipient to one of codeigniter applications' email.php config file. The original was created by an employee who has since left our business and I am struggling to add a bcc recipient into the code.
I have searched stackoverflow and tried endless variations but I am not having any luck. All I want to do is define one bcc email recipient.
I would really really really appreciate anybody's help :)
Here is a portion of the the current code I think is relevant:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Email Class
*
* Permits email to be sent using Mail, Sendmail, or SMTP.
*
* #package CodeIgniter
* #subpackage Libraries
* #category Libraries
* #author ExpressionEngine Dev Team
* #link http://codeigniter.com/user_guide/libraries/email.html
*/
class CI_Email {
var $useragent = "CodeIgniter";
var $mailpath = "/usr/sbin/sendmail"; // Sendmail path
var $protocol = "mail"; // mail/sendmail/smtp
var $smtp_host = ""; // SMTP Server. Example: mail.earthlink.net
var $smtp_user = ""; // SMTP Username
var $smtp_pass = ""; // SMTP Password
var $smtp_port = "25"; // SMTP Port
var $smtp_timeout = 5; // SMTP Timeout in seconds
var $smtp_crypto = ""; // SMTP Encryption. Can be null, tls or ssl.
var $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off
var $wrapchars = "76"; // Number of characters to wrap at.
var $mailtype = "text"; // text/html Defines email formatting
var $charset = "utf-8"; // Default char set: iso-8859-1 or us-ascii
var $multipart = "mixed"; // "mixed" (in the body) or "related" (separate)
var $alt_message = ''; // Alternative message for HTML emails
var $validate = FALSE; // TRUE/FALSE. Enables email validation
var $priority = "3"; // Default priority (1 - 5)
var $newline = "\n"; // Default newline. "\r\n" or "\n" (Use "\r\n" to comply with RFC 822)
var $crlf = "\n"; // The RFC 2045 compliant CRLF for quoted-printable is "\r\n". Apparently some servers,
// even on the receiving end think they need to muck with CRLFs, so using "\n", while
// distasteful, is the only thing that seems to work for all environments.
var $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like multipart alternative, so this is an override. Set to FALSE for Yahoo.
var $bcc_batch_mode = FALSE; // TRUE/FALSE Turns on/off Bcc batch feature
var $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max number of Bccs in each batch
var $_safe_mode = FALSE;
var $_subject = "";
var $_body = "";
var $_finalbody = "";
var $_alt_boundary = "";
var $_atc_boundary = "";
var $_header_str = "";
var $_smtp_connect = "";
var $_encoding = "8bit";
var $_IP = FALSE;
var $_smtp_auth = FALSE;
var $_replyto_flag = FALSE;
var $_debug_msg = array();
var $_recipients = array();
var $_cc_array = array();
var $_bcc_array = array();
var $_headers = array();
var $_attach_name = array();
var $_attach_type = array();
var $_attach_disp = array();
var $_protocols = array('mail', 'sendmail', 'smtp');
var $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets (excluding language suffix)
var $_bit_depths = array('7bit', '8bit');
var $_priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
/**
* Constructor - Sets Email Preferences
*
* The constructor can be passed an array of config values
*/
public function __construct($config = array())
{
if (count($config) > 0)
{
$this->initialize($config);
}
else
{
$this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
$this->_safe_mode = ((boolean)#ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
}
log_message('debug', "Email Class Initialized");
}
// --------------------------------------------------------------------
/**
* Initialize preferences
*
* #access public
* #param array
* #return void
*/
public function initialize($config = array())
{
foreach ($config as $key => $val)
{
if (isset($this->$key))
{
$method = 'set_'.$key;
if (method_exists($this, $method))
{
$this->$method($val);
}
else
{
$this->$key = $val;
}
}
}
$this->clear();
$this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
$this->_safe_mode = ((boolean)#ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
return $this;
}
// --------------------------------------------------------------------
/**
* Initialize the Email Data
*
* #access public
* #return void
*/
public function clear($clear_attachments = FALSE)
{
$this->_subject = "";
$this->_body = "";
$this->_finalbody = "";
$this->_header_str = "";
$this->_replyto_flag = FALSE;
$this->_recipients = array();
$this->_cc_array = array();
$this->_bcc_array = array();
$this->_headers = array();
$this->_debug_msg = array();
$this->_set_header('User-Agent', $this->useragent);
$this->_set_header('Date', $this->_set_date());
if ($clear_attachments !== FALSE)
{
$this->_attach_name = array();
$this->_attach_type = array();
$this->_attach_disp = array();
}
return $this;
}
// --------------------------------------------------------------------
/**
* Set FROM
*
* #access public
* #param string
* #param string
* #return void
*/
public function from($from, $name = '')
{
if (preg_match( '/\<(.*)\>/', $from, $match))
{
$from = $match['1'];
}
if ($this->validate)
{
$this->validate_email($this->_str_to_array($from));
}
// prepare the display name
if ($name != '')
{
// only use Q encoding if there are characters that would require it
if ( ! preg_match('/[\200-\377]/', $name))
{
// add slashes for non-printing characters, slashes, and double quotes, and surround it in double quotes
$name = '"'.addcslashes($name, "\0..\37\177'\"\\").'"';
}
else
{
$name = $this->_prep_q_encoding($name, TRUE);
}
}
$this->_set_header('From', $name.' <'.$from.'>');
$this->_set_header('Return-Path', '<'.$from.'>');
return $this;
}
// --------------------------------------------------------------------
/**
* Set Reply-to
*
* #access public
* #param string
* #param string
* #return void
*/
public function reply_to($replyto, $name = '')
{
if (preg_match( '/\<(.*)\>/', $replyto, $match))
{
$replyto = $match['1'];
}
if ($this->validate)
{
$this->validate_email($this->_str_to_array($replyto));
}
if ($name == '')
{
$name = $replyto;
}
if (strncmp($name, '"', 1) != 0)
{
$name = '"'.$name.'"';
}
$this->_set_header('Reply-To', $name.' <'.$replyto.'>');
$this->_replyto_flag = TRUE;
return $this;
}
// --------------------------------------------------------------------
/**
* Set Recipients
*
* #access public
* #param string
* #return void
*/
public function to($to)
{
$to = $this->_str_to_array($to);
$to = $this->clean_email($to);
if ($this->validate)
{
$this->validate_email($to);
}
if ($this->_get_protocol() != 'mail')
{
$this->_set_header('To', implode(", ", $to));
}
switch ($this->_get_protocol())
{
case 'smtp' :
$this->_recipients = $to;
break;
case 'sendmail' :
case 'mail' :
$this->_recipients = implode(", ", $to);
break;
}
return $this;
}
// --------------------------------------------------------------------
/**
* Set CC
*
* #access public
* #param string
* #return void
*/
public function cc($cc)
{
$cc = $this->_str_to_array($cc);
$cc = $this->clean_email($cc);
if ($this->validate)
{
$this->validate_email($cc);
}
$this->_set_header('Cc', implode(", ", $cc));
if ($this->_get_protocol() == "smtp")
{
$this->_cc_array = $cc;
}
return $this;
}
// --------------------------------------------------------------------
/**
* Set BCC
*
* #access public
* #param string
* #param string
* #return void
*/
public function bcc($bcc, $limit = '')
{
if ($limit != '' && is_numeric($limit))
{
$this->bcc_batch_mode = TRUE;
$this->bcc_batch_size = $limit;
}
$bcc = $this->_str_to_array($bcc);
$bcc = $this->clean_email($bcc);
if ($this->validate)
{
$this->validate_email($bcc);
}
if (($this->_get_protocol() == "smtp") OR ($this->bcc_batch_mode && count($bcc) > $this->bcc_batch_size))
{
$this->_bcc_array = $bcc;
}
else
{
$this->_set_header('Bcc', implode(", ", $bcc));
}
return $this;
}
// --------------------------------------------------------------------
Could you please try below that code in your any controller index function and run it.
$this->load->library('email');
$this->email->from('your#example.com', 'Your Name');
$this->email->to('someone#example.com');
$this->email->cc('another#another-example.com');
$this->email->bcc('them#their-example.com');
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
$this->email->send();
echo $this->email->print_debugger();
Simple var $bcc_batch_mode = TRUE;
Edit FALSE to TRUE and give a try!!
Related
i am trying to check email exist or not but its giving correct result while i am checking gmail and on other domain it's giving available for all email
is there any php class which can used for all domain names please suggest me.
<?php
/**
* Validate Email Addresses Via SMTP
* This queries the SMTP server to see if the email address is accepted.
* #copyright http://creativecommons.org/licenses/by/2.0/ - Please keep this comment intact
* #author gabe#fijiwebdesign.com
* #contributers adnan#barakatdesigns.net
* #version 0.1a
*/
class SMTP_validateEmail {
/**
* PHP Socket resource to remote MTA
* #var resource $sock
*/
var $sock;
/**
* Current User being validated
*/
var $user;
/**
* Current domain where user is being validated
*/
var $domain;
/**
* List of domains to validate users on
*/
var $domains;
/**
* SMTP Port
*/
var $port = 25;
/**
* Maximum Connection Time to an MTA
*/
var $max_conn_time = 30;
/**
* Maximum time to read from socket
*/
var $max_read_time = 5;
/**
* username of sender
*/
var $from_user = 'user';
/**
* Host Name of sender
*/
var $from_domain = 'localhost';
/**
* Nameservers to use when make DNS query for MX entries
* #var Array $nameservers
*/
var $nameservers = array(
'192.168.0.1'
);
var $debug = false;
/**
* Initializes the Class
* #return SMTP_validateEmail Instance
* #param $email Array[optional] List of Emails to Validate
* #param $sender String[optional] Email of validator
*/
function SMTP_validateEmail($emails = false, $sender = false) {
if ($emails) {
$this->setEmails($emails);
}
if ($sender) {
$this->setSenderEmail($sender);
}
}
function _parseEmail($email) {
$parts = explode('#', $email);
$domain = array_pop($parts);
$user= implode('#', $parts);
return array($user, $domain);
}
/**
* Set the Emails to validate
* #param $emails Array List of Emails
*/
function setEmails($emails) {
foreach($emails as $email) {
list($user, $domain) = $this->_parseEmail($email);
if (!isset($this->domains[$domain])) {
$this->domains[$domain] = array();
}
$this->domains[$domain][] = $user;
}
}
/**
* Set the Email of the sender/validator
* #param $email String
*/
function setSenderEmail($email) {
$parts = $this->_parseEmail($email);
$this->from_user = $parts[0];
$this->from_domain = $parts[1];
}
/**
* Validate Email Addresses
* #param String $emails Emails to validate (recipient emails)
* #param String $sender Sender's Email
* #return Array Associative List of Emails and their validation results
*/
function validate($emails = false, $sender = false) {
$results = array();
if ($emails) {
$this->setEmails($emails);
}
if ($sender) {
$this->setSenderEmail($sender);
}
// query the MTAs on each Domain
foreach($this->domains as $domain=>$users) {
$mxs = array();
// retrieve SMTP Server via MX query on domain
list($hosts, $mxweights) = $this->queryMX($domain);
// retrieve MX priorities
for($n=0; $n < count($hosts); $n++){
$mxs[$hosts[$n]] = $mxweights[$n];
}
asort($mxs);
// last fallback is the original domain
array_push($mxs, $this->domain);
$this->debug(print_r($mxs, 1));
$timeout = $this->max_conn_time/(count($hosts)>0 ? count($hosts) : 1);
// try each host
while(list($host) = each($mxs)) {
// connect to SMTP server
$this->debug("try $host:$this->port\n");
if ($this->sock = fsockopen($host, $this->port, $errno, $errstr, (float) $timeout)) {
stream_set_timeout($this->sock, $this->max_read_time);
break;
}
}
// did we get a TCP socket
if ($this->sock) {
$reply = fread($this->sock, 2082);
$this->debug("<<<\n$reply");
preg_match('/^([0-9]{3})/ims', $reply, $matches);
$code = isset($matches[1]) ? $matches[1] : '';
if($code != '220') {
// MTA gave an error...
foreach($users as $user) {
$results[$user.'#'.$domain] = false;
}
continue;
}
// say helo
$this->send("HELO ".$this->from_domain);
// tell of sender
$this->send("MAIL FROM: <".$this->from_user.'#'.$this->from_domain.">");
// ask for each recepient on this domain
foreach($users as $user) {
// ask of recepient
$reply = $this->send("RCPT TO: <".$user.'#'.$domain.">");
// get code and msg from response
preg_match('/^([0-9]{3}) /ims', $reply, $matches);
$code = isset($matches[1]) ? $matches[1] : '';
if ($code == '250') {
// you received 250 so the email address was accepted
$results[$user.'#'.$domain] = true;
} elseif ($code == '451' || $code == '452') {
// you received 451 so the email address was greylisted (or some temporary error occured on the MTA) - so assume is ok
$results[$user.'#'.$domain] = true;
} else {
$results[$user.'#'.$domain] = false;
}
}
// quit
$this->send("quit");
// close socket
fclose($this->sock);
}
}
return $results;
}
function send($msg) {
fwrite($this->sock, $msg."\r\n");
$reply = fread($this->sock, 2082);
$this->debug(">>>\n$msg\n");
$this->debug("<<<\n$reply");
return $reply;
}
/**
* Query DNS server for MX entries
* #return
*/
function queryMX($domain) {
$hosts = array();
$mxweights = array();
if (function_exists('getmxrr')) {
getmxrr($domain, $hosts, $mxweights);
} else {
// windows, we need Net_DNS
require_once 'Net/DNS.php';
$resolver = new Net_DNS_Resolver();
$resolver->debug = $this->debug;
// nameservers to query
$resolver->nameservers = $this->nameservers;
$resp = $resolver->query($domain, 'MX');
if ($resp) {
foreach($resp->answer as $answer) {
$hosts[] = $answer->exchange;
$mxweights[] = $answer->preference;
}
}
}
return array($hosts, $mxweights);
}
/**
* Simple function to replicate PHP 5 behaviour. http://php.net/microtime
*/
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function debug($str) {
if ($this->debug) {
echo htmlentities($str);
}
}
}
?>
<?php
require_once("smtpvalidateclass.php");
// the email to validate
$emails = array('infodhcjkdshjkhdksrahul#yahoo.com');
// an optional sender
$sender = 'user#example.com';
// instantiate the class
$SMTP_Valid = new SMTP_validateEmail();
// do the validation
$result = $SMTP_Valid->validate($emails, $sender);
// view results
var_dump($result);
echo ' is '.($result ? 'valid' : 'invalid')."\n";
// send email?
if ($result) {
//mail(...);
}
?>
Can someone help/tell me how to get yclas phpmail to BBC to a mailadres and ad a REPLY TO? its a marketplace script open source.
Thanks for your input, after 3 days i'm getting no results, i'm not a expert.
The phpmail file is:
<?php defined('SYSPATH') or die('No direct script access.');
/**
* Simple email class
*
* #package OC
* #category Core
* #author Chema <chema#open-classifieds.com>, Slobodan <slobodan#open-classifieds.com>
* #copyright (c) 2009-2013 Open Classifieds Team
* #license GPL v3
*/
class Email {
/**
* sends an email using our configs
* #param string/array $to array(array('name'=>'chema','email'=>'chema#'),)
* #param [type] $to_name [description]
* #param [type] $subject [description]
* #param [type] $body [description]
* #param [type] $reply [description]
* #param [type] $replyName [description]
* #param [type] $file [description]
* #return boolean
*/
public static function send($to,$to_name='',$subject,$body,$reply,$replyName,$file = NULL,$content = NULL)
{
$result = FALSE;
//multiple to but theres none...
if (is_array($to) AND count($to)==0)
return FALSE;
$body = Text::nl2br($body);
//get the unsubscribe link
$email_encoded = NULL;
//is sent to a single user get hash to auto unsubscribe
if (!is_array($to) OR count($to)==1)
{
//from newsletter sent
if (isset($to[0]['email']))
$email_encoded = $to[0]['email'];
else
$email_encoded = $to;
//encodig the email for extra security
$encrypt = new Encrypt(Core::config('auth.hash_key'), MCRYPT_MODE_NOFB, MCRYPT_RIJNDAEL_128);
$email_encoded = Base64::fix_to_url($encrypt->encode($email_encoded));
}
$unsubscribe_link = Route::url('oc-panel',array('controller'=>'auth','action'=>'unsubscribe','id'=>$email_encoded));
//get the template from the html email boilerplate
$body_original = $body;
$body = View::factory('email',array('title'=>$subject,'content'=>$body,'unsubscribe_link'=>$unsubscribe_link))->render();
switch (core::config('email.service')) {
case 'elasticemail':
$result = ElasticEmail::send($to,$to_name, $subject, $body, $reply, $replyName);
break;
case 'mailgun':
//todo
break;
case 'pepipost':
//todo
break;
case 'smtp':
case 'mail':
default:
$result = self::phpmailer($to,$to_name,$subject,$body,$reply,$replyName,$file);
break;
}
// notify user (pusher)
if (Core::config('general.pusher_notifications')){
if (is_array($to)){
foreach ($to as $user_email) {
Model_User::pusher($user_email['email'], Text::limit_chars(Text::removebbcode($body), 80, NULL, TRUE),$content);
}
} else
Model_User::pusher($to, Text::limit_chars(Text::removebbcode($body), 80, NULL, TRUE),$content);
}
return $result;
}
/**
* sends an email using content from model_content
* #param string $to
* #param string $to_name
* #param string $from
* #param string $from_name
* #param string $content seotitle from Model_Content
* #param array $replace key value to replace at subject and body
* #param array $file file to attach to email
* #return boolean s
*/
public static function content($to, $to_name='', $from = NULL, $from_name =NULL, $content, $replace, $file=NULL)
{
$email = Model_Content::get_by_title($content,'email');
//content found
if ($email->loaded())
{
if ($replace===NULL)
$replace = array();
if ($from === NULL)
$from = $email->from_email;
if ($from_name === NULL )
$from_name = core::config('general.site_name');
if (isset($file) AND self::is_valid_file($file))
$file_upload = $file;
else
$file_upload = NULL;
//adding extra replaces
$replace+= array('[SITE.NAME]' => core::config('general.site_name'),
'[SITE.URL]' => core::config('general.base_url'),
'[USER.NAME]' => $to_name);
if(!is_array($to))
$replace += array('[USER.EMAIL]'=>$to);
//adding anchor tags to any [URL.* match
foreach ($replace as $key => $value)
{
if(strpos($key, '[URL.')===0 OR $key == '[SITE.URL]' AND $value!='')
$replace[$key] = ''.parse_url($value, PHP_URL_HOST).'';
}
$subject = str_replace(array_keys($replace), array_values($replace), $email->title);
$body = str_replace(array_keys($replace), array_values($replace), $email->description);
return Email::send($to,$to_name,$subject,$body,$from,$from_name, $file_upload,$content);
}
else
return FALSE;
}
/**
* returns true if file is of valid type.
* Its used to check file sent to user from advert usercontact
* #param array file
* #return BOOL
*/
public static function is_valid_file($file)
{
//catch file
$file = $_FILES['file'];
//validate file
if( $file !== NULL)
{
if (
! Upload::valid($file) OR
! Upload::not_empty($file) OR
! Upload::type($file, array('jpg', 'jpeg', 'png', 'pdf','doc','docx')) OR
! Upload::size($file,'3M'))
{
return FALSE;
}
return TRUE;
}
}
/**
* returns an array of administrators and moderators
* #return array
*/
public static function get_notification_emails()
{
$arr = array();
$users = new Model_User();
$users = $users->where('id_role','in',array(Model_Role::ROLE_ADMIN,Model_Role::ROLE_MODERATOR))
->where('status','=',Model_User::STATUS_ACTIVE)
->where('subscriber','=',1)
->cached()->find_all();
foreach ($users as $user)
{
$arr[] = array('name'=>$user->name,'email'=>$user->email);
}
return $arr;
}
/**
* returns the spam score of a raw email using api from postmarkapp
* #param string $raw_email entire RAW email with headers etc....
* #return numeric/false spam score or FALSE is something went wrong....
*/
public static function get_spam_score($raw_email)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://spamcheck.postmarkapp.com/filter');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('email' => $raw_email,'options'=>'short')));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
//something went wrong with the request
if(empty($response) || curl_error($ch) || curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200){
curl_close($ch);
return FALSE;
}
curl_close($ch);
$score = json_decode($response);
if ($score->success == TRUE AND is_numeric($score->score))
return $score->score;
else
return FALSE;
}
public static function phpmailer($to,$to_name='',$subject,$body,$reply,$replyName,$file = NULL)
{
require_once Kohana::find_file('vendor', 'php-mailer/phpmailer','php');
$mail= new PHPMailer();
$mail->CharSet = Kohana::$charset;
if(core::config('email.service') == 'smtp')
{
require_once Kohana::find_file('vendor', 'php-mailer/smtp','php');
$mail->IsSMTP();
$mail->Timeout = 5;
//SMTP HOST config
if (core::config('email.smtp_host')!="")
$mail->Host = core::config('email.smtp_host'); // sets custom SMTP server
//SMTP PORT config
if (core::config('email.smtp_port')!="")
$mail->Port = core::config('email.smtp_port'); // set a custom SMTP port
//SMTP AUTH config
if (core::config('email.smtp_auth') == TRUE)
{
$mail->SMTPAuth = TRUE; // enable SMTP authentication
$mail->Username = core::config('email.smtp_user'); // SMTP username
$mail->Password = core::config('email.smtp_pass'); // SMTP password
}
// sets the prefix to the server
$mail->SMTPSecure = core::config('email.smtp_secure');
}
$mail->From = core::config('email.notify_email');
$mail->FromName = core::config('email.notify_name');
$mail->Subject = $subject;
$mail->MsgHTML($body);
if($file !== NULL)
$mail->AddAttachment($file['tmp_name'],$file['name']);
$mail->AddReplyTo($reply,$replyName);//they answer here
if (is_array($to))
{
foreach ($to as $contact)
$mail->AddBCC($contact['email'],$contact['name']);
}
else
$mail->AddAddress($to,$to_name);
$mail->IsHTML(TRUE); // send as HTML
//to multiple destinataries, check spam score
if (is_array($to))
{
$mail->preSend();
$spam_score = Email::get_spam_score($mail->getSentMIMEMessage());
if ($spam_score >= 5 OR $spam_score === FALSE)
{
Alert::set(Alert::ALERT,"Please review your email. Got a Spam Score of " . $spam_score);
return $spam_score;
}
}
try {
$result = $mail->Send();
} catch (Exception $e) {
$result = FALSE;
$mail->ErrorInfo = $e->getMessage();
}
if(!$result)
{//to see if we return a message or a value bolean
Alert::set(Alert::ALERT,"Mailer Error: " . $mail->ErrorInfo);
return FALSE;
}
else
return TRUE;
}
} //end email
Ok a few weeks ago my script stopped working and today I notice I'm getting an error: [05-Mar-2017 06:31:32 America/Denver] PHP Notice: Undefined index: transfer_encoding in /home2/website/public_html/maps_apps/EasyWebFetch.php on line 105.
Here is what line 105 is:
if ($this->_resp_headers['transfer_encoding'] == 'chunked') {
Can someone point me in the right direction on getting this fixed?
Here is the main code:
<?php
require_once '/home2/website/public_html/maps_apps/EasyWebFetch.php';
$callback = isset($_GET['callback']) ? $_GET['callback'] : 'mymap.weatherhandler';
$station = isset($_GET['rid']) ? $_GET['rid'] : 'FWS';
$product = isset($_GET['product']) ? $_GET['product'] : 'NCR';
$nframes = isset($_GET['frames']) ? $_GET['frames'] : 10;
if (strlen($product) != 3 || strlen($station) != 3) { exit; }
// fetch directory listing
$wf = new EasyWebFetch;
if (!$wf->get("https://radar.weather.gov/ridge/RadarImg/$product/$station/")) {
print $wf->getErrorMessage();
exit;
}
$page = $wf->getContents();
echo $page."\n\n";
$size = preg_match_all( "/href=\"({$station}[\d_]+{$product}\.gif)\"/" , $page, $match);
$files = $match[1];
if ($nframes == 'all') { $nframes = count($files); }
$nframes = min(count($files), $nframes);
$files = array_slice($files, -$nframes);
echo $callback."\n(\n{\ndirectory:\n[\n";
for ($i=0; $i < $nframes; $i++) {
echo "\"ridge/RadarImg/$product/$station/$files[$i]\",\n";
}
echo "]\n}\n)\n;"
?>
and here is EasyWebFetch.php
<?php
/*
* EasyWebFetch - Fetch a page by opening socket connection, no dependencies
*
* PHP version 5
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* #author Nashruddin Amin <me#nashruddin.com>
* #copyright Nashruddin Amin 2008
* #license GNU General Public License 3.0
* #package EasyWebFetch
* #version 1.1
*/
class EasyWebFetch
{
private $_request_url;
private $_host;
private $_path;
private $_query;
private $_fragment;
private $_headers_only;
private $_portnum = 80;
private $_user_agent = "SimpleHttpClient/3.0";
private $_req_timeout = 30;
private $_maxredirs = 5;
private $_use_proxy = false;
private $_proxy_host;
private $_proxy_port;
private $_proxy_user;
private $_proxy_pass;
private $_status;
private $_resp_headers;
private $_resp_body;
private $_is_error;
private $_errmsg;
/**
* class constructor
*/
public function __construct()
{
$this->_resp_headers = array();
$this->_resp_body = "";
}
/**
* get the requested page
*
* #param string $url URL of the requested page
* #param boolean $headers_only true to return headers only,
* false to return headers and body
*
* #return boolean true on success, false on failure
*/
public function get($url = '', $headers_only = false)
{
$this->_request_url = $url;
$this->_headers_only = $headers_only;
$redir = 0;
while(($redir++) <= $this->_maxredirs) {
$this->parseUrl($this->_request_url);
if (($response = $this->makeRequest()) == false) {
return(false);
}
/* split head and body */
$neck = strpos($response, "\r\n\r\n");
$head = substr($response, 0, $neck);
$body = substr($response, $neck+2);
/* read response headers */
$this->_resp_headers = $this->parseHeaders($head);
/* check for redirects */
if ($this->getStatus() == 301 || $this->getStatus() == 302) {
$follow = $this->_resp_headers['location'];
$this->_request_url = $this->setFullPath($follow, $this->_request_url);
continue;
} else {
/* no redirects, start reading response body */
break;
}
}
/* read the body part */
if ($this->_resp_headers['transfer_encoding'] == 'chunked') {
$this->_resp_body = $this->joinChunks($body);
} else {
$this->_resp_body = $body;
}
return(true);
}
/**
* build HTTP header and perform HTTP request
*
* #return mixed HTTP response on success, false on failure
*/
private function makeRequest()
{
$method = ($this->_headers_only == true) ? "HEAD" : "GET";
$proxy_auth = base64_encode("$this->_proxy_user:$this->_proxy_pass");
$response = "";
if ($this->_use_proxy) {
$headers = "$method $this->_request_url HTTP/1.1\r\n"
. "Host: $this->_host\r\n"
. "Proxy-Authorization: Basic $proxy_auth\r\n"
. "User-Agent: $this->_user_agent\r\n"
. "Connection: Close\r\n\r\n";
$fp = fsockopen($this->_proxy_host, $this->_proxy_port, $errno, $errmsg, $this->_req_timeout);
} else {
$headers = "$method $this->_path$this->_query$this->_fragment HTTP/1.1\r\n"
. "Host: $this->_host\r\n"
. "User-Agent: $this->_user_agent\r\n"
. "Connection: Close\r\n\r\n";
$fp = fsockopen($this->_host, $this->_portnum, $errno, $errmsg, $this->_req_timeout);
}
if (!$fp) {
$this->_is_error = true;
$this->_errmsg = "Unknown error";
return(false);
}
fwrite($fp, $headers);
while(!feof($fp)) {
$response .= fgets($fp, 4096);
}
fclose($fp);
return($response);
}
/**
* parse the requested URL to its host, path, query and fragment
*
* #return void
*/
private function parseUrl($url)
{
$this->_host = parse_url($url, PHP_URL_HOST);
$this->_path = parse_url($url, PHP_URL_PATH);
$this->_query = parse_url($url, PHP_URL_QUERY);
$this->_fragment = parse_url($url, PHP_URL_FRAGMENT);
if (empty($this->_path)) {
$this->_path = '/';
}
}
/**
* get the full path of the page to redirect. if the requested page is
* http://www.example.com and it redirects to redirpage.html, then the
* new request is http://www.example.com/redirpage.html
*
* #param string $loc new location from the HTTP response headers
* #param string $parent_url the parent's URL
*
* #return string full path of the page to redirect
*/
private function setFullPath($loc, $parent_url)
{
$parent_url = preg_replace("/\/[^\/]*$/", "", $parent_url);
if (strpos($loc, 'http://') !== false) {
return($loc);
}
if (strpos($loc, '../') === false) {
return("$parent_url/$loc");
}
while (strpos($loc, '../') !== false) {
$loc = preg_replace("/^\.\.\//", "", $loc);
$parent_url = preg_replace("/\/[^\/]+$/", "", $parent_url);
}
return("$parent_url/$loc");
}
/**
* parse HTTP response headers to array
*
* #param string $string HTTP response headers
*
* #return array
*/
private function parseHeaders($string)
{
$string = trim($string);
$headers = array();
$lines = explode("\r\n", $string);
$headers['http_status'] = $lines[0];
/* read HTTP _status in first line */
preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $lines[0], $m);
$this->_status = $m[2];
array_splice($lines, 0, 1); /* remove first line */
foreach ($lines as $line) {
list($key, $val) = explode(': ', $line);
$key = str_replace("-", "_", $key);
$key = strtolower($key);
$val = trim($val);
$headers[$key] = $val;
}
return($headers);
}
/**
* join parts of the HTTP response body with chunked transfer-encoding
*
* #param string $chunks HTTP response body
*
* #return string full body
*/
private function joinChunks($chunks)
{
preg_match("/\r\n([0-9a-z]+)(;?.*)\r\n/", $chunks, $match);
$size = hexdec($match[1]);
$body = "";
while($size > 0) {
/* remove line with chunk size */
$chunks = preg_replace("/\r\n.+\r\n/m", "", $chunks, 1);
$part = substr($chunks, 0, $size);
$chunks = substr($chunks, $size);
$body .= $part;
/* get next chunk size */
preg_match("/\r\n([0-9a-z]+)(;?.*)\r\n/", $chunks, $match);
$size = hexdec($match[1]);
}
return($body);
}
/**
* set the requested URL
*
* #param string $url URL of the requested page
*/
public function setRequestUrl($url)
{
$this->_request_url = $url;
}
/**
* set to return headers only
*
* #param boolean $headers_only true to return headers only,
* false to return headers and body
*/
public function returnHeadersOnly($headers_only)
{
$this->_headers_only = $headers_only;
}
/**
* set proxy host and port
*
* #param string $hostport proxy host and proxy port in format proxy_host:proxy_port
*/
public function setProxyHost($hostport)
{
list($this->_proxy_host, $this->_proxy_port) = explode(':', $hostport);
$this->_use_proxy = true;
}
/**
* set proxy user and password
*
* #param string $userpass proxy user and password in format proxy_user:proxy_password
*/
public function setProxyUser($userpass)
{
list($this->_proxy_user, $this->_proxy_pass) = explode(':', $userpass);
}
/**
* get the HTTP response status (200, 404, etc)
*
* #return string
*/
public function getStatus()
{
return($this->_status);
}
/**
* get the requested URL
*
* #return string
*/
public function getRequestUrl()
{
return($this->_request_url);
}
/**
* set maximum redirects
*
* #param int $maxredirs
*/
public function setMaxRedirs($maxredirs)
{
$this->_maxredirs = $maxredirs;
}
/**
* get HTTP response headers
*
* #return array
*/
public function getHeaders()
{
return($this->_resp_headers);
}
/**
* get the HTTP response body, usually in HTML
*
* #return string
*/
public function getContents()
{
return($this->_resp_body);
echo $this->_resp_body;
}
/**
* get error message
*
* #return string
*/
public function getErrorMessage()
{
return($this->_errmsg);
}
/**
* print debug information
*/
private function debug($text)
{
print "$text\n";
}
}
?>
The array _resp_headers doesn't have any element with key transfer_encoding.
To fix the notice, you should check if the array has the key transfer_encoding:
if (array_key_exists('transfer_encoding', $this->_resp_headers) && $this->_resp_headers['transfer_encoding'] == 'chunked') {
But I can't tell you why the key is not set and why the script has stopped working if you don't show more code.
difficult to answer with such a small sample of code but you can check for the index's existence before
if (isset($this->_resp_headers['transfer_encoding']) &&
$this->_resp_headers['transfer_encoding'] == 'chunked') {
I need to change the code below that belongs to Impresspages CMS to use SMTP instead of sendmail. How can I do this?
<?php
/**
* Queue controls the amount of emails per hour.
* All emails ar placed in queue and send as quiq as possible.
* Parameter "hourlyLimit" defines how much emails can be send in one hour.
* If required amount of emails is bigger than this parameter, part of messages will wait until next hour.
*
* #package ImpressPages
*
*
*/
namespace Ip\Internal\Email;
/**
* Class to send emails. Typically all emails should be send trouht this class.
* #package ImpressPages
*/
class Module
{
/**
* Adds email to the queue
*
* Even if there is a big amount of emails, there is always reserved 20% of traffic for immediate emails.
* Such emails are: registration cofirmation, contact form data and other.
* Newsletters, greetings always can wait a litle. So they are not immediate and will not be send if is less than 20% of traffic left.
*
* #param string $from email address from whish an email should be send
* #param $fromName
* #param string $to email address where an email should be send
* #param $toName
* #param $subject
* #param string $email email html text
* #param bool $immediate indicate hurry of an email.
* #param bool $html true if email message should be send as html
* #param array $files files that should be attached to the email. Files should be accessible for php at this moment. They will be cached until send time.
* #internal param $string #fromName
* #internal param $string #toName
*/
function addEmail($from, $fromName, $to, $toName, $subject, $email, $immediate, $html, $files = null)
{
$cached_files = [];
$cached_fileNames = [];
$cached_fileMimeTypes = [];
if ($files) {
if (is_string($files)) {
$files = array($files);
}
foreach ($files as $fileSetting) {
$file = [];
if (is_array($fileSetting)) {
$file['real_name'] = $fileSetting[0];
$file['required_name'] = basename($fileSetting[1]);
} else {
$file['real_name'] = $fileSetting;
$file['required_name'] = basename($fileSetting);
}
$new_name = 'contact_form_' . rand();
$new_name = \Ip\Internal\File\Functions::genUnoccupiedName($new_name, ipFile('file/tmp/'));
if (copy($file['real_name'], ipFile('file/tmp/' . $new_name))) {
$cached_files[] = ipFile('file/tmp/' . $new_name);
$cached_fileNames[] = $file['required_name'];
$tmpMimeType = \Ip\Internal\File\Functions::getMimeType($file['real_name']);
if ($tmpMimeType == null) {
$tmpMimeType = 'Application/octet-stream';
}
$cached_fileMimeTypes[] = $tmpMimeType;
} else {
trigger_error('File caching failed');
}
}
}
$cachedFilesStr = implode("\n", $cached_files);
$cachedFileNamesStr = implode("\n", $cached_fileNames);
$cachedFileMimeTypesStr = implode("\n", $cached_fileMimeTypes);
$email = str_replace('src="' . ipConfig()->baseUrl(), 'src="', $email);
Db::addEmail(
$from,
$fromName,
$to,
$toName,
$subject,
$email,
$immediate,
$html,
$cachedFilesStr,
$cachedFileNamesStr,
$cachedFileMimeTypesStr
);
}
/**
* Checks if there are some emails waiting in queue and sends them if possible.
*/
function send()
{
$alreadySent = Db::sentOrLockedCount(60);
if ($alreadySent !== false) {
$available = floor(ipGetOption('Email.hourlyLimit') * 0.8 - $alreadySent); //20% for immediate emails
$lockKey = md5(uniqid(rand(), true));
if ($available > 0) {
if ($available > 5 && !defined('CRON')) { //only cron job can send many emails at once.
$available = 5;
}
$locked = Db::lock($available, $lockKey);
} else {
$available = 0;
$locked = 0;
}
if ($locked == $available) { //if in queue left some messages
if (ipGetOption('Email.hourlyLimit') - ($alreadySent + $available) > 0) {
$locked = $locked + Db::lockOnlyImmediate(
ipGetOption('Email.hourlyLimit') - ($alreadySent + $available),
$lockKey
);
}
}
if ($locked) {
$emails = Db::getLocked($lockKey);
foreach ($emails as $key => $email) {
if (function_exists('set_time_limit')) {
set_time_limit((sizeof($emails) - $key) * 10 + 100);
}
$mail = new \PHPMailer();
/* $mail->Sender = $email['from'];
$mail->addCustomHeader("Return-Path: " . $email['from']);*/
$mail->From = $email['from'];
$mail->FromName = $email['fromName'];
$mail->AddReplyTo($email['from'], $email['fromName']);
$mail->WordWrap = 50; // set word wrap
$mail->CharSet = ipConfig()->get('charset');
$mail->Subject = $email['subject'];
/* foreach($this->posted_files as $file){
if(isset($_FILES[$file]['tmp_name']) && $_FILES[$file]['error'] == 0){
$mail->AddAttachment($_FILES[$file]['tmp_name'], $_FILES[$file]['name']);
}
}*/
$files = explode("\n", $email['files']);
$fileNames = explode("\n", $email['fileNames']);
$fileMimeTypes = explode("\n", $email['fileMimeTypes']);
$fileCount = min(count($files), count($fileNames), count($fileMimeTypes));
for ($i = 0; $i < $fileCount; $i++) {
if ($files[$i] != '') {
if ($fileMimeTypes[$i] == '') {
$answer = $mail->AddAttachment($files[$i], $fileNames[$i]);
} else {
$answer = $mail->AddAttachment(
$files[$i],
$fileNames[$i],
"base64",
$fileMimeTypes[$i]
);
}
if (!$answer) {
ipLog()->error(
'Email.addAttachmentFailed: {subject} to {to}',
array(
'to' => $email['to'],
'subject' => $email['subject'],
'filename' => $fileNames[$i],
)
);
return false;
}
}
}
if ($email['html']) {
$mail->IsHTML(true); // send as HTML
$mail->MsgHTML($email['email']);
try {
$altBody = \Ip\Internal\Text\Html2Text::convert($email['email']);
} catch (\Ip\Internal\Text\Html2TextException $e) {
$altBody = $email['email'];
}
$mail->AltBody = $altBody;
} else {
/*$h2t = new \Ip\Internal\Text\Html2Text($content, false);
$mail->Body = $h2t->get_text();*/
$mail->Body = $email['email'];
}
$mail->AddAddress($email['to'], $email['toName']);
$mail = ipFilter('ipSendEmailPHPMailerObject', $mail, $email);
if (!$mail->Send()) {
ipLog()->error(
'Email.sendFailed: {subject} to {to}',
array('to' => $email['to'], 'subject' => $email['subject'], 'body' => $email['email'])
);
return false;
}
if (sizeof($emails) > 5) {
sleep(1);
}
Db::unlockOne($email['id']);
}
}
}
return null;
}
}
A default error logging using vqmod is as follows:
---------- Date: 2012-10-09 19:46:06 ~ IP : 127.0.0.1 ----------
REQUEST URI : /oc/
MOD DETAILS:
modFile : C:\wamp\www\oc\vqmod\xml\templace.xml
id : Template
version : 1.5.2 - 1.5.2.1
vqmver : 1.0.8
author : templace.com
SEARCH NOT FOUND (ABORTING MOD): require_once(foo . 'library/template.php');
----------------------------------------------------------------------
Example vqmod causing the error
<modification>
<id>Templace</id>
<version>1.5.2 - 1.5.2.1</version>
<author>templace.com</author>
<vqmver>1.0.8</vqmver>
<file name="system/startup.php">
<operation>
<search position="before"><![CDATA[
require_once(foo . 'library/template.php');
]]></search>
<add><![CDATA[
require_once(DIR_SYSTEM . 'library/templace.php');
]]></add>
</operation>
</file>
</modification>
To resole this issue I would have to open the vqmod file templace.xml and search for the file[name] this error is referring too.
QUESTION: How could I add the parent file[name] the actual error is referring too?
E.g adding: "system/startup.php" to the error message to make it easier to debug.
vqmod.php
/**
* VQMod
* #description Main Object used
*/
final class VQMod {
private $_vqversion = '2.1.7';
private $_modFileList = array();
private $_mods = array();
private $_filesModded = array();
private $_cwd = '';
private $_doNotMod = array();
private $_virtualMode = true;
public $useCache = false;
public $logFilePath = 'vqmod/vqmod.log';
public $vqCachePath = 'vqmod/vqcache/';
public $protectedFilelist = 'vqmod/vqprotect.txt';
public $logging = true;
public $cacheTime = 5; // local=5secs live=60secs
public $log;
/**
* VQMod::__construct()
*
* #param bool $path File path to use
* #param bool $logging Enable/disabled logging
* #return null
* #description Startup of VQMod
*/
public function __construct($path = false, $logging = true) {
if(!class_exists('DOMDocument')) {
die('ERROR - YOU NEED DOMDocument INSTALLED TO USE VQMod');
}
if(!$path){
$path = dirname(dirname(__FILE__));
}
$this->_setCwd($path);
$this->logging = (bool) $logging;
$this->log = new VQModLog($this);
$this->_getMods();
$this->_loadProtected();
}
/**
* VQMod::modCheck()
*
* #param string $sourceFile path for file
* #return string
* #description Checks if a file has modifications and applies them, returning cache files or the file name
*/
public function modCheck($sourceFile) {
if(!preg_match('%^([a-z]:)?[\\\\/]%i', $sourceFile)) {
$sourcePath = $this->path($sourceFile);
} else {
$sourcePath = realpath($sourceFile);
}
if(!$sourcePath || is_dir($sourcePath) || in_array($sourcePath, $this->_doNotMod)) {
return $sourceFile;
}
$stripped_filename = preg_replace('~^' . preg_quote($this->getCwd(), '~') . '~', '', $sourcePath);
$cacheFile = $this->_cacheName($stripped_filename);
if($this->useCache && file_exists($cacheFile)) {
//return $cacheFile; // useCache being Deprecated in favor of cacheTime
}
if(isset($this->_filesModded[$sourcePath])) {
return $this->_filesModded[$sourcePath]['cached'] ? $cacheFile : $sourceFile;
}
$changed = false;
$fileHash = sha1_file($sourcePath);
$fileData = file_get_contents($sourcePath);
foreach($this->_mods as $modObject) {
foreach($modObject->mods as $path => $mods) {
if($this->_checkMatch($path, $sourcePath)) {
$modObject->applyMod($mods, $fileData);
}
}
}
// START QPHORIA CACHELOCK CODE
//
if (sha1($fileData) != $fileHash) {
$writePath = $cacheFile;
$cacheLock = false;
if(file_exists($writePath) && ((filemtime($writePath) + (float)$this->cacheTime) >= time())) {
$cacheLock = true;
$changed = true;
}
if(!$cacheLock && (!file_exists($writePath) || is_writable($writePath))) {
file_put_contents($writePath, $fileData);
$changed = true;
} else {
//file_put_contents('./cachelock.txt', "$writePath \r\n", FILE_APPEND); // debugging only.
}
//file_put_contents('./cachetotal.txt', "$writePath \r\n", FILE_APPEND);
} // END QPHORIA CACHELOCK CODE
/* Original Code
if(sha1($fileData) != $fileHash) {
$writePath = $this->_virtualMode ? $cacheFile : $sourcePath;
if(!file_exists($writePath) || is_writable($writePath)) {
file_put_contents($writePath, $fileData);
$changed = true;
}
}*/
$this->_filesModded[$sourcePath] = array('cached' => $changed);
return $changed ? $writePath : $sourcePath;
}
/**
* VQMod::path()
*
* #param string $path File path
* #param bool $skip_real If true path is full not relative
* #return bool, string
* #description Returns the full true path of a file if it exists, otherwise false
*/
public function path($path, $skip_real = false) {
$tmp = $this->_cwd . $path;
$realpath = $skip_real ? $tmp : realpath($tmp);
if(!$realpath) {
return false;
}
if(is_dir($realpath)) {
$realpath = rtrim($realpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
return $realpath;
}
/**
* VQMod::getCwd()
*
* #return string
* #description Returns current working directory
*/
public function getCwd() {
return $this->_cwd;
}
/**
* VQMod::_getMods()
*
* #return null
* #description Gets list of XML files in vqmod xml folder for processing
*/
private function _getMods() {
$this->_modFileList = glob($this->path('vqmod/xml/') . '*.xml');
if($this->_modFileList) {
$this->_parseMods();
} else {
$this->log->write('NO MODS IN USE');
}
}
/**
* VQMod::_parseMods()
*
* #return null
* #description Loops through xml files and attempts to load them as VQModObject's
*/
private function _parseMods() {
$dom = new DOMDocument('1.0', 'UTF-8');
foreach($this->_modFileList as $modFileKey => $modFile) {
if(file_exists($modFile)) {
if(#$dom->load($modFile)) {
$mod = $dom->getElementsByTagName('modification')->item(0);
$this->_mods[] = new VQModObject($mod, $modFile, $this);
} else {
$this->log->write('DOM UNABLE TO LOAD: ' . $modFile);
}
} else {
$this->log->write('FILE NOT FOUND: ' . $modFile);
}
}
}
/**
* VQMod::_loadProtected()
*
* #return null
* #description Loads protected list and adds them to _doNotMod array
*/
private function _loadProtected() {
$file = $this->path($this->protectedFilelist);
if($file && is_file($file)) {
$protected = file_get_contents($file);
if(!empty($protected)) {
$protected = preg_replace('~\r?\n~', "\n", $protected);
$paths = explode("\n", $protected);
foreach($paths as $path) {
$fullPath = $this->path($path);
if($fullPath && !in_array($fullPath, $this->_doNotMod)) {
$this->_doNotMod[] = $fullPath;
}
}
}
}
}
/**
* VQMod::_cacheName()
*
* #param string $file Filename to be converted to cache filename
* #return string
* #description Returns cache file name for a path
*/
private function _cacheName($file) {
return $this->path($this->vqCachePath) . 'vq2-' . preg_replace('~[/\\\\]+~', '_', $file);
}
/**
* VQMod::_setCwd()
*
* #param string $path Path to be used as current working directory
* #return null
* #description Sets the current working directory variable
*/
private function _setCwd($path) {
$realpath = realpath($path);
if(!$realpath) {
die('COULDNT RESOLVE CWD REALPATH');
}
$this->_cwd = rtrim($realpath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
/**
* VQMod::_checkMatch()
*
* #param string $modFilePath Modification path from a <file> node
* #param string $checkFilePath File path
* #return bool
* #description Checks a modification path against a file path
*/
private function _checkMatch($modFilePath, $checkFilePath) {
$modFilePath = str_replace('\\', '/', $modFilePath);
$checkFilePath = str_replace('\\', '/', $checkFilePath);
$modFilePath = preg_replace('/([^*]+)/e', 'preg_quote("$1", "~")', $modFilePath);
$modFilePath = str_replace('*', '[^/]*', $modFilePath);
$return = (bool) preg_match('~^' . $modFilePath . '$~', $checkFilePath);
return $return;
}
}
/**
* VQModLog
* #description Object to log information to a file
*/
class VQModLog {
private $_sep;
private $_vqmod;
private $_defhash = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';
private $_logs = array();
/**
* VQModLog::__construct()
*
* #param VQMod $vqmod VQMod main class as reference
* #return null
* #description Object instantiation method
*/
public function __construct(VQMod $vqmod) {
$this->_vqmod = $vqmod;
$this->_sep = str_repeat('-', 70);
}
/**
* VQModLog::__destruct()
*
* #return null
* #description Logs any messages to the log file just before object is destroyed
*/
public function __destruct() {
if(empty($this->_logs) || $this->_vqmod->logging == false) {
return;
}
$txt = array();
$txt[] = str_repeat('-', 10) . ' Date: ' . date('Y-m-d H:i:s') . ' ~ IP : ' . (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'N/A') . ' ' . str_repeat('-', 10);
$txt[] = 'REQUEST URI : ' . $_SERVER['REQUEST_URI'];
foreach($this->_logs as $count => $log) {
if($log['obj']) {
$vars = get_object_vars($log['obj']);
$txt[] = 'MOD DETAILS:';
foreach($vars as $k => $v) {
if(is_string($v)) {
$txt[] = ' ' . str_pad($k, 10, ' ', STR_PAD_RIGHT) . ': ' . $v;
}
}
}
foreach($log['log'] as $msg) {
$txt[] = $msg;
}
if ($count > count($this->_logs)-1) {
$txt[] = '';
}
}
$txt[] = $this->_sep;
$txt[] = str_repeat(PHP_EOL, 2);
$logPath = $this->_vqmod->path($this->_vqmod->logFilePath, true);
if(!file_exists($logPath)) {
$res = file_put_contents($logPath, '');
if($res === false) {
die('COULD NOT WRITE TO LOG FILE');
}
}
file_put_contents($logPath, implode(PHP_EOL, $txt), FILE_APPEND);
}
/**
* VQModLog::write()
*
* #param string $data Text to be added to log file
* #param VQModObject $obj Modification the error belongs to
* #return null
* #description Adds error to log object ready to be output
*/
public function write($data, VQModObject $obj = NULL) {
if($obj) {
$hash = sha1($obj->id);
} else {
$hash = $this->_defhash;
}
if(empty($this->_logs[$hash])) {
$this->_logs[$hash] = array(
'obj' => $obj,
'log' => array()
);
}
$this->_logs[$hash]['log'][] = $data;
}
}
/**
* VQModObject
* #description Object for the <modification> that orchestrates each applied modification
*/
class VQModObject {
public $modFile = '';
public $id = '';
public $version = '';
public $vqmver = '';
public $author = '';
public $mods = array();
private $_vqmod;
private $_skip = false;
/**
* VQModObject::__construct()
*
* #param DOMNode $node <modification> node
* #param string $modFile File modification is from
* #param VQMod $vqmod VQMod object as reference
* #return null
* #description Loads modification meta information
*/
public function __construct(DOMNode $node, $modFile, VQmod $vqmod) {
if($node->hasChildNodes()) {
foreach($node->childNodes as $child) {
$name = (string) $child->nodeName;
if(isset($this->$name)) {
$this->$name = (string) $child->nodeValue;
}
}
}
$this->modFile = $modFile;
$this->_vqmod = $vqmod;
$this->_parseMods($node);
}
/**
* VQModObject::skip()
*
* #return bool
* #description Returns the skip status of a modification
*/
public function skip() {
return $this->_skip;
}
/**
* VQModObject::applyMod()
*
* #param array $mods Array of search add nodes
* #param string $data File contents to be altered
* #return null
* #description Applies all modifications to the text data
*/
public function applyMod($mods, &$data) {
if($this->_skip) return;
$tmp = $data;
foreach($mods as $mod) {
$indexCount = 0;
$tmp = $this->_explodeData($tmp);
$lineMax = count($tmp) - 1;
switch($mod['search']->position) {
case 'top':
$tmp[$mod['search']->offset] = $mod['add']->getContent() . $tmp[$mod['search']->offset];
break;
case 'bottom':
$offset = $lineMax - $mod['search']->offset;
if($offset < 0){
$tmp[-1] = $mod['add']->getContent();
} else {
$tmp[$offset] .= $mod['add']->getContent();
}
break;
case 'all':
$tmp = array($mod['add']->getContent());
break;
default:
$changed = false;
foreach($tmp as $lineNum => $line) {
if($mod['search']->regex == 'true') {
$pos = #preg_match($mod['search']->getContent(), $line);
if($pos === false) {
if($mod['error'] == 'log' || $mod['error'] == 'abort' ) {
$this->_vqmod->log->write('INVALID REGEX ERROR - ' . $mod['search']->getContent(), $this);
}
continue 2;
} elseif($pos == 0) {
$pos = false;
}
} else {
$pos = strpos($line, $mod['search']->getContent());
}
if($pos !== false) {
$indexCount++;
$changed = true;
if(!$mod['search']->indexes() || ($mod['search']->indexes() && in_array($indexCount, $mod['search']->indexes()))) {
switch($mod['search']->position) {
case 'before':
$offset = ($lineNum - $mod['search']->offset < 0) ? -1 : $lineNum - $mod['search']->offset;
$tmp[$offset] = empty($tmp[$offset]) ? $mod['add']->getContent() : $mod['add']->getContent() . "\n" . $tmp[$offset];
break;
case 'after':
$offset = ($lineNum + $mod['search']->offset > $lineMax) ? $lineMax : $lineNum + $mod['search']->offset;
$tmp[$offset] = $tmp[$offset] . "\n" . $mod['add']->getContent();
break;
default:
if(!empty($mod['search']->offset)) {
for($i = 1; $i <= $mod['search']->offset; $i++) {
if(isset($tmp[$lineNum + $i])) {
$tmp[$lineNum + $i] = '';
}
}
}
if($mod['search']->regex == 'true') {
$tmp[$lineNum] = preg_replace($mod['search']->getContent(), $mod['add']->getContent(), $line);
} else {
$tmp[$lineNum] = str_replace($mod['search']->getContent(), $mod['add']->getContent(), $line);
}
break;
}
}
}
}
if(!$changed) {
$skip = ($mod['error'] == 'skip' || $mod['error'] == 'log') ? ' (SKIPPED)' : ' (ABORTING MOD)';
if($mod['error'] == 'log' || $mod['error'] == 'abort') {
$this->_vqmod->log->write('SEARCH NOT FOUND' . $skip . ': ' . $mod['search']->getContent(), $this);
}
if($mod['error'] == 'abort') {
$this->_skip = true;
return;
}
}
break;
}
ksort($tmp);
$tmp = $this->_implodeData($tmp);
}
$data = $tmp;
}
/**
* VQModObject::_parseMods()
*
* #param DOMNode $node <modification> node to be parsed
* #return null
* #description Parses modifications in preparation for the applyMod method to work
*/
private function _parseMods(DOMNode $node){
$files = $node->getElementsByTagName('file');
foreach($files as $file) {
$fileToMod = $file->getAttribute('name');
$error = ($file->hasAttribute('error')) ? $file->getAttribute('error') : 'log';
$fullPath = $this->_vqmod->path($fileToMod);
if(!$fullPath){
if(strpos($fileToMod, '*') !== false) {
$fullPath = $this->_vqmod->getCwd() . $fileToMod;
} else {
if ($error == 'log' || $error == 'abort') {
$skip = ($error == 'log') ? ' (SKIPPED)' : ' (ABORTING MOD)';
$this->_vqmod->log->write('Could not resolve path for [' . $fileToMod . ']' . $skip, $this);
}
if ($error == 'log' || $error == 'skip') {
continue;
} elseif ($error == 'abort') {
return false;
}
}
}
$operations = $file->getElementsByTagName('operation');
foreach($operations as $operation) {
$error = ($operation->hasAttribute('error')) ? $operation->getAttribute('error') : 'abort';
$this->mods[$fullPath][] = array(
'search' => new VQSearchNode($operation->getElementsByTagName('search')->item(0)),
'add' => new VQAddNode($operation->getElementsByTagName('add')->item(0)),
'error' => $error
);
}
}
}
/**
* VQModObject::_explodeData()
*
* #param string $data File contents
* #return string
* #description Splits a file into an array of individual lines
*/
private function _explodeData($data) {
return explode("\n", $data);
}
/**
* VQModObject::_implodeData()
*
* #param array $data Array of lines
* #return string
* #description Joins an array of lines back into a text file
*/
private function _implodeData($data) {
return implode("\n", $data);
}
}
/**
* VQNode
* #description Basic node object blueprint
*/
class VQNode {
public $trim = 'false';
private $_content = '';
/**
* VQNode::__construct()
*
* #param DOMNode $node Search/add node
* #return null
* #description Parses the node attributes and sets the node property
*/
public function __construct(DOMNode $node) {
$this->_content = $node->nodeValue;
if($node->hasAttributes()) {
foreach($node->attributes as $attr) {
$name = $attr->nodeName;
if(isset($this->$name)) {
$this->$name = $attr->nodeValue;
}
}
}
}
/**
* VQNode::getContent()
*
* #return string
* #description Returns the content, trimmed if applicable
*/
public function getContent() {
$content = ($this->trim == 'true') ? trim($this->_content) : $this->_content;
return $content;
}
}
/**
* VQSearchNode
* #description Object for the <search> xml tags
*/
class VQSearchNode extends VQNode {
public $position = 'replace';
public $offset = 0;
public $index = 'false';
public $regex = 'false';
public $trim = 'true';
/**
* VQSearchNode::indexes()
*
* #return bool, array
* #description Returns the index values to use the search on, or false if none
*/
public function indexes() {
if($this->index == 'false') {
return false;
}
$tmp = explode(',', $this->index);
foreach($tmp as $k => $v) {
if(!is_int($v)) {
unset($k);
}
}
$tmp = array_unique($tmp);
return empty($tmp) ? false : $tmp;
}
}
/**
* VQAddNode
* #description Object for the <add> xml tags
*/
class VQAddNode extends VQNode {
}
Also couple of other ideas to make debugging even easier:
List any other vqmod files which have previously edited this same file.
This is another common issue where I find when two extensions are editing the same file and the latter is causing the error but it would be useful to know about any other vqmods editing the same file. Yes I suppose I could add error="skip" to everything but dont think this is the best approach to just hide all of the errors, the user should be made aware there is an error...
"Suggested Fix", maybe some smart way you can test what type of error it is.
Contradict what I said above but even at its most basic form you could suggest hiding the error if its not essential. So that anybody can read it and understand how it fix it.
E.g
OPEN: vqmod/xml/templace.xml (line:23)
FIND: <operation>
REPLACE <operation error="skip">
Adding the line number in the XML file the error is coming from. It would be lovely not having to search all of the time and could quickly go to the line number in the vqmod
The issue for the file being edited is certainly one that is way overdue and one I plan on adding in the next release of vQmod. As for the other suggestions
Interesting idea, and one that could certainly be considered. The only problem I see with this is that it would possibly make some log files enormous
This is going to be next to impossible to incorporate
This is impossible without some pretty expensive runtime. The error doesn't lie in the XML as such, so would require re-opening the xml that's been parsed, searching for the line in question line by line and then reporting that. it sounds simple, but you have to remember that xml's can have the same search parameter for multiple operations - so in that situation you'd be no better off than searching the file yourself