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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Falk
      Hi!
      After temporarily using Module Image Extra, which I completely removed, I had some troubles with my imagefield (unused table columns).
      So I just imported a previous version of this column via PHPmyAdmin, which worked pretty well.
      Anyways, in Processwire Backend all image tags are gone, although they are OK in the database.
      Other image related things work (thumbnail, title etc are OK).
      Is there any way to recreate all the images or something? Or may this be an cache-related issue?
       
      Thanks in advance 😃
       
    • By Xonox
      Hi,
      There's something happening in ProcessWire that doesn't compute abd it has to do with images.
      Situation:
      On the homepage template there's a repeater that takes two images to build a slider:
      slide_image: A wide image for desktops
      slide_image_mobile: A more "verticalized" image for small screens
      Now I have this code:
      foreach($page->home_slides as $slide) { // Create desktop slide if(isset($slide->slide_image)) { // Create desktop slide $slide_image = $slide->slide_image->size(1170,400); // Create mobile slide if(isset($slide->slide_image_mobile)) { $slide_image_mobile = $slide->slide_image_mobile->size(1048,800); } else { $slide_image_mobile = $slide->slide_image->size(1048,800); } ?> <div class="slide-content"> <a href="<?php echo $slide->link; ?>" class="slide"> <img src="<?php echo $slide_image->url; ?>" class="img-fluid d-none d-md-block" title="<?php echo $slide->slide_title; ?>" alt="<?php echo $slide->slide_title; ?>" /> <img src="<?php echo $slide_image_mobile->url; ?>" class="img-fluid d-block d-md-none" title="<?php echo $slide->slide_title; ?>" alt="<?php echo $slide->slide_title; ?>" /> </a> </div> <?php } } On my dev server, the small image is detected and placed in content, however in my production server this doesn't happen.
      I've double checked fields names and the fields contain images. I've even imported the database into the Dev Server.
      I don't have any clue why it works locally and not in server.
      Can anyone shed som light?
      Thank you!
    • By Peter Knight
      I have 2 repeater types working with the Repeater Matrix.
      To keep things simple, I have
      image gallery a downloads gallery. I can't quite figure out how to echo the contents from within a product_gallery. 
      I can get the code below to display the text 'An image gallery' but not the bunch of images within this.
      I'm not sure though if it's my variable trail or my nested echo statement.
       
      <?php foreach($page->components as $item) { if($item->type == 'product_gallery') { echo " An image gallery..."; foreach($product_gallery->images as $photo) { echo " An image <image src='{$photo->url}'> "; } } else if($item->type == 'downloads') { echo " A download gallery... "; } } ?> Thanks
      P
    • By Robin S
      I created this module a while ago and never got around to publicising it, but it has been outed in the latest PW Weekly so here goes the support thread...
      Unique Image Variations
      Ensures that all ImageSizer options and focus settings affect image variation filenames.

      Background
      When using methods that produce image variations such as Pageimage::size(), ProcessWire includes some of the ImageSizer settings (height, width, cropping location, etc) in the variation filename. This is useful so that if you change these settings in your size() call a new variation is generated and you see this variation on the front-end.
      However, ProcessWire does not include several of the other ImageSizer settings in the variation filename:
      upscaling cropping, when set to false or a blank string interlace sharpening quality hidpi quality focus (whether any saved focus area for an image should affect cropping) focus data (the top/left/zoom data for the focus area) This means that if you change any of these settings, either in $config->imageSizerOptions or in an $options array passed to a method like size(), and you already have variations at the requested size/crop, then ProcessWire will not create new variations and will continue to serve the old variations. In other words you won't see the effect of your changed ImageSizer options on the front-end until you delete the old variations.
      Features
      The Unique Image Variations module ensures that any changes to ImageSizer options and any changes to the focus area made in Page Edit are reflected in the variation filename, so new variations will always be generated and displayed on the front-end.
      Installation
      Install the Unique Image Variations module.
      In the module config, set the ImageSizer options that you want to include in image variation filenames.
      Warnings
      Installing the module (and keeping one or more of the options selected in the module config) will cause all existing image variations to be regenerated the next time they are requested. If you have an existing website with a large number of images you may not want the performance impact of that. The module is perhaps best suited to new sites where image variations have not yet been generated.
      Similarly, if you change the module config settings on an existing site then all image variations will be regenerated the next time they are requested.
      If you think you might want to change an ImageSizer option in the future (I'm thinking here primarily of options such as interlace that are typically set in $config->imageSizerOptions) and would not want that change to cause existing image variations to be regenerated then best to not include that option in the module config after you first install the module.
       
      https://github.com/Toutouwai/UniqueImageVariations
      https://modules.processwire.com/modules/unique-image-variations/
    • By louisstephens
      So I was tinkering around with the "select fields" field type and added it to a repeater. My thoughts were I could have a user select a field (textarea, text, etc etc) that I defined and give it a name (another field in the repeater) and create their own form on the page. To be honest, I am now a little lost with rendering the form and mailing the results as potentially the form will be unique and custom every time.  The only way I know to handle the output is by going about it this way:
      $forms = $page->form_select_fields; foreach($forms as $form) { if($form->name === "form_input") { //output input with custom name } elseif($form->name === "form_textarea") { //output input with custom name } } Is there a better way to go about rendering the elements from the repeater? As far as the custom sending goes, I am really at a loss since it would be pretty dynamic. Has anyone used this type of approach, and if so, how did you handle this without going insane?
×
×
  • Create New...