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
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(...);
}
?>
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!!
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;
}
}
I am working on a codeigniter project which requires push notificatios to be sent to ios devices.
While importing th eapn library i just can't figure out where to put the .pem file which i exported from ios app project.
and also I can't figure out how to reference it's path.
Here is Pushnotification.php Library
<?php
class APN
{
protected $server;
protected $keyCertFilePath;
protected $passphrase;
protected $pushStream;
protected $feedbackStream;
protected $timeout;
protected $idCounter = 0;
protected $expiry;
protected $allowReconnect = true;
protected $additionalData = array();
protected $apnResonses = array(
0 => 'No errors encountered',
1 => 'Processing error',
2 => 'Missing device token',
3 => 'Missing topic',
4 => 'Missing payload',
5 => 'Invalid token size',
6 => 'Invalid topic size',
7 => 'Invalid payload size',
8 => 'Invalid token',
255 => 'None (unknown)',
);
private $connection_start;
public $error;
public $payloadMethod = 'simple';
/**
* Connects to the server with the certificate and passphrase
*
* #return <void>
*/
protected function connect($server) {
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $this->null);
stream_context_set_option($ctx, 'ssl', 'passphrase', $this->null);
$stream = stream_socket_client($server, $err, $errstr, $this->timeout, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
log_message('debug',"APN: Maybe some errors: $err: $errstr");
if (!$stream) {
if ($err)
show_error("APN Failed to connect: $err $errstr");
else
show_error("APN Failed to connect: Something wrong with context");
return false;
}
else {
stream_set_timeout($stream,20);
log_message('debug',"APN: Opening connection to: {$server}");
return $stream;
}
}
/**
* Generates the payload
*
* #param <string> $message
* #param <int> $badge
* #param <string> $sound
* #return <string>
*/
protected function generatePayload($message, $badge = NULL, $sound = NULL, $newstand = false) {
$body = array();
// additional data
if (is_array($this->additionalData) && count($this->additionalData))
{
$body = $this->additionalData;
}
//message
$body['aps'] = array('alert' => $message);
//badge
if ($badge)
$body['aps']['badge'] = $badge;
if ($badge == 'clear')
$body['aps']['badge'] = 0;
//sound
if ($sound)
$body['aps']['sound'] = $sound;
//newstand content-available
if($newstand)
$body['aps']['content-available'] = 1;
$payload = json_encode($body);
log_message('debug',"APN: generatePayload '$payload'");
return $payload;
}
/**
* Writes the contents of payload to the file stream
*
* #param <string> $deviceToken
* #param <string> $payload
*/
protected function sendPayloadSimple($deviceToken, $payload){
$this->idCounter++;
log_message('debug',"APN: sendPayloadSimple to '$deviceToken'");
$msg = chr(0) // command
. pack('n',32) // token length
. pack('H*', $deviceToken) // device token
. pack('n',strlen($payload)) // payload length
. $payload; // payload
log_message('debug',"APN: payload: '$msg'");
log_message('debug',"APN: payload length: '".strlen($msg)."'");
$result = fwrite($this->pushStream, $msg, strlen($msg));
if ($result)
return true;
else
return false;
}
/**
* Writes the contents of payload to the file stream with enhanced api (expiry, debug)
*
* #param <string> $deviceToken
* #param <string> $payload
*/
protected function sendPayloadEnhance($deviceToken, $payload, $expiry = 86400) {
if (!is_resource($this->pushStream))
$this->reconnectPush();
$this->idCounter++;
log_message('debug',"APN: sendPayloadEnhance to '$deviceToken'");
$payload_length = strlen($payload);
$request = chr(1) // command
. pack("N", time()) // identifier
. pack("N", time() + $expiry) // expiry
. pack('n', 32) // token length
. pack('H*', $deviceToken) // device token
. pack('n', $payload_length) // payload length
. $payload;
$request_unpacked = #unpack('Ccommand/Nidentifier/Nexpiry/ntoken_length/H64device_token/npayload_length/A*payload', $request); // payload
log_message('debug', "APN: request: '$request'");
log_message('debug', "APN: unpacked request: '" . print_r($request_unpacked, true) . "'");
log_message('debug', "APN: payload length: '" . $payload_length . "'");
$result = fwrite($this->pushStream, $request, strlen($request));
if ($result)
{
return $this->getPayloadStatuses();
}
return false;
}
protected function timeoutSoon($left_seconds = 5)
{
$t = ( (round(microtime(true) - $this->connection_start) >= ($this->timeout - $left_seconds)));
return (bool)$t;
}
* Connects to the APNS server with a certificate and a passphrase
*
* #param <string> $server
* #param <string> $keyCertFilePath
* #param <string> $passphrase
*/
function __construct() {
$this->_ci = get_instance();
$this->_ci->config->load('apn',true);
if(!file_exists($this->_ci->config->item('PermissionFile','apn')))
{
show_error("APN Failed to connect: APN Permission file not found");
}
$this->pushServer = $this->_ci->config->item('Sandbox','apn') ? $this->_ci->config->item('PushGatewaySandbox','apn') : $this->_ci->config->item('PushGateway','apn');
$this->feedbackServer = $this->_ci->config->item('Sandbox','apn') ? $this->_ci->config->item('FeedbackGatewaySandbox','apn') : $this->_ci->config->item('FeedbackGateway','apn');
$this->keyCertFilePath = $this->_ci->config->item('PermissionFile','apn');
$this->passphrase = $this->_ci->config->item('PassPhrase','apn');
$this->timeout = $this->_ci->config->item('Timeout','apn') ? $this->_ci->config->item('Timeout','apn') : 60;
$this->expiry = $this->_ci->config->item('Expiry','apn') ? $this->_ci->config->item('Expiry','apn') : 86400;
}
/**
* Public connector to push service
*/
public function connectToPush()
{
if (!$this->pushStream or !is_resource($this->pushStream))
{
log_message('debug',"APN: connectToPush");
$this->pushStream = $this->connect($this->pushServer);
if ($this->pushStream)
{
$this->connection_start = microtime(true);
//stream_set_blocking($this->pushStream,0);
}
}
return $this->pushStream;
}
/**
* Public connector to feedback service
*/
public function connectToFeedback()
{
log_message('info',"APN: connectToFeedback");
return $this->feedbackStream = $this->connect($this->feedbackServer);
}
/**
* Public diconnector to push service
*/
function disconnectPush()
{
log_message('debug',"APN: disconnectPush");
if ($this->pushStream && is_resource($this->pushStream))
{
$this->connection_start = 0;
return #fclose($this->pushStream);
}
else
return true;
}
/**
* Public disconnector to feedback service
*/
function disconnectFeedback()
{
log_message('info',"APN: disconnectFeedback");
if ($this->feedbackStream && is_resource($this->feedbackStream))
return #fclose($this->feedbackStream);
else
return true;
}
function reconnectPush()
{
$this->disconnectPush();
if ($this->connectToPush())
{
log_message('debug',"APN: reconnect");
return true;
}
else
{
log_message('debug',"APN: cannot reconnect");
return false;
}
}
function tryReconnectPush()
{
if ($this->allowReconnect)
{
if($this->timeoutSoon())
{
return $this->reconnectPush();
}
}
return false;
}
/**
* Sends a message to device
*
* #param <string> $deviceToken
* #param <string> $message
* #param <int> $badge
* #param <string> $sound
*/
public function sendMessage($deviceToken, $message, $badge = NULL, $sound = NULL, $expiry = '', $newstand = false)
{
$this->error = '';
if (!ctype_xdigit($deviceToken))
{
log_message('debug',"APN: Error - '$deviceToken' token is invalid. Provided device token contains not hexadecimal chars");
$this->error = 'Invalid device token. Provided device token contains not hexadecimal chars';
return false;
}
// restart the connection
$this->tryReconnectPush();
log_message('info',"APN: sendMessage '$message' to $deviceToken");
//generate the payload
$payload = $this->generatePayload($message, $badge, $sound, $newstand);
$deviceToken = str_replace(' ', '', $deviceToken);
//send payload to the device.
if ($this->payloadMethod == 'simple')
$this->sendPayloadSimple($deviceToken, $payload);
else
{
if (!$expiry)
$expiry = $this->expiry;
return $this->sendPayloadEnhance($deviceToken, $payload, $expiry);
}
}
/**
* Writes the contents of payload to the file stream
*
* #param <string> $deviceToken
* #param <string> $payload
* #return <bool>
*/
function getPayloadStatuses()
{
$read = array($this->pushStream);
$null = null;
$changedStreams = stream_select($read, $null, $null, 0, 2000000);
if ($changedStreams === false)
{
log_message('error',"APN Error: Unabled to wait for a stream availability");
}
elseif ($changedStreams > 0)
{
$responseBinary = fread($this->pushStream, 6);
if ($responseBinary !== false || strlen($responseBinary) == 6) {
if (!$responseBinary)
return true;
$response = #unpack('Ccommand/Cstatus_code/Nidentifier', $responseBinary);
log_message('debug','APN: debugPayload response - '.print_r($response,true));
if ($response && $response['status_code'] > 0)
{
log_message('error','APN: debugPayload response - status_code:'.$response['status_code'].' => '.$this->apnResonses[$response['status_code']]);
$this->error = $this->apnResonses[$response['status_code']];
return false;
}
else
{
if (isset($response['status_code']))
log_message('debug','APN: debugPayload response - '.print_r($response['status_code'],true));
}
}
else
{
log_message('debug',"APN: responseBinary = $responseBinary");
return false;
}
}
else
log_message('debug',"APN: No streams to change, $changedStreams");
return true;
}
/**
* Gets an array of feedback tokens
*
* #return <array>
*/
public function getFeedbackTokens() {
log_message('debug',"APN: getFeedbackTokens {$this->feedbackStream}");
$this->connectToFeedback();
$feedback_tokens = array();
//and read the data on the connection:
while(!feof($this->feedbackStream)) {
$data = fread($this->feedbackStream, 38);
if(strlen($data)) {
//echo $data;
$feedback_tokens[] = unpack("N1timestamp/n1length/H*devtoken", $data);
}
}
$this->disconnectFeedback();
return $feedback_tokens;
}
/**
* Sets additional data which will be send with main apn message
*
* #param <array> $data
* #return <array>
*/
public function setData($data)
{
if (!is_array($data))
{
log_message('error',"APN: cannot add additional data - not an array");
return false;
}
if (isset($data['apn']))
{
log_message('error',"APN: cannot add additional data - key 'apn' is reserved");
return false;
}
return $this->additionalData = $data;
}
/**
* Closes the stream
*/
function __destruct(){
$this->disconnectPush();
$this->disconnectFeedback();
}
}//end of class
You can put this key file(.pem) anywhere in the project. But the best way to put this file inside /library folder, create one new folder says keys
Now in your library file you have to add real path.
function __construct() {
$this->keyCertFilePath = APPPATH.'library/keys/'.$this->_ci->config->item('PermissionFile','apn');
This is the best way, Let me know if it not works.
create a config file in application/config folder
say, 'ios.php'
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/* Development */
$config['host'] = 'gateway.sandbox.push.apple.com';
$config['port'] = '2195';
$config['cert'] = 'complete_path/application/libraries/cert.pem';
$config['passphrase'] = 'private_key_password';
In libraries folder, application/libraries, place your pem file and in your Pushnotification.php file,
public function __construct() {
$ci = & get_instance();
$ci->load->config('ios', true);
$this->cert = $ci->config->item('cert', 'ios');
$this->host = $ci->config->item('host', 'ios');
$this->port = $ci->config->item('port', 'ios');
$this->passphrase = $ci->config->item('passphrase', 'ios');
}
Hope this will help
I am trying to use the code from #eyecatchup (https://github.com/eyecatchup/php-webmaster-tools-downloads) to get data via the Google Webmaster Tools API. I am able to get "TOP_PAGES" and "TOP QUERIES" but that is it. What I really want is "EXTERNAL_LINKS" or even "LATEST_LINKS".
Here is the gwtdata.php code:
<pre>
<?php
/**
* PHP class for downloading CSV files from Google Webmaster Tools.
*
* This class does NOT require the Zend gdata package be installed
* in order to run.
*
* Copyright 2012 eyecatchUp UG. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* #author: Stephan Schmitz <eyecatchup#gmail.com>
* #link: https://code.google.com/p/php-webmaster-tools-downloads/
*/
class GWTdata
{
const HOST = "https://www.google.com";
const SERVICEURI = "/webmasters/tools/";
public $_language, $_tables, $_daterange, $_downloaded, $_skipped;
private $_auth, $_logged_in;
public function __construct()
{
$this->_auth = false;
$this->_logged_in = false;
$this->_language = "en";
$this->_daterange = array("","");
$this->_tables = array("TOP_PAGES", "TOP_QUERIES",
"CRAWL_ERRORS", "CONTENT_ERRORS", "CONTENT_KEYWORDS",
"INTERNAL_LINKS", "EXTERNAL_LINKS", "SOCIAL_ACTIVITY"
);
$this->_errTablesSort = array(0 => "http",
1 => "not-found", 2 => "restricted-by-robotsTxt",
3 => "unreachable", 4 => "timeout", 5 => "not-followed",
"kAppErrorSoft-404s" => "soft404", "sitemap" => "in-sitemaps"
);
$this->_errTablesType = array(0 => "web-crawl-errors",
1 => "mobile-wml-xhtml-errors", 2 => "mobile-chtml-errors",
3 => "mobile-operator-errors", 4 => "news-crawl-errors"
);
$this->_downloaded = array();
$this->_skipped = array();
}
/**
* Sets content language.
*
* #param $str String Valid ISO 639-1 language code, supported by Google.
*/
public function SetLanguage($str)
{
$this->_language = $str;
}
/**
* Sets features that should be downloaded.
*
* #param $arr Array Valid array values are:
* "TOP_PAGES", "TOP_QUERIES", "CRAWL_ERRORS", "CONTENT_ERRORS",
* "CONTENT_KEYWORDS", "INTERNAL_LINKS", "EXTERNAL_LINKS",
* "SOCIAL_ACTIVITY".
*/
public function SetTables($arr)
{
if(is_array($arr) && !empty($arr) && sizeof($arr) <= 2) {
$valid = array("TOP_PAGES","TOP_QUERIES","CRAWL_ERRORS","CONTENT_ERRORS",
"CONTENT_KEYWORDS","INTERNAL_LINKS","EXTERNAL_LINKS","SOCIAL_ACTIVITY");
$this->_tables = array();
for($i=0; $i < sizeof($arr); $i++) {
if(in_array($arr[$i], $valid)) {
array_push($this->_tables, $arr[$i]);
} else { throw new Exception("Invalid argument given."); }
}
} else { throw new Exception("Invalid argument given."); }
}
/**
* Sets daterange for download data.
*
* #param $arr Array Array containing two ISO 8601 formatted date strings.
*/
public function SetDaterange($arr)
{
if(is_array($arr) && !empty($arr) && sizeof($arr) == 2) {
if(self::IsISO8601($arr[0]) === true &&
self::IsISO8601($arr[1]) === true) {
$this->_daterange = array(str_replace("-", "", $arr[0]),
str_replace("-", "", $arr[1]));
return true;
} else { throw new Exception("Invalid argument given."); }
} else { throw new Exception("Invalid argument given."); }
}
/**
* Returns array of downloaded filenames.
*
* #return Array Array of filenames that have been written to disk.
*/
public function GetDownloadedFiles()
{
return $this->_downloaded;
}
/**
* Returns array of downloaded filenames.
*
* #return Array Array of filenames that have been written to disk.
*/
public function GetSkippedFiles()
{
return $this->_skipped;
}
/**
* Checks if client has logged into their Google account yet.
*
* #return Boolean Returns true if logged in, or false if not.
*/
private function IsLoggedIn()
{
return $this->_logged_in;
}
/**
* Attempts to log into the specified Google account.
*
* #param $email String User's Google email address.
* #param $pwd String Password for Google account.
* #return Boolean Returns true when Authentication was successful,
* else false.
*/
public function LogIn($email, $pwd)
{
$url = self::HOST . "/accounts/ClientLogin";
$postRequest = array(
'accountType' => 'HOSTED_OR_GOOGLE',
'Email' => $email,
'Passwd' => $pwd,
'service' => "sitemaps",
'source' => "Google-WMTdownloadscript-0.1-php"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postRequest);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if($info['http_code'] == 200) {
preg_match('/Auth=(.*)/', $output, $match);
if(isset($match[1])) {
$this->_auth = $match[1];
$this->_logged_in = true;
return true;
} else { return false; }
} else { return false; }
}
/**
* Attempts authenticated GET Request.
*
* #param $url String URL for the GET request.
* #return Mixed Curl result as String,
* or false (Boolean) when Authentication fails.
*/
public function GetData($url)
{
if(self::IsLoggedIn() === true) {
$url = self::HOST . $url;
$head = array("Authorization: GoogleLogin auth=".$this->_auth,
"GData-Version: 2");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_ENCODING, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return ($info['http_code']!=200) ? false : $result;
} else { return false; }
}
/**
* Gets all available sites from Google Webmaster Tools account.
*
* #return Mixed Array with all site URLs registered in GWT account,
* or false (Boolean) if request failed.
*/
public function GetSites()
{
if(self::IsLoggedIn() === true) {
$feed = self::GetData(self::SERVICEURI."feeds/sites/");
if($feed !== false) {
$sites = array();
$doc = new DOMDocument();
$doc->loadXML($feed);
foreach ($doc->getElementsByTagName('entry') as $node) {
array_push($sites,
$node->getElementsByTagName('title')->item(0)->nodeValue);
}
return $sites;
} else { return false; }
} else { return false; }
}
/**
* Gets the download links for an available site
* from the Google Webmaster Tools account.
*
* #param $url String Site URL registered in GWT.
* #return Mixed Array with keys TOP_PAGES and TOP_QUERIES,
* or false (Boolean) when Authentication fails.
*/
public function GetDownloadUrls($url)
{
if(self::IsLoggedIn() === true) {
$_url = sprintf(self::SERVICEURI."downloads-list?hl=%s&siteUrl=%s",
$this->_language,
urlencode($url));
$downloadList = self::GetData($_url);
return json_decode($downloadList, true);
} else { return false; }
}
/**
* Downloads the file based on the given URL.
*
* #param $site String Site URL available in GWT Account.
* #param $savepath String Optional path to save CSV to (no trailing slash!).
*/
public function DownloadCSV($site, $savepath=".")
{
if(self::IsLoggedIn() === true) {
$downloadUrls = self::GetDownloadUrls($site);
$filename = parse_url($site, PHP_URL_HOST) ."-". date("Ymd-His");
$tables = $this->_tables;
foreach($tables as $table) {
if($table=="CRAWL_ERRORS") {
self::DownloadCSV_CrawlErrors($site, $savepath);
}
elseif($table=="CONTENT_ERRORS") {
self::DownloadCSV_XTRA($site, $savepath,
"html-suggestions", "\)", "CONTENT_ERRORS", "content-problems-dl");
}
elseif($table=="CONTENT_KEYWORDS") {
self::DownloadCSV_XTRA($site, $savepath,
"keywords", "\)", "CONTENT_KEYWORDS", "content-words-dl");
}
elseif($table=="INTERNAL_LINKS") {
self::DownloadCSV_XTRA($site, $savepath,
"internal-links", "\)", "INTERNAL_LINKS", "internal-links-dl");
}
elseif($table=="EXTERNAL_LINKS") {
self::DownloadCSV_XTRA($site, $savepath,
"external-links-domain", "\)", "EXTERNAL_LINKS", "external-links-domain-dl");
}
elseif($table=="SOCIAL_ACTIVITY") {
self::DownloadCSV_XTRA($site, $savepath,
"social-activity", "x26", "SOCIAL_ACTIVITY", "social-activity-dl");
}
else {
$finalName = "$savepath/$table-$filename.csv";
$finalUrl = $downloadUrls[$table] ."&prop=ALL&db=%s&de=%s&more=true";
$finalUrl = sprintf($finalUrl, $this->_daterange[0], $this->_daterange[1]);
self::SaveData($finalUrl,$finalName);
}
}
} else { return false; }
}
/**
* Downloads "unofficial" downloads based on the given URL.
*
* #param $site String Site URL available in GWT Account.
* #param $savepath String Optional path to save CSV to (no trailing slash!).
*/
public function DownloadCSV_XTRA($site, $savepath=".", $tokenUri, $tokenDelimiter, $filenamePrefix, $dlUri)
{
if(self::IsLoggedIn() === true) {
$uri = self::SERVICEURI . $tokenUri . "?hl=%s&siteUrl=%s";
$_uri = sprintf($uri, $this->_language, $site);
$token = self::GetToken($_uri, $tokenDelimiter);
$filename = parse_url($site, PHP_URL_HOST) ."-". date("Ymd-His");
$finalName = "$savepath/$filenamePrefix-$filename.csv";
$url = self::SERVICEURI . $dlUri . "?hl=%s&siteUrl=%s&security_token=%s&prop=ALL&db=%s&de=%s&more=true";
$_url = sprintf($url, $this->_language, $site, $token, $this->_daterange[0], $this->_daterange[1]);
self::SaveData($_url,$finalName);
} else { return false; }
}
/**
* Downloads the Crawl Errors file based on the given URL.
*
* #param $site String Site URL available in GWT Account.
* #param $savepath String Optional: Path to save CSV to (no trailing slash!).
* #param $separated Boolean Optional: If true, the method saves separated CSV files
* for each error type. Default: Merge errors in one file.
*/
public function DownloadCSV_CrawlErrors($site, $savepath=".", $separated=false)
{
if(self::IsLoggedIn() === true) {
$type_param = "we";
$filename = parse_url($site, PHP_URL_HOST) ."-". date("Ymd-His");
if($separated) {
foreach($this->_errTablesSort as $sortid => $sortname) {
foreach($this->_errTablesType as $typeid => $typename) {
if($typeid == 1) {
$type_param = "mx";
} else if($typeid == 2) {
$type_param = "mc";
} else {
$type_param = "we";
}
$uri = self::SERVICEURI."crawl-errors?hl=en&siteUrl=$site&tid=$type_param";
$token = self::GetToken($uri,"x26");
$finalName = "$savepath/CRAWL_ERRORS-$typename-$sortname-$filename.csv";
$url = self::SERVICEURI."crawl-errors-dl?hl=%s&siteUrl=%s&security_token=%s&type=%s&sort=%s";
$_url = sprintf($url, $this->_language, $site, $token, $typeid, $sortid);
self::SaveData($_url,$finalName);
}
}
}
else {
$uri = self::SERVICEURI."crawl-errors?hl=en&siteUrl=$site&tid=$type_param";
$token = self::GetToken($uri,"x26");
$finalName = "$savepath/CRAWL_ERRORS-$filename.csv";
$url = self::SERVICEURI."crawl-errors-dl?hl=%s&siteUrl=%s&security_token=%s&type=0";
$_url = sprintf($url, $this->_language, $site, $token);
self::SaveData($_url,$finalName);
}
} else { return false; }
}
/**
* Saves data to a CSV file based on the given URL.
*
* #param $finalUrl String CSV Download URI.
* #param $finalName String Filepointer to save location.
*/
private function SaveData($finalUrl, $finalName)
{
$data = self::GetData($finalUrl);
if(strlen($data) > 1 && file_put_contents($finalName, utf8_decode($data))) {
array_push($this->_downloaded, realpath($finalName));
return true;
} else {
array_push($this->_skipped, $finalName);
return false;
}
}
/**
* Regular Expression to find the Security Token for a download file.
*
* #param $uri String A Webmaster Tools Desktop Service URI.
* #param $delimiter String Trailing delimiter for the regex.
* #return String Returns a security token.
*/
private function GetToken($uri, $delimiter)
{
$matches = array(); $tmp = self::get_data($uri); preg_match_all("#46security_token(.?)$delimiter#si", $tmp, $matches); return #substr($matches[1][0],3,-1);
}
/**
* Validates ISO 8601 date format.
*
* #param $str String Valid ISO 8601 date string (eg. 2012-01-01).
* #return Boolean Returns true if string has valid format, else false.
*/
private function IsISO8601($str)
{
$stamp = strtotime($str);
return (is_numeric($stamp) && checkdate(date('m', $stamp),
date('d', $stamp), date('Y', $stamp))) ? true : false;
}
}
?>
</pre>
And here is the code I am using to try to extract external links:
<pre>
<?php
include 'gwtdata.php';
try {
$email = "***#gmail.com";
$password = "***";
# If hardcoded, don't forget trailing slash!
$website = "***";
# Valid values are "TOP_PAGES", "TOP_QUERIES", "CRAWL_ERRORS",
# "CONTENT_ERRORS", "CONTENT_KEYWORDS", "INTERNAL_LINKS",
# "EXTERNAL_LINKS" and "SOCIAL_ACTIVITY".
$tables = array("EXTERNAL_LINKS");
$gdata = new GWTdata();
if($gdata->LogIn($email, $password) === true)
{
$gdata->SetTables($tables);
$gdata->DownloadCSV($website, "./csv");
}
$files = $gdata->GetDownloadedFiles();
foreach($files as $file)
{
print "Saved $file\n</a>";
}
} catch (Exception $e) {
die($e->getMessage());
}
?>
</pre>
Part of the author's answer here https://stackoverflow.com/a/16002159/624466, is the answer to your question too.
[..] this code is neither released by Google nor makes use of an official
API, but is rather a custom script processing data from the web
interface.
[..] there were some changes to the Google Webmaster Tools web
interface [..]. Thus,
it broke some functionality of the PHP class GWTdata