Php5.3 magic method __call and Memory - memory

I have a script with using a lot of Magic method __call.
The script have 15 000 iterance and the object is bigger.
After every iterance the memory grows. I use unset or $val = null; but the memory continues to grow.
What can i do?
An Exemple :
$data = null;
foreach ($field['method']['actions'] as $action) {
// si l'action ne concerne pas le name space principal
if (!array_key_exists('get', $action)) {
continue;
}
if (array_key_exists('begin', $action)) {
$data .= $action['begin'];
}
if (array_key_exists('action', $action)) {
$obj = $notice->__call('get' . ucfirst($action['action']));
$notice->clear();
if (is_object($obj)) {
$rsl = $obj->__call('get' . ucfirst($action['get']));
$obj->clear();
echo "\n" . 'get' . ucfirst($action['get']) . ' : ' . number_format(memory_get_usage());
$data .= $rsl;
unset($rsl);
} else {
$data .='';
}
$obj = null;
} else {
$data .= $notice->__call('get' . ucfirst($action['get']));
$notice->clear();
echo "\n" . 'get' . ucfirst($action['get']) . ' : ' . number_format(memory_get_usage());
}
if (array_key_exists('end', $action)) {
$data .= $action['end'];
}
}
//--
class Notice{
//--
protected $instanceObj = null;
public function __call($name, $arguments = null) {
$this->instanceObj = $this->$name($arguments);
return $this->instanceObj;
}
public function clear(){
$this->instanceObj = null;
}
//--
}
An exemple of log file :
getField : 24,446,752
getField : 24,447,352
getField : 24,447,720
getField : 24,448,096
getField : 24,483,320
getField : 24,483,336
getField : 24,483,728
...
getField : 25,267,936
...
getField : 35,596,712
...
You can see the memory never stop to brows.

The only solution is to sequence the script several execution. The problem is not PHP Symfony but generates too many objects. So I run the script Pacquet x. Otherwise it led to a saturation of memory.

Related

Google Translate in Flash (SWF) Action Script

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;
}

Hooking up OpenCart with an iOS App via web services

I need to develop an iOS app that fetches data from an OpenCart installation online. This includes ordering online, adding things to wish list, creating a user account. Logging in to an already existing user account and everything else that open cart offers. Basically, it is an iOS version of the OpenCart website that connects to the OpenCart's MySQL database.
I googled a little bit but couldn't find a proper API that I can use to hookup my app with OpenCart. What other options do I have? Does OpenCart offer any web service? (Like WordPress offers XML-RPC). Or is there a good API that I can use?
Unfortunately, OpenCart does not offer any API straight away. (that's for an answer).
There is an opensource OpenCart API project on GitHub that you can download (google it, I do not remember it's name) but this offers only the very limited and basic methods for just reading of data (if I remember correctly there were methods for getting the list of categories, list of products and product details and few more).
This could be your starting point: fork, add methods, share. Or create your own API from a scratch if you wish (again, sharing will be highly welcomed :-) - I believe you could even find users willing to pay for it - I would have created one if I had time - but sadly I have not...).
<?php
include_once 'functions.php';
class ControllerJsonJson extends Controller {
public function index() {
// Menu
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$data['categories'] = array();
$categories = $this->model_catalog_category->getCategories(0);
foreach ($categories as $category) {
if ($category['top']) {
// Level 2
$children_data = array();
$children = $this->model_catalog_category->getCategories($category['category_id']);
foreach ($children as $child) {
if ($child['image']) {
$childpopup = $this->model_tool_image->resize($child['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
$childthumb = $this->model_tool_image->resize($child['image'], 74,74);
} else {
$childthumb='';
$childpopup = '';
}
$filter_data = array(
'filter_category_id' => $child['category_id'],
'filter_sub_category' => true
);
$children_data[] = array(
'popup'=>$childpopup,
'thumb'=>$childthumb,
'id' => $child['category_id'],
'name' => $child['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
'href' => $this->url->link('product/category', 'path=' . $category['category_id'] . '_' . $child['category_id'])
);
}
if ($category['image']) {
$categorypopup = $this->model_tool_image->resize($category['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
$categorythumb = $this->model_tool_image->resize($category['image'], 74,74);
} else {
$categorypopup = '';
$categorythumb='';
}
// Level 1
$data['categories'][] = array(
'popup' => $categorypopup,
'thumb' => $categorythumb,
'id' => $category['category_id'],
'name' => $category['name'],
'children' => $children_data,
'column' => $category['column'] ? $category['column'] : 1,
'href' => $this->url->link('product/category', 'path=' . $category['category_id'])
);
}
}
$obj=new functions();
echo $obj->json_pretty_encode($data);
}
}
<?php
class functions {
//put your code here
public function json_pretty_encode($obj){
header("Content-type: application/json");
$json = json_encode($obj);
if (!$json) return $json;
$f = '';
$len = strlen($json);
$depth = 0;
$newline = false;
for ($i = 0; $i < $len; ++$i)
{
if ($newline)
{
$f .= "\n";
$f .= str_repeat(' ', $depth);
$newline = false;
}
$c = $json[$i];
if ($c == '{' || $c == '[')
{
$f .= $c;
$depth++;
$newline = true;
}
else if ($c == '}' || $c == ']')
{
$depth--;
$f .= "\n";
$f .= str_repeat(' ', $depth);
$f .= $c;
}
else if ($c == '"')
{
$s = $i;
do {
$c = $json[++$i];
if ($c == '\\')
{
$i += 2;
$c = $json[$i];
}
} while ($c != '"');
$f .= substr($json, $s, $i-$s+1);
}
else if ($c == ':')
{
$f .= ': ';
}
else if ($c == ',')
{
$f .= ',';
$newline = true;
}
else
{
$f .= $c;
}
}
return $f;
}
}

.swf file upload script files will not upload

Im trying to get this very basic script to upload .swf files to my server with no luck.
I get an invalid file error when i try to upload.
.jpg,gifs,pngs all upload fine.
I tried changing a few things putting swf where jpg is etc. but no joy.
Is it not possible to upload swf files in this way?
and help appreciated, many thanks.
`
Filename:
<?php
$allowedExts = array("gif", "jpeg", "jpg","swf","png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "application/x-shockwave-flash/swf")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 8388608)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?> `
function addAdFields($post,$files){
//print_r( $files);
$allowedExts = array("gif", "jpeg", "jpg", "png" ,"tiff","tif","swf");
$fileType=$files["bannerType"]["type"];
$tmpName=$files["bannerType"]["tmp_name"];
$fileName=$files["bannerType"]["name"];
$imageName = mysql_real_escape_string($files["bannerType"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($files["bannerType"]["tmp_name"]));
$imageType = mysql_real_escape_string($files["bannerType"]["type"]);
list($width, $height, $type, $attr) = getimagesize($tmpName);
$dimArr= array($width, $height);
$temp = explode(".", $fileName);
$files["bannerType"]["name"];
$extension = end($temp);
$fileTmpName= mysql_real_escape_string($tmpName);
$curDate = "";
$ipadd = $_SERVER['REMOTE_ADDR'];
$camDetail=explode('_',$post['campaignType']);
$this -> tableName = "_ads";
$this -> fieldValues['campaignID'] = $camDetail[0];
$this -> fieldValues['campaignName'] =$camDetail[1];
$this -> fieldValues['adTitle'] = $post['adTitle'];
$this -> fieldValues['bannerID'] = $post['bannerType'];
if($_SESSION['bannerTyp']=='Placement')
{
$this -> fieldValues['uploadFileName'] = $post['placementText'];
}
else{
$this -> fieldValues['uploadFileName'] = $imageName;
$this -> fieldValues['uploadedFile'] = $imageData;
}
$this -> fieldValues['dimantation'] = json_encode($dimArr);
$this -> fieldValues['addDateTime'] = $curDate;
$this -> fieldValues['addIpAddress'] = $ipadd;
$this->insert();
//echo $this->query;
header('Location: main.html?action=add-ads&menuid=155');
}

How to avoid fatal error: Uncaught OAuthException when using cron job

Hi hope somone can help with this one. Ive had a birthday reminder app built, that aquires the usual permissions including offline access etc.
The app requires a daily cron job to be run on my server.
When I run the cron file a recieve the below error
Fatal error: Uncaught OAuthException: Invalid OAuth access token signature. thrown in blah/base_facebook.php on line 1140;
Is there a common reason for the error, am i doing anything wrong that stands out, and should i be displaying more code to get help from people?
below are the lines leading up to the error. My code ends on line 1140;
<?php
$name = 'api';
if (isset($READ_ONLY_CALLS[strtolower($method)])) {
$name = 'api_read';
} else if (strtolower($method) == 'video.upload') {
$name = 'api_video';
}
return self::getUrl($name, 'restserver.php');
}
protected function getUrl($name, $path='', $params=array())
{
$url = self::$DOMAIN_MAP[$name];
if ($path) {
if ($path[0] === '/') {
$path = substr($path, 1);
}
$url .= $path;
}
if ($params) {
$url .= '?' . http_build_query($params, null, '&');
}
return $url;
}
protected function getCurrentUrl() {
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
$protocol = 'http://';
}
$currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$parts = parse_url($currentUrl);
$query = '';
if (!empty($parts['query'])) {
// drop known fb params
$params = explode('&', $parts['query']);
$retained_params = array();
foreach ($params as $param) {
if ($this->shouldRetainParam($param)) {
$retained_params[] = $param;
}
}
if (!empty($retained_params)) {
$query = '?'.implode($retained_params, '&');
}
}
// use port if non default
$port =
isset($parts['port']) &&
(($protocol === 'http://' && $parts['port'] !== 80) ||
($protocol === 'https://' && $parts['port'] !== 443))
? ':' . $parts['port'] : '';
// rebuild
return $protocol . $parts['host'] . $port . $parts['path'] . $query;
}
protected function shouldRetainParam($param) {
foreach (self::$DROP_QUERY_PARAMS as $drop_query_param) {
if (strpos($param, $drop_query_param.'=') === 0) {
return false;
}
}
return true;
}
protected function throwAPIException($result) {
$e = new FacebookApiException($result);
?>
CRON.php
<?php
require_once("src/facebook.php");
include("custom.php");
set_time_limit(0);
$config = array();
$config['array'] = $appID;
$config['secret'] = $appSecret;
$facebook = new Facebook($config);
$day = abs(date("j"));
$month = abs(date("n"));
$result = mysql_query("SELECT uid, uid2, name2 FROM birthdays WHERE birthmonth = '$month' AND birthday = '$day'");
while(($row = mysql_fetch_assoc($result)) && mysql_num_rows($result)) {
$link = $hostURL.'post.php?uid='.$row['uid'].'&uid2='.$row['uid2'];
$facebook->api('/'.$row['uid'].'/feed', 'POST',
array(
'link' => $link,
'from' => '299185790135651',
'picture' => $hostURL.'image.php?id='.$row['uid2'],
'name' => 'Send Cake',
'message' => 'It\'s '.$row['name2'].'\'s birthday today! Send them a virtual cake!',
'caption' => 'Sponsored by Intercake Ltd'
));
}
?>
also... what is 'from' => '299185790135651', ?
want to check my developer has put the right number here. Thanks
The best way to handle this is to use a try...catch statement. As follows:
try {
// some code that calls Facebook
} catch ( Exception $e ) {
// $e will contain the error - do what you want with it here
// e.g. log it or send an email alert etc.
}
The 'from' => '299185790135651' is a User / Page ID that publishes the message to the Feed. In this case, it's pointing to a Test Facebook Page.

preg_replace is not working

I want to convert every pattern >>'number' (eg: >>4) on users' threads automatically to
>>4
So I made this function but it's not working.
Could you tell me what is wrong with the function?
function autolink($content) {
$pattern = "/>>[0-9]/i" ;
$replacement = ">>\\0";
return preg_replace($pattern, $replacement, $content, -1);
This function works well. This function automatically converts the urls into clickable hyperlink. I don't know why the first function isn't working.
function autolink2($contents) {
$pattern = "/(http|https|ftp|mms):\/\/[0-9a-z-]+(\.[_0-9a-z-]+)+(:[0-9]{2,4})?\/?"; // domain+port
$pattern .= "([\.~_0-9a-z-]+\/?)*"; // sub roots
$pattern .= "(\S+\.[_0-9a-z]+)?" ; // file & extension string
$pattern .= "(\?[_0-9a-z#%&=\-\+]+)*/i"; // parameters
$replacement = "\\0";
return preg_replace($pattern, $replacement, $contents, -1);}
Try this
function autolink($content){
return preg_replace('#\>\>([0-9]+)#','>>$1', $content);
}
Tested and works.

Resources