Below is my code for uploading images, creating posts and to fanpage. Auto posting works fine apart from one thing - when images are posted to album, nothing shows up on the fan page timeline. Could you help me resolve the problem or point to some documentation. I have tried to google it, but none of the results from stackoverflow or facebook developer helped me.
$function ips_fanpage_post( $id, $row = false, $force_type = 'post' )
{
require_once( ABS_PATH . '/connect/facebook/facebook.php');
if( !is_array( $row ) )
{
$row = PD::getInstance()->simpleSelect( IPS__FILES, "`id` = '$id'", 1);
if( empty($row) )
{
ips_log( "ips_fanpage_post($id)" );
return;
}
global ${IPS_LNG};
$row['type'] = 'post';
$row['caption'] = ${IPS_LNG}['meta_site_title'];
$row['description'] = 'เยี่ยมไหม แย่ไหม ชอบไหม';
$row['image'] = IMG_LINK . '/' . $row['img_url'];
$row['link'] = seoLink($row['id'], $row['title']);
$row['message'] = 'เยี่ยมไหม แย่ไหม ชอบไหม';
}
$image = null;
if( !empty( $_FILES["file"]["tmp_name"] ) )
{
$image = realpath($_FILES["file"]["tmp_name"]);
}
else
{
if( file_exists( IMG_PATH . '/' . basename( $row['image'] ) ) )
{
$image = IMG_PATH . '/' . basename( $row['image'] );
}
elseif( file_exists( ABS_PATH . '/upload/img_obrazki/' . basename( $row['image'] ) ) )
{
$image = ABS_PATH . '/upload/img_obrazki/' . basename( $row['image'] );
}
elseif( file_exists( ABS_PATH . '/upload/import/' . basename( $row['image'] ) ) )
{
$image = ABS_PATH . '/upload/import/' . basename( $row['image'] );
}
}
if( empty( $image ) )
{
return array('Nie można odnależć określonego obrazka.');
}
$fanpage_id = Config::GET('apps_facebook_fanpageid');
$facebook = new Facebook(array(
'appId' => Config::GET('apps_facebook_appid'),
'secret' => Config::GET('apps_facebook_appsecret'),
'cookie' => true,
'fileUpload' => true
));
if( $row['type'] == 'upload' || $force_type == 'upload' )
{
$params = array(
'access_token' => Config::GET('apps_facebook_token')
);
$accounts = $facebook->api('/me/accounts', 'GET', $params);
foreach($accounts['data'] as $account)
{
if( $account['id'] == $fanpage_id || (isset($account['name']) && $account['name'] == $fanpage_id) )
{
$fanpage_token = $account['access_token'];
}
}
$image = str_replace( '_middle', '', $image );
if( !isset( $fanpage_token ) )
{
ips_log( 'Pusty $fanpage_token, prawdopodobnie nie jest adminem.' );
return false;
}
$params = array(
'message' => 'เยี่ยมไหม แย่ไหม ชอบไหม',
'image' => '#' . $image,
'no_story' => 1,
'aid' => $row['album_id'],
'access_token' => $fanpage_token
);
try
{
$rest = $facebook->api( '$row['album_id']' . '/photos', 'post', $params );
if( $rest )
{
$data = array(
'id' => 'NULL',
'file_id' => $row['album_id'],
'post_id' => $rest['id'],
'title' => $row['title'],
'data' => date("Y-m-d H:i:s"),
'link_post' => 'https://www.facebook.com/photo.php?fbid=' . $rest['id'],
'type' => 'upload'
);
PD::getInstance()->insert("fanpage_post", $data);
return true;
}
ips_log( $rest );
return false;
} catch (FacebookApiException $e) {
ips_log($e);
return $e->getMessage();
}
}
else
{
$image = str_replace( ABS_PATH, substr( ABS_URL, 0 , -1 ), $image );
if( substr( $image, 0 , 4 ) != 'http' )
{
$image = substr( ABS_URL, 0 , -1 ) . $image;
}
$attachment = '{
"name":"คลิกที่นี่ ตอนนี้",
"href":"'. $row['link'] .'",
"caption":"'. $row['caption'] .'",
"description":"'. $row['description'] .'",
"properties":null,
"media":[{
"type":"image",
"src":"' . $image . '",
"href":"' . $row['link'] . '",
}],
"auto_publish":true
}';
try {
$rest = $facebook->api(array(
"uid" => $fanpage_id,
"method" => "stream.publish",
"access_token" => Config::GET('apps_facebook_token'),
"message" => $row['message'],
"attachment" => $attachment,
"caption" => $row['caption']
));
if( $rest )
{
$data = array(
'id' => 'NULL',
'file_id' => $id,
'post_id' => $rest,
'title' => $row['title'],
'data' => date("Y-m-d H:i:s"),
'link_post' => 'https://www.facebook.com/'. str_replace('_', '/posts/', $rest),
'type' => 'post'
);
PD::getInstance()->insert("fanpage_post", $data);
return true;
}
ips_log( $rest );
return false;
} catch (FacebookApiException $e) {
/**
* Błąd zapisany do pliku log
*/
ips_log($e);
return false;
}
}
}
https://developers.facebook.com/docs/reference/api/page/#photos:
no_story: If set to 1, optionally suppresses the feed story that is automatically generated on the page when you upload a photo.
Related
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 am working with multi file upload with gravity form. So after uploading I want to show the uploaded file in single post page (single.php). How to show the uploaded files in the post page. I have been using this.
(http://pastebin.com/r9w2beDW)
class GW_Multi_File_Merge_Tag {
private static $instance = null;
private $_merge_tag_args = array();
private $_settings = array();
private function __construct() {
add_filter( 'gform_pre_replace_merge_tags', array( $this, 'replace_merge_tag' ), 10, 7 );
}
public static function get_instance() {
if( null == self::$instance )
self::$instance = new self;
return self::$instance;
}
public function get_default_args() {
return array(
'form_id' => false,
'exclude_forms' => array(),
'default_markup' => '{filename}.{ext}',
'markup' => array(
array(
'file_types' => array( 'jpg', 'png', 'gif' ),
'markup' => ''
),
array(
'file_types' => array( 'mp4', 'ogg', 'webm' ),
'markup' => '
Your browser does not support the video tag.
'
),
array(
'file_types' => array( 'ogv' ),
'markup' => '
Your browser does not support the video tag.
'
)
)
);
}
public function register_settings( $args = array() ) {
$args = wp_parse_args( $args, $this->get_default_args() );
if( ! $args['form_id'] ) {
$this->_settings['global'] = $args;
} else {
$this->_settings[$args['form_id']] = $args;
}
}
public function replace_merge_tag( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
preg_match_all( '/{[^{]*?:(\d+(\.\d+)?)(:(.*?))?}/mi', $text, $matches, PREG_SET_ORDER );
foreach( $matches as $match ) {
$input_id = $match[1];
$field = GFFormsModel::get_field( $form, $input_id );
if( ! $this->is_applicable_field( $field ) )
continue;
if( $format != 'html' ) {
$value = $this->_merge_tag_args['value'];
} else {
if( $entry['id'] == null && is_callable( array( 'GWPreviewConfirmation', 'preview_image_value' ) ) ) {
$files = GWPreviewConfirmation::preview_image_value( 'input_' . $field->id, $field, $form, $entry );
} else {
$value = GFFormsModel::get_lead_field_value( $entry, $field );
$files = empty( $value ) ? array() : json_decode( $value, true );
}
$value = '';
foreach( $files as &$file ){
$value .= $this->get_file_markup( $file, $form['id'] );
}
}
$text = str_replace( $match[0], $value, $text );
}
return $text;
}
public function get_file_markup( $file, $form_id ) {
$value = str_replace( " ", "%20", $file );
$file_info = pathinfo( $value );
extract( $file_info ); // gives us $dirname, $basename, $extension, $filename
if( ! $extension )
return $value;
$markup_settings = $this->get_markup_settings( $form_id );
if( empty( $markup_settings ) )
return $value;
$markup_found = false;
foreach( $markup_settings as $file_type_markup ) {
$file_types = array_map( 'strtolower', $file_type_markup['file_types'] );
if( ! in_array( strtolower( $extension ), $file_types ) )
continue;
$markup_found = true;
$markup = $file_type_markup['markup'];
$tags = array(
'{url}' => $file,
'{filename}' => $filename,
'{basename}' => $basename,
'{ext}' => $extension
);
foreach( $tags as $tag => $tag_value ) {
$markup = str_replace( $tag, $tag_value, $markup );
}
$value = $markup;
break;
}
if( ! $markup_found && $default_markup = $this->get_default_markup( $form_id ) ) {
$tags = array(
'{url}' => $file,
'{filename}' => $filename,
'{basename}' => $basename,
'{ext}' => $extension
);
foreach( $tags as $tag => $tag_value ) {
$default_markup = str_replace( $tag, $tag_value, $default_markup );
}
$value = $default_markup;
}
return $value;
}
public function get_markup_settings( $form_id ) {
$form_markup_settings = rgars( $this->_settings, "$form_id/markup" ) ? rgars( $this->_settings, "$form_id/markup" ) : array();
$global_markup_settings = rgars( $this->_settings, 'global/markup' ) ? rgars( $this->_settings, 'global/markup' ) : array();
return array_merge( $form_markup_settings, $global_markup_settings );
}
public function get_default_markup( $form_id ) {
$default_markup = rgars( $this->_settings, "$form_id/default_markup" );
if( ! $default_markup )
$default_markup = rgars( $this->_settings, 'global/default_markup' );
return $default_markup;
}
public function is_excluded_form( $form_id ) {
$has_global_settings = isset( $this->_settings['global'] );
$excluded_forms = (array) rgars( $this->_settings, 'global/exclude_forms' );
$explicity_excluded = $has_global_settings && in_array( $form_id, $excluded_forms );
$passively_excluded = ! $has_global_settings && ! isset( $this->_settings[$form_id] );
return $explicity_excluded || $passively_excluded;
}
public function is_applicable_field( $field ) {
$is_valid_form = ! $this->is_excluded_form( $field['formId'] );
$is_file_upload_filed = GFFormsModel::get_input_type( $field ) == 'fileupload';
$is_multi = rgar( $field, 'multipleFiles' );
return $is_valid_form && $is_file_upload_filed && $is_multi;
}
}
function gw_multi_file_merge_tag() {
return GW_Multi_File_Merge_Tag::get_instance();
}
gw_multi_file_merge_tag()->register_settings( array(
'form_id' => 1,
'markup' => array(
array(
'file_types' => array( 'jpg', 'jpeg', 'png', 'gif' ),
'markup' => '{filename}'
),
array(
'file_types' => array( 'pdf', 'txt' ),
'markup' => '{filename}{filenam}'
),
array(
'file_types' => array( 'mp4', 'ogg', 'webm' ),
'markup' => 'Your browser does not support the video tag.{filename}'
),
array(
'file_types' => array( 'ogv' ),
'markup' => 'Your browser does not support the video tag.{filename}'
)
)
) );
But cannot show the file or file link in post page. Can anyone help me?
At work, I've been tasked with modifying the Wordpress Social Board plugin by duplicating their RSS feed functionality to display an XML feed specific to our calendaring system.
For example, this is what our XML feed outputs:
<?xml version="1.0"?>
<events>
<event>
<eventid>1449080815796</eventid>
<sponsorid>14</sponsorid>
<inputsponsor>Administration</inputsponsor>
<displayedsponsor>Lesbian, Gay, Bisexual, and Transgender (LGBT) Resource Center, The Division of Student Affairs</displayedsponsor>
<displayedsponsorurl></displayedsponsorurl>
<date>2016-01-25</date>
<timebegin>18:00</timebegin>
<timeend>20:00</timeend>
<repeat_vcaldef></repeat_vcaldef>
<repeat_startdate></repeat_startdate>
<repeat_enddate></repeat_enddate>
<categoryid>119</categoryid>
<category>Diversity</category>
<title>New 2 'Quse Discussion Group</title>
<description>New 2 'Quse is a discussion group for students who are new to SU/ESF and the lesbian, gay, bisexual, transgender, queer, asexual, and ally (LGBTQA) campus communities.</description>
<location>LGBT Resource Center (750 Ostrom)</location>
<price></price>
<contact_name>Abby Fite</contact_name>
<contact_phone>443-3983</contact_phone>
<contact_email>alfite#syr.edu</contact_email>
<url>http://lgbt.syr.edu</url>
<recordchangedtime>2015-12-02 13:26:55</recordchangedtime>
<recordchangeduser>dsalgbt2</recordchangeduser>
</event>
</events>
There is one place in the code that actually formats their RSS feed:
elseif ( $feed_class == 'rss' ) {
$rss_output = (#$this->sboption['section_rss']['rss_output']) ? $this->sboption['section_rss']['rss_output'] : array('title' => true, 'thumb' => true, 'text' => true, 'user' => true, 'tags' => false, 'share' => true, 'info' => true);
$iframe = #$this->sboption['section_rss']['rss_iframe'];
$fcount = 0;
if ( $channel = #$feed->channel ) { // rss
if (#$channel->item)
foreach($channel->item as $item) {
$link = #$item->link;
if ( $this->make_remove($link) ) {
$fcount++;
$thumb = $url = '';
foreach($item->children('media', true)->thumbnail as $thumbnail) {
$thumb = $thumbnail->attributes()->url;
}
if ( ! $thumb) {
foreach($item->children('media', true)->content as $content) {
$thumb = $content->children('media', true)->thumbnail->attributes()->url;
if (#$content->attributes()->type == 'image/jpeg')
$url = #$content->attributes()->url;
}
}
if ( ! $thumb) {
if (#$item->enclosure->attributes()->type == 'image/jpeg')
$thumb = #$item->enclosure->attributes()->url;
}
if (#$item->category && #$rss_output['tags'])
foreach($item->category as $category) {
$cats[] = (string) $category;
}
// set Snippet or Full Text
$text = $description = '';
if (#$this->sboption['section_rss']['rss_text'])
$description = $item->description;
else
$description = (#$item->children("content", true)->encoded) ? $item->children("content", true)->encoded : $item->description;
if (#$description) {
$description = preg_replace("/<script.*?\/script>/s", "", $description);
if (#$attr['words']) {
if ( ! $thumb) {
$thumb = sb_getsrc($description);
}
$text = $this->word_limiter($description, $link);
} else {
$text = $description;
}
}
if ($iframe) {
if ( ! $url)
$url = (#$thumb) ? $thumb : '';
}
$sbi = $this->make_timestr($item->pubDate, $link);
$itemdata = array(
'thumb' => (#$thumb) ? $thumb : '',
'thumburl' => $url,
'title' => '<a href="' . $link . '"'.$target.'>' . (#$attr['titles'] ? $this->title_limiter($item->title) : $item->title) . '</a>',
'text' => $text,
'tags' => #implode(', ', $cats),
'url' => $link,
'iframe' => $iframe ? 'icbox' : '',
'date' => $item->pubDate,
'user' => array(
'name' => $channel->title,
'url' => $channel->link,
'image' => #$channel->image->url
),
'type' => 'pencil',
'icon' => array(#$themeoption['social_icons'][12], #$themeoption['type_icons'][0])
);
$final[$sbi] = $layoutobj->sb_create_item($feed_class, $itemdata, $attr, $rss_output, $sbi);
if ( isset($slideshow) ) {
$itemdata['text'] = #$this->format_text($description);
if ($url)
$itemdata['thumb'] = $url;
$finalslide[$sbi] = $slidelayoutobj->sb_create_slideitem($feed_class, $itemdata, $attr, $rss_output, $sbi);
}
if ( $fcount >= $results ) break;
}
}
} elseif ( $entry = #$feed->entry ) { // atom
// get feed link
foreach($feed->link as $link) {
if ($link->attributes()->rel == 'alternate')
$user_url = $link->attributes()->href;
}
foreach($feed->entry as $item) {
$link = #$item->link[0]->attributes()->href;
if ( $this->make_remove($link) ) {
$fcount++;
$title = (string) $item->title;
$thumb = $url = '';
foreach($item->media as $thumbnail) {
$thumb = $thumbnail->attributes()->url;
}
if ( ! $thumb) {
foreach($item->link as $linkitem) {
if (#$linkitem->attributes()->rel == 'enclosure') {
if (#$linkitem->attributes()->type == 'image/jpeg')
$thumb = #$content->attributes()->url;
}
}
}
$cats = '';
if (#$item->category && #$rss_output['tags']) {
foreach($item->category as $category) {
$cats .= $category->attributes()->term.', ';
}
$cats = rtrim($cats, ", ");
}
// set Snippet or Full Text
$text = $description = '';
if (#$this->sboption['section_rss']['rss_text']) {
$description = (string) $item->summary;
} else {
$content = (string) #$item->content;
$description = ($content) ? $content : (string) $item->summary;
}
if (#$description) {
if (#$attr['words']) {
if ( ! $thumb) {
$thumb = sb_getsrc($description);
}
$text = $this->word_limiter($description, $link);
}
else {
$text = $description;
}
}
if ($iframe)
$url = (#$thumb) ? $thumb : '';
$sbi = $this->make_timestr($item->published, $link);
$itemdata = array(
'thumb' => #$thumb,
'thumburl' => $url,
'title' => '<a href="' . $link . '"'.$target.'>' . (#$attr['titles'] ? $this->title_limiter($title) : $title) . '</a>',
'text' => #$text,
'tags' => #$cats,
'url' => $link,
'iframe' => $iframe ? 'icbox' : '',
'date' => $item->published,
'user' => array(
'name' => $feed->title,
'url' => #$user_url,
'image' => #$feed->logo
),
'type' => 'pencil',
'icon' => array(#$themeoption['social_icons'][12], #$themeoption['type_icons'][0])
);
$final[$sbi] = $layoutobj->sb_create_item($feed_class, $itemdata, $attr, $rss_output, $sbi);
if ( isset($slideshow) ) {
$itemdata['text'] = #$this->format_text($description);
if ($url)
$itemdata['thumb'] = $url;
$finalslide[$sbi] = $slidelayoutobj->sb_create_slideitem($feed_class, $itemdata, $attr, $rss_output, $sbi);
}
if ( $fcount >= $results ) break;
}
}
}
}
I've duplicated the code into another feed class and modified, but it is not pulling any values it seems:
elseif ( $feed_class == 'dsa' ) {
$rss_output = (#$this->sboption['section_dsa']['dsa_output']) ? $this->sboption['section_dsa']['dsa_output'] : array('title' => true, 'thumb' => true, 'text' => true, 'user' => true, 'tags' => false, 'share' => true, 'info' => true);
$iframe = #$this->sboption['section_dsa']['dsa_iframe'];
$fcount = 0;
if ( $channel = #$feed->events ) { // rss
if (#$channel->event)
foreach($channel->event as $item) {
$link = #$item->displayedsponsorurl;
if ( $this->make_remove($link) ) {
$fcount++;
$thumb = $url = '';
foreach($item->children('media', true)->thumbnail as $thumbnail) {
$thumb = $thumbnail->attributes()->url;
}
if ( ! $thumb) {
foreach($item->children('media', true)->content as $content) {
$thumb = $content->children('media', true)->thumbnail->attributes()->url;
if (#$content->attributes()->type == 'image/jpeg')
$url = #$content->attributes()->url;
}
}
if ( ! $thumb) {
if (#$item->enclosure->attributes()->type == 'image/jpeg')
$thumb = #$item->enclosure->attributes()->url;
}
if (#$item->category && #$rss_output['tags'])
foreach($item->category as $category) {
$cats[] = (string) $category;
}
// set Snippet or Full Text
$text = $description = '';
if (#$this->sboption['section_dsa']['dsa_text'])
$description = $item->description;
else
$description = (#$item->children("content", true)->encoded) ? $item->children("content", true)->encoded : $item->description;
if (#$description) {
$description = preg_replace("/<script.*?\/script>/s", "", $description);
if (#$attr['words']) {
if ( ! $thumb) {
$thumb = sb_getsrc($description);
}
$text = $this->word_limiter($description, $link);
} else {
$text = $description;
}
}
if ($iframe) {
if ( ! $url)
$url = (#$thumb) ? $thumb : '';
}
$sbi = $this->make_timestr($item->pubDate, $link);
$itemdata = array(
'thumb' => (#$thumb) ? $thumb : '',
'thumburl' => $url,
'title' => '<a href="' . $link . '"'.$target.'>' . (#$attr['titles'] ? $this->title_limiter($item->title) : $item->title) . '</a>',
'text' => $text,
'tags' => #implode(', ', $cats),
'url' => $link,
'iframe' => $iframe ? 'icbox' : '',
'date' => $item->date,
'user' => array(
'name' => $channel->title,
'url' => $channel->link,
'image' => #$channel->image->url
),
'type' => 'pencil',
'icon' => array(#$themeoption['social_icons'][12], #$themeoption['type_icons'][0])
);
$final[$sbi] = $layoutobj->sb_create_item($feed_class, $itemdata, $attr, $rss_output, $sbi);
if ( isset($slideshow) ) {
$itemdata['text'] = #$this->format_text($description);
if ($url)
$itemdata['thumb'] = $url;
$finalslide[$sbi] = $slidelayoutobj->sb_create_slideitem($feed_class, $itemdata, $attr, $rss_output, $sbi);
}
if ( $fcount >= $results ) break;
}
}
} elseif ( $entry = #$feed->entry ) { // atom
// get feed link
foreach($feed->link as $link) {
if ($link->attributes()->rel == 'alternate')
$user_url = $link->attributes()->href;
}
foreach($feed->entry as $item) {
$link = #$item->link[0]->attributes()->href;
if ( $this->make_remove($link) ) {
$fcount++;
$title = (string) $item->title;
$thumb = $url = '';
foreach($item->media as $thumbnail) {
$thumb = $thumbnail->attributes()->url;
}
if ( ! $thumb) {
foreach($item->link as $linkitem) {
if (#$linkitem->attributes()->rel == 'enclosure') {
if (#$linkitem->attributes()->type == 'image/jpeg')
$thumb = #$content->attributes()->url;
}
}
}
$cats = '';
if (#$item->category && #$rss_output['tags']) {
foreach($item->category as $category) {
$cats .= $category->attributes()->term.', ';
}
$cats = rtrim($cats, ", ");
}
// set Snippet or Full Text
$text = $description = '';
if (#$this->sboption['section_dsa']['dsa_text']) {
$description = (string) $item->summary;
} else {
$content = (string) #$item->content;
$description = ($content) ? $content : (string) $item->summary;
}
if (#$description) {
if (#$attr['words']) {
if ( ! $thumb) {
$thumb = sb_getsrc($description);
}
$text = $this->word_limiter($description, $link);
}
else {
$text = $description;
}
}
if ($iframe)
$url = (#$thumb) ? $thumb : '';
$sbi = $this->make_timestr($item->published, $link);
$itemdata = array(
'thumb' => #$thumb,
'thumburl' => $url,
'title' => '<a href="' . $link . '"'.$target.'>' . (#$attr['titles'] ? $this->title_limiter($title) : $title) . '</a>',
'text' => #$text,
'tags' => #$cats,
'url' => $link,
'iframe' => $iframe ? 'icbox' : '',
'date' => $item->published,
'user' => array(
'name' => $feed->title,
'url' => #$user_url,
'image' => #$feed->logo
),
'type' => 'pencil',
'icon' => array(#$themeoption['social_icons'][12], #$themeoption['type_icons'][0])
);
$final[$sbi] = $layoutobj->sb_create_item($feed_class, $itemdata, $attr, $rss_output, $sbi);
if ( isset($slideshow) ) {
$itemdata['text'] = #$this->format_text($description);
if ($url)
$itemdata['thumb'] = $url;
$finalslide[$sbi] = $slidelayoutobj->sb_create_slideitem($feed_class, $itemdata, $attr, $rss_output, $sbi);
}
if ( $fcount >= $results ) break;
}
}
}
}
I apologize for this being a highly specific question. I am inexperienced with PHP, especially for Wordpress plugins and have been tasked to get this working ASAP...
Am I just missing something with the operators not pulling in the values? I haven't set all the values yet, I'm just modifying the ones that already exist before moving onto adding anything.
There are no direct errors my logs pulled, so I believe it's just not pulling in the right values, but I'm not sure how to fix that.
I've got this basic function as below:
function buy()
{
$item_id = ( int )$this->uri->segment( 3 );
if ( $item_id > '0' )
{
$item = $this->db->where( 'shop_id', $item_id )->get( 'shop' )->row();
if ( $item )
{
$player = $this->user->info( $this->user->id() );
if ( $player->users_money >= $item->shop_req_money && $player->users_credits >= $item->shop_req_credits)
{
$this->db->update( 'users_items', array( 'users_id' => $this->user->id(), 'users_motors_id' => '0' ), array( 'users_items_id' => $item->users_items_id ) );
$this->db->update( 'users', array( 'users_money' => $player->users_money - $item->shop_req_money, 'users_credits' => $player->users_credits - $item->shop_req_credits ), array( 'users_id' => $this->user->id() ) );
$this->db->query( 'UPDATE users SET users_money=users_money+' . $item->shop_req_money . ', users_credits=users_credits+' . $item->shop_req_credits . ' WHERE users_id=' . $this->db->escape( $item->shop_users_id ) );
$this->db->delete( 'shop', array( 'shop_id' => $item->shop_id ) );
$this->session->set_flashdata( 'success', true );
}
else
$this->session->set_flashdata( 'error', true );
}
}
header( 'Location: ' . $_SERVER['HTTP_REFERER'] );
}
and I edited it like that to add additional check if the reg ip isn't the same as the other one and if so to set an error message.
function buy()
{
$item_id = ( int )$this->uri->segment( 3 );
if ( $item_id > '0' )
{
$item = $this->db->where( 'shop_id', $item_id )->get( 'shop' )->row();
if ( $item )
{
$player = $this->user->info( $this->user->id() );
$players = $this->user->info( $item->shop_users_id );
if ( $players->users_reg_ip === $player->users_reg_ip )
{
$this->session->set_flashdata( 'errorip', true );
}
elseif ( $player->users_money >= $item->shop_req_money && $player->users_credits >= $item->shop_req_credits)
{
$this->db->update( 'users_items', array( 'users_id' => $this->user->id(), 'users_motors_id' => '0' ), array( 'users_items_id' => $item->users_items_id ) );
$this->db->update( 'users', array( 'users_money' => $player->users_money - $item->shop_req_money, 'users_credits' => $player->users_credits - $item->shop_req_credits ), array( 'users_id' => $this->user->id() ) );
$this->db->query( 'UPDATE users SET users_money=users_money+' . $item->shop_req_money . ', users_credits=users_credits+' . $item->shop_req_credits . ' WHERE users_id=' . $this->db->escape( $item->shop_users_id ) );
$this->db->delete( 'shop', array( 'shop_id' => $item->shop_id ) );
$this->session->set_flashdata( 'success', true );
}
else
$this->session->set_flashdata( 'error', true );
}
}
header( 'Location: ' . $_SERVER['HTTP_REFERER'] );
}
It works the way it is BUT basically I am asking if thats the correct way of doing that or there should be something else I can do similiar to that but better? Would be really appreciated if there any comments on my question. Thanks in advance!
Yes you can include that on the condition block. Like this:
if ( $players->users_reg_ip === $player->users_reg_ip) {
// trying to buy from the same IP
$this->session->set_flashdata( 'errorip', true );
}
elseif ( $player->users_money < $item->shop_req_money && $player->users_credits < $item->shop_req_credits) {
// if user has not enough money and user credits is less than shop requirement credits
// or maybe you mean OR ||
$this->session->set_flashdata( 'error', true );
}
else {
$this->db->update('users_items',
array( 'users_id' => $this->user->id(), 'users_motors_id' => '0' ),
array( 'users_items_id' => $item->users_items_id )
);
$this->db->update( 'users',
array( 'users_money' => $player->users_money - $item->shop_req_money,
'users_credits' => $player->users_credits - $item->shop_req_credits
),
array( 'users_id' => $this->user->id() )
);
$this->db->query( 'UPDATE users SET users_money=users_money+' . $item->shop_req_money . ', users_credits=users_credits+' . $item->shop_req_credits . ' WHERE users_id=' . $this->db-> escape( $item->shop_users_id ) );
$this->db->delete( 'shop', array( 'shop_id' => $item->shop_id ) );
$this->session->set_flashdata( 'success', true );
}
// instead of using referrer why not
// redirect('controller/method'); ?
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 ) );