Using $this when not in object context error - php

I'm getting a fatal PHP error when trying to execute my script: Using $this when not in object context The script collects data from Google Analytics via API, then displays it on a page.
Below is the piece of code where the script dies:
$records = $this->getAnalyticRecords ( date ( 'Y-m-d', $startTime ), date ( 'Y-m-d', $endEnd ), 'ga:date', 'ga:visitors,ga:newVisits,ga:visits,ga:pageviews,ga:timeOnPage,ga:bounces,ga:entrances,ga:exits' );
getAnalyticsRecords is set by:
function getAnalyticRecords($startDate, $endDate, $dimensions, $metrics, $sort = '', $maxResults = '') {
$url = 'https://www.google.com/analytics/feeds/data';
$url .= "?ids=" . $this->profile;
$url .= "&start-date=" . $startDate;
$url .= "&end-date=" . $endDate;
$url .= "&dimensions=" . $dimensions;
$url .= "&metrics=" . $metrics;
if (! empty ( $sort )) {
$url .= "&sort=" . $sort;
}
if (! empty ( $maxResults )) {
$url .= "&max-results=" . $maxResults;
}
if (($feedData = $this->fetchFeed ( $url )) === FALSE) {
return array ();
}
$doc = new DOMDocument ( );
$doc->loadXML ( $feedData );
$results = array ();
$aggregates = $doc->getElementsByTagName ( 'aggregates' );
foreach ( $aggregates as $aggregate ) {
$metrics = $aggregate->getElementsByTagName ( 'metric' );
foreach ( $metrics as $metric ) {
$results ['aggregates'] ['metric'] [$metric->getAttribute ( 'name' )] = $metric->getAttribute ( 'value' );
}
}
$entries = $doc->getElementsByTagName ( 'entry' );
foreach ( $entries as $entry ) {
$record = array ();
$record ["title"] = $entry->getElementsByTagName ( 'title' )->item ( 0 )->nodeValue;
$dimensions = $entry->getElementsByTagName ( 'dimension' );
foreach ( $dimensions as $dimension ) {
$record ['dimension'] [$dimension->getAttribute ( 'name' )] = $dimension->getAttribute ( 'value' );
}
$metrics = $entry->getElementsByTagName ( 'metric' );
foreach ( $metrics as $metric ) {
$record ['metric'] [$metric->getAttribute ( 'name' )] = $metric->getAttribute ( 'value' );
}
$results ['entry'] [] = $record;
}
return $results;
}

You should listen to the error. You are using $this when not in a class.
Try either enclosing your code in a class or omitting $this->. Use global instead.

Related

Run a function inside a worpress shortcode php function

I am trying to create a shortcode to connect to an API but there is a problem with the shortcode. I know that it is because a function is inside a functinon but I can't figure out how to fix. I tried something that didn't work.
// Add Shortcode
function api_test() {
function execute_request( $args ) {
global $base_url;
$target_url = add_query_arg( $args, $base_url );
$data = wp_remote_get( $target_url );
echo '<pre><code>';
print_r( $data['body'] );
echo '<code></pre>';
}
if ( ! current_user_can( 'manage_options' ) ) die();
// API variables, please override
$base_url = 'https://website.com';
$email = 'email#gmail.com';
$product_id = '1146';
$license_key = '0g96b29x5v27fmfnmbr4hxaflky';
$instance = '';
$request = ( isset( $_GET['request'] ) ) ? $_GET['request'] : '';
$links = array(
'check' => 'Check request',
'activation' => 'Activation request',
'deactivation' => 'Deactivation',
'version_check' => 'Version Check',
);
foreach ( $links as $key => $value ) {
echo '' . $value . ' | ';
}
// Valid check request
if ( $request == 'check' ) {
$args = array(
'wc-api' => 'serial-numbers-api',
'request' => 'check',
'email' => $email,
'serial_key' => $license_key,
'product_id' => $product_id
);
echo '<br>';
echo '<br>';
echo '<b>Valid check request:</b><br />';
//execute_request( $args );
$this->execute_request($args);
}
}
add_shortcode( 'api-test', 'api_test' );
Just create execute_request() outside of shortcode.
function execute_request( $args ) {
global $base_url;
$target_url = add_query_arg( $args, $base_url );
$data = wp_remote_get( $target_url );
echo '<pre><code>';
print_r( $data['body'] );
echo '<code></pre>';
}
function api_test() {
if ( ! current_user_can( 'manage_options' ) ) die();
// API variables, please override
$base_url = 'https://website.com';
$email = 'email#gmail.com';
$product_id = '1146';
$license_key = '0g96b29x5v27fmfnmbr4hxaflky';
$instance = '';
$request = ( isset( $_GET['request'] ) ) ? $_GET['request'] : '';
$links = array(
'check' => 'Check request',
'activation' => 'Activation request',
'deactivation' => 'Deactivation',
'version_check' => 'Version Check',
);
foreach ( $links as $key => $value ) {
echo '' . $value . ' | ';
}
// Valid check request
if ( $request == 'check' ) {
$args = array(
'wc-api' => 'serial-numbers-api',
'request' => 'check',
'email' => $email,
'serial_key' => $license_key,
'product_id' => $product_id
);
echo '<br>';
echo '<br>';
echo '<b>Valid check request:</b><br />';
//execute_request( $args );
execute_request($args);
}
}
add_shortcode( 'api-test', 'api_test' );

I have used return create_function in my application below. php 7.2

how to win?
PHP 7.2.0, the create_function() is deprecated.
Thanks for your help,
or wait for developers?
Edited and cleared Code
return create_function( '', "
global $chery_core_version;
$path = trailingslashit( dirname( __FILE__ ) ) . 'cherry-core.php';
$data = get_file_data( $path, array(
'version' => 'Version'
) );
if ( isset( $data['version'] ) ) {
$version = $data['version'];
}
$old_versions = null;
if ( null !== $chery_core_version ) {
$old_versions = array_keys( $chery_core_version );
}
if ( is_array( $old_versions ) && isset( $old_versions[0] ) ) {
$compare = version_compare( $old_versions[0], $version, '<' );
if ( $compare ) {
$chery_core_version = array();
$chery_core_version[ $version ] = $path;
}
} else {
$chery_core_version = array();
$chery_core_version[ $version ] = $path;
}
" );
Use anonymous functions instead:
return function () {
global $chery_core_version;
$path = trailingslashit(__DIR__) . 'cherry-core.php';
$data = get_file_data( $path, [
'version' => 'Version'
] );
if ( isset( $data['version'] ) ) {
$version = $data['version'];
}
$old_versions = null;
if ( null !== $chery_core_version ) {
$old_versions = array_keys( $chery_core_version );
}
if ( is_array( $old_versions ) && isset( $old_versions[0] ) ) {
$compare = version_compare( $old_versions[0], $version, '<' );
if ( $compare ) {
$chery_core_version = [];
$chery_core_version[ $version ] = $path;
}
} else {
$chery_core_version = [];
$chery_core_version[ $version ] = $path;
}
};

magento: can't get custom product attributes (select type)

I am writting my own rest api for magento app.
I want to get the custom product attr value.
But the result is alway
value : N/A
This mean I can't get the attributes value.
I don't know why. Anyone can help? Many Thanks.
The code is like follow. Thanks.
public function _getAditional(array $excludeAttr = array()) {
$data = array ();
$productId = ( int ) $this->getRequest ()->getParam ( 'productid' );
$product = Mage::getModel ( "catalog/product" )->load ( $productid );
$attributes = $product->getAttributes ();
//$attributes = Mage::getBlockSingleton('catalog/product_view_attributes')->getAdditionalData($product);
foreach ( $attributes as $attribute ) {
if ($attribute->getIsVisibleOnFront() && !in_array($attribute->getAttributeCode(), $excludeAttr)) {
$value = $attribute->getFrontend()->getValue($product);
if (!$product->hasData($attribute->getAttributeCode())) {
$value = Mage::helper('catalog')->__('N/A');
} elseif ((string)$value == '') {
$value = Mage::helper('catalog')->__('No');
} elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
$value = Mage::app()->getStore()->convertPrice($value, true);
}
if (is_string($value) && strlen($value)) {
$data[$attribute->getAttributeCode()] = array(
'label' => $attribute->getStoreLabel(),
'value' => $value,
'code' => $attribute->getAttributeCode()
);
}
}
}
return $data;
}
And the ProductsController.php
class Sunpop_RestConnect_ProductsController extends Mage_Core_Controller_Front_Action {
public function getcustomoptionAction() {
$baseCurrency = Mage::app ()->getStore ()->getBaseCurrency ()->getCode ();
$currentCurrency = Mage::app ()->getStore ()->getCurrentCurrencyCode ();
$productid = $this->getRequest ()->getParam ( 'productid' );
$product = Mage::getModel ( "catalog/product" )->load ( $productid );
$selectid = 1;
$select = array ();
foreach ( $product->getOptions () as $o ) {
if (($o->getType () == "field") || ($o->getType () == "file")) {
$select [$selectid] = array (
'option_id' => $o->getId (),
'custom_option_type' => $o->getType (),
'custom_option_title' => $o->getTitle (),
'is_require' => $o->getIsRequire (),
'price' => number_format ( Mage::helper ( 'directory' )->currencyConvert ( $o->getPrice (), $baseCurrency, $currentCurrency ), 2, '.', '' ),
'price_type' => $o->getPriceType (),
'sku' => $o->getSku (),
'max_characters' => $o->getMaxCharacters ()
);
} else {
$max_characters = $o->getMaxCharacters ();
$optionid = 1;
$options = array ();
$values = $o->getValues ();
foreach ( $values as $v ) {
$options [$optionid] = $v->getData ();
if(null!==$v->getData('price') && null!==$v->getData('default_price')){
$options [$optionid]['price']=number_format ( Mage::helper ( 'directory' )->currencyConvert ( $v->getPrice (), $baseCurrency, $currentCurrency ), 2, '.', '' );
$options [$optionid]['default_price']=number_format ( Mage::helper ( 'directory' )->currencyConvert ( $v->getDefaultPrice (), $baseCurrency, $currentCurrency ), 2, '.', '' );
}
$optionid ++;
}
$select [$selectid] = array (
'option_id' => $o->getId (),
'custom_option_type' => $o->getType (),
'custom_option_title' => $o->getTitle (),
'is_require' => $o->getIsRequire (),
'price' => number_format ( Mage::helper ( 'directory' )->currencyConvert ( $o->getFormatedPrice (), $baseCurrency, $currentCurrency ), 2, '.', '' ),
'max_characters' => $max_characters,
'custom_option_value' => $options
);
}
$selectid ++;
// echo "----------------------------------<br/>";
}
echo json_encode ( $select );
}
public function getproductdetailAction() {
$productdetail = array ();
$baseCurrency = Mage::app ()->getStore ()->getBaseCurrency ()->getCode ();
$currentCurrency = Mage::app ()->getStore()->getCurrentCurrencyCode();
$productid = $this->getRequest ()->getParam ("productid");
$product = Mage::getModel ("catalog/product")->load ($productid);
$storeUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
//$description = nl2br ( $product->getDescription () );
$description = $product->getDescription ();
$description = str_replace("{{media url=\"",$storeUrl,$description);
$description = str_replace("\"}}","",$description);
if ($product->getOptions ())
$has_custom_options = true;
else
$has_custom_options = false;
$addtionatt=$this->_getAditional();
$productdetail = array (
'entity_id' => $product->getId (),
'sku' => $product->getSku (),
'name' => $product->getName (),
'news_from_date' => $product->getNewsFromDate (),
'news_to_date' => $product->getNewsToDate (),
'special_from_date' => $product->getSpecialFromDate (),
'special_to_date' => $product->getSpecialToDate (),
'image_url' => $product->getImageUrl (),
'url_key' => $product->getProductUrl (),
'is_in_stock' => $product->isAvailable (),
'has_custom_options' => $has_custom_options,
'regular_price_with_tax' => number_format ( Mage::helper ( 'directory' )->currencyConvert ( $product->getPrice (), $baseCurrency, $currentCurrency ), 2, '.', '' ),
'final_price_with_tax' => number_format ( Mage::helper ( 'directory' )->currencyConvert ( $product->getSpecialPrice (), $baseCurrency, $currentCurrency ), 2, '.', '' ),
'storeUrl' => $storeUrl,
'symbol' => Mage::app ()->getLocale ()->currency ( Mage::app ()->getStore ()->getCurrentCurrencyCode () )->getSymbol () ,
'weight'=>number_format($product->getWeight()),
'additional'=>$addtionatt,
'description' => $description
);
echo json_encode ( $productdetail );
}
public function getPicListsAction() {
$productId = ( int ) $this->getRequest ()->getParam ( 'product' );
$_product = Mage::getModel ( "catalog/product" )->load ( $productid );
$_images = Mage::getModel ( 'catalog/product' )->load ( $productId )->getMediaGalleryImages ();
$images = array ();
foreach ( $_images as $_image ) {
$images [] = array (
'url' => $_image->getUrl (),
'position' => $_image->getPosition ()
);
}
echo json_encode ( $images );
}
public function _getAditional(array $excludeAttr = array()) {
$data = array ();
$productId = ( int ) $this->getRequest ()->getParam ( 'productid' );
$product = Mage::getModel ( "catalog/product" )->load ( $productid );
$attributes = $product->getAttributes ();
//$attributes = Mage::getBlockSingleton('catalog/product_view_attributes')->getAdditionalData($product);
foreach ( $attributes as $attribute ) {
if ($attribute->getIsVisibleOnFront() && !in_array($attribute->getAttributeCode(), $excludeAttr)) {
$value = $attribute->getFrontend()->getValue($product);
if (!$product->hasData($attribute->getAttributeCode())) {
$value = Mage::helper('catalog')->__('N/A');
} elseif ((string)$value == '') {
$value = Mage::helper('catalog')->__('No');
} elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
$value = Mage::app()->getStore()->convertPrice($value, true);
}
if (is_string($value) && strlen($value)) {
$data[$attribute->getAttributeCode()] = array(
'label' => $attribute->getStoreLabel(),
'value' => $value,
'code' => $attribute->getAttributeCode()
);
}
}
}
return $data;
}
}

Wordpress twitter api 1.1 search class

I'm trying to use a class to made some search using the twitter api v1.1 but everytime I get and authentication error message:
This is the link to the original class: https://gist.github.com/tw2113/5468916
This is the code I'm using:
<?php
/**
* Class for connecting to Twitter's API 1.1 using WordPress APIs
*/
class TwitterAuth11 {
protected $consumer_key = 'MCQ8u3TMuBAidL4AKBtQ';
protected $consumer_secret = 'HIyZbh1FTDtpOK9qdX5yP3ZmNobnJcb2lKnhPONg6WI';
protected $access_token = '104977066-dLQj8ibcxlafcsGiwTOanw1buy0OIejhy51PzFsc';
protected $access_token_secret = 'nUkWIGX21LICgw8ZqoxwfasisB4ma3YpzwXr7EzY8';
protected $url = 'https://api.twitter.com/1.1/';
protected function authenticate( $user, $return = true ) {
$body = json_decode( $body );
if ( $body && !empty( $response['headers']['status'] ) && $response['headers']['status'] == '200 OK' ) {
if ( $return == false ) $body = null;
$noauth = '';
$badauth = 'good';
} else {
$body = null;
$badauth = 'error';
$noauth = true;
}
return array(
'response' => $body,
'badauth' => $badauth,
'noauth' => $noauth,
);
}
function get_tweets( $user = '', $count = 1 ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'screen_name' => $user, 'count' => $count ) );
$args = $this->header_args( array( 'screen_name' => $user, 'count' => $count ) );
//$this->salida = '<br> url: ' . $url . '<br>Args: ' . '<pre>'. htmlentities( print_r( $args, true ) ) .'</pre>';
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return '<strong>ERROR:</strong> '. $response->get_error_message();
$error = 'Could not access Twitter feed.';
return $this->returnData( $response, $error );
}
function search_tweets( $user = '', $count = 1, $search = '' ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'q' => urlencode( $search ) ), 'search/tweets.json' );
$args = $this->header_args( array( 'q' => urlencode( $search ) ) );
//$this->salida = '<br> url: ' . $url . '<br>Args: ' . '<pre>'. htmlentities( print_r( $args, true ) ) .'</pre>';
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return '<strong>ERROR:</strong> '. $response->get_error_message();
$error = 'Could not access Twitter feed.';
return $this->returnData( $response, $error );
}
function authenticate_user( $user = '' ) {
$this->user = $user;
$url = $this->twAPIurl( array( 'screen_name' => $user ), 'users/lookup.json' );
$args = $this->header_args( array( 'screen_name' => $user ) );
$response = wp_remote_get( $url, $args );
if( is_wp_error( $response ) )
return false;
$error = 'Could not access Twitter user.';
return $this->returnData( $response, $error );
}
protected function returnData( $response, $error_message = '' ) {
$body = wp_remote_retrieve_body( $response );
$json = json_decode( $body );
if ( isset( $json->errors ) ) {
$errors = new WP_Error( 'twitter_auth_error', $error_message );
foreach ( $json->errors as $key => $error ) {
$errors->add( 'twitter_auth_error', '<strong>ERROR '. $error->code .':</strong> '. $error->message );
}
return $errors;
}
return $json;
}
protected function header_args( $args = array() ) {
if ( !isset( $this->user ) || ! $this->user )
return null;
// Set our oauth data
$defaults = array(
//'screen_name' => $this->user,
'oauth_consumer_key' => $this->consumer_key,
'oauth_nonce' => base64_encode( substr(md5(rand(0, 1000000)), 0, 32 ) ),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $this->access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$oauth = wp_parse_args( $defaults, $args );
//echo '<pre>'. htmlentities( print_r( $oauth, true ) ) .'</pre>';
//echo '<br><br><hr><br>';
$base_info = $this->build_base( $this->base_url(), $oauth );
$composite_key = $this->consumer_secret .'&'. $this->access_token_secret;
// create our oauth signature
$oauth['oauth_signature'] = base64_encode( hash_hmac( 'sha1', $base_info, $composite_key, true ) );
echo '<span>'.$base_info .'</span>';
echo '<br><br><hr><br>';
echo '<span>'. urldecode( $base_info ) .'</span>';
echo '<br><br><hr><br>';
$auth_args = array(
'sslverify' => false,
'headers' => array(
'Authorization' => 'OAuth '. $this->authorize_header( $oauth ),
'Expect' => false,
'Accept-Encoding' => false
),
);
return $auth_args;
}
protected function build_base( $baseURI, $params ) {
$base = array();
ksort( $params );
foreach( $params as $key => $value ){
$base[] = $key .'='. rawurlencode( $value );
}
return 'GET&'. rawurlencode( $baseURI ) .'&'. rawurlencode( implode( '&', $base ) );
}
protected function authorize_header( $oauth ) {
$header = '';
$values = array();
foreach( $oauth as $key => $value ) {
if ( $key == 'screen_name' || $key == 'count' )
continue;
$values[] = $key .'="'. rawurlencode( $value ) .'"';
}
$header .= implode( ', ', $values );
return $header;
}
protected function twAPIurl( $params = false, $trail = 'statuses/user_timeline.json' ) {
// append trailing path
$this->base_url = $this->url . $trail;
// append query args
return $params ? add_query_arg( $params, $this->base_url ) : $this->base_url;
}
protected function base_url() {
// set it up
if ( !isset( $this->base_url ) )
$this->twAPIurl();
return $this->base_url;
}
}
add_action( 'all_admin_notices', 'testing_twitter_api');
/**
* Test the api in the WordPress Dashboard
*/
function testing_twitter_api() {
echo '<div id="message" class="updated"><p>';
$twitter = new TwitterAuth11();
// Search api
$search = $twitter->search_tweets( 'ntrzacatecas', 3, '#ntr from:212Toga OR from:jasonbarkerm OR from:ntrzacatecas OR from:AlbertoChiu OR from:marcazac OR from:ortegasaul' );
// uses proper wp_error objects
if ( is_wp_error( $search ) )
echo implode( '<br/>', $search->get_error_messages( 'twitter_auth_error' ) );
else
echo '<pre>'. htmlentities( print_r( $search, true ) ) .'</pre>';
echo '</p></div>';
}
Any ideas?
Thanks for the help
Try using the Twitter API 1.1 Client for WordPress.
It's very easy to implement and all you need is your consumer_key and consumer_secret.
Example (from the README):
<?php
// Include Twitter API Client
require_once( 'class-wp-twitter-api.php' );
// Set your personal data retrieved at https://dev.twitter.com/apps
$credentials = array(
'consumer_key' => 'xxxxxxxxxxxxxxxx',
'consumer_secret' => 'xxxxxxxxxxxxxxxx'
);
// Let's instantiate Wp_Twitter_Api with your credentials
$twitter_api = new Wp_Twitter_Api( $credentials );
// Example a - Retrieve last 5 tweets from my timeline (default type statuses/user_timeline)
$query = 'count=5&include_entities=true&include_rts=true&screen_name=micc1983';
var_dump( $twitter_api->query( $query ) );

Modify Wordpress function get_pagenum_link

is there any possiblity that I can change the following link:
xxx.com/page/2
to
xxx.com/?paged=2
Here the current function:
function get_pagenum_link($pagenum = 1) {
global $wp_rewrite;
$pagenum = (int) $pagenum;
$request = remove_query_arg( 'paged' );
$home_root = parse_url(home_url());
$home_root = ( isset($home_root['path']) ) ? $home_root['path'] : '';
$home_root = preg_quote( trailingslashit( $home_root ), '|' );
$request = preg_replace('|^'. $home_root . '|', '', $request);
$request = preg_replace('|^/+|', '', $request);
if ( !$wp_rewrite->using_permalinks() || is_admin() ) {
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $pagenum > 1 ) {
$result = add_query_arg( 'paged', $pagenum, $base . $request );
} else {
$result = $base . $request;
}
} else {
$qs_regex = '|\?.*?$|';
preg_match( $qs_regex, $request, $qs_match );
if ( !empty( $qs_match[0] ) ) {
$query_string = $qs_match[0];
$request = preg_replace( $qs_regex, '', $request );
} else {
$query_string = '';
}
$request = preg_replace( "|$wp_rewrite->pagination_base/\d+/?$|", '', $request);
$request = preg_replace( '|^index\.php|', '', $request);
$request = ltrim($request, '/');
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $wp_rewrite->using_index_permalinks() && ( $pagenum > 1 || '' != $request ) )
$base .= 'index.php/';
if ( $pagenum > 1 ) {
$request = ( ( !empty( $request ) ) ? trailingslashit( $request ) : $request ) . user_trailingslashit( $wp_rewrite->pagination_base . "/" . $pagenum, 'paged' );
}
$result = $base . $request . $query_string;
}
$result = apply_filters('get_pagenum_link', $result);
return $result;
}
from wordpress-includes/link-template.php
How I can modify the function without editing it in the core?
Thanks
From the source, it looks like you should just be able to disable permalinks to get it to page like that.
//start of function code
// ...
if ( !$wp_rewrite->using_permalinks() || is_admin() ) {
$base = trailingslashit( get_bloginfo( 'url' ) );
if ( $pagenum > 1 ) {
$result = add_query_arg( 'paged', $pagenum, $base . $request );
} else {
$result = $base . $request;
}
}
//rest of function code
// ...
Docs for add_query_arg()

Categories