Google Translate in Flash (SWF) Action Script - actionscript

We tried to code Google Translate in action script for Flash Professional CS6, but it does not function .
Can anyone help ?
The code does not return the trasnlated result .
The Code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function () {
var str:String = unescape(this);
var txtContent;
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
}
Code Explained :
Sample
LoadVars.sendAndLoad( )
Method Code Explained :
https://flylib.com/books/en/4.13.1.377/1/
================================================
Edit 1:
I edited my code :
I added the return code to the main function , so the main function has output .
but still the function does not return any transalted content .
The improved code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
var txtContent;
result_lv.onLoad = function () {
var str:String = unescape(this);
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
return txtContent.text;
}
================================================
Edit 2:
We have found a working PHP function that return the translated result properly :
https://github.com/statickidz/php-google-translate-free/blob/1.1.1/src/GoogleTranslate.php
Now we are trying to load the PHP function result in the Action Script 2 for Adobe Flash Professional CS6.
here is some explanation about how this is possible :
Flash calling a PHP function
================================================
Edit 3:
A Good and Complete Book about PHP for Flash :
Foundation PHP for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-Steve-Webster/dp/1903450160
================================================
Edit 4:
Some Other Good and Complete Books about PHP for Flash :
Foundation PHP 5 for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-David-Powers/dp/B0096EPX7Q
Advanced PHP for Flash 1st ed. Edition :
https://www.amazon.com/Advanced-PHP-Flash-Steve-Webster/dp/1590591879
================================================
Edit 5:
We have rewritten the action script function that now use the PHP GoogleTranslate function .
See the answers below .
But it does not return the Translated result .
Please can someone help ?
Thanks

In the PHP-script that you've mentioned in comments, authors used the link https://translate.google.com/translate_a/single?... with some client authenticaton data like iid and also set User-Agent to Android phone:
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
I think this script is trying to masquerade request like it was sent from Android Google Translate App.
But in your AcrionScript code you are using another URL:
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
This simple-HTTP Google Translate API v1 is very old and already not available.
You can check it yourself by following this link - it's responds 404.

Here is the code that we have written :
Our function is written using the sample code on the below address :
Easy way to bring a php variable on flash with AS2
but it does not return the translated result . when I set the return String value to e variable the function work . but when I set the return to $output variable it does not function .
Action Script 2 Code :
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// define onLoad Callback
lv.onLoad = onLoadCallBack;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", lv, "POST");
var $output;
// onLoad Callback
function onLoadCallBack(succes)
{
// if succes
if(succes)
{
// trace variables
$output = this.lVarresult;
}
else
{
// loading failed
$output = "Loading Error!!";
}
}
return $output;
}
=============================================================
Edit :
The PHP (google-translate-result.php) Code is changed :
$_POST changed to $_GET and now the result php code is working itself through using this url :
Server_URL/google-translate-result.php?sVar1=fa&sVar2=en&sVar3=%DA%A9%D8%AA%D8%A7%D8%A8%20%D8%AA%D8%B3%D8%AA
but still the ActionScript does not return the Translated Result .
=============================================================
PHP Code (google-translate-result.php) :
<?php
require_once('GoogleTranslate.php');
// get variables
$var1 = $_GET['sVar1'];
$var2 = $_GET['sVar2'];
$var3 = $_GET['sVar3'];
$result = GoogleTranslate::translate($var1,$var2,$var3);
// send variables
echo "&lVarresult=$result&";
PHP Code (GoogleTranslate.php) :
<?php
/**
* GoogleTranslate.class.php
*
* Class to talk with Google Translator for free.
*
* #package PHP Google Translate Free;
* #category Translation
* #author Adrián Barrio Andrés
* #author Paris N. Baltazar Salguero <sieg.sb#gmail.com>
* #copyright 2016 Adrián Barrio Andrés
* #license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* #version 2.0
* #link https://statickidz.com/
*/
/**
* Main class GoogleTranslate
*
* #package GoogleTranslate
*
*/
class GoogleTranslate
{
/**
* Retrieves the translation of a text
*
* #param string $source
* Original language of the text on notation xx. For example: es, en, it, fr...
* #param string $target
* Language to which you want to translate the text in format xx. For example: es, en, it, fr...
* #param string $text
* Text that you want to translate
*
* #return string a simple string with the translation of the text in the target language
*/
public static function translate($source, $target, $text)
{
// Request translation
$response = self::requestTranslation($source, $target, $text);
// Get translation text
// $response = self::getStringBetween("onmouseout=\"this.style.backgroundColor='#fff'\">", "</span></div>", strval($response));
// Clean translation
$translation = self::getSentencesFromJSON($response);
return $translation;
}
/**
* Internal function to make the request to the translator service
*
* #internal
*
* #param string $source
* Original language taken from the 'translate' function
* #param string $target
* Target language taken from the ' translate' function
* #param string $text
* Text to translate taken from the 'translate' function
*
* #return object[] The response of the translation service in JSON format
*/
protected static function requestTranslation($source, $target, $text)
{
// Google translate URL
$url = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e";
$fields = array(
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text)
);
// URL-ify the data for the POST
$fields_string = "";
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
/**
* Dump of the JSON's response in an array
*
* #param string $json
* The JSON object returned by the request function
*
* #return string A single string with the translation
*/
protected static function getSentencesFromJSON($json)
{
$sentencesArray = json_decode($json, true);
$sentences = "";
foreach ($sentencesArray["sentences"] as $s) {
$sentences .= isset($s["trans"]) ? $s["trans"] : '';
}
return $sentences;
}
}

According to the Comments of the previous answer Action Script 2 Code changed to:
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
var result_lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", result_lv, "POST");
return result_lv.lVarresult;
}

Related

Using GET to retrieve Data from my Webpage

I'm trying to use an ESP8266 NodeMCU to retrieve data from a database on my web page to control a LED. I'm struggling with the code on both sides for the ESP8266 to ask for the data and the web page to return it. I have the web page and database built. Here is the relevant bit of the server side PHP file, which isn't working....
if(!empty($_GET['mode']) && !empty($_GET['brightness']))
{
$mode = $_GET['mode'];
$brightness = $_GET['brightness'];
$sql = "SELECT * FROM config ORDER BY id DESC LIMIT 1 (mode, brightness)
$result = $conn->query($sql);
SELECT fields FROM table ORDER BY id DESC LIMIT 1;
VALUES ('".$mode."', '".$brightness."')";
if ($conn->query($sql) === TRUE) {
echo "1" . $row["id"]."<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
<code>
and on the ESP8266 side....
getData = "?mode=" "&brightness=";
Link = "http://***.com/Feed.php" + getData;
http.begin(Link); //Specify request destination
int httpCode = http.GET();
String payload = http.getString();
Mode = payload.substring(0,3);
String Brightness = payload.substring (4,6);
Thanks in advance!
I changed my approach and got it working. Instead of trying to return data from the web page to the ESP8266 I displayed the data on a very simple page....
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
if (mysqli_connect_errno()) { echo "Failed to connect to config: " . mysqli_connect_error(); }
$result = mysqli_query($con,"SELECT * FROM config ORDER BY id DESC LIMIT 1");
while ($row = $result->fetch_assoc()) {
$mode = $row[mode]; $brightness = $row[brightness]; $speed = $row[speed];
print $mode;
print $brightness;
print $speed;
}
?>
and then had the ESP download the entire page and parsed out the data using substring like so...
HTTPClient http; //Declare object of class HTTPClient
Link = "http://*****.com/*****.php";
http.begin(Link); //Specify request destination
int httpCode = http.GET(); //Send the request
String payload = http.getString(); //Get the response payload
Mode = payload.substring(156,158).toInt();
Speed = payload.substring(158,160).toInt();
Brightness = payload.substring(160,162).toInt();

TYPO3 8 LTS how to generate frontend page URL in CLI/Scheduler context

I'm trying to figure out how to generate absolute frontend page URLs from CLI/Scheduler context. I've created the following helper class:
class FrontendUrlProvider
{
/**
* #var ObjectManagerInterface
*/
private $objectManager;
/**
* #var LoggerInterface
*/
private $logger;
/**
* #param ObjectManagerInterface $objectManager
* #param LoggerInterface $logger
*/
public function __construct(ObjectManagerInterface $objectManager, LoggerInterface $logger)
{
$this->objectManager = $objectManager;
$this->initializeTimeTracker();
$this->logger = $logger;
}
/**
* #param int $pageId
* #param int $languageId
* #return Uri
*/
public function pageUrl($pageId, $languageId)
{
$url = '';
$this->logger->error('generating preview link');
try {
$this->initializeTypoScriptFrontend($pageId);
$this->setUpPageDomainIfCliContext($pageId);
$contentRenderer = $this->objectManager->get(ContentObjectRenderer::class);
$command = $this->linkCommand($pageId, $languageId);
$url = $contentRenderer->typoLink_URL($command);
$this->logger->error("preview link is: $url");
} catch (\Exception $exception) {
$this->logger->error($exception->getMessage());
$this->logger->error($exception->getTraceAsString());
}
return new Uri($url);
}
private function initializeTimeTracker()
{
if (!is_object($GLOBALS['TT'])) {
$GLOBALS['TT'] = new \TYPO3\CMS\Core\TimeTracker\NullTimeTracker();
}
}
/**
* #param int $pageId
*/
private function initializeTypoScriptFrontend($pageId)
{
if (isset($GLOBALS['TSFE']) && is_object($GLOBALS['TFSE'])) {
return;
}
$GLOBALS['TSFE'] = $this->objectManager->get(TypoScriptFrontendController::class, $GLOBALS['TYPO3_CONF_VARS'], $pageId, '');
$GLOBALS['TSFE']->sys_page = $this->objectManager->get(PageRepository::class);
$GLOBALS['TSFE']->sys_page->init(false);
$GLOBALS['TSFE']->tmpl = $this->objectManager->get(TemplateService::class);
$GLOBALS['TSFE']->tmpl->init();
$GLOBALS['TSFE']->connectToDB();
$GLOBALS['TSFE']->initFEuser();
$GLOBALS['TSFE']->determineId();
$GLOBALS['TSFE']->initTemplate();
$GLOBALS['TSFE']->getConfigArray();
}
/**
* #param int $pageId
*/
private function setUpPageDomainIfCliContext($pageId)
{
if (!isset($_SERVER['HTTP_HOST']) || !$_SERVER['HTTP_HOST']) {
$domainData = $GLOBALS['TSFE']->getDomainDataForPid($pageId);
if (is_array($domainData) && isset($domainData['domainName']) && !empty($domainData['domainName'])) {
$_SERVER['HTTP_HOST'] = $domainData['domainName'] ?: '';
}
}
}
/**
* #param int $pageId
* #param int $languageId
* #return array
*/
private function linkCommand($pageId, $languageId)
{
$languageQuery = http_build_query(['L' => $languageId], null, '&', PHP_QUERY_RFC3986);
return array(
'parameter' => $pageId,
'useCacheHash' => false,
'forceAbsoluteUrl' => true,
'linkAccessRestrictedPages' => true,
'additionalParams' => '&' . $languageQuery,
);
}
}
I'm at the point that it works fine in TYPO3 7 LTS, as long as there's a domain record for the root line.
However this same snippet doesn't work in TYPO3 8 LTS and I need it working for both 7 and 8 at the same time. Obviously, I have set the domain record on the root line in v8, I cleared all the caches, etc. but I can't get an absolute URL in place. I only get the relative URL. At this point I'm not that interested in realUrl or anything like that.
For TYPO3 7 I basically reverse engineered it but with TYPO3 8 it seems a bit more complicated. Do you know what can I do more to get the page frontend URL?
It seems that the issue was an internal cache of the GeneralUtility, which cached a null value for the HTTP_HOST of $_SERVER superglobal.
Therefore the following line from my example above had no effect
$_SERVER['HTTP_HOST'] = $domainData['domainName'] ?: '';
In order to make it work under the CLI/Scheduler scope I had to clear the internal cache of the GeneralUtility by calling
TYPO3\CMS\Core\Utility\GeneralUtility::flushInternalRuntimeCaches();
before making a call to $contentRenderer->typoLink_URL($command);
Now frontend URL generation works fine on both TYPO3 7 and 8 LTS.
https://wissen.netzhaut.de/typo3/extensionentwicklung/typolink-realurl-in-scheduler-tasks/
But really: I'd recommend using a curl call against a custom page which will deliver the link (sort of as a rest API) - because thereby you go around almost all issues - and there are more beyond not having tsfe (e.g. safePath \ images).

nicUpload says "Invalid Upload ID", cant make it works

Im trying to implement nicEdit with the nicupload plugin, but when I select a file to upload it says "Failed to upload image", and the server response says "Invalid Upload ID".
This is the code that calls the script and initializes:
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">//<![CDATA[
bkLib.onDomLoaded(function() {
new nicEditor({uploadURI : '../../nicedit/nicUpload.php'}).panelInstance('area1');
});
//]]>
</script>
The path to nicUpload.php is correct, and the code is the one that can be found in the documentation: http://nicedit.com/src/nicUpload/nicUpload.js
I made the upload folder changes, and set write permissions. According to the documentation (http://wiki.nicedit.com/w/page/515/Configuration%20Options), thats all, but i keep getting errors. Any ideas?
After looking for an solution a long time (lot of posts without real solution), i now fixed the code myself. I'm now able to upload an image to my own server. Thx to firebug and eclipse ;-)
The main problem is that the nicUpload.php is old and not working with the current nicEdit-Upload function.
Missing is the error handling, feel free to add this...
Add the nicEditor to your php file and configure it to use the nicEdit.php:
new nicEditor({iconsPath : 'pics/nicEditorIcons.gif', uploadURI : 'script/nicUpload.php'}
Download the nicEdit.js uncompressed and change the following lines in nicEdit.js:
uploadFile : function() {
var file = this.fileInput.files[0];
if (!file || !file.type.match(/image.*/)) {
this.onError("Only image files can be uploaded");
return;
}
this.fileInput.setStyle({ display: 'none' });
this.setProgress(0);
var fd = new FormData();
fd.append("image", file);
fd.append("key", "b7ea18a4ecbda8e92203fa4968d10660");
var xhr = new XMLHttpRequest();
xhr.open("POST", this.ne.options.uploadURI || this.nicURI);
xhr.onload = function() {
try {
var res = JSON.parse(xhr.responseText);
} catch(e) {
return this.onError();
}
//this.onUploaded(res.upload); // CHANGE HERE
this.onUploaded(res);
}.closure(this);
xhr.onerror = this.onError.closure(this);
xhr.upload.onprogress = function(e) {
this.setProgress(e.loaded / e.total);
}.closure(this);
xhr.send(fd);
},
onUploaded : function(options) {
this.removePane();
//var src = options.links.original; // CHANGE HERE
var src = options['url'];
if(!this.im) {
this.ne.selectedInstance.restoreRng();
//var tmp = 'javascript:nicImTemp();';
this.ne.nicCommand("insertImage", src);
this.im = this.findElm('IMG','src', src);
}
var w = parseInt(this.ne.selectedInstance.elm.getStyle('width'));
if(this.im) {
this.im.setAttributes({
src : src,
width : (w && options.image.width) ? Math.min(w, options.image.width) : ''
});
}
}
Change the nicUpload.php like this
<?php
/* NicEdit - Micro Inline WYSIWYG
* Copyright 2007-2009 Brian Kirchoff
*
* NicEdit is distributed under the terms of the MIT license
* For more information visit http://nicedit.com/
* Do not remove this copyright message
*
* nicUpload Reciever Script PHP Edition
* #description: Save images uploaded for a users computer to a directory, and
* return the URL of the image to the client for use in nicEdit
* #author: Brian Kirchoff <briankircho#gmail.com>
* #sponsored by: DotConcepts (http://www.dotconcepts.net)
* #version: 0.9.0
*/
/*
* #author: Christoph Pahre
* #version: 0.1
* #description: different modification, so that this php file is working with the newest nicEdit.js (needs also modification - #see)
* #see http://stackoverflow.com/questions/11677128/nicupload-says-invalid-upload-id-cant-make-it-works
*/
define('NICUPLOAD_PATH', '../images/uploadedImages'); // Set the path (relative or absolute) to
// the directory to save image files
define('NICUPLOAD_URI', '../images/uploadedImages'); // Set the URL (relative or absolute) to
// the directory defined above
$nicupload_allowed_extensions = array('jpg','jpeg','png','gif','bmp');
if(!function_exists('json_encode')) {
die('{"error" : "Image upload host does not have the required dependicies (json_encode/decode)"}');
}
if($_SERVER['REQUEST_METHOD']=='POST') { // Upload is complete
$file = $_FILES['image'];
$image = $file['tmp_name'];
$id = $file['name'];
$max_upload_size = ini_max_upload_size();
if(!$file) {
nicupload_error('Must be less than '.bytes_to_readable($max_upload_size));
}
$ext = strtolower(substr(strrchr($file['name'], '.'), 1));
#$size = getimagesize($image);
if(!$size || !in_array($ext, $nicupload_allowed_extensions)) {
nicupload_error('Invalid image file, must be a valid image less than '.bytes_to_readable($max_upload_size));
}
$filename = $id;
$path = NICUPLOAD_PATH.'/'.$filename;
if(!move_uploaded_file($image, $path)) {
nicupload_error('Server error, failed to move file');
}
$status = array();
$status['done'] = 1;
$status['width'] = $size[0];
$rp = realpath($path);
$status['url'] = NICUPLOAD_URI ."/".$id;
nicupload_output($status, false);
exit;
}
// UTILITY FUNCTIONS
function nicupload_error($msg) {
echo nicupload_output(array('error' => $msg));
}
function nicupload_output($status, $showLoadingMsg = false) {
$script = json_encode($status);
$script = str_replace("\\/", '/', $script);
echo $script;
exit;
}
function ini_max_upload_size() {
$post_size = ini_get('post_max_size');
$upload_size = ini_get('upload_max_filesize');
if(!$post_size) $post_size = '8M';
if(!$upload_size) $upload_size = '2M';
return min( ini_bytes_from_string($post_size), ini_bytes_from_string($upload_size) );
}
function ini_bytes_from_string($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
function bytes_to_readable( $bytes ) {
if ($bytes<=0)
return '0 Byte';
$convention=1000; //[1000->10^x|1024->2^x]
$s=array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB');
$e=floor(log($bytes,$convention));
return round($bytes/pow($convention,$e),2).' '.$s[$e];
}
?>
You can manually pass an id to your script: e.g nicUpload.php?id=introPicHeader and it will become introPicHeader.jpg (or appropriate extension) in the images folder you defined.
However, I have noticed that this script is broken and cannot access the configuration option uploadURI if specified directly in nicEdit.js during the nicEditorAdvancedButton.extend({. This causes access to an relatively pathed "Unknown" resource, causing an error.
The documentation implies otherwise and the fact that the nicURI was specified here for imgur.com (maybe as a default) gave me the impression I could also add a uploadURI reference to the nicUpload.php script in a single place rather than on every editor instantiation.
Update
This works if you pass it during instantiation, which I guess does allow for easy dynamic id population.
Unfortunately, the nicUpload.php is riddled with errors and it's output is not JSON. The editor expects to parse JSON and finds a script tag and errors with unexpected token "<".
There are a raft of other errors which I will attempt to identify:
In nicEdit.js
A.append("image") should be infact A.append("nicImage")
this.onUploaded(D.upload) should become this.onUploaded(D)
this.onUploaded(D) should be moved to within the try block after var D=JSON.parse(C.responseText) to fix variable scope issues
B.image.width needs to become B.width
In nicUpload.php
JSON output is not formed correctly, comment out html output and output just json_encode($status).
JSON output needs to return a key/value pair named links rather than url although renaming the var D=B.links to var D=B.url in nicEdit.js would also suffice as a fix.
Both php and javascript code leaves a lot to be desired, I get many errors regularly and have been fixing them myself.

ActionScript retrieval from PHP and returns null value

I am trying to retrieve data from database through php scripts and display in flash using actionscript 3.
For actionscript 3, I have 2 functions:
private var postArrayTxt:Array;
public function stampTwo() {
// constructor code
var stampNumber1:MovieClip = new stamp1();
var stampNumber2:MovieClip = new stamp2();
var stampNumber3:MovieClip = new stamp3();
postArrayTxt = new Array();
postArrayTxt[0] = stampNumber1;
postArrayTxt[1] = stampNumber2;
postArrayTxt[2] = stampNumber3;
trace("All stamps works");
retrieveDetailsFromDB();
}
The data retrieved from database will be displayed in the various movieclips where it will be calling retrieveDetailsFromDB().
public function retrieveDetailsFromDB():void {
var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myLoader.load(new URLRequest("http://localhost/Converse/stampGalore/tryout.php"));
myLoader.addEventListener(Event.COMPLETE, onDataLoad);
// Error Handling
myLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
// Could be an error or just a message
myLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
function onDataLoad(evt:Event): void {
//var loader:Loader = new Loader();
//stamp221.addChild(loader);
//loader.load(new URLRequest(evt.target.data.facebookRemarks));
var delimiter:String = "|^_^|";
var stamp:String = evt.target.data.databaseRemarks;
trace(stamp);
var stampRemarkArr:Array = new Array();
stampRemarkArr = stamp.split(delimiter);
for (var i:Number=0; i<stampRemarkArr.length; i++) {
postArrayTxt[i].text = String(stampRemarkArr[i]);
trace("ended");
}
}
// error callbacks
function onIOError(evt:IOErrorEvent) {
trace("IOError: " + evt.text);
}
function onHTTPStatus(evt:HTTPStatusEvent) {
trace("HTTPStatus: " + evt.status);
}
function onSecurityError(evt:SecurityErrorEvent) {
trace("SecurityError: " + evt.text);
}
}
Last but not least, this is my php script.
<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
include_once "mysqli.connect.php";
$sql = "SELECT remarks FROM stamp";
$result = $mysqli->query($sql);
if ($mysqli->errno)
{
error_log($mysqli->error);
return;
}
$facebook = "";
$counter = 0;
while ($row = $result->fetch_array())
{
$database = $row["remarks"];
$delimiter = "|^_^|";
if ($counter == 0) {
$facebook .=$database;
} else {
//Use a delimiter "|^_^|" to seperate the records
$facebook .= $delimiter . $database;
}
$counter++;
}
$mysqli->close();
echo "databaseRemarks=" . $facebook;
?>
if I were to run the php script itself, the data could be retrieved from database. However, if I run in Flash, it returns a null value. Please help me as I have wasted a lot of time on this retrieve function. Thank you
This won't work:
var stamp:String = evt.target.data.databaseRemarks;
Flash doesn't know in which format is your data so you need to parse it first. So first read the data:
var rawData:String = evt.currentTarget.data;
Then parse it:
var parsedData:* = someFunctionToParseYourData(rawData);

Including OAuth in PHP stops OAuth separate Class from working

I am working with Google Analytics and Google Adwords, and I've installed the OAuth "pecl" package to get the Google Adwords working and now my Analytics code doesn't work.
When I open up my php.ini file and comment out (and restart apache)
extension=oauth.so
The analytics example code works (I adapted it from the OAuth playground that google has open sourced). Is there any way that I could keep my example code from working? I have found that the script crashes on this line:
require_once('common.inc.php');
Common.inc.php looks like this:
<?php
/* Copyright (c) 2009 Google Inc.
*
* 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: Eric Bidelman <e.bidelman#google.com>
*/
$PRIV_KEY_FILE = '/path/to/your/rsa_private_key.pem';
// OAuth library - http://oauth.googlecode.com/svn/code/php/
require_once('OAuth.php');
// Google's accepted signature methods
$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
$rsa_method = new OAuthSignatureMethod_RSA_SHA1();
$SIG_METHODS = array($rsa_method->get_name() => $rsa_method,
$hmac_method->get_name() => $hmac_method);
/**
* Makes an HTTP request to the specified URL
*
* #param string $http_method The HTTP method (GET, POST, PUT, DELETE)
* #param string $url Full URL of the resource to access
* #param array $extraHeaders (optional) Additional headers to include in each
* request. Elements are header/value pair strings ('Host: example.com')
* #param string $postData (optional) POST/PUT request body
* #param bool $returnResponseHeaders True if resp. headers should be returned.
* #return string Response body from the server
*/
function send_signed_request($http_method, $url, $extraHeaders=null,
$postData=null, $returnResponseHeaders=true) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// Return request headers in the reponse
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
// Return response headers ni the response?
if ($returnResponseHeaders) {
curl_setopt($curl, CURLOPT_HEADER, true);
}
$headers = array();
//$headers[] = 'GData-Version: 2.0'; // use GData v2 by default
if (is_array($extraHeaders)) {
$headers = array_merge($headers, $extraHeaders);
}
// Setup default curl options for each type of HTTP request.
// This is also a great place to add additional headers for each request.
switch($http_method) {
case 'GET':
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
break;
case 'POST':
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
break;
case 'PUT':
$headers[] = 'If-Match: *';
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
break;
case 'DELETE':
$headers[] = 'If-Match: *';
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
break;
default:
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
// Execute the request. If an error occures, fill the response body with it.
$response = curl_exec($curl);
if (!$response) {
$response = curl_error($curl);
}
// Add server's response headers to our response body
$response = curl_getinfo($curl, CURLINFO_HEADER_OUT) . $response;
curl_close($curl);
return $response;
}
/**
* Takes XML as a string and returns it nicely indented
*
* #param string $xml The xml to beautify
* #param boolean $html_output True if returned XML should be escaped for HTML.
* #return string The beautified xml
*/
function xml_pretty_printer($xml, $html_output=false) {
$xml_obj = new SimpleXMLElement($xml);
$level = 2;
// Get an array containing each XML element
$xml = explode("\n", preg_replace('/>\s*</', ">\n<", $xml_obj->asXML()));
// Hold current indentation level
$indent = 0;
$pretty = array();
// Shift off opening XML tag if present
if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) {
$pretty[] = array_shift($xml);
}
foreach ($xml as $el) {
if (preg_match('/^<([\w])+[^>\/]*>$/U', $el)) {
// opening tag, increase indent
$pretty[] = str_repeat(' ', $indent) . $el;
$indent += $level;
} else {
if (preg_match('/^<\/.+>$/', $el)) {
$indent -= $level; // closing tag, decrease indent
}
if ($indent < 0) {
$indent += $level;
}
$pretty[] = str_repeat(' ', $indent) . $el;
}
}
$xml = implode("\n", $pretty);
return $html_output ? htmlentities($xml) : $xml;
}
/**
* Joins key/value pairs by $inner_glue and each pair together by $outer_glue.
*
* Example: implode_assoc('=', '&', array('a' => 1, 'b' => 2)) === 'a=1&b=2'
*
* #param string $inner_glue What to implode each key/value pair with
* #param string $outer_glue What to impode each key/value string subset with
* #param array $array Associative array of query parameters
* #return string Urlencoded string of query parameters
*/
function implode_assoc($inner_glue, $outer_glue, $array) {
$output = array();
foreach($array as $key => $item) {
$output[] = $key . $inner_glue . urlencode($item);
}
return implode($outer_glue, $output);
}
/**
* Explodes a string of key/value url parameters into an associative array.
* This method performs the compliment operations of implode_assoc().
*
* Example: explode_assoc('=', '&', 'a=1&b=2') === array('a' => 1, 'b' => 2)
*
* #param string $inner_glue What each key/value pair is joined with
* #param string $outer_glue What each set of key/value pairs is joined with.
* #param array $array Associative array of query parameters
* #return array Urlencoded string of query parameters
*/
function explode_assoc($inner_glue, $outer_glue, $params) {
$tempArr = explode($outer_glue, $params);
foreach($tempArr as $val) {
$pos = strpos($val, $inner_glue);
$key = substr($val, 0, $pos);
$array2[$key] = substr($val, $pos + 1, strlen($val));
}
return $array2;
}
?>
I was wondering if anybody had experience with this extension. Perhaps I could rename some of the OAuth classnames? It seems to be that some of these classes are conflicting causing this not to work. I'm going to need to have these scripts working side by side, (ie. under the same php.ini configuration).
Another alternative that I have been wondering about: Is there a way to include an extension in the php.ini file for only one script (Adwords Script)? And then by default not include the extension?
Any advice would help! Thank you
I actually got around this by using dl() to dynamically load the extension
http://php.net/manual/en/function.dl.php

Resources