how to capture recource link using simplepie parser - xml-parsing

Im new to RSS feed parsing and having a little trouble. How would I use simplepie to capture the following resource?
<enc:enclosure resource="http://images.craigslist.org/00202_lQ0CCpDIPk0_300x300.jpg" type="image/jpeg"/>

You would use the get_enclosures() function.
$feed = new SimplePie();
$feed->set_feed_url('http://simplepie.org/blog/feed/');
$feed->init();
$feed->handle_content_type();
foreach ($feed->get_items() as $item)
{
foreach ($item->get_enclosures() as $enclosure)
{
echo $enclosure->embed();
}
}

Previous responder doesn't realize how SimplePie works. You don't use the get_enclosures() because the XML is not formatted as <enclosure> ...
Instead you do it like this:
require( 'autoloader.php' );
$feed = new SimplePie();
$feed->set_feed_url('https://denver.craigslist.org/search/msa?format=rss&query=left%20handed%20%7C%20lefthanded%20%7C%20lefty');
$feed->init();
$feed->handle_content_type();
foreach ($feed->get_items() as $item) {
$encs = $item->get_item_tags( 'http://purl.oclc.org/net/rss_2.0/enc#', 'enclosure' );
if ( !isset( $encs ) )
continue;
foreach ( $encs as $enclosure){
if ( !isset( $enclosure['attribs'] ) )
continue;
foreach ( $enclosure['attribs'] as $attr ) {
echo "\n" . $attr['resource'];
}
}
}

Related

Change upload_dir folder at a certain cpt but cant change back

im try something with the upload_dir filter
I check the current CPT with this function
function get_current_post_type() {
global $post, $typenow, $current_screen;
//we have a post so we can just get the post type from that
if ( $post && $post->post_type ) {
return $post->post_type;
} //check the global $typenow - set in admin.php
elseif ( $typenow ) {
return $typenow;
} //check the global $current_screen object - set in sceen.php
elseif ( $current_screen && $current_screen->post_type ) {
return $current_screen->post_type;
} //lastly check the post_type querystring
elseif ( isset( $_REQUEST['post_type'] ) ) {
return sanitize_key( $_REQUEST['post_type'] );
}
//we do not know the post type!
return NULL;
}
now i want to change the 'upload_dir' on at a certain cpt called "rsg_download"
add_action( 'admin_init', 'call_from_admin' );
function call_from_admin() {
//Here i get the Current custom Post type is the Post type = "rsg_download" then i want upload in a other folder called "rsg-uploads"
$currentCPT = get_current_post_type();
if ( $currentCPT = 'rsg_download' ) {
add_filter( 'upload_dir', 'change_upload_dir' );
}
}
When i use only
$currentCPT = get_current_post_type();
if ( $currentCPT = 'rsg_download' ) {
add_filter( 'upload_dir', 'change_upload_dir' );
}
The 'change_upload_dir' function is called twice dont know why also i call this from 'admin_init' with the function 'call_from_admin' and it calls only one time so far so good
i go to my CPT "rsg_download" and the uploade files are in the right place at wp-content/uploads/rsg-uploads/ this works so far
now i go to "Pages" and i upload a File but i want the files not in /rsg-upload but in the default path
Function to change the upload_dir this function should only be called when the custom post type is 'rsg_download':
function change_upload_dir( $param ) {
$mydir = '/rsg-uploads';
$param['path'] = $param['basedir'] . $mydir;
$param['url'] = $param['baseurl'] . $mydir;
return $param;
}
I found! this will only change the upload dir when upload in the "rsg_download" CPT
add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );
function rsg_pre_upload( $file ) {
add_filter( 'upload_dir', 'rsg_custom_upload_dir' );
return $file;
}
function rsg_custom_upload_dir( $param ) {
$id = $_REQUEST['post_id'];
$parent = get_post( $id )->post_parent;
if( "rsg_download" == get_post_type( $id ) || "rsg_download" == get_post_type( $parent ) ) {
$mydir = '/rsg-uploads';
$param['path'] = $param['basedir'] . $mydir;
$param['url'] = $param['baseurl'] . $mydir;
}
return $param;
}

Hooking up OpenCart with an iOS App via web services

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

Jquery mobile, How to use changePage to update changeHash and Parameters

options.dataUrl = urlObj.href;
$.mobile.changePage( $page, options );
dataUrl contains the complete url with parameters
http://example.com/#sales?p=page
but the above code only updates the url with hash only, after the new page loads... the url changes to
http://example.com/#sales
and does not apply ?p=page.
Here is the complete function, check the last few lines....
function getSPList( urlObj, options ){
var pageName = urlObj.hash.replace( /.*p=/, "" ),
pageSelector = urlObj.hash.replace( /\?.*$/, "" );
$.ajax({
url:"getSPList.php",
dataType: 'json',
data: {p: pageName},
success:function(result){
if ( result ) {
var $page = $( pageSelector ),
$header = $page.children( ":jqmData(role=header)" ),
$content = $page.children( ":jqmData(role=content)" ),
markup = "<ul data-role='listview' data-filter='true' data-filter-placeholder='Search Salesperson...'>";
for ( var i = 0; i < result.sp.length; i++ ) {
markup += "<li><a href='#addClient?p="+ result.sp[i].id +"' data-transition='slide'>" + result.sp[i].name + "</a></li>";
}
markup += "</ul>";
$content.html( markup );
$page.page();
$content.find( ":jqmData(role=listview)" ).listview();
options.dataUrl = urlObj.href;
options.changeHash = true;
$.mobile.changePage( $page, options );
}
}
});
return
}
I have experienced the same problem and here is what I've found as of version 1.3.2:
Inside $.mobile.changePage(toPage, options) options.dataUrl is passed through path.convertUrlToDataUrl() before being stored and used.
Inside path.convertUrlToDataUrl() everything before and including the '#' as well as everything after and including the '?' is stripped.
Further down inside of $.mobile.changePage() before the url is passed to $.mobile.navigate() I see this:
// rebuilding the hash here since we loose it earlier on
// TODO preserve the originally passed in path
if( !path.isPath( url ) && url.indexOf( "#" ) < 0 ) {
url = "#" + url;
}
So it seems to be a bug in jQm. For my app I'm adding this inside the bottom of the previously mentioned if statement:
var query_index = (settings.dataUrl || '').indexOf('?');
if (query_index > -1) {
url += settings.dataUrl.substring(query_index);
}
This solves the initial problem but I'm unsure about potential negative side effects or if there is a better workaround out there.

Checking how many fields have changed upon saving a form

I am saving records in a transaction using symfony1.4 and Doctrine.
The rows inserted are coming from a CSV file which is updated regularly. I have already got a method that checks if the records in the CSV match that in the DB and do not insert.
What I'm ideally wanting to do though, is to set a user flash telling them how many rows have been updated whenever they import the CSV file.
$conn = ProductTable::getInstance()->getConnection();
$conn->beginTransaction();
try {
$row = 1;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row > 1) {
$values = array(
'blah' => null
);
$obj= ProductTable::getInstance()->findOrCreateNewProduct(
$values['blah']
);
$obj->merge($values);
$obj->save($conn);
}
$row++;
}
$conn->commit();
} catch (Doctrine_Exception $e) {
$conn->rollback();
throw $e;
}
I'm wondering how I'd get these updated fields. Is it in the actions.class.php or is it in the actual form.class.php file?
Thanks
On the you can call a Doctrine_Record::getModified() which will give you an array of fields modified (with their values though that doesnt matter for you). Then you can call count on the returned array and keep a cumulative total outside your loop.
$conn = ProductTable::getInstance()->getConnection();
$conn->beginTransaction();
$nbModified = 0;
try {
$row = 1;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row > 1) {
$values = array(
'blah' => null
);
$obj= ProductTable::getInstance()->findOrCreateNewProduct(
$values['blah']
);
$obj->merge($values);
$nbModified += count($obj->getModified());
$obj->save($conn);
}
$row++;
}
$conn->commit();
// return $nbModified or otherwise do something with it here
} catch (Doctrine_Exception $e) {
$conn->rollback();
// youre rolling back so just for consistency set $nbModified to zero
$nbModified = 0;
throw $e;
}

How to correctly use oembed to pull thumbs from youtube

I show a lot of thumbs on my homepage from youtube videos. I was using this function below to grab the thumb from a youtube url which works fast but it doesn't work for url's in the shortned form like youtu.be/JSHDLSKL.
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
So I tried to use Oembed to get the thumbs instead which works for all variations of the youtube url but it retrieves the 480px/360px thumb which causes a lot of cropping to get it down to the 120px/90px size I use to display them. The other issue was it caused my page speed to increase by 4 seconds which Im guessing is a problem with the way I'm implementing it. Here's how I call the thumb inside a loop.
<?php
require_once(ABSPATH.'wp-includes/class-oembed.php');
$oembed= new WP_oEmbed;
$name = get_post_meta($post->ID,'video_code',true);
$url = $name;
//As noted in the comments below, you can auto-detect the video provider with the following
$provider = $oembed->discover($name);
//$provider = 'http://www.youtube.com/oembed';
$video = $oembed->fetch($provider, $url, array('width' => 300, 'height' => 175));
$thumb = $video->thumbnail_url; if ($thumb) { ?>
<img src="<?php echo $thumb; ?>" width="120px" height="90px" />
<?php } ?>
So how should I be doing this to maximize efficiency?
I came across this page from youtube explaining their oembed support, They mentioned that they output to json format so I made a function that gets the json data and then enables you to use it.
Feel free to ask if you need more help.
<?php
$youtube_url = 'http://youtu.be/oHg5SJYRHA0'; // url to youtube video
function getJson($youtube_url){
$baseurl = 'http://www.youtube.com/oembed?url='; // youtube oembed base url
$url = $baseurl . $youtube_url . '&format=json'; // combines the url with format json
$json = json_decode(file_get_contents($url)); // gets url and decodes the json
return $json;
}
$json = getJson($youtube_url);
// from this point on you have all your data placed in variables.
$provider_url = $json->{'provider_url'};
$thumbnail_url = $json->{'thumbnail_url'};
$title = $json->{'title'};
$html = $json->{'html'};
$author_name = $json->{'author_name'};
$height = $json->{'height'};
$thumbnail_width = $json->{'thumbnail_width'};
$thumbnail_height = $json->{'thumbnail_height'};
$width = $json->{'width'};
$version = $json->{'version'};
$author_url = $json->{'author_url'};
$provider_name = $json->{'provider_name'};
$type = $json->{'type'};
echo '<img src="'.$thumbnail_url.'" />'; // echo'ing out the thumbnail image
Ok I came up with a solution from pieces of other questions. First we need to get the id from any type of url youtube has using this function.
function getVideoId($url)
{
$parsedUrl = parse_url($url);
if ($parsedUrl === false)
return false;
if (!empty($parsedUrl['query']))
{
$query = array();
parse_str($parsedUrl['query'], $query);
if (!empty($query['v']))
return $query['v'];
}
if (strtolower($parsedUrl['host']) == 'youtu.be')
return trim($parsedUrl['path'], '/');
return false;
}
Now we can get use YouTube Data API to get the thumbnail from the video id. Looks like this.
<?php
$vid_id = getVideoId($video_code);
$json = json_decode(file_get_contents("http://gdata.youtube.com/feeds/api/videos/$vid_id?v=2&alt=jsonc"));
echo '<img src="' . $json->data->thumbnail->sqDefault . '" width="176" height="126">';
?>
The problem is that is causing an extra 2 seconds load time so I simply use the $vid_id and place it inside http://i3.ytimg.com/vi/<?php echo $vid_id; ?>/default.jpg which gets rid of the 2 seconds added by accessing the youtube api.

Resources