IPN Simulator says accepted, but verification always comes back as "invalid" - paypal

I have a script basically created from the few examples of a PayPal IPN calling I could find. When I run it through the simulator it says handshake was received and all's good. But based on the data sent back to me, the IPN is always coming back as invalid. Have no clude what is wrong and am in a tight space. Please help! Code below.
Listener page:
<?php
namespace Listener;
// Set this to true to use the sandbox endpoint during testing:
$enable_sandbox = true;
// Use this to specify all of the email addresses that you have attached to paypal:
$my_email_addresses = array("payment#mysite.com", "payment#mysite.com");
// Set this to true to send a confirmation email:
$send_confirmation_email = true;
$confirmation_email_address = "payment#mysite.com";
$from_email_address = "payment#mysite.com";
// Set this to true to save a log file:
$save_log_file = true;
$log_file_dir = __DIR__ . "/logs";
// Here is some information on how to configure sendmail:
// http://php.net/manual/en/function.mail.php#118210
require('PaypalIPN.php');
use PaypalIPN;
$ipn = new PaypalIPN();
if ($enable_sandbox) {
$ipn->useSandbox();
}
$verified = $ipn->verifyIPN();
$data_text = "";
foreach ($_POST as $key => $value) {
$data_text .= $key . " = " . $value . "\r\n";
}
$test_text = "";
if ($_POST["test_ipn"] == 1) {
$test_text = "Test ";
}
// Check the receiver email to see if it matches your list of paypal email addresses
$receiver_email_found = false;
foreach ($my_email_addresses as $a) {
if (strtolower($_POST["receiver_email"]) == strtolower($a)) {
$receiver_email_found = true;
break;
}
}
date_default_timezone_set("America/Chicago");
list($year, $month, $day, $hour, $minute, $second, $timezone) = explode(":", date("Y:m:d:H:i:s:T"));
$date = $year . "-" . $month . "-" . $day;
$timestamp = $date . " " . $hour . ":" . $minute . ":" . $second . " " . $timezone;
$dated_log_file_dir = $log_file_dir . "/" . $year . "/" . $month;
$paypal_ipn_status = "VERIFICATION FAILED";
if ($verified) {
$paypal_ipn_status = "RECEIVER EMAIL MISMATCH";
if ($receiver_email_found) {
$paypal_ipn_status = "Completed Successfully";
// Process IPN
// A list of variables are available here:
// https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/
}
} elseif ($enable_sandbox) {
if ($_POST["test_ipn"] != 1) {
$paypal_ipn_status = "RECEIVED FROM LIVE WHILE SANDBOXED";
}
} elseif ($_POST["test_ipn"] == 1) {
$paypal_ipn_status = "RECEIVED FROM SANDBOX WHILE LIVE";
}
if ($save_log_file) {
// Create log file directory
if (!is_dir($dated_log_file_dir)) {
if (!file_exists($dated_log_file_dir)) {
mkdir($dated_log_file_dir, 0777, true);
if (!is_dir($dated_log_file_dir)) {
$save_log_file = false;
}
} else {
$save_log_file = false;
}
}
// Restrict web access to files in the log file directory
$htaccess_body = "RewriteEngine On" . "\r\n" . "RewriteRule .* - [L,R=404]";
if ($save_log_file && (!is_file($log_file_dir . "/.htaccess") || file_get_contents($log_file_dir . "/.htaccess") !== $htaccess_body)) {
if (!is_dir($log_file_dir . "/.htaccess")) {
file_put_contents($log_file_dir . "/.htaccess", $htaccess_body);
if (!is_file($log_file_dir . "/.htaccess") || file_get_contents($log_file_dir . "/.htaccess") !== $htaccess_body) {
$save_log_file = false;
}
} else {
$save_log_file = false;
}
}
if ($save_log_file) {
// Save data to text file
file_put_contents($dated_log_file_dir . "/" . $test_text . "paypal_ipn_" . $date . ".txt", "paypal_ipn_status = " . $paypal_ipn_status . "\r\n" . "paypal_ipn_date = " . $timestamp . "\r\n" . $data_text . "\r\n", FILE_APPEND);
}
}
if ($send_confirmation_email) {
// Send confirmation email
mail($confirmation_email_address, $test_text . "PayPal IPN : " . $paypal_ipn_status, "paypal_ipn_status = " . $paypal_ipn_status . "\r\n" . "paypal_ipn_date = " . $timestamp . "\r\n" . $data_text, "From: " . $from_email_address);
}
// Reply with an empty 200 response to indicate to paypal the IPN was received correctly
header("HTTP/1.1 200 OK");
?>
And the PayPalINP class:
<?php
class PaypalIPN
{
/** #var bool Indicates if the sandbox endpoint is used. */
private $use_sandbox = true;
/** #var bool Indicates if the local certificates are used. */
private $use_local_certs = false;
/** Production Postback URL */
const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
/** Sandbox Postback URL */
const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
/** Response from PayPal indicating validation was successful */
const VALID = 'VERIFIED';
/** Response from PayPal indicating validation failed */
const INVALID = 'INVALID';
/**
* Sets the IPN verification to sandbox mode (for use when testing,
* should not be enabled in production).
* #return void
*/
public function useSandbox()
{
$this->use_sandbox = true;
}
/**
* Sets curl to use php curl's built in certs (may be required in some
* environments).
* #return void
*/
public function usePHPCerts()
{
$this->use_local_certs = false;
}
/**
* Determine endpoint to post the verification data to.
*
* #return string
*/
public function getPaypalUri()
{
if ($this->use_sandbox) {
return self::SANDBOX_VERIFY_URI;
} else {
return self::VERIFY_URI;
}
}
/**
* Verification Function
* Sends the incoming post data back to PayPal using the cURL library.
*
* #return bool
* #throws Exception
*/
public function verifyIPN()
{
if ( ! count($_POST)) {
throw new Exception("Missing POST Data");
}
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = array();
foreach ($raw_post_array as $keyval) {
$keyval = explode('=', $keyval);
if (count($keyval) == 2) {
// Since we do not want the plus in the datetime string to be encoded to a space, we manually encode it.
/*if ($keyval[0] === 'payment_date') {
if (substr_count($keyval[1], '+') === 1) {
$keyval[1] = str_replace('+', '%2B', $keyval[1]);
}
}*/
$myPost[$keyval[0]] = $keyval[1];
}
}
// Build the body of the verification post request, adding the _notify-validate command.
$req = 'cmd=_notify-validate';
$get_magic_quotes_exists = false;
if (function_exists('get_magic_quotes_gpc')) {
$get_magic_quotes_exists = true;
}
foreach ($myPost as $key => $value) {
if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
$value = stripslashes($value);
} else {
$value = $value;
}
$req .= "&$key=$value";
}
// Post the data back to PayPal, using curl. Throw exceptions if errors occur.
$ch = curl_init($this->getPaypalUri());
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
// This is often required if the server is missing a global cert bundle, or is using an outdated one.
if ($this->use_local_certs) {
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/cert/cacert.pem");
}
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'User-Agent: PHP-IPN-Verification-Script',
'Connection: Close',
));
$res = curl_exec($ch);
if ( ! ($res)) {
$errno = curl_errno($ch);
$errstr = curl_error($ch);
curl_close($ch);
throw new Exception("cURL error: [$errno] $errstr");
}
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
if ($http_code != 200) {
throw new Exception("PayPal responded with http code $http_code");
}
curl_close($ch);
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
return true;
} else {
return false;
}
}
}

Related

Woocommerce static email attachment

Is there a way i can attach the static pdf file: https://smagdansk.dk/wp-content/uploads/2018/08/SMAGdansk-Fortrydelsesformular.pdf to all my woocommerce order complete emails?
Tested OK with WooCommerce 3.5.4
add_filter('woocommerce_email_attachments', 'attach_terms_conditions_pdf_to_email', 10, 3);
function attach_terms_conditions_pdf_to_email($attachments, $id, $object) {
$your_pdf_path = 'https://smagdansk.dk/wp-content/uploads/2018/08/SMAGdansk-Fortrydelsesformular.pdf';
if (!class_exists('WP_Http'))
include_once( ABSPATH . WPINC . '/class-http.php' );
$http = new WP_Http();
$response = $http->request($your_pdf_path);
if ($response['response']['code'] != 200) {
return false;
}
$upload = wp_upload_bits(basename($your_pdf_path), null, $response['body']);
if (!empty($upload['error'])) {
return false;
}
$file_path = $upload['file'];
$attachments[] = $file_path;
return $attachments;
}

Webmaster Tool Api Crawl Optimize

By using webmaster tool API to parse data from google. The speed of downloading is very slow, Is there any way to optimize, Or use another method. It can take more than hour depending on the data.
Regards.
const HOST = "https://www.google.com";
const SERVICEURI = "/webmasters/tools/";
public function __construct()
{
$this->_auth = $this->_loggedIn = $this->_domain = false;
$this->_data = array();
}
public function getArray($domain)
{
if ($this->_validateDomain($domain)) {
if ($this->_prepareData()) {
return $this->_data;
} else {
throw new Exception('Error receiving crawl issues for ' . $domain);
}
} else {
throw new Exception('The given domain is not connected to your Webmastertools account!');
exit;
}
}
public function getCsv($domain, $localPath = false)
{
if ($this->_validateDomain($domain)) {
if ($this->_prepareData()) {
if (!$localPath) {
$this->_HttpHeaderCSV();
$this->_outputCSV();
} else {
$this->_outputCSV($localPath);
}
} else {
throw new Exception('Error receiving crawl issues for ' . $domain);
}
} else {
throw new Exception('The given domain is not connected to your Webmastertools account!');
exit;
}
}
public function getSites()
{
if ($this->_loggedIn) {
$feed = $this->_getData('feeds/sites/');
if ($feed) {
$doc = new DOMDocument();
$doc->loadXML($feed);
$sites = array();
foreach ($doc->getElementsByTagName('entry') as $node) {
array_push($sites, $node->getElementsByTagName('title')->item(0)->nodeValue);
}
return (0 < sizeof($sites)) ? $sites : false;
} else {
return false;
}
} else {
return false;
}
}
public function login($mail, $pass)
{
$postRequest = array(
'accountType' => 'HOSTED_OR_GOOGLE',
'Email' => $mail,
'Passwd' => $pass,
'service' => "sitemaps",
'source' => "Google-WMTdownloadscript-0.11-php"
);
// Before PHP version 5.2.0 and when the first char of $pass is an # symbol,
// send data in CURLOPT_POSTFIELDS as urlencoded string.
if ('#' === (string) $pass[0] || version_compare(PHP_VERSION, '5.2.0') < 0) {
$postRequest = http_build_query($postRequest);
}
$ch = curl_init(self::HOST . '/accounts/ClientLogin');
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $postRequest,
));
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if (200 != $info['http_code']) {
throw new Exception('Login failed!');
exit;
} else {
#preg_match('/Auth=(.*)/', $output, $match);
if (isset($match[1])) {
$this->_auth = $match[1];
$this->_loggedIn = true;
return true;
} else {
throw new Exception('Login failed!');
exit;
}
}
}
private function _prepareData()
{
if ($this->_loggedIn) {
$currentIndex = 1;
$maxResults = 100;
$encUri = urlencode($this->_domain);
/*
* Get the total result count / result page count
*/
$feed = $this->_getData("feeds/{$encUri}/crawlissues?start-index=1&max-results=1");
if (!$feed) {
return false;
}
$doc = new DOMDocument();
$doc->loadXML($feed);
$totalResults = (int) $doc->getElementsByTagNameNS('http://a9.com/-/spec/opensearch/1.1/', 'totalResults')->item(0)->nodeValue;
$resultPages = (0 != $totalResults) ? ceil($totalResults / $maxResults) : false;
unset($feed, $doc);
if (!$resultPages) {
return false;
}
/*
* Paginate over issue feeds
*/
else {
// Csv data headline
$this->_data = Array(
Array(
'Issue Id',
'Crawl type',
'Issue type',
'Detail',
'URL',
'Date detected',
'Last detected'
)
);
while ($currentIndex <= $resultPages) {
$startIndex = ($maxResults * ($currentIndex - 1)) + 1;
$feed = $this->_getData("feeds/{$encUri}/crawlissues?start-index={$startIndex}&max-results={$maxResults}");
$doc = new DOMDocument();
$doc->loadXML($feed);
foreach ($doc->getElementsByTagName('entry') as $node) {
$issueId = str_replace(self::HOST . self::SERVICEURI . "feeds/{$encUri}/crawlissues/", '', $node->getElementsByTagName('id')->item(0)->nodeValue);
$crawlType = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'crawl-type')->item(0)->nodeValue;
$issueType = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'issue-type')->item(0)->nodeValue;
$detail = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'detail')->item(0)->nodeValue;
$url = $node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'url')->item(0)->nodeValue;
$dateDetected = date('d/m/Y', strtotime($node->getElementsByTagNameNS('http://schemas.google.com/webmasters/tools/2007', 'date-detected')->item(0)->nodeValue));
$updated = date('d/m/Y', strtotime($node->getElementsByTagName('updated')->item(0)->nodeValue));
// add issue data to results array
array_push($this->_data, Array(
$issueId,
$crawlType,
$issueType,
$detail,
$url,
$dateDetected,
$updated
));
}
unset($feed, $doc);
$currentIndex++;
}
return true;
}
} else {
return false;
}
}
private function _getData($url)
{
if ($this->_loggedIn) {
$header = array(
'Authorization: GoogleLogin auth=' . $this->_auth,
'GData-Version: 2'
);
$ch = curl_init(self::HOST . self::SERVICEURI . $url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_ENCODING => 1,
CURLOPT_HTTPHEADER => $header
));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return (200 != $info['http_code']) ? false : $result;
} else {
return false;
}
}
private function _HttpHeaderCSV()
{
header('Content-type: text/csv; charset=utf-8');
header('Content-disposition: attachment; filename=gwt-crawlerrors-' . $this->_getFilename());
header('Pragma: no-cache');
header('Expires: 0');
}
private function _outputCSV($localPath = false)
{
$outstream = !$localPath ? 'php://output' : $localPath . DIRECTORY_SEPARATOR . $this->_getFilename();
$outstream = fopen($outstream, "w");
if (!function_exists('__outputCSV')) {
function __outputCSV(&$vals, $key, $filehandler)
{
fputcsv($filehandler, $vals); // add parameters if you want
}
}
array_walk($this->_data, "__outputCSV", $outstream);
fclose($outstream);
}
private function _getFilename()
{
return 'gwt-crawlerrors-' . parse_url($this->_domain, PHP_URL_HOST) . '-' . date('Ymd-His') . '.csv';
}
private function _validateDomain($domain)
{
if (!filter_var($domain, FILTER_VALIDATE_URL)) {
return false;
}
$sites = $this->getSites();
if (!$sites) {
return false;
}
foreach ($sites as $url) {
if (parse_url($domain, PHP_URL_HOST) == parse_url($url, PHP_URL_HOST)) {
$this->_domain = $domain;
return true;
}
}
return false;
}
The url from Google is in error Google has added a false extension look carefully and you will see it.
Google Crap!
Your site is probably fine.

Notification.php for Windows Azure notification hub API using PHP

I want to send the notification, using windows azure notification hub api in PHP.
You have to interface directly with REST (http://msdn.microsoft.com/en-us/library/dn495827.aspx).
The code you will have to write is basically this one:
class Notification {
public $format;
public $payload;
# array with keynames for headers
# Note: Some headers are mandatory: Windows: X-WNS-Type, WindowsPhone: X-NotificationType
# Note: For Apple you can set Expiry with header: ServiceBusNotification-ApnsExpiry in W3C DTF, YYYY-MM-DDThh:mmTZD (for example, 1997-07-16T19:20+01:00).
public $headers;
function __construct($format, $payload) {
if (!in_array($format, ["template", "apple", "windows", "gcm", "windowsphone"])) {
throw new Exception('Invalid format: ' . $format);
}
$this->format = $format;
$this->payload = $payload;
}
}
class NotificationHub {
const API_VERSION = "?api-version=2013-10";
private $endpoint;
private $hubPath;
private $sasKeyName;
private $sasKeyValue;
function __construct($connectionString, $hubPath) {
$this->hubPath = $hubPath;
$this->parseConnectionString($connectionString);
}
private function parseConnectionString($connectionString) {
$parts = explode(";", $connectionString);
if (sizeof($parts) != 3) {
throw new Exception("Error parsing connection string: " . $connectionString);
}
foreach ($parts as $part) {
if (strpos($part, "Endpoint") === 0) {
$this->endpoint = "https" . substr($part, 11);
} else if (strpos($part, "SharedAccessKeyName") === 0) {
$this->sasKeyName = substr($part, 20);
} else if (strpos($part, "SharedAccessKey") === 0) {
$this->sasKeyValue = substr($part, 16);
}
}
}
private function generateSasToken($uri) {
$targetUri = strtolower(rawurlencode(strtolower($uri)));
$expires = time();
$expiresInMins = 60;
$expires = $expires + $expiresInMins * 60;
$toSign = $targetUri . "\n" . $expires;
$signature = rawurlencode(base64_encode(hash_hmac('sha256', $toSign, $this->sasKeyValue, TRUE)));
$token = "SharedAccessSignature sr=" . $targetUri . "&sig="
. $signature . "&se=" . $expires . "&skn=" . $this->sasKeyName;
return $token;
}
public function broadcastNotification($notification) {
$this->sendNotification($notification, "");
}
public function sendNotification($notification, $tagsOrTagExpression) {
if (is_array($tagsOrTagExpression)) {
$tagExpression = implode(" || ", $tagsOrTagExpression);
} else {
$tagExpression = $tagsOrTagExpression;
}
# build uri
$uri = $this->endpoint . $this->hubPath . "/messages" . NotificationHub::API_VERSION;
$ch = curl_init($uri);
if (in_array($notification->format, ["template", "apple", "gcm"])) {
$contentType = "application/json";
} else {
$contentType = "application/xml";
}
$token = $this->generateSasToken($uri);
$headers = [
'Authorization: '.$token,
'Content-Type: '.$contentType,
'ServiceBusNotification-Format: '.$notification->format
];
if ("" !== $tagExpression) {
$headers[] = 'ServiceBusNotification-Tags: '.$tagExpression;
}
# add headers for other platforms
if (is_array($notification->headers)) {
$headers = array_merge($headers, $notification->headers);
}
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $notification->payload
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
if ($info['http_code'] <> 201) {
throw new Exception('Error sending notificaiton: '. $info['http_code'] . ' msg: ' . $response);
}
}
}
And use it this way: initialize your Notification Hubs client (substitute the connection string and hub name as instructed in the Get started tutorial):
$hub = new NotificationHub("connection string", "hubname");
Then add the send code depending on your target mobile platform.
Windows Store and Windows Phone 8.1 (non-Silverlight)
$toast = '<toast><visual><binding template="ToastText01"><text id="1">Hello from PHP!</text></binding></visual></toast>';
$notification = new Notification("windows", $toast);
$notification->headers[] = 'X-WNS-Type: wns/toast';
$hub->sendNotification($notification);
iOS
$alert = '{"aps":{"alert":"Hello from PHP!"}}';
$notification = new Notification("apple", $alert);
$hub->sendNotification($notification);
Android
$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("gcm", $message);
$hub->sendNotification($notification);
Windows Phone 8.0 and 8.1 Silverlight
$toast = '<?xml version="1.0" encoding="utf-8"?>' .
'<wp:Notification xmlns:wp="WPNotification">' .
'<wp:Toast>' .
'<wp:Text1>Hello from PHP!</wp:Text1>' .
'</wp:Toast> ' .
'</wp:Notification>';
$notification = new Notification("mpns", $toast);
$notification->headers[] = 'X-WindowsPhone-Target : toast';
$notification->headers[] = 'X-NotificationClass : 2';
$hub->sendNotification($notification);
Kindle Fire
$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("adm", $message);
$hub->sendNotification($notification);
For registration management you have to follow the content formats shown in the MSDN topic linked above, and probably do some nasty xml parsing... Be warned that element order is important and things will not work if the element are out of order.

Magento - Upload file in contact form

I have to create a new field in contact form to upload file.
I followed tuts and this is what i did :
in form.phtml :
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post" enctype="multipart/form-data">
Then i added the field in the contact form :
<li>
<label for="attachment"><?php echo Mage::helper('contacts')->__('Attachment') ?></label>
<div class="input-box">
<input name="MAX_FILE_SIZE" type="hidden" value="2000000" />
<input name="attachment" id="attachment" class="input-text" type="file" />
</div>
I modified the IndexController.php in : /www/app/code/core/Mage/Contacts/controllers as :
<?php
/**
* Contacts index controller
*
* #category Mage
* #package Mage_Contacts
* #author Magento Core Team <core#magentocommerce.com>
*/
class Mage_Contacts_IndexController extends Mage_Core_Controller_Front_Action
{
const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
const XML_PATH_ENABLED = 'contacts/contacts/enabled';
public function preDispatch()
{
parent::preDispatch();
if( !Mage::getStoreConfigFlag(self::XML_PATH_ENABLED) ) {
$this->norouteAction();
}
}
public function indexAction()
{
$this->loadLayout();
$this->getLayout()->getBlock('contactForm')
->setFormAction( Mage::getUrl('*/*/post') );
$this->_initLayoutMessages('customer/session');
$this->_initLayoutMessages('catalog/session');
$this->renderLayout();
}
public function postAction()
{
$post = $this->getRequest()->getPost();
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* #var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
/**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************//**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg', 'jpeg', 'png', 'bmp', 'gif'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts';
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path . DS, $fileName );
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************/
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* #var $mailTemplate Mage_Core_Model_Email_Template */
/**************************************************************/
//sending file as attachment
$attachmentFilePath = Mage::getBaseDir('media'). DS . 'contacts' . DS . $fileName;
if(file_exists($attachmentFilePath)){
$fileContents = file_get_contents($attachmentFilePath);
$attachment = $mailTemplate->getMail()->createAttachment($fileContents);
$attachment->filename = $fileName;
}
/**************************************************************/
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
$this->_redirect('*/*/');
return;
}
} else {
$this->_redirect('*/*/');
}
}
}
I created a contacts directory in medias with 777 rights
The contact form is correctly shown in my page, i can choose a file, but it isnt uploaded. In medias/contacts/ no file, and in my email i have a attached file called noname
Impossible to use it. Im sure i did something wrong but i cant find what exactly is wrong.
Im not a pro Magento admin, so if you can explain me in details that will be cool :)
Thanks all
i have tried recreating your scenario in my local installation and changed your contoller file uploader code with one of my working modules.
/**************************************************************/
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'contacts' . DS ;
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path, $_FILES['attachment']['contacts'] );
$newFilename = $uploader->getUploadedFileName();
} catch (Exception $e) {
$error = true;
}
}
/**************************************************************/
This is working 100% correctly i have tested this for pdf also.
Please try changing once.
Replace
if(file_exists($attachmentFilePath)){
With this
if(file_exists($attachmentFilePath) && is_file($attachmentFilePath)){
Because file_exists results to TRUE if the file OR the directory exists. My email being sent out would send a blank "Mail Attachment" file because the file upload input on my contact form was optional.

getting yahoo contacts in php (yahoo OAuth)

I'm developing an invite_friends tool for a website. I read these articles and taken the steps:
http://anandafit.info/2011/01/06/yahoo-contact-list-reader-in-php/
http://nullinfo.wordpress.com/oauth-yahoo/
but when i execute that, at the end, Yahoo says:
{ "error": { "lang": "en-US", "description": "Please provide valid credentials. OAuth oauth_problem=\"token_rejected\", realm=\"yahooapis.com\"" } }
:((
These are my codes:
getreqtok.php
<?php
require 'modules/invite/yahoo/globals.php';
require 'modules/invite/yahoo/oauth_helper.php';
// Callback can either be 'oob' or a url whose domain must match
// the domain that you entered when registering your application
$callback='http://www.warzone.in/modules.php?name=invite&op=yahoo_get_contacts';
// Get the request token using HTTP GET and HMAC-SHA1 signature
$retarr = get_request_token(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,
$callback, false, true, true);
//echo $retarr[3]["oauth_token_secret"]."<br>
//<br>
//";
session_start();
$_SESSION["oauth_token_secret"] = $retarr[3]["oauth_token_secret"];
//echo $_SESSION["oauth_token_secret"]."<br>
//<br>
//<br>
//";
if (! empty($retarr)){
list($info, $headers, $body, $body_parsed) = $retarr;
if ($info['http_code'] == 200 && !empty($body)) {
//print "Have the user go to xoauth_request_auth_url to authorize your app\n";
?>
YAHOO
<?php
}
}
/**
* Get a request token.
* #param string $consumer_key obtained when you registered your app
* #param string $consumer_secret obtained when you registered your app
* #param string $callback callback url can be the string 'oob'
* #param bool $usePost use HTTP POST instead of GET
* #param bool $useHmacSha1Sig use HMAC-SHA1 signature
* #param bool $passOAuthInHeader pass OAuth credentials in HTTP header
* #return array of response parameters or empty array on error
*/
function get_request_token($consumer_key, $consumer_secret, $callback, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=false)
{
$retarr = array(); // return value
$response = array();
$url = 'https://api.login.yahoo.com/oauth/v2/get_request_token';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_callback'] = $callback;
// compute signature and add it to the params list
if ($useHmacSha1Sig) {
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params,
$consumer_secret, null);
} else {
$params['oauth_signature_method'] = 'PLAINTEXT';
$params['oauth_signature'] =
oauth_compute_plaintext_sig($consumer_secret, null);
}
// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, FALSE);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("getreqtok:INFO:request_url:$request_url");
logit("getreqtok:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
logit("getreqtok:INFO:request_url:$request_url");
$response = do_get($request_url, 443, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
$body_parsed = oauth_parse_str($body);
if (! empty($body_parsed)) {
logit("getreqtok:INFO:response_body_parsed:");
//print_r($body_parsed);
}
$retarr = $response;
$retarr[] = $body_parsed;
}
return $retarr;
}
?>
getacctok.php
<?php
session_start();
require 'modules/invite/yahoo/globals.php';
require 'modules/invite/yahoo/oauth_helper.php';
// Fill in the next 3 variables.
$request_token=$_REQUEST["oauth_token"];
$request_token_secret=$_SESSION["oauth_token_secret"];
$oauth_verifier= $_REQUEST["oauth_verifier"];
//echo $request_token." xxxx ".$request_token_secret." yyyy ".$oauth_verifier."<br>
//<br>
//<br>
//";
// Get the access token using HTTP GET and HMAC-SHA1 signature
$retarr = get_access_token(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,
$request_token, $request_token_secret,
$oauth_verifier, false, true, true);
if (! empty($retarr)) {
list($info, $headers, $body, $body_parsed) = $retarr;
if ($info['http_code'] == 200 && !empty($body)) {
// print "Use oauth_token as the token for all of your API calls:\n" .
rfc3986_decode($body_parsed['oauth_token']);
}
}
/**
* Get an access token using a request token and OAuth Verifier.
* #param string $consumer_key obtained when you registered your app
* #param string $consumer_secret obtained when you registered your app
* #param string $request_token obtained from getreqtok
* #param string $request_token_secret obtained from getreqtok
* #param string $oauth_verifier obtained from step 3
* #param bool $usePost use HTTP POST instead of GET
* #param bool $useHmacSha1Sig use HMAC-SHA1 signature
* #param bool $passOAuthInHeader pass OAuth credentials in HTTP header
* #return array of response parameters or empty array on error
*/
function get_access_token($consumer_key, $consumer_secret, $request_token, $request_token_secret, $oauth_verifier, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=true)
{
$retarr = array(); // return value
$response = array();
$url = 'https://api.login.yahoo.com/oauth/v2/get_token';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_token']= $request_token;
$params['oauth_verifier'] = $oauth_verifier;
// compute signature and add it to the params list
if ($useHmacSha1Sig) {
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params,
$consumer_secret, $request_token_secret);
} else {
$params['oauth_signature_method'] = 'PLAINTEXT';
$params['oauth_signature'] =
oauth_compute_plaintext_sig($consumer_secret, $request_token_secret);
}
// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, false);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("getacctok:INFO:request_url:$request_url");
logit("getacctok:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
logit("getacctok:INFO:request_url:$request_url");
$response = do_get($request_url, 443, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
$body_parsed = oauth_parse_str($body);
if (! empty($body_parsed)) {
logit("getacctok:INFO:response_body_parsed:");
//print_r($body_parsed);
}
$retarr = $response;
$retarr[] = $body_parsed;
}
return $retarr;
}
$guid = $retarr[3]["xoauth_yahoo_guid"];
$access_token = $retarr[3]["oauth_token"];
$access_token_secret = $retarr[3]["oauth_token_secret"];
// Call Contact API
$retarr = callcontact(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,
$guid, $access_token, $access_token_secret,
false, true);
function callcontact($consumer_key, $consumer_secret, $guid, $access_token, $access_token_secret, $usePost=false, $passOAuthInHeader=true)
{
$retarr = array(); // return value
$response = array();
$url = 'http://social.yahooapis.com/v1/user/' . $guid . '/contacts;count=5';
$params['format'] = 'json';
$params['view'] = 'compact';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_token'] = $access_token;
// compute hmac-sha1 signature and add it to the params list
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params,
$consumer_secret, $access_token_secret);
// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, true);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("callcontact:INFO:request_url:$request_url");
logit("callcontact:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 80, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
logit("callcontact:INFO:request_url:$request_url");
$response = do_get($request_url, 80, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
if ($body) {
logit("callcontact:INFO:response:");
print(json_pretty_print($body));
}
$retarr = $response;
}
return $retarr;
}
?>
class YahooContacts
{
protected static $oauthConsumerKey ="";
protected static $OauthConsumerSecret ="";
protected static $oauthDomain="";
public function __construct(){
//Check Session is Start Or not
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
/**
* Authentication user And Access Refresh and access token
*
* #author <Pawan Kumar>
* #return type boolean
**/
protected function getAuthorization($code)
{
$url = "https://api.login.yahoo.com/oauth2/get_token";
$data="grant_type=authorization_code&redirect_uri=".self::$oauthDomain."&code=".$code;
$auth = base64_encode(self::$oauthConsumerKey.":".self::$OauthConsumerSecret);
$headers = array(
'Authorization: Basic '.$auth,
'Content-Type: application/x-www-form-urlencoded'
);
try{
$resultSet =self::makeRequest($url,$data,$headers);
if($resultSet->access_token){
$this->setAccessToken($resultSet->access_token);
$this->setRefreshToken($resultSet->refresh_token);
$this->setGuidToken($resultSet->xoauth_yahoo_guid);
return true;
}
}catch(Exception $ex){
throw($ex);
}
}
/**
* Get All Contacts list From Yahoo API using Auth Access Token And oAuth Guid Token
*
* #author <Pawan Kumar>
* #return type Object
**/
public function getUserContactsDetails()
{
/** Refresh Access Token is Expired **/
$this->generateAccessToken();
$guid =$this->getGuidToken();
$token =$this->getAccessToken();
$contactUrl="https://social.yahooapis.com/v1/user/$guid/contacts?format=json";
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Authorization: Bearer $token"
)
);
$context = stream_context_create($opts);
$file = file_get_contents($contactUrl, false, $context);
$output =json_decode($file);
return $output;
}
/**
* Get New Access Token using Refresh Token
*
* #author <Pawan Kumar>
* #return type boolean
**/
protected function generateAccessToken()
{
$url = "https://api.login.yahoo.com/oauth2/get_token";
$refreshToken = $this->getRefreshToken();
$data="grant_type=refresh_token&redirect_uri=".self::$oauthDomain."&refresh_token=".$refreshToken;
$auth = base64_encode(self::$oauthConsumerKey.":".self::$OauthConsumerSecret);
$headers = array(
'Authorization: Basic '.$auth,
'Content-Type: application/x-www-form-urlencoded'
);
try{
$resultSet =self::makeRequest($url,$data,$headers);
if($resultSet->access_token){
$this->setAccessToken($resultSet->access_token);
return true;
}else{
return false;
}
}catch(Exception $ex){
throw($ex);
}
}
/**
* Build a login url using oAuth Consumber Key And Redirect Domain
*
* #author Pawan Kumar
* #return type String
**/
public static function getLoginUrl()
{
$loginUrl = "https://api.login.yahoo.com/oauth2/request_auth";
$buildUrl =$loginUrl."?client_id=".self::$oauthConsumerKey."&redirect_uri=".self::$oauthDomain."&response_type=code&language=en-us";
return $buildUrl;
}
/**
* Make a Remote Post Request using MakeRequest Function
*
* #param Url String
* #param $postData String Send Post Data With Request
* #param headers Array Contain Auth basic information
* #author Pawan Kumar
* #return type Object
**/
public static function makeRequest($url,$postData,$headers){
try{
if (empty($url))throw new Exception("Url is Not Format.");
if (empty($postData))throw new Exception("Post Parameters is Not Defined");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postData);
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
$output =json_decode($result);
return $output;
}catch(\Exception $ex){
throw($ex);
}
}
/**
* #param RefreshToken to set String Token Into Session
*/
public function setRefreshToken($token)
{
$_SESSION['refresh_token']=$token;
}
/**
* #return String Refresh Token From Session
*/
public function getRefreshToken()
{
return $_SESSION['refresh_token'];
}
/**
* #param AccessToken to set String Token into Session
*/
public function setAccessToken($token)
{
$_SESSION['access_token']=$token;
}
/**
* #return String Access Token From Session
*/
public function getAccessToken()
{
return $_SESSION['access_token'];
}
/**
* #param GuidToken to set String Token into Session
*/
public function setGuidToken($token)
{
$_SESSION['xoauth_yahoo_guid']=$token;
}
/**
* #return String Guid Token from Session
*/
public function getGuidToken()
{
return $_SESSION['xoauth_yahoo_guid'];
}
}
// Initialize Session If Session is Not Start
session_start();
if(isset($_GET['code'])){
$code = $_GET['code'];
if(!empty($code)){
// create a instance of yahoo contacts
$obj = new YahooContacts();
//Successfully Authorization Process
$obj->getAuthorization($code);
Header("Location:http://yahoo.fansunite.com.au");die;
}
}else{
if(isset($_SESSION['access_token'])){
// create a instance of yahoo contacts
$obj = new YahooContacts();
//After Authorization Get User Contacts Email
$res = $obj->getUserContactsDetails();
print "<pre>";
print_r($res);
}else{
$url = YahooContacts::getLoginUrl();
echo "<center><strong><a href='$url'>Login With Yahoo Mail !</a></strong></center>";
}
}