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 Spyros
      Hello
      I'm having a strange issue with the $page->find(), for some reason I'm missing some of the pages from the results. I found then that I was missing all the pages with the same "PAGE NAME". Is it a bug or am I missing something?
      PS 
      If I change the "PAGE NAME" of one of the missing ones then I'm retrieving the page without any problem.
      Thank you
    • By EyeDentify
      Hello Dear PW Gurus.

      Hope you fair well in these Corona Crisis times.

      Anyhow, i have a problem with a Cryptic error message that shows up when i am trying to Delete images out of a Images field.
      The Error message does say a little but it does not make sense to me why i can´t delete the images because of it.

      Is it some permission issue perhaps?

      I will attach screenshots of it and what i did prior to it.
      I am from sweden so ignore the funny words here and there.

      Hope you all can send me on the right track.
      i am running PW 3.0.139 on this install.

      Step1:

      Step 2: Select the images with the trashcan symbol

       
      Step 3: Cryptic Error message

      I am scratching my head on this one, have not seen this before.

      Thankfull for all help.
      /EyeDentify
    • By Guy Incognito
      This short script loops through some images from an XML feed and pushes new ones to an image field. It all works perfectly, except for some reason the last image (only) in the loop each time doesn't receive the image description... can everyone spot why? TIA! 🙂 
      foreach ($propertyImages as $img) { $fileName = trim($img[0]); if ( !empty($fileName) ) { $imgPath = '../property_data/'.$fileName; if(file_exists($imgPath) && !in_array(strtolower($fileName),$currentImages)) { $p->property_images->add($imgPath); $p->save(); $newImg = $p->property_images->last(); $newImg->description = $img[1]; $p->save(); } } }  
    • 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!
×
×
  • Create New...