How to get my zend script picture filename into a hidden field - zend-framework

OK, I am stumped here. I'm using a Zend script that helps me to upload pictures. It works great, but I am trying to capture the pictures name into a hidden field for a form. I'd like to note that the name changes, so I'd need to get whichever it ends up being put into the hidden field. Here is the Zend script:
<?php
if (isset($_POST['upload'])) {
require_once('scripts/library.php');
try {
$destination = 'xxxxxxxx';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '90kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
if (!$uploader->isValid()) {
$messages = $uploader->getMessages();
} else {
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$uploaded .= " and renamed $no_spaces";
}
$messages[] = "$uploaded";
}
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
Here I am trying to make the $pic variable not to throw an error for now (on the form page)
if (isset($_POST['upload'])) { } else { $pic = "unknown";}
The $pic variable is what I was trying to have the filename from the zend script copied into. Any feedback is greaaaatly appreciated :)

Related

How to get new uploaded file name in controller?

1.Can anyone suggest me how to get new uploaded file name in controller action? I'm using validation rule like..
'validators' => [
[
'name' => '\User\Validator\ImageValidator',
'options' => [
'minSize' => '1',
'maxSize' => '1024',
'newFileName' => time() . 'newFileName2',
'uploadPath' => getcwd() . '/public/uploads/platform/'
],
],
],
and it's working properly but I have no idea to how to get file name or error in controller action.
How to overwrite the minSize and maxSize error message? My validator file code is:
namespace User\Validator;
use Zend\Validator\File\Extension;
use Zend\File\Transfer\Adapter\Http;
use Zend\Validator\File\FilesSize;
use Zend\Filter\File\Rename;
use Zend\Validator\File\MimeType;
use Zend\Validator\AbstractValidator;
class ImageValidator extends AbstractValidator
{
const FILE_EXTENSION_ERROR = 'invalidFileExtention';
const FILE_NAME_ERROR = 'invalidFileName';
const FILE_INVALID = 'invalidFile';
const FALSE_EXTENSION = 'fileExtensionFalse';
const NOT_FOUND = 'fileExtensionNotFound';
const TOO_BIG = 'fileFilesSizeTooBig';
const TOO_SMALL = 'fileFilesSizeTooSmall';
const NOT_READABLE = 'fileFilesSizeNotReadable';
public $minSize = 64; //KB
public $maxSize = 1024; //KB
public $overwrite = true;
public $newFileName = null;
public $uploadPath = './data/';
public $extensions = array('jpg', 'png', 'gif', 'jpeg');
public $mimeTypes = array(
'image/gif',
'image/jpg',
'image/png',
);
protected $messageTemplates = array(
self::FILE_EXTENSION_ERROR => "File extension is not correct",
self::FILE_NAME_ERROR => "File name is not correct",
self::FILE_INVALID => "File is not valid",
self::FALSE_EXTENSION => "File has an incorrect extension",
self::NOT_FOUND => "File is not readable or does not exist",
self::TOO_BIG => "// want to overwrite these message",
self::TOO_SMALL => "// want to overwrite these message",
self::NOT_READABLE => "One or more files can not be read",
);
protected $fileAdapter;
protected $validators;
protected $filters;
public function __construct($options)
{
$this->fileAdapter = new Http();
parent::__construct($options);
}
public function isValid($fileInput)
{
$options = $this->getOptions();
$extensions = $this->extensions;
$minSize = $this->minSize;
$maxSize = $this->maxSize;
$newFileName = $this->newFileName;
$uploadPath = $this->uploadPath;
$overwrite = $this->overwrite;
if (array_key_exists('extensions', $options)) {
$extensions = $options['extensions'];
}
if (array_key_exists('minSize', $options)) {
$minSize = $options['minSize'];
}
if (array_key_exists('maxSize', $options)) {
$maxSize = $options['maxSize'];
}
if (array_key_exists('newFileName', $options)) {
$newFileName = $options['newFileName'];
}
if (array_key_exists('uploadPath', $options)) {
$uploadPath = $options['uploadPath'];
}
if (array_key_exists('overwrite', $options)) {
$overwrite = $options['overwrite'];
}
$fileName = $fileInput['name'];
$fileSizeOptions = null;
if ($minSize) {
$fileSizeOptions['min'] = $minSize*1024 ;
}
if ($maxSize) {
$fileSizeOptions['max'] = $maxSize*1024 ;
}
if ($fileSizeOptions) {
$this->validators[] = new FilesSize($fileSizeOptions);
}
$this->validators[] = new Extension(array('extension' => $extensions));
if (! preg_match('/^[a-z0-9-_]+[a-z0-9-_\.]+$/i', $fileName)) {
$this->error(self::FILE_NAME_ERROR);
return false;
}
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
if (! in_array($extension, $extensions)) {
$this->error(self::FILE_EXTENSION_ERROR);
return false;
}
if ($newFileName) {
$destination = $newFileName.".$extension";
if (! preg_match('/^[a-z0-9-_]+[a-z0-9-_\.]+$/i', $destination)) {
$this->error(self::FILE_NAME_ERROR);
return false;
}
} else {
$destination = $fileName;
}
$renameOptions['target'] = $uploadPath.$destination;
$renameOptions['overwrite'] = $overwrite;
$this->filters[] = new Rename($renameOptions);
$this->fileAdapter->setFilters($this->filters);
$this->fileAdapter->setValidators($this->validators);
if ($this->fileAdapter->isValid()) {
$this->fileAdapter->receive();
return true;
} else {
$messages = $this->fileAdapter->getMessages();
if ($messages) {
$this->setMessages($messages);
foreach ($messages as $key => $value) {
$this->error($key);
}
} else {
$this->error(self::FILE_INVALID);
}
return false;
}
}
}
I'm new to Zend framework so unable to understand how this validator code is working.
Thank you

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.

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.

How to create a category and add an image programatically

I've written a script that creates a category and adds a thumbnail image. It is inserted in the database but the thumbnail is not displayed.
When I upload from the backend it works fine.
This is my code.
<?php
require_once 'businessclasses.php';
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(1); // Mage_Core_Model_App::ADMIN_STORE_ID
$count = 0;
importRootCategories('us', '1/31/32', 4);
function importRootCategories($language, $path, $storeID)
{
$data = new getCSV();
$rows = $data->getRootCategories(); // Gets the list of root categories.
foreach($rows as $row) {
$categoryName = utf8_decode(iconv('ISO-8859-1','UTF-8',strip_tags(trim($row[$language])))); // Name of Category
if($language == "us") {
if($row[$language] == "")
$categoryName = utf8_decode(iconv('ISO-8859-1','UTF-8',strip_tags(trim($row["en"])))); // Name of Category
}
// Create category object
$category = Mage::getModel('catalog/category');
$category->setStoreId($storeID); // 'US-Store' store is assigned to this category
$rootCategory['name'] = $categoryName;
$rootCategory['path'] = $path; // this is the catgeory path - 1 for root category
$rootCategory['display_mode'] = "PRODUCTS";
$rootCategory['include_in_menu'] = 1;
$rootCategory['is_active'] = 1;
$rootCategory['is_anchor'] = 1;
$rootCategory['thumbnail'] = _getCategoryImageFile($row['catimg'].'.jpg');
$category->addData($rootCategory);
try {
$category->save();
echo $rootCategoryId = $category->getId();
}
catch (Exception $e){
echo $e->getMessage();
}
}
}
function _getCategoryImageFile($filename)
{
$filePath = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS . $filename;
$fileUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'import/category/'. $filename;
$imageUrl=file_get_contents($imageUrl);
$file_handler=fopen($filePath,'w');
if(fwrite($file_handler,$fileUrl)==false){
Mage::log('ERROR: ', null,'error');
}
else{
Mage::log('Image Created Successfully', null, '');
}
fclose($file_handler);
return $filename;
}
?>

Sending messages with facebook xmpp api

I have copied and modified some of the facebook's given chat api code, now I want to send a message to my friend. I found that we send a xml <message from="" to=""> to send a message. But that did not happen. maybe it's because i don't know what to put on from and to attribs?
The Code:
<?php
$STREAM_XML = '<stream:stream '.
'xmlns:stream="http://etherx.jabber.org/streams" '.
'version="1.0" xmlns="jabber:client" to="chat.facebook.com" '.
'xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">';
$AUTH_XML = '<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" '.
'mechanism="X-FACEBOOK-PLATFORM"></auth>';
$CLOSE_XML = '</stream:stream>';
$RESOURCE_XML = '<iq type="set" id="3">'.
'<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">'.
'<resource>fb_xmpp_script</resource></bind></iq>';
$SESSION_XML = '<iq type="set" id="4" to="chat.facebook.com">'.
'<session xmlns="urn:ietf:params:xml:ns:xmpp-session"/></iq>';
$START_TLS = '<starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls"/>';
$MESSAGE = '<message from="-cyberkiller.nishchal#chat.facebook.com" to="-nootan.ghimire#chat.facebook.com">
<body>This is the test message! Sent from App. by, "Nishchal"</body>
</message>';
function open_connection($server) {
$fp = fsockopen($server, 5222, $errno, $errstr);
if (!$fp) {
print "$errstr ($errno)<br>";
} else {
print "connnection open<br>";
}
return $fp;
}
function send_xml($fp, $xml) {
fwrite($fp, $xml);
}
function recv_xml($fp, $size=4096) {
$xml = fread($fp, $size);
if (!preg_match('/^</', $xml)) {
$xml = '<' . $xml;
}
if ($xml === "") {
return null;
}
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xml, $val, $index);
xml_parser_free($xml_parser);
return array($val, $index);
}
function find_xmpp($fp, $tag, $value=null, &$ret=null) {
static $val = null, $index = null;
do {
if ($val === null && $index === null) {
list($val, $index) = recv_xml($fp);
if ($val === null || $index === null) {
return false;
}
}
foreach ($index as $tag_key => $tag_array) {
if ($tag_key === $tag) {
if ($value === null) {
if (isset($val[$tag_array[0]]['value'])) {
$ret = $val[$tag_array[0]]['value'];
}
return true;
}
foreach ($tag_array as $i => $pos) {
if ($val[$pos]['tag'] === $tag && isset($val[$pos]['value']) &&
$val[$pos]['value'] === $value) {
$ret = $val[$pos]['value'];
return true;
}
}
}
}
$val = $index = null;
} while (!feof($fp));
return false;
}
function xmpp_connect($options, $access_token) {
global $STREAM_XML, $AUTH_XML, $RESOURCE_XML, $SESSION_XML, $CLOSE_XML, $START_TLS;
$fp = open_connection($options['server']);
if (!$fp) {
return false;
}
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp, 'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) {
return false;
}
send_xml($fp, $START_TLS);
if (!find_xmpp($fp, 'PROCEED', null, $proceed)) {
return false;
}
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp, 'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'MECHANISM', 'X-FACEBOOK-PLATFORM')) {
return false;
}
send_xml($fp, $AUTH_XML);
if (!find_xmpp($fp, 'CHALLENGE', null, $challenge)) {
return false;
}
$challenge = base64_decode($challenge);
$challenge = urldecode($challenge);
parse_str($challenge, $challenge_array);
$resp_array = array(
'method' => $challenge_array['method'],
'nonce' => $challenge_array['nonce'],
'access_token' => $access_token,
'api_key' => $options['app_id'],
'call_id' => 0,
'v' => '1.0',
);
$response = http_build_query($resp_array);
$xml = '<response xmlns="urn:ietf:params:xml:ns:xmpp-sasl">'.
base64_encode($response).'</response>';
send_xml($fp, $xml);
if (!find_xmpp($fp, 'SUCCESS')) {
return false;
}
send_xml($fp, $STREAM_XML);
if (!find_xmpp($fp,'STREAM:STREAM')) {
return false;
}
if (!find_xmpp($fp, 'STREAM:FEATURES')) {
return false;
}
send_xml($fp, $RESOURCE_XML);
if (!find_xmpp($fp, 'JID')) {
return false;
}
send_xml($fp, $SESSION_XML);
if (!find_xmpp($fp, 'SESSION')) {
return false;
}
send_xml($fp, $MESSAGE);
if (!find_xmpp($fp, 'BODY')) {
return false;
}
send_xml($fp, $CLOSE_XML);
print ("Authentication complete<br>");
fclose($fp);
return true;
}
function get_access_token(){
$token=new Facebook(array("AppId"=>"my app id","AppSecret"=>"my app secret"));
$token=$facebook->getAccessToken();
return $token;
}
function _main() {
require_once("facebook.php");
$app_id='app id';
$app_secret='app secret';
$my_url = "http://localhost/message.php";
$uid = 'cyberkiller.nishchal#chat.facebook.com';
$access_token = get_access_token();
$options = array(
'uid' => $uid,
'app_id' => $app_id,
'server' => 'chat.facebook.com',
);
if (xmpp_connect($options, $access_token)) {
print "Done<br>";
} else {
print "An error ocurred<br>";
}
}
_main();
so what do I need to do to send a message to that user through this, i tried to create a xml with the message but got strucked there, can any one please suggest something, When I run the code, socket enable crypto is being executed after that it is taking some time like 20 secs, then it displays an error occured, do I have to remove the send_xml($fp,$STREAM_XML); for the second time after the stream_socket_enable_crypto($fp, false, STREAM_CRYPTO_METHOD_TLS_CLIENT);
I changed the second parameter of this call to false because I don't have an ssl connection, what should I do next?
Use Facebook ID instead of the url username.Get it by requesting http://graph.facebook.com/{username}
Then replace it on "from" and "to" attributes.Also remove the hyphen on "from" attribute, or just remove all of it (from my experience its still going to work).Hyphen on "to" attribute is mandatory.