Can someone please help. I am getting a fatal error on the following PHP script.
I am getting an error "unidentified method Pass::_createpass()" whick relates to the second last line of the code below.
<?php
$engine = Pass::start('xxxxxxxxxxxxxxxx');
$pass = $engine->createPassFromTemplate(xxxxxxxxxxxxxx);
$engine->redirectToPass($pass);
if (!function_exists('curl_init')) {
throw new Exception('Pass needs the CURL PHP extension.');
}
if (!function_exists('json_decode')) {
throw new Exception('Pass needs the JSON PHP extension.');
}
$engine = Pass::start($appKey);
$values = array(
'first' => 'John',
'last' => 'Platinum',
);
$images = array(
'thumbnail' => 'image1.jpg'
);
$pass = $engine->createPassFromTemplate(5688667418918912, $values, $images);
$passData = $engine->downloadPass($pass);
$engine->redirectToPass($pass);
class Pass
{
private $_appKey = null;
private $_endpoint = 'https://pass.center/api/v1';
private $_debug = false;
private static $_instance = null;
private static $_imageTypes = array('icon', 'logo', 'strip', 'thumbnail', 'background', 'footer');
const VERSION = '0.5';
const USER_AGENT = 'PassSDK-PHP/0.5';
public function __construct($appKey = null, $endpoint = null, $debug = false)
{
if (is_null($appKey)) {
throw new Exception('App Key required');
}
$this->_appKey = $appKey;
if ($endpoint !== null) {
$this->_endpoint = $endpoint;
}
$this->_debug = $debug;
}
public static function start($appKey = null, $endpoint = null, $debug = false)
{
if (self::$_instance == null) {
self::$_instance = new self($appKey, $endpoint, $debug);
}
return self::$_instance;
}
public function createPassFromTemplate($templateId, $values = array(), $images = array())
{
$resource = sprintf("https://xxxxxxx/api/v1/templates/names/Test/pass", $templateId);
return $this->_createPass($resource, $values, $images);
}
}
I hope someone can help me as I am not familiar with Functions PHP.
Thanks All
Rob
The function createPass is missing.
You need something like this:
/**
* Prepares the values and image for the pass and creates it
*
* #param string $resource Resource URL for the pass creation
* #param array $values Values
* #param array $images Images
* #return object Pass
*/
private function _createPass($resource, $values, $images)
{
$multipart = count($images) > 0;
if ($multipart) {
$content = array();
foreach ($images as $imageType => $image) {
$this->_addImage($image, $imageType, $content, $imageType);
}
var_dump($content);
// Write json to file for curl
$jsonPath = array_search('uri', #array_flip(stream_get_meta_data(tmpfile())));
file_put_contents($jsonPath, json_encode($values));
$content['values'] = sprintf('#%s;type=application/json', $jsonPath);
} else {
$content = $values;
}
return $this->_restCall('POST', $resource, $content, $multipart);
}
..And full script here
Related
We have several GPS installed in different units and I am trying to retrieve the messages using the Wialon's Remote API but i am getting this error, can someone please help me? Thanks a lot!:
{"error":4, "reason":"VALIDATE_PARAMS_ERROR: {itemId: long, timeFrom: uint, timeTo: uint, flags: uint, flagsMask: uint, loadCount: uint}"}
Below is my script:
<?php
include('wialon.php');
$wialon_api = new Wialon();
$token = '{token here}';
$result = $wialon_api->login($token);
$json = json_decode($result, true);
if(!isset($json['error'])){
echo $wialon_api->messages_load_interval('{"itemId":24611387,"lastTime":1073741831,"lastCount":1,"flags":0,"flagMask":0,"loadCount":1}');
$wialon_api->logout();
} else {
echo WialonError::error($json['error']);
}
?>
Here is the Wialon Class which i downloaded from their site:
<?php
/* Classes for working with Wialon RemoteApi using PHP
*
* License:
* The MIT License (MIT)
*
* Copyright:
* 2002-2015 Gurtam, http://gurtam.com
*/
/** Wialon RemoteApi wrapper Class
*/
class Wialon{
/// PROPERTIES
private $sid = null;
private $base_api_url = '';
private $default_params = array();
/// METHODS
/** constructor */
function __construct($scheme = 'https', $host = 'hst-api.wialon.com', $port = '', $sid = '', $extra_params = array()) {
$this->sid = '';
$this->default_params = array_replace(array(), (array)$extra_params);
$this->base_api_url = sprintf('%s://%s%s/wialon/ajax.html?', $scheme, $host, mb_strlen($port)>0?':'.$port:'');
}
/** sid setter */
function set_sid($sid){
$this->sid = $sid;
}
/** sid getter */
function get_sid(){
return $this->sid;
}
/** update extra parameters */
public function update_extra_params($extra_params){
$this->default_params = array_replace($this->default_params, $extra_params);
}
/** RemoteAPI request performer
* action - RemoteAPI command name
* args - JSON string with request parameters
*/
public function call($action, $args){
$url = $this->base_api_url;
if (stripos($action, 'unit_group') === 0) {
$svc = $action;
$svc[mb_strlen('unit_group')] = '/';
} else {
$svc = preg_replace('\'_\'', '/', $action, 1);
}
$params = array(
'svc'=> $svc,
'params'=> $args,
'sid'=> $this->sid
);
$all_params = array_replace($this->default_params , $params);
$str = '';
foreach ($all_params as $k => $v) {
if(mb_strlen($str)>0)
$str .= '&';
$str .= $k.'='.urlencode(is_object($v) || is_array($v) ? json_encode($v) : $v);
}
/* cUrl magic */
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $str
);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if($result === FALSE)
$result = '{"error":-1,"message":'.curl_error($ch).'}';
curl_close($ch);
return $result;
}
/** Login
* user - wialon username
* password - password
* return - server response
*/
public function login($token) {
$data = array(
'token' => urlencode($token),
);
$result = $this->token_login(json_encode($data));
$json_result = json_decode($result, true);
if(isset($json_result['eid'])) {
$this->sid = $json_result['eid'];
}
return $result;
}
/** Logout
* return - server responce
*/
public function logout() {
$result = $this->core_logout();
$json_result = json_decode($result, true);
if($json_result && $json_result['error']==0)
$this->sid = '';
return $result;
}
/** Unknonwn methods hadler */
public function __call($name, $args) {
return $this->call($name, count($args) === 0 ? '{}' : $args[0]);
}
}
/** Wialon errorCode to textMessage converter
*/
class WialonError{
/// PROPERTIES
/** list of error messages with codes */
public static $errors = array(
1 => 'Invalid session',
2 => 'Invalid service',
3 => 'Invalid result',
4 => 'Invalid input',
5 => 'Error performing request',
6 => 'Unknow error',
7 => 'Access denied',
8 => 'Invalid user name or password',
9 => 'Authorization server is unavailable, please try again later',
1001 => 'No message for selected interval',
1002 => 'Item with such unique property already exists',
1003 => 'Only one request of given time is allowed at the moment'
);
/// METHODS
/** error message generator */
public static function error($code = '', $text = ''){
$code = intval($code);
if ( isset(self::$errors[$code]) )
$text = self::$errors[$code].' '.$text;
$message = sprintf('%d: %s', $code, $text);
return sprintf('WialonError( %s )', $message);
}
}
?>
I'm working on a function to recursively remove arrays and objects recursively. The problem is that certain recursions may be inside private properties of objects.
below is what I tried as well as the entries I tried to use.
this is my entrie
class TestOBJ{
private $fooClosure = null;
public $bar = 5;
private $myPrivateRecursion = null;
private $aimArrayAndContainsRecursion = [];
public function __construct()
{
$this->fooClosure = function(){
echo 'pretty closure';
};
}
public function setMyPrivateRecursion(&$obj){
$this->myPrivateRecursion = &$obj;
}
public function setObjInsideArray(&$obj){
$this->aimArrayAndContainsRecursion[] = &$obj;
}
}
$std = new stdClass();
$std->std = 'any str';
$std->obj = new stdClass();
$std->obj->other = &$std;
$obj = new TestOBJ();
$obj->bar = new TestOBJ();
$obj->bar->bar = 'hey brow, please works';
$obj->bar->setMyPrivateRecursion($std);
my entrie is var $obj
and this is my function / solution
function makeRecursionStack($vector, &$stack = [], $from = null)
{
if ($vector) {
if (is_object($vector) && !in_array($vector, $stack, true) && !is_callable($vector)) {
$stack[] = &$vector;
if (get_class($vector) === 'stdClass') {
foreach ($vector as $key => $value) {
if (in_array($vector->{$key}, $stack, true)) {
$vector->{$key} = null;
} else {
$vector->{$key} = $this->makeRecursionStack($vector->{$key}, $stack, $key);
}
}
return $vector;
} else {
$object = new \ReflectionObject($vector);
$reflection = new \ReflectionClass($vector);
$properties = $reflection->getProperties();
if ($properties) {
foreach ($properties as $property) {
$property = $object->getProperty($property->getName());
$property->setAccessible(true);
if (!is_callable($property->getValue($vector))) {
$private = false;
if ($property->isPrivate()) {
$property->setAccessible(true);
$private = true;
}
if (in_array($property->getValue($vector), $stack, true)) {
$property->setValue($vector, null);
} else {
//if($property->getName() === 'myPrivateRecursion' && $from === 'bar'){
//$get = $property->getValue($vector);
//$set = $this->makeRecursionStack($get, $stack, $property->getName());
//$property->setValue($vector, $set);
//pre_clear_buffer_die($property->getValue($vector));
//}
$property->setValue($vector, $this->makeRecursionStack($property->getValue($vector), $stack, $property->getName()));
}
if ($private) {
$property->setAccessible(false);
}
}
}
}
return $vector;
}
} else if (is_array($vector)) {
$nvector = [];
foreach ($vector as $key => $value) {
$nvector[$key] = $this->makeRecursionStack($value, $stack, $key);
}
return $nvector;
} else {
if (is_object($vector) && !is_callable($vector)) {
return null;
}
}
}
return $vector;
}
The place where I have comments is where I noticed the problem. if the If is not commented there $get would receive a stdClass that has recursion and this works perfectly and $set would receive the stdClass without recursion. In that order.
$get =
$set =
After this lines
$property->setValue($vector, $set);
pre_clear_buffer_die($property->getValue($vector));
i obtain this
I try to put other value like an bool or null inside property and after set the $set but it's not works.
P.S: pre_clear_buffer_die kill php buffer, init other buffer and show var inside a <pre> after exit from script. Is an debugger function.
I am trying to modify a class that I found that is a Steam API class. I want it to work with codeigniter. I keep getting the error in the question title when I call the getProfileData function. Not sure why it's happening. Here is the code:
The library:
<?php
// Disable XML warnings to avoid problems when SteamCommunity is down
libxml_use_internal_errors(true);
// Use SteamUtility to fetch URLs and other stuff
require_once 'SteamUtility.php';
/**
* SteamUser - Representation of any Steam user profile
*
* #category SteamAPI
* #copyright Copyright (c) 2012 Matt Ryder (www.mattryder.co.uk)
* #license GPLv2 License
* #version v1.3
* #link https://github.com/MattRyder/SteamAPI/blob/master/steam/SteamUser.php
* #since Class available since v1.0
*/
class SteamUser {
private $userID;
private $vanityURL;
private $apiKey;
public $info;
/**
* Constructor
* #param mixed $id User's steamID or vanityURL
* #param string $apiKey API key for http://steamcommunity.com/dev/
*/
/**
* GetProfileData
* - Accesses Steam Profile XML and parses the data
*/
function __construct($params){
$userId = $params['userId'];
$this->CI =& get_instance();
$this->CI->load->config('steam');
if(empty($userId)) {
echo "Error: No Steam ID or URL given!", PHP_EOL;
return NULL;
}
if(is_numeric($userId)) {
$this->userID = $userId;
}
else {
$this->vanityURL = strtolower($userId);
}
$this->apiKey = $this->CI->config->item('api_key');
}
function getProfileData() {
$info = array();
//Set Base URL for the query:
if(empty($this->vanityURL)) {
$base = "http://steamcommunity.com/profiles/{$this->userId}/?xml=1";
} else {
$base = "http://steamcommunity.com/id/{$this->vanityURL}/?xml=1";
}
try {
$content = SteamUtility::fetchURL($base);
if ($content) {
$parsedData = new SimpleXMLElement($content);
} else {
return null;
}
} catch (Exception $e) {
//echo "Whoops! Something went wrong!\n\nException Info:\n" . $e . "\n\n";
return null;
}
if(!empty($parsedData)) {
$info['steamID64'] = (string)$parsedData->steamID64;
$info['steamID'] = (string)$parsedData->steamID;
$info['stateMessage'] = (string)$parsedData->stateMessage;
$info['visibilityState'] = (int)$parsedData->visibilityState;
$info['privacyState'] = (string)$parsedData->privacyState;
$info['avatarIcon'] = (string)$parsedData->avatarIcon;
$info['avatarMedium'] = (string)$parsedData->avatarMedium;
$info['avatarFull'] = (string)$parsedData->avatarFull;
$info['vacBanned'] = (int)$parsedData->vacBanned;
$info['tradeBanState'] = (string)$parsedData->tradeBanState;
$info['isLimitedAccount'] = (string)$parsedData->isLimitedAccount;
$info['onlineState'] = (string)$parsedData->onlineState;
$info['inGameServerIP'] = (string)$parsedData->inGameServerIP;
//If their account is public, get that info:
if($info['privacyState'] == "public") {
$info['customURL'] = (string)$parsedData->customURL;
$info['memberSince'] = (string)$parsedData->memberSince;
$info['steamRating'] = (float)$parsedData->steamRating;
$info['hoursPlayed2Wk'] = (float)$parsedData->hoursPlayed2Wk;
$info['headline'] = (string)$parsedData->headline;
$info['location'] = (string)$parsedData->location;
$info['realname'] = (string)$parsedData->realname;
$info['summary'] = (string)$parsedData->summary;
}
//If they're in a game, grab that info:
if($info['onlineState'] == "in-game") {
$info['inGameInfo']['inGameInfo'] = array();
$info['inGameInfo']["gameName"] = (string)$parsedData->inGameInfo->gameName;
$info['inGameInfo']["gameLink"] = (string)$parsedData->inGameInfo->gameLink;
$info['inGameInfo']["gameIcon"] = (string)$parsedData->inGameInfo->gameIcon;
$info['inGameInfo']["gameLogo"] = (string)$parsedData->inGameInfo->gameLogo;
$info['inGameInfo']["gameLogoSmall"] = (string)$parsedData->inGameInfo->gameLogoSmall;
}
//Get their most played video games:
if(!empty($parsedData->mostPlayedGames)) {
$info['mostPlayedGames'] = array();
$i = 0;
foreach ($parsedData->mostPlayedGames->mostPlayedGame as $mostPlayedGame) {
$info['mostPlayedGames'][$i] = new stdClass();
$info['mostPlayedGames'][$i]['gameName'] = (string)$mostPlayedGame->gameName;
$info['mostPlayedGames'][$i]['gameLink'] = (string)$mostPlayedGame->gameLink;
$info['mostPlayedGames'][$i]['gameIcon'] = (string)$mostPlayedGame->gameIcon;
$info['mostPlayedGames'][$i]['gameLogo'] = (string)$mostPlayedGame->gameLogo;
$info['mostPlayedGames'][$i]['gameLogoSmall'] = (string)$mostPlayedGame->gameLogoSmall;
$info['mostPlayedGames'][$i]['hoursPlayed'] = (string)$mostPlayedGame->hoursPlayed;
$info['mostPlayedGames'][$i]['hoursOnRecord'] = (string)$mostPlayedGame->hoursOnRecord;
$info['mostPlayedGames'][$i]['statsName'] = (string)$mostPlayedGame->statsName;
$i++;
}
}
//Any weblinks listed in their profile:
if(!empty($parsedData->weblinks)) {
$this['weblinks'] = array();
$i = 0;
foreach ($parsedData->weblinks->weblink as $weblink) {
$info['weblinks'][$i]['title'] = (string)$weblink->title;
$info['weblinks'][$i]['link'] = (string)$weblink->link;
$i++;
}
}
//And grab any subscribed groups:
if(!empty($parsedData->groups)) {
$this->groups = array();
$i = 0;
foreach ($parsedData->groups->group as $group) {
$info['groups'][$i] = array();
$info['groups'][$i]['groupID64'] = (string)$group->groupID64;
$info['groups'][$i]['groupName'] = (string)$group->groupName;
$info['groups'][$i]['groupURL'] = (string)$group->groupURL;
$info['groups'][$i]['headline'] = (string)$group->headline;
$info['groups'][$i]['summary'] = (string)$group->summary;
$info['groups'][$i]['avatarIcon'] = (string)$group->avatarIcon;
$info['groups'][$i]['avatarMedium'] = (string)$group->avatarMedium;
$info['groups'][$i]['avatarFull'] = (string)$group->avatarFull;
$info['groups'][$i]['memberCount'] = (string)$group->memberCount;
$info['groups'][$i]['membersInChat'] = (string)$group->membersInChat;
$info['groups'][$i]['membersInGame'] = (string)$group->membersInGame;
$info['groups'][$i]['membersOnline'] = (string)$group->membersOnline;
$i++;
}
}
}
return $info;
}
My model where I call it:
function retrieve($member_id = 0){
$info = array();
$this->db->select('memberId AS id, facebookId, steamId, userName, emailAddress, dateJoined, dateBorn')
->from('members')
->where('memberId', $member_id)
->limit(1);
if($query = $this->db->get()){
if($query->num_rows() > 0){
$member = $query->row_array();
var_dump($member);
$info = $member;
if($member['steamId'] != ''){
$this->load->library('SteamUser', array('userId' => $member['steamId']));
$steam = $this->SteamUser->getProfileData();
$info['steam'] = array(
'id' => $member['steamId'],
'avatar' => $steam['avatarIcon']
);
}
}
}
$this->info = $info;
}
Dumping the $member variable returns this:
array (size=7)
'id' => string '11' (length=2)
'facebookId' => string '' (length=0)
'steamId' => string 'STEAM_0:1:000000000' (length=17)
'userName' => string 'John Smith' (length=18)
'emailAddress' => string '' (length=0)
'dateJoined' => string '2015-09-23 19:38:17' (length=19)
'dateBorn' => string '0000-00-00 00:00:00' (length=19)
Try these methods
print_r($member['steamId']); to check data is empty or not.
If you passing data as objective array, then you need to access data with pointing [0],
ex: $this->SteamUser->getProfileData($member[0]['steamId']);
Check aging with print_r
print_r($member[0]['steamId']);
So final code will be
print_r($member['steamId']);//check data exist
print_r($member[0]['steamId']);//check data exist
if($member['steamId'])
{
$this->load->library('SteamUser');
$this->SteamUser->getProfileData($member['steamId']);
$steam = array('id' => $member['steamId'], 'avatar' => $this->SteamUser->avatarIcon);
$info = array_merge($info, $steam);
}
Apparently, when you load a class with CodeIgniter, the name of the object that is given is all lower case. So I was loading $this->SteamUser->getProfileData() when I should have been doing it like $this->steamuser->getProfileData().
I have the simple app below. I'm turning off query logging in Laravel, I'm unsetting where possible, yet this function will only process about 800 records before I'm out of RAM on my 2GB Linode. I know I'm asking a lot of you guys but I can't seem to see where I'm leaking memory.
There are really only two major steps.
Step 1 - Move records from a temp table to production
class ListingMigrator
{
public function __construct($tempListing, $feed)
{
$this->tempListing = $tempListing;
$this->listing = $this->listingInstance();
$this->feed = $feed;
}
public static function migrateListing($listing, $feed)
{
$instance = new static($listing, $feed);
return $instance->migrate();
}
public function migrate()
{
$this->addExternalData();
$this->populateListing();
$this->processPhotos();
$this->deleteTempListing();
}
private function listingInstance()
{
DB::connection()->disableQueryLog();
$listing = Listing::findByMud($this->tempListing->matrix_unique_id);
return $listing ?: new Listing;
}
private function processPhotos()
{
$retsApi = new RetsFeedApi($this->feed);
/* Initialize Object */
$rets = $retsApi->findMostRecent();
$photos = $rets->getPhotosForListing($this->listing->matrix_unique_id);
foreach ($photos as $photo)
{
$uploader = new PhotoProcessor($this->listing, $photo);
$uploader->process();
}
}
private function populateListing()
{
DB::connection()->disableQueryLog();
$this->listing->fill($this->tempListing->toArray());
$this->listing->imported_at = $this->tempListing->created_at;
$this->listing->board = $this->tempListing->board;
return $this->listing->save();
}
private function addExternalData()
{
// Get Google lattitude and longitude
$googlecoords = getGoogleMapInfo($this->tempListing->FullAddress, $this->tempListing->City);
$this->listing->GoogleLat = $googlecoords['GoogleLat'];
$this->listing->GoogleLong = $googlecoords['GoogleLong'];
// Add or update the Subdivision Table (helper function)
$subdivisiondata = SubdivisionUpdate($this->tempListing->board, $this->tempListing->SubCondoName, $this->tempListing->Development);
$this->listing->SubdivisionID = $subdivisiondata['id'];
}
private function deleteTempListing()
{
return $this->tempListing->delete();
}
}
Step 2 - Download photos and reupload to Amazon S3
class PhotoProcessor
{
public function __construct(Listing $listing, $photoData)
{
$this->bucket = 'real-estate-listings';
$this->s3 = App::make('aws')->get('s3');
$this->tempFileName = 'app/storage/processing/images/retsphotoupload';
$this->photoData = $photoData;
$this->listing = $listing;
$this->photo = new RetsPhoto;
}
public function process()
{
$this->storeTempFile();
$this->storeFileInfo();
$this->buildPhoto();
$success = $this->pushToS3();
// if Result has the full URL or you want to build it, add it to $this->photo
DB::connection()->disableQueryLog();
$this->listing->photos()->save($this->photo);
$this->removeTempFile();
unset ($this->photoData);
return $success;
}
private function storeTempFile()
{
return File::put($this->tempFileName, $this->photoData['Data']) > 0;
}
private function storeFileInfo()
{
$fileInfo = getimagesize($this->tempFileName);
// Could even be its own object
$this->fileInfo = [
'width' => $fileInfo[0],
'height' => $fileInfo[1],
'mimetype' => $fileInfo['mime'],
'extension' => $this->getFileExtension($fileInfo['mime'])
];
}
private function buildPhoto()
{
$this->photo->number = $this->photoData['Object-ID']; // Storing this because it is relevant order wise
$this->photo->width = $this->fileInfo['width'];
$this->photo->height = $this->fileInfo['height'];
$this->photo->path = $this->getFilePath();
}
private function getFilePath()
{
$path = [];
if ($this->listing->City == NULL)
{
$path[] = Str::slug('No City');
}
else
{
$path[] = Str::slug($this->listing->City, $separator = '-');
}
if ($this->listing->Development == NULL)
{
$path[] = Str::slug('No Development');
}
else
{
$path[] = Str::slug($this->listing->Development, $separator = '-');
}
if ($this->listing->Subdivision == NULL)
{
$pathp[] = Str::slug('No Subdivision');
}
else
{
$path[] = Str::slug($this->listing->Subdivision, $separator = '-');
}
if ($this->listing->MLSNumber == NULL)
{
$pathp[] = Str::slug('No MLSNumber');
}
else
{
$path[] = Str::slug($this->listing->MLSNumber, $separator = '-');
}
$path[] = $this->photoData['Object-ID'].'.'.$this->fileInfo['extension'];
return strtolower(join('/', $path));
}
private function pushToS3()
{
return $this->s3->putObject([
'Bucket' => $this->bucket,
'Key' => $this->photo->path,
'ContentType'=> $this->fileInfo['mimetype'],
'SourceFile' => $this->tempFileName
]);
}
private function getFileExtension($mime)
{
// Use better algorithm than this
$ext = str_replace('image/', '', $mime);
return $ext == 'jpeg' ? 'jpg' : $ext;
}
private function removeTempFile()
{
return File::delete($this->tempFileName);
}
}
Edit to show RetsPhoto
class RetsPhoto extends Eloquent {
protected $table = 'rets_property_photos';
public function listing() {
return $this->belongsTo('Listing', 'matrix_unique_id', 'matrix_unique_id');
}
}
Edit #2: Chunk Call
This is in the app/command and the only thing in there is the fire() function below:
public function fire()
{
// Turn off query logging
DB::connection()->disableQueryLog();
$feeds = RetsFeed::where('active','=',1)->get();
foreach ($feeds as $feed)
{
$class = "TempListing{$feed->board}";
$listings = $class::orderBy('MatrixModifiedDT','desc');
$listings->chunk(50, function($listings) use($feed) {
$listings->each(function($listing) use ($feed) {
ListingMigrator::migrateListing($listing,$feed);
echo "Feed: $feed->board\r\n";
echo "SubcondoName: $listing->SubCondoName\r\n";
echo "Development: $listing->Development\r\n";
echo "\r\n";
});
});
}
}
I think I have figured it out.
Your system holds in memory all of the photo data. As witnessed by the unset ($this->photoData);
The problem is that you need to first complete the process function. Your application is not likely processing ANY photos so when you keep grabbing them from the file system you run out of memory BEFORE you even process a single one.
To Confirm this, simply grab 1 file not using the chunk method.
I am not very familar with Laravel, it could be grabbing all of the files all at once as well and eating the ram.
You can do some tracing with memory_get_usage(true) to find out exactly where the ram is getting eaten from. I would suggest analysing the fire method first.
Okay I have installed a theme in wordpress that returns a few errors.
Warning: Invalid argument supplied for foreach() in /home/mvprop/public_html/wp-content/themes/yoo_vox_wp/warp/systems/wordpress.3.0/helpers/system.php on line 339
This problem is resolved on these forums
but I can't understand what the last post is about. The guy posts a bunch of random code that solves the problem. He doesn't specify where it's from or where to put it. Just pastes code that doesn't seem to have to do with anything.
line 334 to the end of the file
function getWidgets($position = null) {
if (empty($this->widgets)) {
foreach (wp_get_sidebars_widgets() as $pos => $ids) {
$this->widgets[$pos] = array();
foreach ($ids as $id) {
$this->widgets[$pos][$id] = $this->getWidget($id);
}
}
}
if (!is_null($position)) {
return isset($this->widgets[$position]) ? $this->widgets[$position] : array();
}
return $this->widgets;
}
/*
Function: displayWidget
Checks if a widget should be displayed
Returns:
Boolean
*/
function displayWidget($widget) {
if (!isset($widget->options['display']) || in_array('*', $widget->options['display'])) return true;
foreach ($this->getQuery() as $q) {
if (in_array($q, $widget->options['display'])) {
return true;
}
}
return false;
}
/*
Function: overrideConfig
Overrides default config based on page
Returns:
Void
*/
function overrideConfig() {
if (!count($this->config_overrides)) return;
foreach ($this->getQuery() as $q) {
if (isset($this->config_overrides[$q])) {
$this->warp->config->parseString($this->config_overrides[$q]);
}
}
}
/*
Function: isBlog
Returns:
Boolean
*/
function isBlog() {
return true;
}
/*
Function: isPreview
Checks for default widgets in theme preview
Returns:
Boolean
*/
function isPreview($position) {
// preview postions
$positions = array('logo', 'right');
return is_preview() && in_array($position, $positions);
}
/*
Function: ajaxSearch
Ajax search callback
Returns:
String
*/
function ajaxSearch(){
global $wp_query;
$result = array('results' => array());
$query = isset($_REQUEST['s']) ? $_REQUEST['s']:"";
if (strlen($query)>=3) {
$wp_query->query_vars['s'] = $query;
$wp_query->is_search = true;
foreach ($wp_query->get_posts() as $post) {
$content = !empty($post->post_excerpt) ? strip_tags(do_shortcode($post->post_excerpt)) : strip_tags(do_shortcode($post->post_content));
if (strlen($content) > 255) {
$content = substr($content, 0, 254).'...';
}
$result['results'][] = array(
'title' => $post->post_title,
'text' => $content,
'url' => get_permalink($post->ID)
);
}
}
die(json_encode($result));
}
/*
Function: _adminInit
Admin init actions
Returns:
Void
*/
function _adminInit() {
if ((defined('DOING_AJAX') && DOING_AJAX) && isset($_POST['warp-ajax-save'])) {
// update option values
foreach ($_POST as $option => $value) {
if (preg_match('/^(warp_|'.preg_quote($this->prefix, '/').')/', $option)) {
update_option($option, $value);
}
}
die();
}
wp_enqueue_script('warp-admin', rtrim(get_bloginfo('template_url'),'/').'/warp/systems/wordpress.3.0/js/wp-admin.js', false, '1.0');
add_action('wp_ajax_save_nav_settings', array($this,'_save_nav_settings'));
add_action('wp_ajax_get_nav_settings', array($this,'_get_nav_settings'));
}
/*
Function: _adminHead
Admin head actions
Returns:
Void
*/
function _adminHead() {
// init vars
$path =& $this->getHelper('path');
$head[] = '<link rel="stylesheet" href="'.$path->url('warp:systems/wordpress.3.0/css/admin.css').'" type="text/css" />';
$head[] = '<script type="text/javascript" src="'.$path->url('warp:systems/wordpress.3.0/js/admin.js').'"></script>';
echo implode("\n", $head);
}
/*
Function: _adminMenu
Admin menu actions
Returns:
Void
*/
function _adminMenu() {
// init vars
$path =& $this->getHelper('path');
$name = $this->xml->document->getElement('name');
$icon = $path->url('warp:systems/wordpress.3.0/images/yoo_icon_16.png');
if (function_exists('add_object_page')) {
add_object_page('', $name->data(), 8, 'warp', false, $icon);
} else {
add_menu_page('', $name->data(), 8, 'warp', false, $icon);
}
add_submenu_page('warp', 'Theme Options', 'Theme Options', 8, 'warp', array($this, '_adminThemeOptions'));
add_submenu_page('warp', 'Widget Options', 'Widget Options', 8, 'warp_widget', array($this, '_adminWidgetOptions'));
}
/*
Function: _adminThemeOptions
Render admin theme options layout
Returns:
Void
*/
function _adminThemeOptions() {
// init vars
$path =& $this->getHelper('path');
$xml =& $this->getHelper('xml');
$http =& $this->getHelper('http');
$check =& $this->getHelper('checksum');
// get warp xml
$warp_xml = $xml->load($path->path('warp:warp.xml'), 'xml', true);
// update check
$update = null;
if ($url = $warp_xml->document->getElement('updateUrl')) {
// get template info
$template = get_template();
$version = $this->xml->document->getElement('version');
$url = sprintf('%s?application=%s&version=%s&format=raw', $url->data(), $template, $version->data());
// only check once a day
if (get_option($this->prefix.'update_check') != date('Y-m-d').' '.$version->data()) {
if ($request = $http->get($url)) {
update_option($this->prefix.'update_check', date('Y-m-d').' '.$version->data());
update_option($this->prefix.'update_data', $request['body']);
}
}
// decode update response
$update = json_decode(get_option($this->prefix.'update_data'));
}
// verify theme files
if (($checksums = $path->path('template:checksums')) && filesize($checksums)) {
$check->verify($path->path('template:'), $log);
} else {
$log = false;
}
echo $this->warp->template->render('admin/theme_options', array('xml' => $this->xml, 'warp_xml' => $warp_xml, 'update' => $update, 'checklog' => $log));
}
/*
Function: _adminWidgetOptions
Render admin widget options layout
Returns:
Void
*/
function _adminWidgetOptions() {
// get position settings
$position_settings = $this->warp->config->get('warp.positions');
// get module settings
$module_settings = array();
$settings = $this->xml->document->getElement('modulesettings');
foreach ($settings->children() as $setting) {
$module_settings[$setting->attributes('name')] = $setting;
}
echo $this->warp->template->render('admin/widget_options', compact('position_settings', 'module_settings'));
}
/*
Function: getMenuItemOptions
Retrieve menu by id
Parameters:
$id - Menu Item ID
Returns:
Array
*/
function getMenuItemOptions($id) {
$menu_settings = array(
'columns' => 1,
'columnwidth' => -1,
'image' => ''
);
if (isset($this->menu_item_options[$id])) {
$menu_settings = array_merge($menu_settings, $this->menu_item_options[$id]);
}
return $menu_settings;
}
/*
Function: _save_nav_settings
Saves menu item settings
Returns:
Void
*/
function _save_nav_settings() {
if (isset($_POST['menu-item'])) {
$menu_item_settings = $this->menu_item_options;
foreach ($_POST['menu-item'] as $itemId=>$settings){
$menu_item_settings[$itemId] = $settings;
}
update_option($this->prefix.'menu-items', $menu_item_settings);
$this->menu_item_options = $menu_item_settings;
}
die();
}
/*
Function: _get_nav_settings
Returns menu item settings as json
Returns:
Boolean
*/
function _get_nav_settings() {
die(json_encode($this->menu_item_options));
}
}
/*
Function: mb_strpos
mb_strpos function for servers not using the multibyte string extension
*/
if (!function_exists('mb_strpos')) {
function mb_strpos($haystack, $needle, $offset = 0) {
return strpos($haystack, $needle, $offset);
}
}
Basically what this warning message tells you is that the variable you're passing into your foreach is not an array or object. Make sure your variable is valid by testing it ( is_array($var) or is_object($var) ) or placing this block of code in a try-catch.
If $var is supposed to be an array, you should also initialize it just to be certain.
$var = Array();
.
. // code that may change the data type of $var
.
if (is_array($var)) {
foreach($var as $v) {
//code here
}
}
From the manual at http://php.net/manual/en/control-structures.foreach.php:
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.