A quick fix for the YouTube SimpleGallery WordPress plugin

Тази статия е на английски поради необходимостта да достигне до по-широка аудитория. Тя касае решаването на много специфичен проблем, който в момента представлява интерес за определена група хора, които не говорят български.

Hi Folks,

I did some digging and found that this plugin (YouTube SimpleGallery @ https://wordpress.org/plugins/youtube-simplegallery/) is broken on two levels:

  1. The format of the YouTube oEmbed code has apparently changed
  2. The YouTube has deprecated its v2 API, which this plugin uses

So, unfortunately for the people wanting a „code clean“ solution (from the following thread https://wordpress.org/support/topic/just-broke-shows-only-first-video), there is none. Also unfortunately but for everybody (including me), this plugin is dead, the last update is almost 2 years old. However I like the simple building of galleries very much, so I had to fix the plugin. Keep in mind that the fix is quick and dirty, apply on your own risk.

I tried to do the fix the right way but I was not able to disable the automatic use of oEmbed for YouTube. Maybe, sometime in the future I will return to this code and make my first plugin the right way. But for now, here is what you need to do this:

[youtubegallery]
vAJFM9qZlrI
qnRJ5Z-HP3E
BZ3Xc7bG10U
WBq_jNgpSYE
[/youtubegallery]

instead of this:

[youtubegallery]
http : // youtu . be/vAJFM9qZlrI
http : // youtu . be/qnRJ5Z-HP3E
http : // youtu . be/BZ3Xc7bG10U
http : // youtu . be/WBq_jNgpSYE
[/youtubegallery]

I don’t really like this (as I have to edit several pages on my other blog) but parsing that mess of an HTML returned by the oEmbed was beyond my PHP/Wordpress skills. So put the video IDs only, one on a line.

Then apply the following patch (using git or any other way you prefer): http://blog.pvalley.info/wp-content/uploads/2015/05/0001-Fixed-the-youtube-gallery.patch. But before that read the notes under the patch text as they are important.

From 69cb15c3624592f810e87cdba1a5891dfd24f506 Mon Sep 17 00:00:00 2001
From: Kaloyan Dimitrov <admin@pvalley.info>
Date: Tue, 12 May 2015 21:25:48 +0300
Subject: [PATCH] Fixed the youtube gallery.

 - Using the new API
 - Broken the vimeo gallery
---
 inc/shortcode.php         | 198 +++++++++++++++-------------------------------
 youtube_simplegallery.php |  14 +---
 2 files changed, 63 insertions(+), 149 deletions(-)

diff --git a/inc/shortcode.php b/inc/shortcode.php
index dc0b83e..de1b8ea 100644
--- a/inc/shortcode.php
+++ b/inc/shortcode.php
@@ -3,26 +3,7 @@
 // SHORTCODE: YOUTUBEGALLERY / VIMEOGALLERY
 function show_youtubegallery( $atts = array(), $youtubelinks = null ) {
 
-	// CLEAN UP OEMBED
-	if (stripos($youtubelinks, "</iframe>") !== false) {
-		$embededmess = explode('<p>', $youtubelinks);
-
-		foreach($embededmess as $line):
-			if (stripos($line, "</iframe>") !== false) {
-				$removeoembed = yotube_gallery_getAttribute('src', $line);
-				$newarray[] = str_replace('http://player.vimeo.com/video', 'http://vimeo.com', $removeoembed);
-			}
-			else {
-				$newarray[] = trim($line);
-			}
-		endforeach;
-
-		$youtubelinks = array_filter($newarray, 'strlen');
-
-	}
-	else {
-		$youtubelinks = explode("\n", $youtubelinks);
-	}
+	$youtubelinks = explode("\n", $youtubelinks);
 	
 	return global_output_youtubegallery( $atts, $youtubelinks );
 }
@@ -101,143 +82,88 @@ function global_output_youtubegallery( $atts = array(), $youtubelinks = null ) {
 	$x = $youtube_gallery_count;
 	$youtube_gallery_ID++;
 
-	// GET LINKS AND CAPTIONS
-	$thisgallery = array();
-	$nol = 0; /* Counter for array */
-	foreach ( $youtubelinks as $l ):
+	$thisgallerycount = 0;
+	$showgallery = ('<div id="youtube_gallery_'.$youtube_gallery_ID.'" class="youtube_gallery"><div class="youtube_gallery_center">'."\n");
+	foreach ( $youtubelinks as $videoID ):
+		$videoID = trim(strip_tags($videoID));
+		if ($videoID != '') {
+		    $x++;
+		    $thisgallerycount++;
+		}
+		else {
+		    continue;
+		}
 
-		$captions = 0;
+		// get options
+		if($youtubeoptions['hd']=='usehd') $ytsghd = 'hd=1'; else $ytsg = 'hd=0';
+		if($youtubeoptions['start']=='autoplay') $ytsgstart = 'autoplay=1'; else $ytsgstart = 'autoplay=0';
+		if($youtubeoptions['related']=='dontshow') $ytsgrel = 'rel=0'; else $ytsgrel = 'rel=1';
 
-		// Check if has caption
-		if(strstr($l, '|')) { 
-			$thumb = explode('|', $l); 
-			$captions = 1;
+		$API_KEY = "FIXME: add your API key here";
+		$videodata_raw = wp_remote_fopen('https://www.googleapis.com/youtube/v3/videos?id=' . $videoID . '&key=' . $API_KEY . '&part=snippet');
+		$videodata = json_decode($videodata_raw, true);
+
+		$items = $videodata["items"];
+		if(count($items) == 0) {
+		    $showgallery .= '<div class="youtube_gallery_item"><div class="youtube_gallery_error"><p><strong>ERROR!</strong></p></div></div>'."\r\n\r\n";
+		    continue;
 		}
-		if($captions) {
-			$thisgallery[$nol]['caption'] = stripslashes($thumb[0]);
-			$thisgallery[$nol]['url'] = strip_tags($thumb[1]);
-			if(strstr($thumb[1], 'youtube.com')) $thisgallery[$nol]['source'] = 'youtube';
-			if(strstr($thumb[1], 'vimeo.com')) $thisgallery[$nol]['source'] = 'vimeo';
+
+		$videoembedlink = 'http://www.youtube.com/embed/'.$videoID.'?'.$ytsgstart.'&'.$ytsghd.'&'.$ytsgrel;
+		if($youtubeoptions['timthumb']=='off') {
+			$videothumb = $items[0]["snippet"]["thumbnails"]["high"]["url"];
 		}
 		else {
-			$thisgallery[$nol]['url'] = strip_tags($l);
-			if(strstr($l, 'youtube.com')) $thisgallery[$nol]['source'] = 'youtube';
-			if(strstr($l, 'vimeo.com')) $thisgallery[$nol]['source'] = 'vimeo';
+			$videothumb = get_bloginfo('url').'/wp-content/plugins/youtube-simplegallery/scripts/timthumb.php?src=' . $items[0]["snippet"]["thumbnails"]["high"]["url"];
 		}
 
-		// Clean item if item is empty
-		if(!strstr($thisgallery[$nol]['url'], 'http://')) unset($thisgallery[$nol]);	
-		// Else increase counter
-		else $nol++; 
-	endforeach;
 
-	$thisgallerycount = 0;
-	$showgallery = ('<div id="youtube_gallery_'.$youtube_gallery_ID.'" class="youtube_gallery"><div class="youtube_gallery_center">'."\n");
-	foreach ( $thisgallery as $link ):
-		$x++;
-		$thisgallerycount++;
-
-			// get options
-			if($youtubeoptions['hd']=='usehd') $ytsghd = 'hd=1'; else $ytsg = 'hd=0';
-			if($youtubeoptions['start']=='autoplay') $ytsgstart = 'autoplay=1'; else $ytsgstart = 'autoplay=0';
-			if($youtubeoptions['related']=='dontshow') $ytsgrel = 'rel=0'; else $ytsgrel = 'rel=1';
-
-			/* This link is YouTube */
-			if($link['source']=='youtube') { 
-				$videoID = yotube_gallery_getYouTubeIdFromURL($link['url']);
-				
-				if(!isset($youtubeoptions['api']))
-				$videodata = yotube_gallery_getYouTubeDataFromID($videoID);
-
-				if( isset($videodata) && $videodata != 'error' ) {
-					$autotitle = $videodata->title;
-				}
-
-				$videoembedlink = 'http://www.youtube.com/embed/'.$videoID.'?'.$ytsgstart.'&'.$ytsghd.'&'.$ytsgrel;
-				if($youtubeoptions['timthumb']=='off')
-					$videothumb = 'http://img.youtube.com/vi/'.$videoID.'/0.jpg';
-				else
-					$videothumb = get_bloginfo('url').'/wp-content/plugins/youtube-simplegallery/scripts/timthumb.php?src=http://img.youtube.com/vi/'.$videoID.'/0.jpg&w=480&h=270&zc=1';
-			}
+		$caption = $items[0]["snippet"]["title"];
 
-			/* This link is Vimeo */
-			elseif($link['source']=='vimeo') { 
-				$videoID = str_replace('http://vimeo.com/', '', $link['url']);
-				$videodata = yotube_gallery_getVimeoDataFromID($videoID);
-				if( isset($videodata) && $videodata != 'error' ) {
-					$videoembedlink = 'http://player.vimeo.com/video/'.$videoID.'?'.$ytsgstart;
-					if($youtubeoptions['timthumb']=='off')
-						$videothumb = trim($videodata['thumbnail_large']);
-					else
-						$videothumb = get_bloginfo('url').'/wp-content/plugins/youtube-simplegallery/scripts/timthumb.php?src='.trim($videodata['thumbnail_large']).'&w=480&h=270&zc=1';
-					$autotitle = $videodata['title'];
-				}
-			}
-
-			// IF ERROR; OUTPUT ERROR MESSAGE
-			if($videodata == 'error') {
-				if( !isset($youtubeoptions['error']) ) {
-					$showgallery .= '<div class="youtube_gallery_item"><div class="youtube_gallery_error"><p><strong>ERROR!</strong> <a href="'.$link['url'].'" target="_blank">'.$link['url'].'</a> does not seem to be a valid video. Please verify the URL.</p></div></div>'."\r\n\r\n";
-					if(isset($cols)) // if cols, output break
-						if($thisgallerycount%$cols==0) $showgallery .= '<br clear="all" style="clear: both;" />';
-				}
-				else {
-					$thisgallerycount--;
-					$x--;
-				}
-				continue;
-			}
+		// START OUTPUT
+		$showgallery .= '<div id="youtube_gallery_item_'.$x.'" class="youtube_gallery_item">'."\n";
 
-			// get caption if exists
-			if( isset($autotitle) && $autotitles == 'fetch' ) $caption = $autotitle;
-			if( $autotitles != 'fetch' ) $caption = null;
-			if(isset($link['caption'])) $caption = strip_tags($link['caption']);
-			
-				// START OUTPUT
-				$showgallery .= '<div id="youtube_gallery_item_'.$x.'" class="youtube_gallery_item">'."\n";
+		// if title above
+		if($youtubeoptions['title'] == 'above' && $caption ) $showgallery .= ('<div class="youtube_gallery_caption">'.strip_tags($caption).'</div>');
 
-				// if title above
-				if($youtubeoptions['title'] == 'above' && $caption ) $showgallery .= ('<div class="youtube_gallery_caption">'.strip_tags($caption).'</div>');
+		$showgallery .= '<div class="youtube_gallery_player">';
 
-				$showgallery .= '<div class="youtube_gallery_player">';
+		// if use shadowbox
+		if($youtubeoptions['thickbox'] == 'shadowbox') 
+			$showgallery .= '<a rel="shadowbox[Mixed];width='.$youtubeoptions['width'].';height='.$youtubeoptions['height'].';" href="'.$videoembedlink.'" title="'.strip_tags($caption).'">';
 
-				// if use shadowbox
-				if($youtubeoptions['thickbox'] == 'shadowbox') 
-					$showgallery .= '<a rel="shadowbox[Mixed];width='.$youtubeoptions['width'].';height='.$youtubeoptions['height'].';" href="'.$videoembedlink.'" title="'.strip_tags($caption).'">';
+		// if use fancybox
+		elseif($youtubeoptions['thickbox'] == 'fancybox') 
+			$showgallery .= '<a class="fancybox iframe" href="'.$videoembedlink.'" title="'.strip_tags($caption).'">';
 
-				// if use fancybox
-				elseif($youtubeoptions['thickbox'] == 'fancybox') 
-					$showgallery .= '<a class="fancybox iframe" href="'.$videoembedlink.'" title="'.strip_tags($caption).'">';
+		// if use thickbox
+		elseif($youtubeoptions['thickbox'] == 'thickbox') 
+			$showgallery .= '<a class="thickbox" href="'.$videoembedlink.'&KeepThis=true&TB_iframe=true&height='.$youtubeoptions['height'].'&width='.$youtubeoptions['width'].'?'.$ytsgstart.'&'.$ytsghd.'&'.$ytsgrel.'" title="'.strip_tags($caption).'">';
 
-				// if use thickbox
-				elseif($youtubeoptions['thickbox'] == 'thickbox') 
-					$showgallery .= '<a class="thickbox" href="'.$videoembedlink.'&KeepThis=true&TB_iframe=true&height='.$youtubeoptions['height'].'&width='.$youtubeoptions['width'].'?'.$ytsgstart.'&'.$ytsghd.'&'.$ytsgrel.'" title="'.strip_tags($caption).'">';
-
-				// if go to youtube.com
-				elseif($youtubeoptions['thickbox'] == 'none') {
-					$showgallery .= '<a href="http://www.youtube.com/watch?v='.str_replace('<br />', '', $videoID).'"';
-					if($youtubeoptions['openlinks']) $showgallery .= ' target="_blank"';
-					$showgallery .= '>';
-				}
+		// if go to youtube.com
+		elseif($youtubeoptions['thickbox'] == 'none') {
+			$showgallery .= '<a href="http://www.youtube.com/watch?v='.str_replace('<br />', '', $videoID).'"';
+			if($youtubeoptions['openlinks']) $showgallery .= ' target="_blank"';
+			$showgallery .= '>';
+		}
 
-				// if add play btn
-				if($youtubeoptions['pb'] == 'usepb') $showgallery .= '<img src="'.get_bloginfo('wpurl').'/wp-content/plugins/youtube-simplegallery/img/play.png" alt=" " class="ytsg_play" border="0" />';
+		// if add play btn
+		if($youtubeoptions['pb'] == 'usepb') $showgallery .= '<img src="'.get_bloginfo('wpurl').'/wp-content/plugins/youtube-simplegallery/img/play.png" alt=" " class="ytsg_play" border="0" />';
 
-				// output thumb
-				$showgallery .= '<img src="'.$videothumb.'" border="0"></a><br />';
+		// output thumb
+		$showgallery .= '<img src="'.$videothumb.'" border="0"></a><br />';
 
-				// if title below
-				if($youtubeoptions['title'] == 'below' && isset($caption) ) $showgallery .= ('<div class="youtube_gallery_caption">'.strip_tags($caption).'</div>');
+		// if title below
+		if($youtubeoptions['title'] == 'below' && isset($caption) ) $showgallery .= ('<div class="youtube_gallery_caption">'.strip_tags($caption).'</div>');
 
-				// close divs
-				$showgallery .= '</div>';
-				$showgallery .='</div>'."\r\n\r\n";
+		// close divs
+		$showgallery .= '</div>';
+		$showgallery .='</div>'."\r\n\r\n";
 
+		if(isset($cols)) // if cols, output break
+			if($thisgallerycount%$cols==0) $showgallery .= '<br clear="all" style="clear: both;" />';
 
-			if(isset($cols)) // if cols, output break
-				if($thisgallerycount%$cols==0) $showgallery .= '<br clear="all" style="clear: both;" />';
-				
-			$caption = null;
+		$caption = null;
 
 	endforeach;
 	$showgallery .= '<div class="youtube_gallery_divider"></div>'."\r\n";
diff --git a/youtube_simplegallery.php b/youtube_simplegallery.php
index 3427c96..87417f6 100644
--- a/youtube_simplegallery.php
+++ b/youtube_simplegallery.php
@@ -54,18 +54,6 @@ function yotube_gallery_getYouTubeIdFromURL($url) {
 	return isset($matches[1]) ? $matches[1] : false;
 }
 
-// GET YOUTUBE VIDEO DATA 
-function yotube_gallery_getYouTubeDataFromID($vID) {
-	$videodata = wp_remote_fopen('http://gdata.youtube.com/feeds/api/videos/'.trim($vID));
-	if($videodata=='Video not found') {
-		return 'error';
-	}
-	else {
-		$videodata = new SimpleXMLElement($videodata);
-		return $videodata;
-	}
-}
-
 // GET VIMEO VIDEO DATA 
 function yotube_gallery_getVimeoDataFromID($vID) {
 	$videodata = wp_remote_fopen('http://vimeo.com/api/v2/video/'.trim($vID).'.json');
@@ -153,6 +141,6 @@ add_action('wp_footer', 'youtube_gallery_shortcode_styles');
 // HOOK IT UP TO WORDPRESS
 register_activation_hook(__FILE__,'youtubegallery_install');	
 register_deactivation_hook(__FILE__,'youtubegallery_uninstall');
-add_filter("plugin_action_links_$plugin", 'youtubegallery_settings_link' ); 
+add_filter("plugin_action_links_$plugin", 'youtubegallery_settings_link' );
 
 ?>
-- 
1.9.1

You will need to disable Timthumb, as it is not working. I haven’t had the time to investigate the issue. Also be aware that this patch is breaking the Vimeo support and that it is only fixing the youtubegallery, to the youtubeuserfeed shortcode. Finally you will need an YouTube API key. It should be put here:

FIXME: add your API key here.

And at the end, a word of warning. Use on your own risk.

I hope this helps.

Cheers,
ShaMan-H_Fel

This entry was posted in Разни and tagged , . Bookmark the permalink.

4 Responses to A quick fix for the YouTube SimpleGallery WordPress plugin