Receive external data - Magento - magento

First I want to say that this text was translated by Google Translate ( Excuses !).
How do I send data from an external server for my Magento store?
I looked hard for it today and found nothing basically want another system sends a notification to my Magento store and change the status of my order , I have not found a way to receiving external data in my store.
If you already have a related question I apologize.
Edit
This is my external file that sends the data:
$fields = '';
foreach($data as $key => $value) {
$fields .= $key . '=' . $value . '&';
}
rtrim($fields, '&');
$post = curl_init();
curl_setopt($post, CURLOPT_URL, $url);
curl_setopt($post, CURLOPT_POST, 1);
curl_setopt($post, CURLOPT_POSTFIELDS, $fields);
curl_setopt($post, CURLOPT_RETURNTRANSFER, 1);
var_dump($fields);
try {
$result = curl_exec($post);
$info = curl_getinfo($post);
echo curl_getinfo($post, CURLINFO_HTTP_CODE);
echo "<br>";
echo var_dump($info);
} catch (\Exception $e) {
$result = $e->getMessage();
echo $e;
}
}
$data = array(
"name" => "c.bavota",
"website" => "http://bavotasan.com",
"twitterID" => "bavotasan"
);
post_to_url("http://localhost/magento/safe/teste/mostra/", $data);
?>
This is my controller in Magento:
<?php
class Name_MyModule_TesteController extends Mage_Core_Controller_Front_Action{
public function mostraAction(){
$teste = $this->getRequest()->getPost('name');
echo 'Olá mundo';
echo '<br>Teste: '.isset($teste);
}
}
ps: I'm testing with locally with WAMP

Related

How to Redirect a login request to an external domain using PHP (Using Laravel 4)

I have two webs (Client side and Admin side) but are independent, I mean are in different domains but both using the same DB. I want to allow the Admins to login from Client side but once I recognize that isn't a normal user I want to redirect the login request to the other web and parse everything from the Admin side, just if I was trying to login from the admin web.
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password'),
);
$message = "Wrong Data";
try {
if(Auth::attempt($credentials)) {
if(Auth::user()->role_id < 4) {
$url = 'http://externaldomain.info/login';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
return $response;
}
return Redirect::to('/');
}
} catch( \Toddish\Verify\UserNotFoundException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserUnverifiedException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserDisabledException $e ) {
$message = _("User disabled");
}
Instead of the dashboard I get the login screen, I checked it with fiddler and didn't see any post request to the external domain, I just saw the login page request(GET).
EDIT
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password'),
);
$message = "Wrong Data";
try {
if(Auth::attempt($credentials)) {
if(Auth::user()->role_id < 4) {
$url = 'http://externaldomain.info/login';
$html = new \Htmldom($url);
$token = "";
foreach($html->find('input') as $element) {
if($element->name == "_token") {
$token = $element->value;
}
}
$credentials['_token'] = $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
return $response;
}
return Redirect::to('/');
}
} catch( \Toddish\Verify\UserNotFoundException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserUnverifiedException $e ) {
$message = _("User not found");
} catch( \Toddish\Verify\UserDisabledException $e ) {
$message = _("User disabled");
}
I'm using "yangqi/htmldom": "dev-master" to get the "_token", but I can't see the Request in fiddler, it keeps redirecting me to the login page instead of the dashboard.
It's probably because you forgot to add "_token" and "remember" fields.
The post you need to make should contain those for default login panel:
_token JB6nC85wLkFQtTglpiuoWk06YxI3Jx3no0xVQx0K
email admin#blabala.com
password 123456
remember on
Token is created by Laravel automatically for protecting your application from CSRF attacks.
You have two ways, first make request to your login page scrap the token. Then make a second request for post with that token.
Second you can disable the token for login page.
Ok, after your edit missing thing to do adding COOKIEJAR in curl request. Your current request is working like a browser with cookies disabled.
$url = 'http://externaldomain.info/login';
$file = "cookiefile.txt";
$fp = #fopen($file, "x");
if($fp)
fclose($fp);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_token = curl_exec ($ch);
curl_close ($ch);
$html = new \Htmldom();
// Load HTML from a string
$html->load($response_token);
$token = "";
foreach($html->find('input') as $element) {
if($element->name == "_token") {
$token = $element->value;
}
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $file);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$credentials);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
BTW, your first request to page should also need to use same cookie file. I suggest you to use curl for making the first request too.

retrieve google image search using foreach

I used the following function to get google search images
function get_images($query){
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
$url .= urlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
//decoding request
$result = json_decode($data, true);
return $result;
}
It works good when I output all results using print_r()
$images = get_images("porsche");
print_r($images);
But when I want to get a specific value using foreach()
foreach ($images->responseData->results as $result) {
echo $result->url;
}
I got an error:
Notice: Trying to get property of non-object
How can I get any specific value separetly using foreach()?
Try this :
<?php
function get_images($query){
$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';
$url .= urlencode($query);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
//decoding request
$result = json_decode($data, true);
return $result;
}
$images = get_images("porsche");
//print_r($images);
foreach ($images['responseData']['results'] as $result) {
echo $result['url']. "<br>";
}
?>
Output
http://upload.wikimedia.org/wikipedia/commons/e/e7/2012_NAIAS_Red_Porsche_991_convertible_(world_premiere).jpg
http://www.inautonews.com/wp-content/uploads/2012/05/porsche-911-club-coupe-1.jpg
http://o.aolcdn.com/hss/storage/adam/6e58b30fb96bf0d28d10fa6d290682e7/porsche-exclusive-911t-cab.jpg
http://media.caranddriver.com/images/media/510773/porsche-960-updated-inline-photo-514518-s-original.jpg

FTP server monitoring

I need to monitor some ftp servers for any changes in file structure, things that I need to monitor is how many times an file is downloaded (not sure if possible), if files are changed or not, if files are deleted or not, if ftp server still exists,
i would like this to be something that i can run server=side and would like a sms message or email if any of the above changes have occured
any one have any experience or would recommend an particular language or script?
thanks
for php i use this simple script
<
?
ini_set('auto_detect_line_endings', true);
error_reporting(E_ALL);
set_time_limit(0);
ini_set('show_errors', 1);
$file = "ftpfile.txt";
$handle = fopen($file, "r");
$date = new DateTime();
$date = $date->setTimezone(new DateTimeZone('America/New_York'));
$date = $date->format('U = Y-m-d H:i:s') . "\n";
if(!filesize($file)>0) {
echo "File is empty!";
}
else {
while (($ftpservers = fgets($handle)) !== false) {
//echo $ftpservers. "<br>";
$ftpserver= explode ("<br>", $ftpservers );
//$pattern = "//";
//preg_match ($pattern, $ftpservers, $output);
foreach ($ftpserver as $ftpserverurl) {
$ch = curl_init(); //this part we set up curl
curl_setopt($ch, CURLOPT_URL,$ftpserverurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,40);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
if(curl_errno($ch))
{
sleep(2); //add sleep in order to not overload hosting server
$echooutput = $date. 'Curl error: ' . curl_error($ch). 'Server Malfunctioned:' .$ftpserverurl;
error_log("$echooutput", 3, "ftperrors.log"); //write error to log
error_log("$echooutput", 1, "your email address"); //email alert
curl_close ($ch);
}
else
{
error_log("$date curl operation is sucessful \n", 3, "curl.log"); //keep track of successful connections for pattern anaylsis
curl_close ($ch);
}
}
}
//if (!feof($handle)) {
//echo "Error: unexpected fgets() fail\n";
//}
fclose($handle);
}
?>

facebook app losing session values after redirection

I am using Facebook PHP SDK 3.1.1
This page is supposed to collect value from header and later use it for uploading images.
Problem: $_SESSION['file'] becomes null after user logs in to Facebook.
<?php
require 'facebook.php';
include('connect.php');
$facebook = new Facebook(array('appId' => "XXXXXX",'secret' => "XXXXX","cookie" => true,'fileUpload' => true));
session_start();
$user_id = $facebook->getUser();
if(isset($_REQUEST["src"]))
{
echo "<center><img src='loader.gif'/></center>";
echo "<center><div id='msg'>Exporting Image..</div></center>";
$_SESSION['file'] = $_REQUEST["src"];
$_SESSION['club'] = $_REQUEST["club"];
}
$code = $_REQUEST["code"];
if(empty($code))
{
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=". $app_id . "&redirect_uri=" . urlencode($my_url) . "&state=". $_SESSION['state'];
echo("<script> top.location.href='" . $dialog_url . "'</script>");
exit();
}
$token_url = "https://graph.facebook.com/oauth/access_token?". "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url). "&client_secret=" . $app_secret . "&scope=user_photos,email,read_stream,publish_stream&code=".$code;
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$response = url_get_contents($token_url);
$params = null;
parse_str($response, $params);
$graph_url = "https://graph.facebook.com/me?access_token=". $params['access_token'];
$user = json_decode(url_get_contents('https://graph.facebook.com/me/albums?access_token='.$params['access_token']),true);
foreach($user as $key=>$value)
{
foreach($user[$key] as $key1=>$value1)
{
if($value1['name'] == "Photos")
{
$album_uid = $value1['id'];
}
}
}
if(!isset($album_uid))
{
echo 'Create an album';
$album_details = array(
'message'=> 'Uploaded via XXX',
'name'=> 'Photos'
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
$album_uid = $create_album['id'];
}
$photo_details = array('message'=>$_SESSION["club"]);
try{
$file = NULL;
$file="../Photos/".$_SESSION['file'].".jpeg";
echo '<script>document.getElementById("msg").innerHTML = "Uploading Image"</script>';
$photo_details['image'] = '#' . realpath($file);
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
}catch(Exception $e){
echo "<script type='text/javascript'>top.location.href = 'http://www.facebook.com/PAGE_URL/';</script>";
exit();
}
$_SESSION['file'] is null
Am I doing it right ? or something is wrong with my web hosting ?
The problem is that your app is running inside of an IFRAME and the session cookies are not being preserved. Please see here:
Facebook Iframe App with multiple pages in Safari Session Variables not persisting

Importing/parsing XML from URL into Magento

I have a URL, which contains XML of products.
What I'm looking to do, is, if possible, parse the contents and then import the details as products into Magento.
Is this possible and If so, what would be the steps I need to do to carry this out?
Thanks
EDIT:
import_products.php
require_once('app/Mage.php');
class import_products extends Mage_Core_Model_Abstract
{
public static function url_contents($url)
{
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
}
import.php
require_once('import_products.php');
$app = Mage::app('default');
$product = Mage::getSingleton('catalog/product');
$objDOM = new DOMDocument();
$objDOM->load("http://www.example.com/products.xml");
$note = $objDOM->getElementsByTagName("car");
// for each note tag, parse the document and get values for
// tasks and details tag.
foreach( $note as $value )
{
$car_ids = $value->getElementsByTagName("Car_ID");
$car_id = $car_ids->item(0)->nodeValue;
$makes = $value->getElementsByTagName("Make");
$make = $makes->item(0)->nodeValue;
$models = $value->getElementsByTagName("Model");
$model = $models->item(0)->nodeValue;
$descriptions = $value->getElementsByTagName("Description");
$description = $descriptions->item(0)->nodeValue;
$short_descriptions = $value->getElementsByTagName("Specification");
$short_description = $short_descriptions->item(0)->nodeValue;
$prices = $value->getElementsByTagName("Price");
$price = $prices->item(0)->nodeValue;
$simple = 'simple';
$product->setAttributeSetId(4);
$product->setSku($task);
$product->setName($detail);
$product->setTypeId($simple);
$product->setPrice($price);
$product->setValue($price);
$product->setDescription($description);
$product->setShortDescription($short_description);
$product->setWeight(100);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
$product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$product->setTaxClassId(2);
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
try {
$product->save();
echo "Saved";
}
catch (Exception $ex) {
echo "<pre>".$ex."</pre>";
}
//echo "$car_id :: $make :: $model :: $description :: $short_description :: $price <br /><br />";
}
you could get the parameter in Magento and use simple xml to turn the string into xml
$xmlstr = self::XML_DECLARATION . urldecode($this->getRequest()->getParam('paramName');
try {
$xml = simplexml_load_string($xmlstr);
}
catch(Exception $ex) {
echo "Unable to process xml file because of the following error<br /><br /> $ex";
exit;
}
if it is a file you are trying to get you can setup a php file with the following code in it to get the contents of the url
function get_url_contents($url){
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
You can use that function and then where in the above we had
$xmlstr = self::XML_DECLARATION . urldecode($this->getRequest()->getParam('paramName');
You should be able to do this
$xmlstr = self::XML_DECLARATION . get_url_contents('http://urlhere.com/xml');
Then you could use simple xml and assign the nodes to a products array, where you could have a collection of products and then loop through those and programmatically create the products in Magento with something like this, obviously change the values that might be hard coded for whatever you might need.
$product = Mage::getSingleton('catalog/product');
// Build the product
$product->setSku($productData['sku']);
$product->setAttributeSetId(26);
$product->setTypeId('simple');
$product->setName($productData['description']);
$product->setCategoryIds(array(162));
$product->setWebsiteIDs(array(1));
$product->setDescription($productData['description']);
$product->setShortDescription($productData['description']);
$product->setPrice($productData['price']); # Set some price
$product->setWeight(4.0000);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
$product->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
$product->setData('is_salable', '1');
$product->setTaxClassId(2); # My default tax class
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
try {
$product->save();
}
catch (Exception $ex) {
//Handle the error
}

Resources