3 * Gallery - a web based photo album viewer and editor
4 * Copyright (C) 2000-2007 Bharat Mediratta
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or (at
9 * your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
21 GalleryCoreApi::requireOnce('modules/gd/classes/GdToolkitHelper.class');
25 * This plugin will handle the addition of embedded video objects
27 * @subpackage UserInterface
28 * @author Alan Pippin <apippin@pippins.net>
29 * @version $Revision: 1.1 $
31 class ItemAddEmbedVideo extends ItemAddPlugin {
34 * @see ItemAddPlugin::handleRequest
36 function handleRequest($form, &$item) {
39 $status = $error = array();
41 if (isset($form['action']['addEmbedVideoPage'])) {
43 $platform =& $gallery->getPlatform();
45 if (empty($extraHeaders)) {
46 $extraHeaders = array('Referer' => str_replace('&', '&', $url));
49 if(isset($form['webPage']['URL'])) {
51 /* Load any stored/set Parameters */
52 list ($ret, $params) =
53 GalleryCoreApi::fetchAllPluginParameters('module', 'embedvideo');
55 return array($ret, null, null);
57 foreach (array('default', 'override') as $type) {
58 $ItemAddUploadApplet[$type] = array();
59 if (!empty($params['embedvideo' . $type . 'Variables'])) {
60 $variablesArray = explode('|', $params['embedvideo' . $type . 'Variables']);
61 foreach ($variablesArray as $variable) {
62 list ($name, $value) = explode('=', $variable);
63 $ItemAddEmbedVideo[$type][$name] = $value;
64 /* print "type: $type name: $name value: $value <br>"; */
69 /* Store any Parameters into some simpler, shorter, local variables */
70 global $debugOutput, $useInternalFlvPlayer, $youtubeDevId;
71 global $width, $height, $externalFlvPlayer, $externalFlvPlayerVars;
72 global $flvThumbnail, $useRemoteSize, $autoStart;
73 global $watermarkVideos, $watermarkImage, $watermarkAlignment;
75 /* Find out what value our parameters should have by looking to see if they
76 * are defined in our overrides section or default section. If they are not
77 * defined in either of these 2 places, pass in a default value to set them to
79 $debugOutput = $this->getParameter($ItemAddEmbedVideo, 'debugOutput', "false");
80 $useInternalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'useInternalFlvPlayer', "true");
81 $youtubeDevId = $this->getParameter($ItemAddEmbedVideo, 'youtubeDevId', "");
82 $youtubeShowRelated = $this->getParameter($ItemAddEmbedVideo, 'youtubeShowRelated', "false");
83 $width = $this->getParameter($ItemAddEmbedVideo, 'width', "320");
84 $height = $this->getParameter($ItemAddEmbedVideo, 'height', "240");
85 $externalFlvPlayer = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayer', "");
86 $externalFlvPlayerVars = $this->getParameter($ItemAddEmbedVideo, 'externalFlvPlayerVars', "");
87 $flvThumbnail = $this->getParameter($ItemAddEmbedVideo, 'flvThumbnail', "");
88 $useRemoteSize = $this->getParameter($ItemAddEmbedVideo, 'useRemoteSize', "false");
89 $autoStart = $this->getParameter($ItemAddEmbedVideo, 'autoStart', "false");
90 $watermarkImage = $this->getParameter($ItemAddEmbedVideo, 'watermarkImage', "");
91 $watermarkVideos = $this->getParameter($ItemAddEmbedVideo, 'watermarkVideos', "false");
92 $watermarkAlignment = $this->getParameter($ItemAddEmbedVideo, 'watermarkAlignment', "left");
94 /* Print our stored/set Parameters */
95 if(!strcmp($debugOutput,"true")) {
97 print "<h2>Variable Parameters</h2>\n";
98 print "debugOutput=$debugOutput<br>\n";
99 print "useInternalFlvPlayer=$useInternalFlvPlayer<br>\n";
100 print "youtubeDevId=$youtubeDevId<br>\n";
101 print "youtubeShowRelated=$youtubeShowRelated<br>\n";
102 print "width=$width<br>\n";
103 print "height=$height<br>\n";
104 print "externalFlvPlayer=$externalFlvPlayer<br>\n";
105 print "externalFlvPlayerVars=$externalFlvPlayerVars<br>\n";
106 print "flvThumbnail=$flvThumbnail<br>\n";
107 print "useRemoteSize=$useRemoteSize<br>\n";
108 print "autoStart=$autoStart<br>\n";
109 print "watermarkVideos=$watermarkVideos<br>\n";
110 print "watermarkImage=$watermarkImage<br>\n";
111 print "watermarkAlignment=$watermarkAlignment<br>\n";
115 /* Store other string constants we'll use later */
118 $youtubeUrlPattern="youtube.com";
119 $youtubeApiUrl="http://www.youtube.com/api2_rest";
120 $youtubeThumbnailUrl="http://img.youtube.com/vi/";
121 /* We can't extract the server size from youtube */
123 $youtubeHeight="350";
126 $googleUrlPattern="video.google.com";
127 $googlePlayer="http://video.google.com/googleplayer.swf";
128 /* We can't extract the server size from google video */
133 $yahooUrlPattern="video.yahoo.com";
134 $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
137 $metacafeUrlPattern="metacafe.com";
138 $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
141 $revverUrlPattern="revver.com";
142 $revverThumbnailUrl="http://frame.revver.com/frame/120x90/";
145 $dailymotionUrlPattern="dailymotion.com";
146 $dailymotionThumbnailUrl="http://www.dailymotion.com/thumbnail/160x120/video/";
149 $divshareUrlPattern="divshare.com";
150 $divshareThumbnailUrl="http://www.divshare.com/direct/video_thumb/";
152 /* Gallery2 specific paths and variables */
153 $urlGenerator =& $gallery->getUrlGenerator();
154 $gallery2_url = $urlGenerator->getCurrentUrlDir();
155 $gallery2_flv_thumbnail = "modules/embedvideo/images/G2video_thumbnail.jpg";
156 $gallery2_video_watermark = "modules/embedvideo/images/G2video_watermark1.png";
157 $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
159 /* Store the passed URL in a shorter local variable */
160 $url = $form['webPage']['URL'];
163 *****************************
164 * Embed a Youtube Video
165 *****************************
167 if(preg_match("/$youtubeUrlPattern/",$url)) {
169 /* Make sure we can find a video_id in the URL */
170 if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
171 $video_id = $matches[1];
173 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
174 "Unable to extract video id from url: $url"),null,null);
177 /* If we have a valid youtube developer id, use that to get information about the video */
178 /* Otherwise, just parse it directly from the HTML page */
179 $dev_id = $youtubeDevId;
180 if(!preg_match("/\w+/",$dev_id)) {
181 /* No developer ID found. Proceed with direct page parsing. */
183 /* Grab the contents of the webpage used to display the video on video.google.com */
184 list ($successfullyCopied, $contents, $response, $headers) =
185 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
186 if (!$successfullyCopied) {
187 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
188 "Unable to get video information at url: $url - $response"),NULL,NULL);
191 /* Extract the summary from the webpage contents */
192 preg_match('/<meta name="description" content="(.+?)">/i', $contents, $matches);
193 $summary=$matches[1];
195 /* Extract the title from the webpage contents */
196 preg_match('/<meta name="title" content="(.+?)">/i', $contents, $matches);
199 /* Extract the thumbnail URL from the webpage contents */
200 $thumbnail=$youtubeThumbnailUrl.$video_id."/default.jpg";
202 /* Determine if the video should autoplay or not based on the autoStart parameter */
204 if(!strcmp($autoStart,"true")) {
205 $autoStartStr="&autoplay=1";
207 $autoStartStr="&autoplay=0";
210 /* Determine if the video should show related videos or not based on the youtubeShowRelated parameter */
211 $youtubeShowRelatedStr="";
212 if(!strcmp($youtubeShowRelated,"false")) {
213 $youtubeShowRelatedStr="&rel=0";
215 $youtubeShowRelatedStr="&rel=1";
218 /* Format the description to hold a reference to the embedded video */
219 if(preg_match('/id=\"embed_code\".+?value=\'(.+?)\'/', $contents, $matches)) {
220 $description=$matches[1];
221 $description=preg_replace("/"/","'",$description);
222 $description=preg_replace("/</","<",$description);
223 $description=preg_replace("/>/",">",$description);
224 $description=preg_replace("/&/","&",$description);
225 $description=preg_replace("/&rel=1/",$autoStartStr.$youtubeShowRelatedStr,$description);
226 if(!strcmp($useRemoteSize,"false")) {
227 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
228 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
230 $description.= "<br>$summary";
232 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
233 "Unable to extract embedded video information from url: $url"),NULL,NULL);
237 /* We found a valid developer ID. Proceed with API calls. */
239 /* Youtube api feed */
240 $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
241 $feed.= "&dev_id=$dev_id&video_id=$video_id";
243 /* Get the youtube xml feed as a string data source */
244 list ($successfullyCopied, $xml, $response, $headers) =
245 GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
246 if (!$successfullyCopied) {
247 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
248 "Unable to get video information at url: $url - $response"),null,null);
251 if(preg_match("/This video is private/",$xml)) {
252 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
253 "Unable to retrieve video information from youtube.".
254 "You cannot embed a private youtube video: $url"),null,null);
257 if(!strcmp($debugOutput,"true")) {
258 print "\n<h2>Youtube XML Dump</h2>";
263 /* Extract certain information from the xml feed */
264 preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
265 preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
266 preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
269 array_shift($thumbnail);
270 array_shift($description);
272 /* Replace html characters. More can be added but this seems to work */
273 for($i=0;$i<count($description[0]);$i++){
274 $description[0][$i] = preg_replace("/</","<",$description[0][$i]);
275 $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);
278 /* Store the information found in some local variables */
279 $title = $title[0][0];
280 $summary = $description[0][0];
281 $thumbnail = $thumbnail[0][0];
283 /* Determine what our width and height should be based on our useRemoteSize parameter */
284 if(!strcmp($useRemoteSize,"true")) {
285 $width = $youtubeWidth;
286 $height = $youtubeHeight;
289 /* Determine if the video should autoplay or not based on the autoStart parameter */
291 if(!strcmp($autoStart,"true")) {
292 $autoStartStr="&autoplay=1";
295 /* Determine if the video should show related videos or not based on the youtubeShowRelated parameter */
296 $youtubeShowRelatedStr="";
297 if(!strcmp($youtubeShowRelated,"false")) {
298 $youtubeShowRelatedStr="&rel=0";
301 /* Format the description to hold a reference to the embedded video */
302 $description = '<object width="'.$width.'" height="'.$height.'">';
303 $description.= '<param name="movie" ';
304 $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
305 $description.= '<param name="wmode" value="transparent"></param>';
306 $description.= '<embed src="http://www.youtube.com/v/';
307 $description.= $video_id.$autoStartStr.$youtubeShowRelatedStr;
308 $description.= '" type="application/x-shockwave-flash" wmode="transparent" ';
309 $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
310 $description.= "<br>$summary";
313 **********************************
314 * Embed a Google Video
315 **********************************
317 } else if(preg_match("/$googleUrlPattern/",$url)) {
319 /* Make sure we can extract a docID */
320 if(preg_match("/docid=(.*)/",$url,$matches)) {
321 $doc_id = $matches[1];
323 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
324 "Unable to extract doc id from url: $url"),null,null);
327 /* Grab the contents of the webpage used to display the video on video.google.com */
328 list ($successfullyCopied, $contents, $response, $headers) =
329 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
330 if (!$successfullyCopied) {
331 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
332 "Unable to get video information at url: $url - $response"),NULL,NULL);
335 /* Extract the summary from the webpage contents */
336 //print "contents: $contents <br>";
337 preg_match('/<meta name="description" content="(.+?)\. \w+ \d+, \d+.*">/i',
338 $contents, $matches);
339 $summary=$matches[1];
341 /* Extract the title from the webpage contents */
343 if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
345 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
349 /* Extract the thumbnail URL from the webpage contents */
350 preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
351 $contents, $matches);
352 $thumbnail=$matches[1];
353 $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
355 /* Determine what our width and height should be based on our useRemoteSize parameter */
356 if(!strcmp($useRemoteSize,"true")) {
357 $width = $googleWidth;
358 $height = $googleHeight;
361 /* Determine if the video should autoplay or not based on the autoStart parameter */
363 if(!strcmp($autoStart,"true")) {
364 $autoStartStr="&autoplay=1";
367 /* Format the description to hold a reference to the embedded video */
368 $description = '<embed ';
369 $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
370 $description.= 'type="application/x-shockwave-flash" ';
371 $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.$autoStartStr.'" flashvars=""> ';
372 $description.= '</embed>';
373 $description.= "<br>$summary";
376 **********************************
377 * Embed a Yahoo Video
378 **********************************
379 * TODO: The autoStart parameter doesn't work with the yahoo video player
381 } else if(preg_match("/$yahooUrlPattern/",$url)) {
383 /* Make sure we can extract a vidID */
384 if(preg_match("/vid=(.*)/",$url,$matches)) {
385 $vid_id = $matches[1];
387 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
388 "Unable to extract vid id from url: $url"),null,null);
391 /* Grab the contents of the webpage used to display the video on video.google.com */
392 list ($successfullyCopied, $contents, $response, $headers) =
393 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
394 if (!$successfullyCopied) {
395 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
396 "Unable to get video information at url: $url - $response"),NULL,NULL);
399 /* Extract the summary from the webpage contents */
400 preg_match('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
401 $summary=$matches[1];
403 /* Extract the title from the webpage contents */
405 if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
407 } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
411 /* Build the thumbnail URL from the vid_id */
412 $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
414 /* Format the description to hold a reference to the embedded video */
415 if(preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches)) {
416 $description=$matches[1];
417 if(!strcmp($useRemoteSize,"false")) {
418 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
419 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
421 $description.= "<br>$summary";
423 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
424 "Unable to extract embedded video information from url: $url"),NULL,NULL);
428 **********************************
429 * Embed a MetaCafe Video
430 **********************************
432 } else if(preg_match("/$metacafeUrlPattern/",$url)) {
434 /* Make sure we can extract a itemID */
435 if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
436 $item_id = $matches[1];
438 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
439 "Unable to extract item id from url: $url"),null,null);
442 /* Grab the contents of the webpage used to display the video on video.google.com */
443 list ($successfullyCopied, $contents, $response, $headers) =
444 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
445 if (!$successfullyCopied) {
446 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
447 "Unable to get video information at url: $url - $response"),NULL,NULL);
450 /* Extract the summary from the webpage contents */
451 preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
452 $summary=$matches[1];
454 /* Extract the title from the webpage contents */
455 preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
458 /* Build the thumbnail URL from the item_id */
459 $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
461 /* Format the description to hold a reference to the embedded video */
462 if(preg_match('/(embed src.+?\/embed)/', $contents, $matches)) {
463 $description="<".$matches[1];
464 $description=preg_replace("/"/","'",$description);
465 if(!strcmp($useRemoteSize,"false")) {
466 $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
467 $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
469 if(!strcmp($autoStart,"true")) {
470 $description=preg_replace("/\.swf/",".swf?playerVars=autoPlay=yes",$description);
472 $description.= "</embed>";
473 $description.= "<br>$summary";
475 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
476 "Unable to extract embedded video information from url: $url"),NULL,NULL);
480 **********************************
481 * Embed a Revver Video
482 **********************************
483 * TODO: The autoStart parameter doesn't work with the yahoo video player
485 } else if(preg_match("/$revverUrlPattern/",$url)) {
487 /* Make sure we can extract a itemID */
488 if(preg_match("/\/watch\/(.+)/",$url,$matches)) {
489 $item_id = $matches[1];
490 $item_id=preg_replace("/\/$/","",$item_id);
492 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
493 "Unable to extract item id from url: $url"),null,null);
496 /* Grab the contents of the webpage used to display the video on video.google.com */
497 list ($successfullyCopied, $contents, $response, $headers) =
498 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
499 if (!$successfullyCopied) {
500 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
501 "Unable to get video information at url: $url - $response"),NULL,NULL);
504 /* Extract the summary from the webpage contents */
505 if(preg_match('/"video_description">(.+?)<\/p>/i', $contents, $matches)) {
506 $summary=$matches[1];
508 if(preg_match('/"video_description">(.+)/i', $contents, $matches)) {
509 $summary=$matches[1];
512 /* Extract the title from the webpage contents */
513 preg_match('/digg_title = \'(.+?)\'/i', $contents, $matches);
516 /* Build the thumbnail URL from the item_id */
517 $thumbnail=$revverThumbnailUrl.$item_id.".jpg";
519 /* Format the description to hold a reference to the embedded video */
520 if(preg_match('/<input class.+?(script src.+?\/script)/', $contents, $matches)) {
521 $description="<".$matches[1];
522 if(!strcmp($useRemoteSize,"false")) {
523 $description=preg_replace("/width:\d+/","width:".$width,$description);
524 $description=preg_replace("/height:\d+/","height:".$height,$description);
526 if(!strcmp($autoStart,"true")) {
527 preg_match('/(height:\d+)/',$description,$matches);
529 $description=preg_replace("/$height/",$height.";autoplay:true",$description);
532 $description.= "<br>$summary";
534 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
535 "Unable to extract embedded video information from url: $url"),NULL,NULL);
539 **********************************
540 * Embed a DailyMotion Video
541 **********************************
542 * TODO: The autoStart parameter doesn't work with the yahoo video player
544 } else if(preg_match("/$dailymotionUrlPattern/",$url)) {
546 /* Make sure we can extract a itemID */
547 if(preg_match("/\/video\/(.+)/",$url,$matches)) {
548 $item_id = $matches[1];
549 $item_id=preg_replace("/\/$/","",$item_id);
551 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
552 "Unable to extract item id from url: $url"),null,null);
555 /* Grab the contents of the webpage used to display the video on video.google.com */
556 list ($successfullyCopied, $contents, $response, $headers) =
557 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
558 if (!$successfullyCopied) {
559 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
560 "Unable to get video information at url: $url - $response"),NULL,NULL);
563 /* Extract the summary from the webpage contents */
564 preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
565 $summary=$matches[1];
567 /* Extract the title from the webpage contents */
568 preg_match('/<meta name="title" content="Dailymotion : (.+?)" \/>/i', $contents, $matches);
571 /* Build the thumbnail URL from the item_id */
572 $thumbnail=$dailymotionThumbnailUrl.$item_id;
574 /* Format the description to hold a reference to the embedded video */
575 if(preg_match('/Embeddable Player:.+?value="(.+?)"/', $contents, $matches)) {
576 $description=$matches[1];
577 $description=preg_replace("/"/","'",$description);
578 $description=preg_replace("/</","<",$description);
579 $description=preg_replace("/>/",">",$description);
580 if(!strcmp($useRemoteSize,"false")) {
581 $description=preg_replace("/width=\"\d+\"/","width=\"".$width."\"",$description);
582 $description=preg_replace("/height=\"\d+\"/","height=\"".$height."\"",$description);
584 $description.= "<br>$summary";
586 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
587 "Unable to extract embedded video information from url: $url"),NULL,NULL);
591 **********************************
592 * Embed a DivShare Video
593 **********************************
595 } else if(preg_match("/$divshareUrlPattern/",$url)) {
597 /* Make sure we can extract a itemID */
598 if(preg_match("/\/download\/(.+)/",$url,$matches)) {
599 $item_id = $matches[1];
600 $item_id=preg_replace("/\/$/","",$item_id);
602 return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
603 "Unable to extract item id from url: $url"),null,null);
606 /* Grab the contents of the webpage used to display the video on video.google.com */
607 list ($successfullyCopied, $contents, $response, $headers) =
608 GalleryCoreApi::fetchWebPage($url, $extraHeaders);
609 if (!$successfullyCopied) {
610 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
611 "Unable to get video information at url: $url - $response"),NULL,NULL);
614 /* Extract the summary from the webpage contents */
615 //preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
616 //$summary=$matches[1];
617 // Right now, the description is a plug for divshare, nothing user specific about it
620 /* Extract the title from the webpage contents */
621 preg_match('/<title>(.+?) - Divshare<\/title>/i', $contents, $matches);
624 /* Build the thumbnail URL from the item_id */
625 $thumbnail=$divshareThumbnailUrl.$item_id;
627 /* Format the description to hold a reference to the embedded video */
628 if(preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches)) {
629 $description=$matches[1];
630 if(!strcmp($useRemoteSize,"false")) {
631 $description=preg_replace("/width=\"\d+\"/","width=\"".$width."\"",$description);
632 $description=preg_replace("/height=\"\d+\"/","height=\"".$height."\"",$description);
634 $description.= "<br>$summary";
636 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
637 "Unable to extract embedded video information from url: $url"),NULL,NULL);
641 **********************************
642 * Embed a remote .swf file
643 **********************************
645 } else if(preg_match("/.*\/(.+?)\.swf/i",$url,$matches)) {
647 /* Set the title and summary to the name of the file */
648 $title = $matches[1];
649 $summary = $matches[1];
652 * Set the thumbnail to some generic jpg image,
653 * since we can't extract it from the remote swf file.
654 * If no parameter is set, set it to a default value.
656 if(preg_match("/\w+/", $flvThumbnail)) {
657 $thumbnail = $flvThumbnail;
659 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
663 * Check to make sure the URL to the remote swf file is valid
664 * (That the file exists at the URL given)
666 list ($successfullyCopied, $response, $headers) =
667 $this->fetchWebFileHeaders($url, $extraHeaders);
668 if (!$successfullyCopied) {
669 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
670 "Unable to find the video at url: $url - $response"),NULL,NULL);
674 * Format the description to hold a reference to the embedded video
677 /* Format the description to hold a reference to the embedded video */
678 $description ='<embed src="'.$url.'">';
681 **********************************
682 * Embed a remote .flv file
683 **********************************
685 } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
687 /* Set the title and summary to the name of the file */
688 $title = $matches[1];
689 $summary = $matches[1];
692 * Set the thumbnail to some generic jpg image,
693 * since we can't extract it from the remote flv file.
694 * If no parameter is set, set it to a default value.
696 if(preg_match("/\w+/", $flvThumbnail)) {
697 $thumbnail = $flvThumbnail;
699 $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
703 * Check to make sure the URL to the remote flv file is valid
704 * (That the file exists at the URL given)
706 list ($successfullyCopied, $response, $headers) =
707 $this->fetchWebFileHeaders($url, $extraHeaders);
708 if (!$successfullyCopied) {
709 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
710 "Unable to find the video at url: $url - $response"),NULL,NULL);
714 * Format the description to hold a reference to the embedded video
715 * This reference will be embedded using the G2 internal player,
716 * or an external player if provided by the user.
718 if(!strcmp($useInternalFlvPlayer,"false")) {
721 * The user has indicated they want to use an external flv player
722 * Make sure one is defined!
724 if(!preg_match("/\w+/",$externalFlvPlayer)) {
725 return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
726 "Invalid/missing external player parameter"),null,null);
729 /* Format the description to hold a reference to the embedded video */
730 $description ='<embed src="'.$externalFlvPlayer.'" ';
731 $description.= 'width="'.$width.'" height="'.$height.'" ';
732 $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
733 $description.= 'type="application/x-shockwave-flash" ';
734 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
735 $description.= 'flashvars="file='.$url;
736 $description.= '&fullscreenpage='.$thumbnail;
737 $description.= '&linktarget=_Blank&image='.$thumbnail;
739 if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
740 /* Format the flashvars for the internal G2 flv player */
741 $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
742 $description.= '&repeat=false&lightcolor=0x9999FF';
743 $description.= '&backcolor=0x888888&frontcolor=0x000000"';
745 /* Format the flashvars for the external G2 flv player */
746 $description.= '&'.$externalFlvPlayerVars;
748 $description.= ' /> </p>';
750 /* Internal FLV player */
752 /* Format the description to hold a reference to the embedded video */
753 $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
754 $description = '<script type="text/javascript">'."\n";
755 $description.= '// <![CDATA['."\n";
756 $description.= 'function divResize(id, nw, nh) {'."\n";
757 $description.= 'var obj = document.getElementById(id);'."\n";
758 $description.= 'obj.style.width = nw + "px";'."\n";
759 $description.= 'obj.style.height = nh + "px";'."\n";
760 $description.= '}'."\n";
761 $description.= '// ]]>'."\n";
762 $description.= '</script>'."\n";
763 $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
764 $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
765 $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
766 $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
767 $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
768 $description.= '<param name="FlashVars" value="flvUrl='.$url;
769 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
770 $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
771 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
772 $description.= '<param name="quality" value="high"/>';
773 $description.= '<param name="scale" value="noscale"/>';
774 $description.= '<param name="salign" value="lt"/>';
775 $description.= '<param name="wmode" value="transparent"/>';
776 $description.= '<param name="allowScriptAccess" value="always"/>';
777 $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
778 $description.= 'flashvars="flvUrl='.$url;
779 $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
780 $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
781 $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
782 $description.= 'type="application/x-shockwave-flash" ';
783 $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
784 $description.= 'wmode="transparent" allowScriptAccess="always" ';
785 $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
786 $description.= '</object></div>';
790 **********************************
791 * Unsupported URL to embed
792 **********************************
795 return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
796 "Unable to embed video from: $url"),null,null);
801 **********************************
802 * Add the video to Gallery
803 **********************************
806 /* Get a local tmp file to save the thumbnail URL to */
807 $tmpDir = $gallery->getConfig('data.gallery.tmp');
808 $tmpFile = $platform->tempnam($tmpDir, 'add');
811 /* Fetch the thumbnail and save it to a local file */
812 list ($successfullyCopied, $response, $headers) =
813 GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
814 if (!$successfullyCopied) {
815 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
816 "Unable to copy thumbnail from url: $thumbnail - $response"),null,null);
819 /* Obtain the mimeType of the thumbnail */
820 list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
822 /* Set the filename for the item we want to add */
824 $fileName = preg_replace("/\s+/","_",$fileName);
825 $fileName = preg_replace("/'/","",$fileName);
826 $fileName = preg_replace("/\"/","",$fileName);
827 $fileName = preg_replace("/&#\d+;/","",$fileName);
829 /* General debug output */
830 if(!strcmp($debugOutput,"true")) {
831 print "\n<h2>Item Parameters</h2>\n";
832 print "url: $url <br>\n";
833 print "title: $title <br>\n";
834 print "thumbnailUrl: <img src=\"".$thumbnail."\"> <br>\n";
835 print "summary: <p>$summary</p>\n";
836 print "description: <p>$description</p>\n";
837 print "thumbnail: $tmpFile <br>\n";
838 print "mimeType: $mimeType <br>\n";
839 print "fileName: $fileName <br>\n";
840 print "width: $width <br>\n";
841 print "height: $height <br>\n";
845 /* Resize the thumbnail image to the size indicated by our album */
847 list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'resize');
849 $debugString.="Checking to see if a toolkit that can resize images was found. <br>";
850 if (isset($toolkit)) {
851 $newTmpFile = $platform->tempnam($tmpDir, 'add');
852 $newTmpFile.= ".jpg";
853 $thumbnailSize = 150;
854 list ($ret, $preferences) =
855 GalleryCoreApi::fetchDerivativePreferencesForItem($item->getId());
857 foreach ($preferences as $preference) {
858 if (preg_match('/thumbnail\|(\d+)/',
859 $preference['derivativeOperations'], $matches)) {
860 $thumbnailSize = $matches[1];
861 $debugString.="Found thumbnail size in album preferences: $thumbnailSize <br>";
867 // Obtain the width and height of the original thumbnail, finding out it's ratio,
868 // and using that ratio when determining the width of the video below.
869 // Example: youtube: 130x97 google: 160x120 metacafe: 90x76 yahoo: 100x70
870 // Set the thumbnailHeight to the current thumbnailSize
871 // Set the thumbnailWidth to the appropriate size based on the thumbnailHeight * ratio
872 $image_data = @getimagesize($tmpFile);
874 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
875 "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
877 $ratio = $image_data[0] / $image_data[1];
878 $debugString.="Using ratio from original thumbnail of $ratio. ";
879 $thumbnailHeight=$thumbnailSize;
880 $thumbnailWidth=round($thumbnailHeight * $ratio);
881 $debugString.="Resizing thumbnail image to $thumbnailWidth x $thumbnailHeight: $tmpFile -> $newTmpFile <br>";
882 $toolkit->performOperation($mimeType, 'resize', $tmpFile, $newTmpFile,
883 array($thumbnailWidth,$thumbnailHeight));
886 if(!strcmp($debugOutput,"true")) {
887 print "\n<h2>Thumbnail Resize</h2>\n";
888 print "$debugString\n";
892 /* Watermark the video thumbnail image if indicated by our parameter */
893 if(!strcmp($watermarkVideos,"true")) {
896 * If no watermarkImage parameter is set, set it to a default value.
898 if(preg_match("/\w+/", $watermarkImage)) {
899 $watermarkImage = $watermarkImage;
901 $watermarkImage = $gallery2_url.$gallery2_video_watermark;
904 /* Get the watermark Image Extension */
905 preg_match('/\.(...)$/', $watermarkImage, $matches);
906 $watermarkExt=$matches[1];
909 * Check to make sure the URL to the watermark image file is valid
910 * (That the file exists at the URL given). Skip this part if it is a local path.
912 if(!preg_match("/^\//", $watermarkImage)) {
913 list ($successfullyCopied, $response, $headers) =
914 $this->fetchWebFileHeaders($watermarkImage, $extraHeaders);
915 if (!$successfullyCopied) {
916 return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
917 "Unable to find the watermark image at url: $watermarkImage - $response"),NULL,NULL);
920 /* Download the watermark image to a local file */
921 $tmpDir = $gallery->getConfig('data.gallery.tmp');
922 $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
923 $watermark.= "." . $watermarkExt;
924 list ($successfullyCopied, $response, $headers) =
925 GalleryCoreApi::fetchWebFile($watermarkImage, $watermark, $extraHeaders);
926 if (!$successfullyCopied) {
927 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
928 "Unable to copy watermark image from url: $watermarkImage - $response"),null,null);
931 $tmpDir = $gallery->getConfig('data.gallery.tmp');
932 $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
933 $watermark.= "." . $watermarkExt;
934 if(!$platform->copy($watermarkImage, $watermark)) {
935 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
936 "Unable to copy watermark image from path: $watermarkImage"),null,null);
940 /* See if there is a toolkit installed that can perform a composite operation */
941 list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'composite');
943 return array($ret->wrap(__FILE__, __LINE__,
944 "Unable to locate a toolkit module to perform the 'composite' watermark operation"), null);
947 /* Make sure we can access the toolkit found */
948 if (!isset($toolkit)) {
949 return array(GalleryStatus::error(ERROR_PERMISSION_DENIED, __FILE__, __LINE__,
950 "Unable to access the toolkit module to perform the 'composite' watermark operation"), null);
953 /* Get the image dimensions of the thumbnail */
954 $image_data = @getimagesize($newTmpFile);
956 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
957 "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
959 $thumbnailWidth = $image_data[0];
960 $thumbnailHeight = $image_data[1];
962 /* Get the image dimensions of the watermark */
963 $image_data = @getimagesize($watermark);
965 return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
966 "Unable to retrieve watermark dimensions for: $tmpFile"),null,null);
968 $watermarkWidth = $image_data[0];
969 $watermarkHeight = $image_data[1];
971 /* Obtain the mimeType of the watermark */
972 list ($ret, $watermarkMimeType) = GalleryCoreApi::getMimeType($watermark);
974 /* Remove the gallery base path from the watermark image path */
975 /* This has to be done to satisfy the argument requirement for the toolkit operation */
976 $dataDir = $gallery->getConfig('data.gallery.base');
977 $dataDir=preg_replace("/\//","\\/",$dataDir);
978 if(preg_match("/$dataDir(.*)/", $watermark, $matches)) {
979 $watermark = $matches[1];
982 /* General debug output */
983 if(!strcmp($debugOutput,"true")) {
984 print "\n<h2>Watermark Operation</h2>\n";
985 print "watermarkImage: $watermarkImage <br>\n";
986 print "watermarkTmpImage: $watermark <br>\n";
987 print "watermarkMimeType: $watermarkMimeType <br>\n";
988 print "watermarkWidth: $watermarkWidth <br>\n";
989 print "watermarkHeight: $watermarkHeight <br>\n";
990 print "watermarkedWidth: $thumbnailWidth <br>\n";
991 print "watermarkedHeight: $thumbnailHeight <br>\n";
994 /* Apply the watermark image to the thumbnail */
995 $tmpFile = $platform->tempnam($tmpDir, 'wmk_');
996 list ($ret, $mimeType) = $toolkit->performOperation(
997 $mimeType, 'composite', $newTmpFile, $tmpFile,
998 array($watermark, $watermarkMimeType,
999 $watermarkWidth, $watermarkHeight,
1000 $watermarkAlignment, 0, 0));
1002 /* Check the return code of the composite operation */
1004 return array($ret->wrap(__FILE__, __LINE__,
1005 "Unable to apply watermark to the video thumbnail image"), null);
1008 if(!strcmp($debugOutput,"true")) {
1009 print "\nwatermarked Image: $tmpFile <br>";
1013 /* Update the path of our thumbnail to point to the new watermarked thumbnail instead */
1014 $newTmpFile = $tmpFile;
1018 /* Make the gallery2 call to add this item to the album */
1019 list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($newTmpFile,
1028 return array($ret, null, null);
1031 $status['addedFiles'][] = array('fileName' => $url,
1032 'id' => $newItem->getId(),
1033 'warnings' => array());
1035 if(!strcmp($debugOutput,"true")) {
1036 print "\n<br><br><h2>Video Successfully Added to your Gallery Album</h2><br><br><hr>";
1040 /* Keep the tmpfiles around if we are in debug mode. Otherwise, remove them. */
1041 if(!strcmp($debugOutput,"false")) {
1042 @$platform->unlink($tmpFile);
1043 @$platform->unlink($newTmpFile);
1048 return array(null, $error, $status);
1052 * A simple function to resolve the value of a parameter from
1053 * the default or override value if it exists, or set it
1054 * to the default passed as an argument.
1056 function getParameter($params, $name, $default="") {
1057 if(isset($params['override'][$name])) {
1058 /* print "override $name = ".$params['override'][$name]."<br>"; */
1059 return($params['override'][$name]);
1060 } else if(isset($params['default'][$name])) {
1061 /* print "default $name = ".$params['default'][$name] ."<br>"; */
1062 return($params['default'][$name]);
1064 /* print "$name = $default <br>"; */
1070 * A simple function to get the headers only (no body) for a given URL
1071 * This was taken from GalleryCoreApi::requestWebPage
1073 function fetchWebFileHeaders($url, $requestHeaders=array()) {
1076 $requestMethod='GET';
1078 /* Convert illegal characters */
1079 $url = str_replace(' ', '%20', $url);
1081 /* Unescape ampersands, since if the URL comes from form input it will be escaped */
1082 $url = str_replace('&', '&', $url);
1084 $platform =& $gallery->getPlatform();
1086 $urlComponents = parse_url($url);
1087 if (empty($urlComponents['port'])) {
1088 $urlComponents['port'] = 80;
1090 if (empty($urlComponents['path'])) {
1091 $urlComponents['path'] = '/';
1094 $handle = @$platform->fsockopen(
1095 $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
1096 if (empty($handle)) {
1097 $gallery->debug("Error $errno: '$errstr' requesting $url");
1098 return array(null, null, null);
1101 $requestUri = $urlComponents['path'];
1102 if (!empty($urlComponents['query'])) {
1103 $requestUri .= '?' . $urlComponents['query'];
1105 $headerLines = array('Host: ' . $urlComponents['host']);
1106 foreach ($requestHeaders as $key => $value) {
1107 $headerLines[] = $key . ': ' . $value;
1110 $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
1113 implode("\r\n", $headerLines),
1116 /* Zero bytes written or false was returned */
1118 "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
1119 return array(null, null, null);
1121 $platform->fflush($handle);
1125 * Read the status line. fgets stops after newlines. The first line is the protocol
1126 * version followed by a numeric status code and its associated textual phrase.
1128 $responseStatus = trim($platform->fgets($handle, 4096));
1129 if (empty($responseStatus)) {
1130 $gallery->debug('Empty http response code, maybe timeout');
1131 return array(null, null, null);
1134 /* Read the headers */
1135 $responseHeaders = array();
1136 while (!$platform->feof($handle)) {
1137 $line = trim($platform->fgets($handle, 4096));
1142 /* Normalize the line endings */
1143 $line = str_replace("\r", '', $line);
1145 list ($key, $value) = explode(':', $line, 2);
1146 if (isset($responseHeaders[$key])) {
1147 if (!is_array($responseHeaders[$key])) {
1148 $responseHeaders[$key] = array($responseHeaders[$key]);
1150 $responseHeaders[$key][] = trim($value);
1152 $responseHeaders[$key] = trim($value);
1155 $platform->fclose($handle);
1157 if(preg_match("/Not found/i", $responseStatus)) {
1161 //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
1163 return array($success, $responseStatus, $responseHeaders);
1167 * @see ItemAdd:loadTemplate
1169 function loadTemplate(&$template, &$form, $item) {
1172 if ($form['formName'] != 'ItemAddEmbedVideo') {
1173 /* First time around, load the form with item data */
1174 $form['webPage'] = '';
1175 $form['formName'] = 'ItemAddEmbedVideo';
1178 $session =& $gallery->getSession();
1180 $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
1183 'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
1184 'modules_embedvideo');
1188 * @see ItemAddPlugin::getTitle
1190 function getTitle() {
1191 list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
1193 return array($ret, null);
1196 return array(null, $module->translate('Embed Video'));