Jump to content
Sergio

How to get and save Flickr albums to a page via API

Recommended Posts

Hello everyone,

greetings from Belo Horizonte / Brazil.

I'm on the process of converting a site from WP to Processwire, this one: http://www.ricardo-vargas.com 

I needed a simple Flickr Gallery and tried to find a way to create album pages via API and download the images to the local filesystem (just a few, for cache purposes).

So I created yesterday a simple script that, given an album ID, download its data using cURL and save the photos to a temp dir. After that, add them to a new page under /pictures/

Feel free to comment on the code, I'm a designer, not a developer, and this is my first time using PW API  :)

You can grab it on GitHub: https://github.com/sjardim/processwire-simple-flickr-album

Instructions

  1. Download the files
  2. Put the templates/get_flickr_sets.php on your templates/ folder.
  3. Create a page on Processwire using this template
  4. Create or edit the page where the albums will be created. In my case it was /pictures/
  5. IMPORTANT: Add guest edit/create permissions to this /pictures/ page, otherwise the script won't work
  6. Create a temp dir on your server and set it on the previous file
  7. Get a Flickr API on https://www.flickr.com/services/apps/create/
  8. Add one or more Flickr album IDs on get_flickr_sets.php
  9. Open the page using the get_flickr_sets.php template on your browser
<?php

include "../lib/curl.class.php";

// You will need to get a Flick API Key
// Get it here: https://www.flickr.com/services/apps/create/
// Load it on the file below
include "../lib/flickr_album_utils.php";

function download_file($url) {

  // Save the image on local filesystem (You need to create this folder first)
  // On your server it can be /var/www/name_of_folder/
  $tempdir = '/Users/XXX/phpFlickrCache/';
  
  $fp = $tempdir . basename(parse_url($url, PHP_URL_PATH));

  // if we already downloaded the images for some reason (like testing), just return it
  if (!file_exists($fp)) {

    $fh = fopen($fp, 'wb');
    
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($curl, CURLOPT_FILE, $fh);

    curl_exec($curl);
    curl_close($curl);
    fclose($fh);

  }

  return $fp;
}

// Get some public album id to test
$albumID = ["72157636029541784"];

//$albumID = ["72157649576832173", "72157633296236495", "72157644132091553", "72157636029541784"];

// Load ProcessWire API
$pages = wire('pages')->get('/pictures/');

 /* 
  --------------------------
  GET ALBUM INFO FROM FLICKR
  --------------------------
  */
 
foreach($albumID as $album) {

  // Via GET, return album and its photos info
	$album = fa_get_album($album);
  
  // create a new post
  $page = new Page();
  $page->template = 'picture_album';
  $page->parent = $pages;
    
  // disable page output formatting
  $page->of(false);

  
  $page->name = wire('sanitizer')->pageName($album['title'], true);  
  
  $page->flickr_album_id = $album['id'];
  $page->title = $album['title'];
  $page->generic_integer = $album['total']; //total number of photos on flickr album – OPTIONAL

  //My client albums descriptions have two phrases, one in English and other in Portuguese
  // let's separate then by the period, but sometimes there is no period, so the PT description will remain blank
  $description = explode('.', $album['description']);

  $en = $languages->get("default");  
  $page->summary->setLanguageValue($en, $description[0]);

  $pt = $languages->get("portuguese");  
  $page->summary->setLanguageValue($pt, $description[1]);
  
  $page->set("status$pt", 1); //activate portuguese page

  $page->save(); // We need to save the page BEFORE adding images
  
  /* 
  ------------------------------------
  DOWNLOAD AND SAVE IMAGES FROM FLICKR
  ------------------------------------
  */

  $images = array();

  $i=1;
  $maxImages = 11;

  foreach($album["all_images"] as $f) {

    //we do not want all the photos, just a little bit
    if ($i >= $maxImages) break;
    
    // mount the flickr photo url using its attributes
    $photo_url = 'https://farm'.$f["farm"].'.staticflickr.com/'.$f["server"].'/'.$f["id"].'_'.$f["secret"].'_b.jpg';
    
    // download and return the image file in the filesystem
    $images[$album['id']][$i] = download_file($photo_url);
    
    // add images to the current page in the loop
    $page->images->add($images[$album['id']][$i]);
    
    $i++;
  }

  $page->save();

  echo "<p>Created page for album: <strong>".$album['title']. "</strong></p>";

  // Tip: Now, after we saved the images to ProcessWire /site/assets/files/, we can safely delete them from the $tempdir if needed
 
}
print "<pre>";
print_r($images);
print "</pre>";

Admin Screenshot 

Screenshot.png

  • Like 7

Share this post


Link to post
Share on other sites

Big thanks for you. I modified your code because I didn't want to fetch images for downloading but just for linking.

I made a new template 'kuvat' (means photos) with fields for Flickr gallery id and image field for main page listing. Only bad thing is that user have to add each gallery separately. But works pretty well and better urls than what we had on Drupal.

I use smaller thumbnails (q is 150 x 150) for faster loading and Photobox effect for normal photos.

<?php
include "../lib/curl.class.php";
include "../lib/flickr_album_utils.php";
$album = fa_get_album($item);
$images = array();
foreach($album["all_images"] as $f) {    
$photo = 'https://farm'.$f["farm"].'.staticflickr.com/'.$f["server"].'/'.$f["id"].'_'.$f["secret"].'_b.jpg';
$thumb = 'https://farm'.$f["farm"].'.staticflickr.com/'.$f["server"].'/'.$f["id"].'_'.$f["secret"].'_q.jpg';
echo "<a class='event' href='$photo'><img src='$thumb' alt=''/>";
}
?>

 

  • Like 2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By MateThemes
      Hello everyone!
      I am working with Processwire since some time. But some topics are quite hard for me.
      I have a Portfolio (Gallery) Page.
      I am build a template with Portfolio Index and pages with portfolio entries.
      Structure:
      Portfolio Index
      -- Portfolio Entry
      -- Portfolio Entry
      and so on.
      Portfolio Entry has an Image field with max 12 images and are accessible Templates. 
      Now I want to display the single Portfolio Entry on the Portfolio Index and Paginate them. In the index page all images of a single Entry page should be displayed (I should not be organized as albums, where a random image of the portfolio entry should be displayed). 
      I have no clue to achieve this. May someone could give me an advice.
      Thank you in advance!
    • By ngrmm
      I have a page with a table. Each table row has a page-reference field and a checkbox.
      The Page sends emails to all users (page-refrence->email-field) and change the value of the checkbox in a row to 1.
      It works with this:
      <?php // event ID fron url query $eventID = $input->get('eventID','int'); // get event-page $event = $pages->get($eventID); // config $fromEmail = $event->event_mail_from; $fromName = $event->event_mail_from_name; $emailSubject = $event->event_subject; // email html body ob_start(); include('./_inc/emailbody.inc'); $emailBody = ob_get_clean(); // make event-page editable $event->of(false); // loop through table and send out emails foreach($event->event_clients_list as $event_table_row) { // get client page $clientPage = $event_table_row->client_name; // get client email $clientEmail = $clientPage->email; // if client isn't invited yet (checkbox not checked) if($event_table_row->client_invited == '') { // send email $m = new WireMail(); $m->to($clientEmail); $m->from($fromEmail, $fromName); $m->subject($emailSubject); $m->bodyHTML($emailBody); $m->send(); // mark client as invited $event_table_row->client_invited = 1; $event->save('event_clients_list'); } } ?> But i have to use a variable in my emailbody.inc which i'm able to get in the table-loop.
      So i do the including of the body inside my loop. But this doesn't work anymore. Page sends out the emails but is unable to change the value of the checkbox.
      I get no errors!
      I'm using ProTable
      <?php // event ID fron url query $eventID = $input->get('eventID','int'); // get event-page $event = $pages->get($eventID); // config $fromEmail = $event->event_mail_from; $fromName = $event->event_mail_from_name; $emailSubject = $event->event_subject; // loop through table and send out emails foreach($event->event_clients_list as $event_table_row) { // get client page $clientPage = $event_table_row->client_name; // get client email $clientEmail = $clientPage->email; // email html body ob_start(); include('./_inc/emailbody.inc'); $emailBody = ob_get_clean(); // make event-page editable $event->of(false); // if client isn't invited yet (checkbox not checked) if($event_table_row->client_invited == '') { // send email $m = new WireMail(); $m->to($clientEmail); $m->from($fromEmail, $fromName); $m->subject($emailSubject); $m->bodyHTML($emailBody); $m->send(); // mark client as invited $event_table_row->client_invited = 1; $event->save('event_clients_list'); } } ?>  
    • By Robin S
      Add Image URLs
      Allows images/files to be added to Image/File fields by pasting URLs.

      Usage
      Install the Add Image URLs module.
      A "Paste URLs" button will be added to all image and file fields. Use the button to show a textarea where URLs may be pasted, one per line. Images/files are added when the page is saved.
       
      https://github.com/Toutouwai/AddImageUrls
      https://modules.processwire.com/modules/add-image-urls/
    • By gebeer
      Hello all,
      sharing my new module FieldtypeImageReference. It provides a configurable input field for choosing any type of image from selectable sources. Sources can be: 
      a predefined folder in site/templates/ and/or a  page (and optionally its children) and/or the page being edited and/or any page on the site CAUTION: this module is under development and not quite yet in a production-ready state. So please test it carefully.
      UPDATE: the new version v2.0.0 introduces a breaking change due to renaming the module. If you have an older version already installed, you need to uninstall it and install the latest master version.
      Module and full description can be found on github https://github.com/gebeer/FieldtypeImageReference
      Install from URL: https://github.com/gebeer/FieldtypeImageReference/archive/master.zip
      Read on for features and use cases.
      Features
      Images can be loaded from a folder inside site/templates/ or site/assets Images in that folder can be uploaded and deleted from within the inputfield Images can be loaded from other pages defined in the field settings Images can be organized into categories. Child pages of the main 'image source page' serve as categories mages can be loaded from any page on the site From the API side, images can be manipulated like native ProcessWire images (resizing, cropping etc.), even the images from a folder Image thumbnails are loaded into inputfield by ajax on demand Source images on other pages can be edited from within this field. Markup of SVG images can be rendered inline with `echo $image->svgcontent` Image names are fully searchable through the API $pages->find('fieldname.filename=xyz.png'); $pages->find('fieldname.filename%=xy.png'); Accidental image deletion is prevented. When you want to delete an image from one of the pages that hold your site-wide images, the module searches all pages that use that image. If any page contains a reference to the image you are trying to delete, deletion will be prevented. You will get an error message with links to help you edit those pages and remove references there before you can finally delete the image. This field type can be used with marcrura's Settings Factory module to store images on settings pages, which was not possible with other image field types When to use ?
      If you want to let editors choose an image from a set of images that is being used site-wide. Ideal for images that are being re-used across the site (e.g. icons, but not limited to that).
      Other than the native ProcessWire images field, the images here are not stored per page. Only references to images that live on other pages or inside a folder are stored. This has several advantages:
      one central place to organize images when images change, you only have to update them in one place. All references will be updated, too. (Provided the name of the image that has changed stays the same) Installation and setup instructions can be found on github.
      Here's how the input field looks like in the page editor:

      If you like to give it a try, I'm happy to hear your comments or suggestions for improvement. Install from URL: https://github.com/gebeer/FieldtypeImageReference/archive/master.zip
      Eventually this will go in the module directory, too. But it needs some more testing before I submit it. So I'd really appreciate your assistance.
      Thanks to all who contributed their feedback and suggestions which made this module what it is now.
       
    • By rushy
      Hi. I've been using Processwire for a few years now and installed it on a few different shared hosting servers without issues, but I'm now running into an issue on a Fasthosts shared server that I've not seen before. The installation goes ok and I have a working default site profile but I am unable to complete any uploads of images. It just hangs at the progress spinner during the upload. I thought it might be a priviledge issue so have temporarily set the dir / file privs. as 777 / 666 just to test that but it made no difference. I have no errors in the wire log. In server error log I have:
      set_time_limit() has been disabled for security reasons in ....htdocs/wire/core/ImageSizerEngine.php on line 1035 and i note in the assets/file dir. where the image is being stored the date on the file being created has a year of 1970 and 0 length. If I leave the page this file disappears and nothing has been stored. 
      Does anyone know how I can enable set_time_limit if this is likely to be the problem? 
      Many thanks! Paul
×
×
  • Create New...