JSON API + wordpress URL - wordpress

I'm using a small JSON API for URL shortener that I would like to integrate on all my Wordpress pages.
I know how to render the Wordpress page URL but what I don't know (due to no experience with APIs) is how to render the API result on the Wordpress page.
Here is the API call:
http://abc.net/api?api=123&url=LONGURL
Here is the API result:
{
"error":"0",
"short":"http://abc.net/ALIAS",
}
Here is the WP url that needs to replace the "LONGURL" above:
<?php echo get_permalink(); ?>
What I need is to show the "short" result.
Any ideas?

Assuming you've set allow_url_fopen to true in php.ini
function get_short_permalink() {
$permalink = get_permalink();
$response = file_get_contents('http://abc.net/api?api=123&url=' . $permalink);
$response = json_decode($response, true);
if($response['error'] == 0) {
return $response['short'];
}
return $permalink;
}
Then replace <?php echo get_permalink(); ?> with <?php echo get_short_permalink(); ?> in your templates.
What this function does:
gets the original permalink
sends a GET request to your API
transforms the response from a JSON string to a PHP array (see the docs for the bool $assoc parameter of json_decode)
returns the shortened link if the error code is 0, or the original link if not
You'll have to work with cURL if you can't (or don't want to) enable url_fopen.
Also, WordPress has a built-in wrapper over cURL that could simplify things a lot: wp_remote_get

Related

Wordpress Mixed content requested an insecure XMLHttpRequest endpoint

OK I checked all other similar answers, but thanks to people that downvote for no reason there is no actual response.
I am using Wordpress and I have a Mixed Content with a website https://oujdaportail.net/
It is generating this error:
Mixed Content: The page at 'https://oujdaportail.net/' was loaded over
HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://oujdaportail.net/'. This request has been blocked; the content
must be served over HTTPS.
Chrome debug console has been completely useless!! It detects the error at the first line of source code where there is nothing to look up.
I am not sure how I should resolve this... I need help to capture the source of this issue.
Finally! I would be someone's hero...
After hours of struggle, it turned out that wp_head and wp_footer where responsible for generating unknown HTTP requests. And to fix it all I had to do is create a custom wp_head and wp_footer function just like this:
/**
* Wrapper for wp_head() which manages SSL
*
* #uses wp_head()
* #param bool $ssl
* #return void
*/
function custom_wp_head() {
// Capture wp_head output with buffering
ob_start();
wp_head();
$wp_head = ob_get_contents();
ob_end_clean();
// Replace plain protocols
$wp_head = preg_replace( '/(["\'])http:\/\//', '\1https://', $wp_head );
// Output
echo $wp_head;
}
function custom_wp_footer() {
// Capture wp_head output with buffering
ob_start();
wp_footer();
$wp_footer = ob_get_contents();
ob_end_clean();
// Replace plain protocols
$wp_footer = preg_replace( '/(["\'])http:\/\//', '\1https://', $wp_footer );
// Output
echo $wp_footer;
}

How to return the entire request url using silverstripe

I have website url like, I would like to get full url so that i can pass to social network for sharing purpose
i.e. www.mysite.com/projects?tab=2
I tried AbsoluteLink but '?tab=2' is left out.
If you are trying to get the complete URL of the current page you can for example combine AbsoluteLink with $_SERVER['QUERY_STRING']:
$url = $page->AbsoluteLink() . '?' . $_SERVER['QUERY_STRING'];
or you build the link with the PHP environment variables:
$url = ($_SERVER["HTTPS"] == 'on') ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
Generally a look at the environment variables of PHP can help a lot. You can just display all of the environment information by running this simple script on your web server:
<?php
phpinfo();
source: http://php.net/manual/en/function.phpinfo.php

Instagram public RSS feed

I was wondering how ink361 was creating an Instagram RSS feed from a username.
Example feed: http://ink361.com/feed/user/snoopdogg
Blog post:
http://blog.ink361.com/post/23664609916/new-rss-instagram-feed-feature-on-ink361-com
Any insight would be appreciated.
Thanks.
Instagram has a publicly accessible RSS API, it's hard to find any information about it, but it works for tags (we do use it).
For tags the syntax is the following:
http://instagr.am/tags/some-tag-you-want-to-follow/feed/recent.rss
I'm not sure whether they have something similar for users' feeds, as I've said it's really hard to find information about it and it may disappear from a day to another in favor of the official API, but right now it works for tags.
Here's an official blog post about it (although it covers only tags): http://blog.instagram.com/post/8755963247/introducing-hashtags-on-instagram
#user2543857 's answer was good. Unfortunately, the structure of the Instagram data has changed. As of the date of posting this, this will work. Copy/paste into a file on your PHP server and use like: yoursite.com/instarss.php?user=name_of_instagram_user This will return valid XML/RSS feed.
EDIT!! Naturally, the output of the page/JSON has changed with instagram's new look/feel. Here is updated code (June, 2015):
<?php
if (!isset($_GET['user'])) {
exit('Not a valid RSS feed. You didn\'nt provide an Instagram user. Send one via a GET variable. Example .../instarss.php?user=snoopdogg');
}
header('Content-Type: text/xml; charset=utf-8');
$html = file_get_contents('http://instagram.com/'.$_GET['user'].'/');
$html = strstr($html, '{"static_root');
$html = strstr($html, '</script>', true);
//$html = substr($html,0,-6);
$html = substr($html, 0, -1);
$data = json_decode($html);
// print_r($data->entry_data->ProfilePage[0]->user->media->nodes);
$rss_feed = '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel>';
$rss_feed .= '<title>'.$_GET['user'].'\'s Instagram Feed</title><atom:link href="http://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"].'" rel="self" type="application/rss+xml" /><link>http://instagram.com/'.$_GET['user'].'</link><description>'.$_GET['user'].'\'s Instagram Feed</description>';
foreach($data->entry_data->ProfilePage[0]->user->media->nodes as $node) {
$rss_feed .= '<item><title>';
if(isset($node->caption) && $node->caption != '') {
$rss_feed .= htmlspecialchars($node->caption, ENT_QUOTES, ENT_HTML5);
} else {
$rss_feed .= 'photo';
}
// pubdate format could also be: "D, d M Y H:i:s T"
$rss_feed .= '</title><link>https://instagram.com/p/'.$node->code.'/</link><pubDate>'.date("r", $node->date).'</pubDate><dc:creator><![CDATA['.$_GET['user'].']]></dc:creator><description><![CDATA[<img src="'.$node->display_src.'" />]]></description><guid>https://instagram.com/p/'.$node->code.'/</guid></item>';
} // foreach "node" (photo)
$rss_feed .= '</channel></rss>';
echo $rss_feed;
?>
Actually, don't use the above code. I'll try to maintain this Gist in the future.
EDIT December 2016: I'm tired of chasing the every-changing Instagram output only to screen scrape it and have it change a few months later. I'd say just use the API.. If you are still interested in making an RSS feed from a user's page, this Gist should give you an idea of how to do it.
You can access the feed for any Instagram user using the /users/user-id/media/recent API endpoint. This endpoint requires an access_token which you can obtain by authorizing some user with Instagram (not necessarily the one you request the feed for). The process for receiving access_token is described here.
So what ink361 may be doing is get an access_token for themselves (their user on Instagram) and use that to make /users/user-id/media/recent requests for any other users' feeds. Simple as that.
Thanks to torvin for the tip.
Here is how you can get instagram images on your site without using the API.
Create json file from url and username (set this as a cron job, X times per day)
<?
$html = file_get_contents('http://instagram.com/username/');
$html = strstr($html, '["lib');
$html = strstr($html, '</script>', true);
$html = substr($html,0,-6);
file_put_contents("username.json",$html);
?>
Display a few images from json feed
<?
$json = file_get_contents('username.json');
$data = json_decode($json);
$img1 = $data[2][0]->props->userMedia[0]->images->standard_resolution->url;
$img2 = $data[2][0]->props->userMedia[1]->images->standard_resolution->url;
$img3 = $data[2][0]->props->userMedia[2]->images->standard_resolution->url;
print '<img src="'.$img1.'" />';
print '<img src="'.$img2.'" />';
print '<img src="'.$img3.'" />';
?>
If I were ink361, I would just crawl Instagram pages, parse HTML and turn it into RSS. No API, no authorization, no problems.
Unfortunately user2543857's solution above doesn't work anymore. Here's a version that works with the current profile page source though.
Create JSON file from URL and username (set this as a cron job, X times per day)
<?php
$json = file_get_contents('http://instagram.com/username');
$json = strstr($json, '{"entry_data"');
$json = strstr($json, '</script>', true);
$json = rtrim($json,';');
file_put_contents("username.json",$json);
?>
Display a few images from JSON feed
<?php
$json = file_get_contents('username.json');
$data = json_decode($json,true);
$img1 = $data['entry_data']['UserProfile'][0]['userMedia'][0]['images']['thumbnail']['url'];
$img2 = $data['entry_data']['UserProfile'][0]['userMedia'][1]['images']['thumbnail']['url'];
$img3 = $data['entry_data']['UserProfile'][0]['userMedia'][2]['images']['thumbnail']['url'];
print '<img src="'.$img1.'" />';
print '<img src="'.$img2.'" />';
print '<img src="'.$img3.'" />';
?>
You can get access to your rss feed for instagram by using their API. Their API uses oAuth2 for authentication. I use this method on my personal blog to pull in instagram pics on the homepage. I suspect this is how the ink361 site works. Ink361 will connect to the instagram api and prompt the user with a login via instagram box which they use to allow ink361 access to their instagram account. The ink361 site will cache the token received by instagram once authentication is successfull so they then can repeatedly go back to the instagram api on a periodic basis using the same token for authentication. Bingo you have access to the users data and you can create an rss feed from it.
The answer is simple.
To access user data you just must have valid access token.
The ink361 has an app in social network http://vk.com/app3225087 which stores authenticated users access tokens in db.
Its only left to find in db a valid one and get whatever user data you want

Configuring IIS to pass POST data through 301 redirect

I am currently working on a site hosted on IIS 7 for a client, and the site is configured to redirect any naked domain requests to redirect to the 'www' subdomain. However, this is causing a problem with some of the forms on the site, which point to the naked domain. When the form is submitted, it forwards to the correct page on the 'www'subdomain, but the POST parameters are lost - the page on the 'www' subdomain is requested with an HTTP GET request regardless of the request type of the original request.
I am very unfamiliar with IIS and its configuration, so I imagine that this is something simple to fix, but how can I ensure that POST requests are preserved over a 301 redirect on IIS?
If you post via 301 the post data will be removed. You need create eq php script that re-parse data and send again
/* FOR test */
$_POST['value'] = 123;
$_POST['key'] = 888;
# Online $_POST check
$_GET['redirect'] = 'https://posttestserver.com/post.php';
/* END: FOR test */
if( filter_var($_GET['redirect'], FILTER_VALIDATE_URL) ) {
if ( is_array($_POST) ) :
echo '<form method="post" action="'. $_GET['redirect'] .'" name="f">';
foreach($_POST as $i => $v){
echo '<input type="hidden" name="'. $i .'" value="'. $v .'">';
}
echo '</form> <script> document.f.submit(); </script>';
else : // IF _GET
$tmp = $_GET['redirect'];
unset($_GET['redirect']);
$ur = http_build_query($_GET);
header("Location: " . $tmp . '?' . $ur);
endif;
}

Fatal error: Call to undefined method Facebook::require_frame() in /home/wubb/public_html/facebook/fbml.php on line 15

I am trying to integrate friend invite for facebook in my website. I am using php. I included the code:
<?PHP
// Get these from http://developers.facebook.com
$api_key = 'xxx';
$secret = 'xxx';
// Names and links
$app_name = "Application name";
$app_url = "app-url"; // Assumes application is at http://apps.facebook.com/app-url/
$invite_href = "invite.php"; // Rename this as needed
require_once 'facebook.php';
$facebook = new Facebook($api_key, $secret);
$facebook->require_frame();
$user = $facebook->require_login();
if(isset($_POST["ids"])) {
echo "<center>Thank you for inviting ".sizeof($_POST["ids"])." of your friends on <b>".$app_name."</b>.<br><br>\n";
echo "<h2>Click here to return to ".$app_name.".</h2></center>";
} else {
// Retrieve array of friends who've already authorized the app.
$fql = 'SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='.$user.') AND is_app_user = 1';
$_friends = $facebook->api_client->fql_query($fql);
// Extract the user ID's returned in the FQL request into a new array.
$friends = array();
if (is_array($_friends) && count($_friends)) {
foreach ($_friends as $friend) {
$friends[] = $friend['uid'];
}
}
// Convert the array of friends into a comma-delimeted string.
$friends = implode(',', $friends);
// Prepare the invitation text that all invited users will receive.
$content =
"<fb:name uid=\"".$user."\" firstnameonly=\"true\" shownetwork=\"false\"/> has started using ".$app_name." and thought it's so cool even you should try it out!\n".
"<fb:req-choice url=\"".$facebook->get_add_url()."\" label=\"Put ".$app_name." on your profile\"/>";
?>
<fb:request-form
action="<? echo $invite_href; ?>"
method="post"
type="<? echo $app_name; ?>"
content="<? echo htmlentities($content,ENT_COMPAT,'UTF-8'); ?>">
<fb:multi-friend-selector
actiontext="Here are your friends who don't have <? echo $app_name; ?> yet. Invite whoever you want -it's free!"
exclude_ids="<? echo $friends; ?>" />
</fb:request-form>
<?PHP
}
?>
[[Image:multi-friend-selector.png]]
Here I included facebook.php file I downloaded from the github .I tried many versions of phpSDK but still the following error is coming
Fatal error: Call to undefined method Facebook::require_frame()
Can anybody suggest which version conatain this function or how to solve this issue. I have lost a lot of time trying to solve this. So respond as soon as possible.
Trikode,
Make sure you are using the most recent version of the php sdk: https://github.com/facebook/facebook-php-sdk. There is a really easy to follow guide here to help you get started: https://developers.facebook.com/docs/reference/php/

Resources