Added support for embedding videos from new video site: vimeo.com
[embedvideo/.git] / ItemAddEmbedVideo.inc
1 <?php
2 /*
3  * Gallery - a web based photo album viewer and editor
4  * Copyright (C) 2000-2007 Bharat Mediratta
5  *
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.
10  *
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.
15  *
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.
19  */
20
21 GalleryCoreApi::requireOnce('modules/gd/classes/GdToolkitHelper.class');
22
23
24 /**
25  * This plugin will handle the addition of embedded video objects
26  * @package embedVideo
27  * @subpackage UserInterface
28  * @author Alan Pippin <apippin@pippins.net>
29  * @version $Revision: 1.1 $
30  */
31 class ItemAddEmbedVideo extends ItemAddPlugin {
32   
33   /**
34    * @see ItemAddPlugin::handleRequest
35    */
36  function handleRequest($form, &$item) {
37    global $gallery, $url;
38     
39    $status = $error = array();
40    
41    if (isset($form['action']['addEmbedVideoPage'])) {
42      
43        $platform =& $gallery->getPlatform();
44
45        if (empty($extraHeaders)) {
46            $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
47        }
48
49        if(isset($form['webPage']['URL'])) {
50          
51            /* Load any stored/set Parameters */
52            list ($ret, $params) =
53              GalleryCoreApi::fetchAllPluginParameters('module', 'embedvideo');
54            if ($ret) {
55                return array($ret, null, null);
56            }
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>"; */
65                    }
66                }
67            }
68            
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;
74
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
78             */
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");
93            $wordwrapSummary = $this->getParameter($ItemAddEmbedVideo, 'wordwrapSummary', "0");
94            $wordwrapDescription = $this->getParameter($ItemAddEmbedVideo, 'wordwrapDescription', "0");
95
96            /* Print our stored/set Parameters */
97            if(!strcmp($debugOutput,"true")) {
98              print "\n<hr>";
99              print "<h2>Variable Parameters</h2>\n";
100              print "debugOutput=$debugOutput<br>\n";
101              print "useInternalFlvPlayer=$useInternalFlvPlayer<br>\n";
102              print "youtubeDevId=$youtubeDevId<br>\n";
103              print "youtubeShowRelated=$youtubeShowRelated<br>\n";
104              print "width=$width<br>\n";
105              print "height=$height<br>\n";
106              print "externalFlvPlayer=$externalFlvPlayer<br>\n";
107              print "externalFlvPlayerVars=$externalFlvPlayerVars<br>\n";
108              print "flvThumbnail=$flvThumbnail<br>\n";
109              print "useRemoteSize=$useRemoteSize<br>\n";
110              print "autoStart=$autoStart<br>\n";
111              print "watermarkVideos=$watermarkVideos<br>\n";
112              print "watermarkImage=$watermarkImage<br>\n";
113              print "watermarkAlignment=$watermarkAlignment<br>\n";
114              print "wordwrapSummary=$wordwrapSummary<br>\n";
115              print "wordwrapDescription=$wordwrapDescription<br>\n";
116              print "<hr>\n";
117            }
118
119            /* Store other string constants we'll use later */
120           
121            /* youtube */
122            $youtubeUrlPattern="youtube.com";
123            $youtubeApiUrl="http://www.youtube.com/api2_rest";
124            $youtubeThumbnailUrl="http://img.youtube.com/vi/";
125            /* We can't extract the server size from youtube */
126            $youtubeWidth="425";
127            $youtubeHeight="350";
128
129            /* google */
130            $googleUrlPattern="video.google.com";
131            $googlePlayer="http://video.google.com/googleplayer.swf";
132            /* We can't extract the server size from google video */
133            $googleWidth="400";
134            $googleHeight="326";
135            
136            /* yahoo */
137            $yahooUrlPattern="video.yahoo.com";
138            $yahooThumbnailUrl="http://thmg01.video.search.yahoo.com/image/";
139            
140            /* metacafe */
141            $metacafeUrlPattern="metacafe.com";
142            $metacafeThumbnailUrl="http://www.metacafe.com/thumb/";
143
144            /* revver */
145            $revverUrlPattern="revver.com";
146            $revverThumbnailUrl="http://frame.revver.com/frame/120x90/";
147
148            /* dailymotion */
149            $dailymotionUrlPattern="dailymotion.com";
150            $dailymotionThumbnailUrl="http://www.dailymotion.com/thumbnail/160x120/video/";
151
152            /* divshare */
153            $divshareUrlPattern="divshare.com";
154            $divshareThumbnailUrl="http://www.divshare.com/direct/video_thumb/";
155
156            /* stickam */
157            $stickamUrlPattern="stickam.com";
158            $stickamThumbnailUrl="http://static.stickam.com/";
159
160            /* myspace */
161            $myspaceUrlPattern="vids.myspace.com";
162            $myspaceUrlPattern2="myspacetv.com";
163            $myspaceThumbnailUrl="http://mediaservices.myspace.com/services/rss.ashx?type=video&videoID=";
164
165            /* vimeo */
166            $vimeoUrlPattern="www.vimeo.com";
167            
168            /* Gallery2 specific paths and variables */
169            $urlGenerator =& $gallery->getUrlGenerator();
170            $gallery2_url = $urlGenerator->getCurrentUrlDir();
171            $gallery2_flv_thumbnail = "modules/embedvideo/images/G2video_thumbnail.jpg";
172            $gallery2_video_watermark = "modules/embedvideo/images/G2video_watermark1.png";
173            $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
174            
175            /* Store the passed URL in a shorter local variable */
176            $url = $form['webPage']['URL'];
177
178            /*
179             *****************************
180             * Embed a Youtube Video
181             *****************************
182             */
183            if(preg_match("/$youtubeUrlPattern/",$url)) {
184              
185                /* Make sure we can find a video_id in the URL */
186                $extra_params = "";
187                if(preg_match("/watch\?v=(.*?)(&\S+=\S+)/",$url,$matches)) {
188                    $video_id = $matches[1];
189                    $extra_params = $matches[2];
190                } else if (preg_match("/watch\?v=(.*)/",$url,$matches)) {
191                    $video_id = $matches[1];
192                } else {
193                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
194                                 "Unable to extract video id from url: $url"),null,null);
195                }
196
197                /* If extra params were given, handle them here */
198                if(strcmp($extra_params,"")) {
199                  /* Handle the HD format information */
200                  if(preg_match("/fmt=(\d+)/",$extra_params,$matches)) {
201                    $extra_params="&ap=%2526fmt%3D".$matches[1];
202                  }
203                }
204                
205                if(!strcmp($debugOutput,"true")) {
206                    print "<h2>URL Parsing Results</h2>";
207                    print "video_id: $video_id<br>";
208                    print "extra_embed_params: $extra_params<br>";
209                    print "<hr>";
210                }
211                
212                /* If we have a valid youtube developer id, use that to get information about the video */
213                /* Otherwise, just parse it directly from the HTML page */
214                $dev_id = $youtubeDevId;
215                if(!preg_match("/\w+/",$dev_id)) {
216                  /* No developer ID found. Proceed with direct page parsing. */
217
218                  /* Grab the contents of the webpage used to display the video on video.google.com */
219                  list ($successfullyCopied, $contents, $response, $headers) =
220                    GalleryCoreApi::fetchWebPage($url, $extraHeaders);
221                  if (!$successfullyCopied) {
222                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
223                                                       "Unable to get video information at url: $url - $response"),NULL,NULL);
224                  }
225                
226                  /* Extract the summary from the webpage contents */
227                  preg_match('/<meta name="description" content="(.+?)">/i', $contents, $matches);
228                  $summary=$matches[1];
229                  
230                  /* Extract the title from the webpage contents */
231                  preg_match('/<meta name="title" content="(.+?)">/i', $contents, $matches);
232                  $title=$matches[1];           
233
234                  /* Extract the thumbnail URL from the webpage contents */
235                  $thumbnail=$youtubeThumbnailUrl.$video_id."/default.jpg";
236                  
237                  /* Determine if the video should autoplay or not based on the autoStart parameter */
238                  $autoStartStr="";
239                  if(!strcmp($autoStart,"true")) {
240                    $autoStartStr="&autoplay=1";
241                  } else {
242                    $autoStartStr="&autoplay=0";
243                  }
244                  
245                  /* Determine if the video should show related videos or not based on the youtubeShowRelated parameter */
246                  $youtubeShowRelatedStr="";
247                  if(!strcmp($youtubeShowRelated,"false")) {
248                    $youtubeShowRelatedStr="&rel=0";
249                  } else {
250                    $youtubeShowRelatedStr="&rel=1";
251                  }
252                                
253                  /* Format the description to hold a reference to the embedded video */
254                  if(preg_match('/id=\"embed_code\".+?value=\'(.+?)\'/', $contents, $matches)) {
255                    $description=$matches[1];
256                    $description=preg_replace("/&quot;/","'",$description);
257                    $description=preg_replace("/&lt;/","<",$description);
258                    $description=preg_replace("/&gt;/",">",$description);
259                    $description=preg_replace("/&amp;/","&",$description);
260                    $description=preg_replace("/$video_id/",$video_id.$autoStartStr.$youtubeShowRelatedStr,$description);
261                    $description=preg_replace("/$video_id/",$video_id.$extra_params,$description);
262                    if(!strcmp($useRemoteSize,"false")) {                   
263                      $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
264                      $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
265                    }
266                  } else {
267                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
268                           "Unable to extract embedded video information from url: $url"),NULL,NULL);
269                  }
270                  
271                } else {
272                  /* We found a valid developer ID. Proceed with API calls. */
273                        
274                  /* Youtube api feed */
275                  $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
276                  $feed.= "&dev_id=$dev_id&video_id=$video_id";
277                  
278                  /* Get the youtube xml feed as a string data source */
279                  list ($successfullyCopied, $xml, $response, $headers) =
280                    GalleryCoreApi::fetchWebPage($feed, $extraHeaders);
281                  if (!$successfullyCopied) {
282                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
283                                                       "Unable to get video information at url: $url - $response"),null,null);
284                  }
285                  
286                  if(preg_match("/This video is private/",$xml)) {
287                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
288                                                       "Unable to retrieve video information from youtube.".
289                                                       "You cannot embed a private youtube video: $url"),null,null);
290                  }
291                  
292                  if(!strcmp($debugOutput,"true")) {
293                    print "\n<h2>Youtube XML Dump</h2>";
294                    print "$xml";
295                    print "<hr>";
296                  }
297                  
298                  /* Extract certain information from the xml feed */
299                  preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
300                  preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
301                  preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
302                  
303                  array_shift($title);
304                  array_shift($thumbnail);
305                  array_shift($description);
306                  
307                  /* Replace html characters. More can be added but this seems to work */
308                  for($i=0;$i<count($description[0]);$i++){        
309                    $description[0][$i] = preg_replace("/&#60;/","<",$description[0][$i]);
310                    $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);      
311                  }
312                  
313                  /* Store the information found in some local variables */
314                  $title = $title[0][0];
315                  $summary = $description[0][0];
316                  $thumbnail = $thumbnail[0][0];
317                  
318                  /* Determine what our width and height should be based on our useRemoteSize parameter */
319                  if(!strcmp($useRemoteSize,"true")) {
320                    $width = $youtubeWidth;
321                    $height = $youtubeHeight;
322                  }
323                  
324                  /* Determine if the video should autoplay or not based on the autoStart parameter */
325                  $autoStartStr="";
326                  if(!strcmp($autoStart,"true")) {
327                    $autoStartStr="&autoplay=1";
328                  }
329                  
330                  /* Determine if the video should show related videos or not based on the youtubeShowRelated parameter */
331                  $youtubeShowRelatedStr="";
332                  if(!strcmp($youtubeShowRelated,"false")) {
333                    $youtubeShowRelatedStr="&rel=0";
334                  }
335                  
336                  /* Format the description to hold a reference to the embedded video */
337                  $description = '<object width="'.$width.'" height="'.$height.'">';
338                  $description.= '<param name="movie" ';
339                  $description.= 'value="http://www.youtube.com/v/'.$video_id.$extra_params.'"></param>';
340                  $description.= '<param name="wmode" value="transparent"></param>';
341                  $description.= '<embed src="http://www.youtube.com/v/';
342                  $description.= $video_id.$extra_params.$autoStartStr.$youtubeShowRelatedStr;
343                  $description.= '" type="application/x-shockwave-flash" wmode="transparent" ';
344                  $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
345                }
346            /*
347             **********************************
348             * Embed a Google Video
349             **********************************
350             */
351            } else if(preg_match("/$googleUrlPattern/",$url)) {
352
353                /* Make sure we can extract a docID */
354                if(preg_match("/docid=(.*)/",$url,$matches)) {
355                    $doc_id = $matches[1];
356                } else {
357                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
358                                 "Unable to extract doc id from url: $url"),null,null);
359                }
360
361                /* Grab the contents of the webpage used to display the video on video.google.com */
362                list ($successfullyCopied, $contents, $response, $headers) =
363                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
364                if (!$successfullyCopied) {
365                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
366                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
367                }
368
369                /* Extract the summary from the webpage contents */
370                //print "contents: $contents <br>";
371                preg_match('/<meta name="description" content="(.+?)\. \w+ \d+, \d+.*">/i',
372                           $contents, $matches);
373                $summary=$matches[1];
374
375                /* Extract the title from the webpage contents */
376                $title="Unknown";
377                if(preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches)) {
378                  $title=$matches[1];
379                } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
380                  $title=$matches[1];
381                }
382
383                /* Extract the thumbnail URL from the webpage contents */
384                preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
385                           $contents, $matches);
386                $thumbnail=$matches[1];
387                $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
388
389                /* Determine what our width and height should be based on our useRemoteSize parameter */
390                if(!strcmp($useRemoteSize,"true")) {
391                  $width = $googleWidth;
392                  $height = $googleHeight;
393                }
394
395                /* Determine if the video should autoplay or not based on the autoStart parameter */
396                $autoStartStr="";
397                if(!strcmp($autoStart,"true")) {
398                  $autoStartStr="&autoplay=1";
399                }
400
401                /* Format the description to hold a reference to the embedded video */
402                $description = '<embed ';
403                $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
404                $description.= 'type="application/x-shockwave-flash" ';
405                $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.$autoStartStr.'" flashvars=""> ';
406                $description.= '</embed>';
407
408            /*
409             **********************************
410             * Embed a Yahoo Video
411             **********************************
412             * TODO: The autoStart parameter doesn't work with the yahoo video player
413             */
414            } else if(preg_match("/$yahooUrlPattern/",$url)) {
415
416                /* Make sure we can extract a vidID */
417                if(preg_match("/vid=(.*)/",$url,$matches)) {
418                    $vid_id = $matches[1];
419                } else {
420                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
421                                 "Unable to extract vid id from url: $url"),null,null);
422                }
423
424                /* Grab the contents of the webpage used to display the video on video.google.com */
425                list ($successfullyCopied, $contents, $response, $headers) =
426                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
427                if (!$successfullyCopied) {
428                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
429                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
430                }
431
432                /* Extract the summary from the webpage contents */
433                preg_match('/Description:<\/em><p>(.+?)<\/p>/', $contents, $matches);
434                $summary=$matches[1];
435
436                /* Extract the title from the webpage contents */
437                $title="Unknown";
438                if(preg_match('/<title>(.+?)\s+- Yahoo! Video<\/title>/i', $contents, $matches)) {
439                  $title=$matches[1];
440                } else if(preg_match('/<title>(.+?)<\/title>/i', $contents, $matches)) {
441                  $title=$matches[1];
442                }
443
444                /* Build the thumbnail URL from the vid_id */
445                $thumbnail=$yahooThumbnailUrl.$vid_id."_01";
446
447                /* Format the description to hold a reference to the embedded video */
448                if(preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches)) { 
449                  $description=$matches[1];
450                  if(!strcmp($useRemoteSize,"false")) {
451                    $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
452                    $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
453                  }
454                } else {
455                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
456                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
457                }
458
459            /*
460             **********************************
461             * Embed a MetaCafe Video
462             **********************************
463             */
464            } else if(preg_match("/$metacafeUrlPattern/",$url)) {
465
466                /* Make sure we can extract a itemID */
467                if(preg_match("/\/watch\/(.+?)\/(.+?)/",$url,$matches)) {
468                    $item_id = $matches[1];
469                } else {
470                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
471                                 "Unable to extract item id from url: $url"),null,null);
472                }
473
474                /* Grab the contents of the webpage used to display the video on video.google.com */
475                list ($successfullyCopied, $contents, $response, $headers) =
476                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
477                if (!$successfullyCopied) {
478                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
479                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
480                }
481
482                /* Extract the summary from the webpage contents */
483                preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
484                $summary=$matches[1];
485
486                /* Extract the title from the webpage contents */
487                preg_match('/<title>(.+?)<\/title>/i', $contents, $matches);
488                $title=$matches[1];
489                
490                /* Build the thumbnail URL from the item_id */
491                $thumbnail=$metacafeThumbnailUrl.$item_id.".jpg";
492
493                /* Format the description to hold a reference to the embedded video */
494                if(preg_match('/(embed src.+?\/embed)/', $contents, $matches)) { 
495                  $description="<".$matches[1];
496                  $description=preg_replace("/&quot;/","'",$description);
497                  if(!strcmp($useRemoteSize,"false")) {
498                    $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
499                    $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
500                  }
501                  if(!strcmp($autoStart,"true")) {
502                    $description=preg_replace("/\.swf/",".swf?playerVars=autoPlay=yes",$description);
503                  }
504                  $description.= "</embed>";
505                } else {
506                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
507                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
508                }
509
510            /*
511             **********************************
512             * Embed a Revver Video
513             **********************************
514             * TODO: The autoStart parameter doesn't work with the yahoo video player
515             */
516            } else if(preg_match("/$revverUrlPattern/",$url)) {
517
518                /* Make sure we can extract a itemID */
519                if(preg_match("/\/watch\/(.+)/",$url,$matches)) {
520                    $item_id = $matches[1];
521                    $item_id=preg_replace("/\/$/","",$item_id);
522                } else {
523                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
524                                 "Unable to extract item id from url: $url"),null,null);
525                }
526
527                /* Grab the contents of the webpage used to display the video on video.google.com */
528                list ($successfullyCopied, $contents, $response, $headers) =
529                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
530                if (!$successfullyCopied) {
531                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
532                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
533                }
534
535                /* Extract the summary from the webpage contents */
536                if(preg_match('/"video_description">(.+?)<\/p>/i', $contents, $matches)) {
537                  $summary=$matches[1];
538                }
539                if(preg_match('/"video_description">(.+)/i', $contents, $matches)) {
540                  $summary=$matches[1];
541                }
542
543                /* Extract the title from the webpage contents */
544                preg_match('/digg_title = \'(.+?)\'/i', $contents, $matches);
545                $title=$matches[1];
546                
547                /* Build the thumbnail URL from the item_id */
548                $thumbnail=$revverThumbnailUrl.$item_id.".jpg";
549
550                /* Format the description to hold a reference to the embedded video */
551                if(preg_match('/<input class.+?(script src.+?\/script)/', $contents, $matches)) {
552                  $description="<".$matches[1];
553                  if(!strcmp($useRemoteSize,"false")) {
554                    $description=preg_replace("/width:\d+/","width:".$width,$description);
555                    $description=preg_replace("/height:\d+/","height:".$height,$description);
556                  }
557                  if(!strcmp($autoStart,"true")) {
558                    preg_match('/(height:\d+)/',$description,$matches);
559                    $height=$matches[1];
560                    $description=preg_replace("/$height/",$height.";autoplay:true",$description);
561                  }
562                  $description.= ">";
563                } else {
564                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
565                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
566                }
567             
568            /*
569             **********************************
570             * Embed a DailyMotion Video
571             **********************************
572             * TODO: The autoStart parameter doesn't work with the yahoo video player
573             */
574            } else if(preg_match("/$dailymotionUrlPattern/",$url)) {
575              
576                /* Make sure we can extract a itemID */
577                if(preg_match("/\/video\/(.+)/",$url,$matches)) {
578                    $item_id = $matches[1];
579                    $item_id=preg_replace("/\/$/","",$item_id);
580                } else {
581                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
582                                 "Unable to extract item id from url: $url"),null,null);
583                }
584
585                /* Grab the contents of the webpage used to display the video on video.google.com */
586                list ($successfullyCopied, $contents, $response, $headers) =
587                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
588                if (!$successfullyCopied) {
589                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
590                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
591                }
592
593                /* Extract the summary from the webpage contents */
594                preg_match('/<div class="description\s+foreground">(.+?)<\/div>/i', $contents, $matches);
595                $summary=$matches[1];
596
597                /* Extract the title from the webpage contents */
598                preg_match('/<meta name="title" content="Dailymotion : (.+?)" \/>/i', $contents, $matches);
599                $title=htmlentities($matches[1], ENT_QUOTES, "UTF-8");
600                
601                /* Build the thumbnail URL from the item_id */
602                $thumbnail=$dailymotionThumbnailUrl.$item_id;
603
604                /* Format the description to hold a reference to the embedded video */
605                if(preg_match('/<textarea id="video_player_embed_code_text".+?>(.+?)<\/textarea>/', $contents, $matches)) { 
606                  $description=$matches[1];
607                  $description=preg_replace("/&quot;/","'",$description);
608                  $description=preg_replace("/&lt;/","<",$description);
609                  $description=preg_replace("/&gt;/",">",$description);
610                  if(!strcmp($useRemoteSize,"false")) {
611                    $description=preg_replace("/width=\"\d+\"/","width=\"".$width."\"",$description);
612                    $description=preg_replace("/height=\"\d+\"/","height=\"".$height."\"",$description);
613                  }
614                } else {
615                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
616                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
617                }
618                
619            /*
620             **********************************
621             * Embed a DivShare Video
622             **********************************
623             */
624            } else if(preg_match("/$divshareUrlPattern/",$url)) {
625              
626                /* Make sure we can extract a itemID */
627                if(preg_match("/\/download\/(.+)/",$url,$matches)) {
628                    $item_id = $matches[1];
629                    $item_id=preg_replace("/\/$/","",$item_id);
630                } else {
631                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
632                                 "Unable to extract item id from url: $url"),null,null);
633                }
634
635                /* Grab the contents of the webpage used to display the video on video.google.com */
636                list ($successfullyCopied, $contents, $response, $headers) =
637                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
638                if (!$successfullyCopied) {
639                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
640                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
641                }
642
643                /* Extract the summary from the webpage contents */
644                //preg_match('/<meta name="description" content="(.+?)" \/>/i', $contents, $matches);
645                //$summary=$matches[1];
646                // Right now, the description is a plug for divshare, nothing user specific about it
647                $summary="";
648
649                /* Extract the title from the webpage contents */
650                preg_match('/<title>(.+?) - Divshare<\/title>/i', $contents, $matches);
651                $title=$matches[1];
652                
653                /* Build the thumbnail URL from the item_id */
654                $thumbnail=$divshareThumbnailUrl.$item_id;
655
656                /* Format the description to hold a reference to the embedded video */
657                if(preg_match('/(<embed src.+?<\/embed>)/', $contents, $matches)) { 
658                  $description=$matches[1];
659                  if(!strcmp($useRemoteSize,"false")) {
660                    $description=preg_replace("/width=\"\d+\"/","width=\"".$width."\"",$description);
661                    $description=preg_replace("/height=\"\d+\"/","height=\"".$height."\"",$description);
662                  }
663                } else {
664                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
665                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
666                }
667
668            /*
669             **********************************
670             * Embed a StickAm Video
671             **********************************
672             */
673            } else if(preg_match("/$stickamUrlPattern/",$url)) {
674
675                /* Make sure we can extract a itemID */
676                if(preg_match("/mId=(.+)/",$url,$matches)) {
677                    $item_id = $matches[1];
678                    $item_id=preg_replace("/\/$/","",$item_id);
679                } else {
680                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
681                                 "Unable to extract item id from url: $url"),null,null);
682                }
683
684                /* Grab the contents of the webpage used to display the video on video.google.com */
685                $url=preg_replace("/&amp;/","&",$url);
686                list ($successfullyCopied, $contents, $response, $headers) =
687                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
688                if (!$successfullyCopied) {
689                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
690                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
691                }
692
693                /* Extract the summary from the webpage contents */
694                preg_match('/<meta name="description" content="(.+?)"\/>/i', $contents, $matches);
695                $summary=$matches[1];
696
697                /* Extract the title from the webpage contents */
698                preg_match('/<meta name="title" content="(.+?)">/i', $contents, $matches);
699                $title=$matches[1];             
700                
701                /* Build the thumbnail URL from the item_id */
702                if(preg_match('/movieName=(.+?)&userId=/i', $contents, $matches)) { 
703                  $thumbnail_url=$matches[1];
704                  $thumbnail_url=preg_replace("/%2F/","/",$thumbnail_url);
705                  $thumbnail=$stickamThumbnailUrl.$thumbnail_url.".jpg";
706                } else {
707                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
708                         "Unable to extract thumbnail from url: $url"),NULL,NULL);
709                }
710
711                /* Format the description to hold a reference to the embedded video */
712                if(preg_match('/input type.+?'.$item_id.'.+?value="(.+?)"/', $contents, $matches)) { 
713                  $description=$matches[1];
714                  $description=preg_replace("/&quot;/","'",$description);
715                  $description=preg_replace("/&lt;/","<",$description);
716                  $description=preg_replace("/&gt;/",">",$description);
717                  if(!strcmp($useRemoteSize,"false")) {
718                    $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
719                    $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
720                  }
721                } else {
722                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
723                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
724                }
725              
726            /*
727             **********************************
728             * Embed a Myspace Video
729             **********************************
730             */
731            } else if(preg_match("/($myspaceUrlPattern|$myspaceUrlPattern2)/",$url)) {
732
733                /* Make sure we can extract a itemID */
734                if(preg_match("/videoid=(.+)/i",$url,$matches)) {
735                    $video_id = $matches[1];
736                    $video_id=preg_replace("/\/$/","",$video_id);
737                } else {
738                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
739                                 "Unable to extract video id from url: $url"),null,null);
740                }
741
742                /* Grab the contents of the webpage used to display the video on video.google.com */
743                list ($successfullyCopied, $contents, $response, $headers) =
744                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
745                if (!$successfullyCopied) {
746                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
747                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
748                }
749
750                /* Extract the summary from the webpage contents */
751                preg_match('/class="description" id="vid_description">(.+?)<\/div>/i', $contents, $matches);
752                $summary=$matches[1];
753
754                /* Extract the title from the webpage contents */
755                preg_match('/<h1>(.+?)<\/h1>/i', $contents, $matches);
756                $title=$matches[1];             
757                
758                /* Build the thumbnail URL from the item_id */
759                $video_info_url=$myspaceThumbnailUrl.$video_id;
760                list ($successfullyCopied, $video_info, $response, $headers) =
761                  GalleryCoreApi::fetchWebPage($video_info_url, $extraHeaders);
762                if (!$successfullyCopied) {
763                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
764                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
765                }
766                if(preg_match('/thumbnail url="(.+?)"/',$video_info, $matches)) {
767                  $thumbnail = $matches[1];
768                } else {
769                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
770                         "Unable to extract thumbnail information from url: $url"),NULL,NULL);
771                }
772
773                /* Format the description to hold a reference to the embedded video */
774                if(preg_match('/(&lt;embed src.+?\/embed&gt;)/', $contents, $matches)) { 
775                  $description=$matches[1];
776                  $description=preg_replace("/&quot;/","'",$description);
777                  $description=preg_replace("/&lt;/","<",$description);
778                  $description=preg_replace("/&gt;/",">",$description);
779                  if(!strcmp($useRemoteSize,"false")) {
780                    $description=preg_replace("/width='\d+'/","width='".$width."'",$description);
781                    $description=preg_replace("/height='\d+'/","height='".$height."'",$description);
782                  }
783                } else {
784                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
785                         "Unable to extract embedded video information from url: $url"),NULL,NULL);
786                }
787
788            /*
789             **********************************
790             * Embed a Vimeo Video
791             **********************************
792             */
793            } else if(preg_match("/$vimeoUrlPattern/",$url)) {
794
795                /* Make sure we can extract a docID */
796                if(preg_match("/$vimeoUrlPattern\/(.*)/",$url,$matches)) {
797                    $video_id = $matches[1];
798                } else {
799                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
800                                 "Unable to extract video id from url: $url"),null,null);
801                }
802
803                /* Grab the contents of the webpage used to display the video on video.google.com */
804                list ($successfullyCopied, $contents, $response, $headers) =
805                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
806                if (!$successfullyCopied) {
807                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
808                                 "Unable to get video information at url: $url - $response"),NULL,NULL);
809                }
810
811                /* Extract the summary from the webpage contents */
812                preg_match('/<meta name="description" content="(.+?)"/i',
813                           $contents, $matches);
814                $summary=$matches[1];
815
816                /* Extract the title from the webpage contents */
817                preg_match('/<meta name="title" content="(.+?)"/i',
818                           $contents, $matches);
819                $title=$matches[1];
820
821                /* Extract the thumbnail URL from the webpage contents */
822                preg_match('/"videothumbnail" href="(.+?)"/i',
823                           $contents, $matches);
824                $thumbnail=$matches[1];
825
826                /* Determine what our width and height should be based on our useRemoteSize parameter */
827                if(!strcmp($useRemoteSize,"true")) {
828                  preg_match('/id="vimeo_player_'.$video_id.'".+?style="width:(\d+)px;height:(\d+)px;"/i',
829                             $contents, $matches);
830                  $width = $matches[1];
831                  $height = $matches[2];
832                }
833
834                /* Determine if the video should autoplay or not based on the autoStart parameter */
835                $autoStartStr="";
836                if(!strcmp($autoStart,"true")) {
837                  $autoStartStr="&amp;autoplay=1";
838                }
839
840                /* Format the description to hold a reference to the embedded video */
841                $description = '<object type="application/x-shockwave-flash" width="'.$width.'" height="'.$height.'"';
842                $description.= 'data="http://www.vimeo.com/moogaloop.swf?clip_id='.$video_id;
843                $description.= '&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1'.$autoStartStr;
844                $description.= '&amp;show_byline=1&amp;show_portrait=0&amp;color=">';
845                $description.= '<param name="quality" value="best" />';
846                $description.= '<param name="allowfullscreen" value="true" />';
847                $description.= '<param name="scale" value="showAll" />';
848                $description.= '<param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id='.$video_id;
849                $description.= '&amp;server=www.vimeo.com&amp;fullscreen=1&amp;show_title=1'.$autoStartStr;
850                $description.= '&amp;show_byline=1&amp;show_portrait=0&amp;color=" />';
851                $description.= '</object>';
852                
853            /*
854             **********************************
855             * Embed a remote .swf file
856             **********************************
857             */
858            } else if(preg_match("/.*\/(.+?)\.swf/i",$url,$matches)) {
859
860                /* Set the title and summary to the name of the file */
861                $title = $matches[1];
862                $summary = $matches[1];
863                
864                /*
865                 * Set the thumbnail to some generic jpg image,
866                 * since we can't extract it from the remote swf file.
867                 * If no parameter is set, set it to a default value.
868                 */
869                if(preg_match("/\w+/", $flvThumbnail)) {
870                  $thumbnail = $flvThumbnail;
871                } else {
872                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
873                }
874
875                /*
876                 * Check to make sure the URL to the remote swf file is valid
877                 * (That the file exists at the URL given)
878                 */
879                list ($successfullyCopied, $response, $headers) =
880                  $this->fetchWebFileHeaders($url, $extraHeaders);
881                if (!$successfullyCopied) {
882                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
883                               "Unable to find the video at url: $url - $response"),NULL,NULL);
884                }
885                
886                /*
887                 * Format the description to hold a reference to the embedded video
888                 */
889
890                /* Format the description to hold a reference to the embedded video */
891                $description ='<embed src="'.$url.'">';
892                
893            /*
894             **********************************
895             * Embed a remote .flv file
896             **********************************
897             */
898            } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
899
900                /* Set the title and summary to the name of the file */
901                $title = $matches[1];
902                $summary = $matches[1];
903                
904                /*
905                 * Set the thumbnail to some generic jpg image,
906                 * since we can't extract it from the remote flv file.
907                 * If no parameter is set, set it to a default value.
908                 */
909                if(preg_match("/\w+/", $flvThumbnail)) {
910                  $thumbnail = $flvThumbnail;
911                } else {
912                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
913                }
914
915                /*
916                 * Check to make sure the URL to the remote flv file is valid
917                 * (That the file exists at the URL given)
918                 */
919                list ($successfullyCopied, $response, $headers) =
920                  $this->fetchWebFileHeaders($url, $extraHeaders);
921                if (!$successfullyCopied) {
922                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
923                               "Unable to find the video at url: $url - $response"),NULL,NULL);
924                }
925                
926                /*
927                 * Format the description to hold a reference to the embedded video
928                 * This reference will be embedded using the G2 internal player,
929                 * or an external player if provided by the user.
930                 */
931                if(!strcmp($useInternalFlvPlayer,"false")) {
932
933                    /*
934                     * The user has indicated they want to use an external flv player
935                     * Make sure one is defined!
936                     */
937                    if(!preg_match("/\w+/",$externalFlvPlayer)) {
938                        return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
939                                    "Invalid/missing external player parameter"),null,null);
940                    }
941
942                    /* Format the description to hold a reference to the embedded video */
943                    $description ='<embed src="'.$externalFlvPlayer.'" ';
944                    $description.= 'width="'.$width.'" height="'.$height.'" ';
945                    $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
946                    $description.= 'type="application/x-shockwave-flash" ';
947                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
948                    $description.= 'flashvars="file='.$url;
949                    $description.= '&fullscreenpage='.$thumbnail;
950                    $description.= '&linktarget=_Blank&image='.$thumbnail;
951
952                    if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
953                        /* Format the flashvars for the internal G2 flv player */
954                        $description.= '&showdigits=true&autostart='.$autoStart.'&showfsbutton=true&';
955                        $description.= '&repeat=false&lightcolor=0x9999FF';
956                        $description.= '&backcolor=0x888888&frontcolor=0x000000"';
957                    } else {
958                        /* Format the flashvars for the external G2 flv player */
959                        $description.= '&'.$externalFlvPlayerVars;
960                    }
961                    $description.=  ' />&nbsp;</p>';
962                
963                /* Internal FLV player */
964                } else {
965                    /* Format the description to hold a reference to the embedded video */
966                    $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
967                    $description = '<script type="text/javascript">'."\n";
968                    $description.= '// <![CDATA['."\n";
969                    $description.= 'function divResize(id, nw, nh) {'."\n";
970                    $description.= 'var obj = document.getElementById(id);'."\n";
971                    $description.= 'obj.style.width = nw + "px";'."\n";
972                    $description.= 'obj.style.height = nh + "px";'."\n";
973                    $description.= '}'."\n";
974                    $description.= '// ]]>'."\n";
975                    $description.= '</script>'."\n";
976                    $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
977                    $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
978                    $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
979                    $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
980                    $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
981                    $description.= '<param name="FlashVars" value="flvUrl='.$url;
982                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
983                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
984                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
985                    $description.= '<param name="quality" value="high"/>';
986                    $description.= '<param name="scale" value="noscale"/>';
987                    $description.= '<param name="salign" value="lt"/>';
988                    $description.= '<param name="wmode" value="transparent"/>';
989                    $description.= '<param name="allowScriptAccess" value="always"/>';
990                    $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
991                    $description.= 'flashvars="flvUrl='.$url;
992                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
993                    $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&autoStart='.$autoStart;
994                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
995                    $description.= 'type="application/x-shockwave-flash" ';
996                    $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
997                    $description.= 'wmode="transparent" allowScriptAccess="always" ';
998                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
999                    $description.= '</object></div>';
1000                }
1001                
1002           /*
1003            **********************************
1004            * Unsupported URL to embed
1005            **********************************
1006            */   
1007            } else {
1008                return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
1009                             "Unable to embed video from: $url"),null,null);
1010            }
1011            
1012
1013            /*
1014            **********************************
1015            * Add the video to Gallery
1016            **********************************
1017            */
1018            
1019            /* Get a local tmp file to save the thumbnail URL to */
1020            $tmpDir = $gallery->getConfig('data.gallery.tmp');
1021            $tmpFile = $platform->tempnam($tmpDir, 'add');
1022            $tmpFile.= ".jpg";
1023                    
1024            /* Fetch the thumbnail and save it to a local file */
1025            list ($successfullyCopied, $response, $headers) =
1026              GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
1027            if (!$successfullyCopied) {
1028                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1029                             "Unable to copy thumbnail from url: $thumbnail - $response"),null,null);
1030            }
1031            
1032            /* Obtain the mimeType of the thumbnail */
1033            list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
1034            
1035            /* Set the filename for the item we want to add */
1036            $fileName = $title;
1037            $fileName = preg_replace("/\s+/","_",$fileName);
1038            $fileName = preg_replace("/'/","",$fileName);
1039            $fileName = preg_replace("/\"/","",$fileName);
1040            $fileName = preg_replace("/&#\d+;/","",$fileName);
1041
1042            /* Wordwrap the description or summary as appropriate */
1043            $description_summary = $summary;
1044
1045            if(strcmp($wordwrapSummary,"0")) {
1046              $summary = wordwrap($summary,$wordwrapSummary,"<br>",FALSE);
1047            }
1048
1049            if(strcmp($wordwrapDescription,"0")) {
1050              $description_summary = wordwrap($description_summary,$wordwrapDescription,"<br>",FALSE);
1051            }
1052            
1053            /* Tack on the summary to the end of the description */
1054            $description.= "<br>$description_summary";
1055            
1056            /* General debug output */
1057            if(!strcmp($debugOutput,"true")) {
1058                print "\n<h2>Item Parameters</h2>\n";
1059                print "url: $url <br>\n";
1060                print "title: $title <br>\n";
1061                print "thumbnailUrl: $thumbnail <br><img src=\"".$thumbnail."\"> <br>\n";
1062                print "summary: <p>$summary</p>\n";
1063                print "description: <p>$description</p>\n";
1064                print "thumbnail: $tmpFile <br>\n";
1065                print "mimeType: $mimeType <br>\n";
1066                print "fileName: $fileName <br>\n";
1067                print "width: $width <br>\n";
1068                print "height: $height <br>\n";
1069                print "<hr>";
1070            }
1071
1072            /* Resize the thumbnail image to the size indicated by our album */
1073            $debugString="";
1074            list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'resize');
1075            if (!$ret) {
1076                $debugString.="Checking to see if a toolkit that can resize images was found. <br>";
1077                if (isset($toolkit)) {
1078                    $newTmpFile = $platform->tempnam($tmpDir, 'add');
1079                    $newTmpFile.= ".jpg";
1080                    $thumbnailSize = 150;
1081                    list ($ret, $preferences) =
1082                      GalleryCoreApi::fetchDerivativePreferencesForItem($item->getId());
1083                    if(!$ret) {
1084                        foreach ($preferences as $preference) {
1085                          if (preg_match('/thumbnail\|(\d+)/',
1086                                         $preference['derivativeOperations'], $matches)) {
1087                              $thumbnailSize = $matches[1];
1088                              $debugString.="Found thumbnail size in album preferences: $thumbnailSize <br>";
1089                              break;
1090                          }
1091                        }
1092                    }
1093                    
1094                    // Obtain the width and height of the original thumbnail, finding out it's ratio,
1095                    // and using that ratio when determining the width of the video below.
1096                    // Example: youtube: 130x97 google: 160x120 metacafe: 90x76 yahoo: 100x70
1097                    // Set the thumbnailHeight to the current thumbnailSize
1098                    // Set the thumbnailWidth to the appropriate size based on the thumbnailHeight * ratio
1099                    $image_data = @getimagesize($tmpFile);
1100                    if(!$image_data) {
1101                      return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1102                             "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
1103                    }
1104                    $ratio = $image_data[0] / $image_data[1];
1105                    $debugString.="Using ratio from original thumbnail of $ratio. ";
1106                    $thumbnailHeight=$thumbnailSize;
1107                    $thumbnailWidth=round($thumbnailHeight * $ratio);
1108                    $debugString.="Resizing thumbnail image to $thumbnailWidth x $thumbnailHeight: $tmpFile -> $newTmpFile <br>";
1109                    $toolkit->performOperation($mimeType, 'resize', $tmpFile, $newTmpFile,
1110                                               array($thumbnailWidth,$thumbnailHeight));
1111                }
1112            }
1113            if(!strcmp($debugOutput,"true")) {
1114                print "\n<h2>Thumbnail Resize</h2>\n";
1115                print "$debugString\n";
1116                print "<hr>\n";
1117            }
1118
1119            /* Watermark the video thumbnail image if indicated by our parameter */
1120            if(!strcmp($watermarkVideos,"true")) {
1121              
1122              /*
1123               * If no watermarkImage parameter is set, set it to a default value.
1124               */
1125              if(preg_match("/\w+/", $watermarkImage)) {
1126                $watermarkImage = $watermarkImage;
1127              } else {
1128                $watermarkImage = $gallery2_url.$gallery2_video_watermark;
1129              }
1130              
1131              /* Get the watermark Image Extension */
1132              preg_match('/\.(...)$/', $watermarkImage, $matches);
1133              $watermarkExt=$matches[1];
1134              
1135              /*
1136               * Check to make sure the URL to the watermark image file is valid
1137               * (That the file exists at the URL given). Skip this part if it is a local path.
1138               */
1139              if(!preg_match("/^\//", $watermarkImage)) {
1140                list ($successfullyCopied, $response, $headers) =
1141                  $this->fetchWebFileHeaders($watermarkImage, $extraHeaders);
1142                if (!$successfullyCopied) {
1143                  return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
1144                         "Unable to find the watermark image at url: $watermarkImage - $response"),NULL,NULL);
1145                }
1146              
1147                /* Download the watermark image to a local file */
1148                $tmpDir = $gallery->getConfig('data.gallery.tmp');
1149                $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
1150                $watermark.= "." . $watermarkExt;
1151                list ($successfullyCopied, $response, $headers) =
1152                  GalleryCoreApi::fetchWebFile($watermarkImage, $watermark, $extraHeaders);
1153                if (!$successfullyCopied) {
1154                  return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1155                         "Unable to copy watermark image from url: $watermarkImage - $response"),null,null);
1156                }
1157              } else {
1158                $tmpDir = $gallery->getConfig('data.gallery.tmp');
1159                $watermark = $platform->tempnam($tmpDir, 'wmk_img_');
1160                $watermark.= "." . $watermarkExt;
1161                if(!$platform->copy($watermarkImage, $watermark)) {
1162                  return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1163                         "Unable to copy watermark image from path: $watermarkImage"),null,null);
1164                }
1165              }
1166              
1167              /* See if there is a toolkit installed that can perform a composite operation */
1168              list ($ret, $toolkit) = GalleryCoreApi::getToolkitByOperation($mimeType, 'composite');
1169              if ($ret) {
1170                return array($ret->wrap(__FILE__, __LINE__,
1171                       "Unable to locate a toolkit module to perform the 'composite' watermark operation"), null);
1172              }
1173
1174              /* Make sure we can access the toolkit found */
1175              if (!isset($toolkit)) {
1176                return array(GalleryStatus::error(ERROR_PERMISSION_DENIED, __FILE__, __LINE__,
1177                       "Unable to access the toolkit module to perform the 'composite' watermark operation"), null);
1178              }
1179              
1180              /* Get the image dimensions of the thumbnail */
1181              $image_data = @getimagesize($newTmpFile);
1182              if(!$image_data) {
1183                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1184                       "Unable to retrieve thumbnail dimensions for: $tmpFile"),null,null);
1185              }
1186              $thumbnailWidth = $image_data[0];
1187              $thumbnailHeight = $image_data[1];
1188
1189              /* Get the image dimensions of the watermark */
1190              $image_data = @getimagesize($watermark);
1191              if(!$image_data) {
1192                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
1193                       "Unable to retrieve watermark dimensions for: $tmpFile"),null,null);
1194              }
1195              $watermarkWidth = $image_data[0];
1196              $watermarkHeight = $image_data[1];
1197
1198              /* Obtain the mimeType of the watermark */
1199              list ($ret, $watermarkMimeType) = GalleryCoreApi::getMimeType($watermark);
1200
1201              /* Remove the gallery base path from the watermark image path */
1202              /* This has to be done to satisfy the argument requirement for the toolkit operation */
1203              $dataDir = $gallery->getConfig('data.gallery.base');
1204              $dataDir=preg_replace("/\//","\\/",$dataDir);
1205              if(preg_match("/$dataDir(.*)/", $watermark, $matches)) { 
1206                $watermark = $matches[1];
1207              }
1208              
1209              /* General debug output */
1210              if(!strcmp($debugOutput,"true")) {
1211                print "\n<h2>Watermark Operation</h2>\n";
1212                print "watermarkImage: $watermarkImage <br>\n";
1213                print "watermarkTmpImage: $watermark <br>\n";
1214                print "watermarkMimeType: $watermarkMimeType <br>\n";
1215                print "watermarkWidth: $watermarkWidth <br>\n";
1216                print "watermarkHeight: $watermarkHeight <br>\n";
1217                print "watermarkedWidth: $thumbnailWidth <br>\n";
1218                print "watermarkedHeight: $thumbnailHeight <br>\n";
1219              }
1220
1221              /* Apply the watermark image to the thumbnail */
1222              $tmpFile = $platform->tempnam($tmpDir, 'wmk_');
1223              list ($ret, $mimeType) = $toolkit->performOperation(
1224                                                                  $mimeType, 'composite', $newTmpFile, $tmpFile,
1225                                                                  array($watermark, $watermarkMimeType,
1226                                                                        $watermarkWidth, $watermarkHeight,
1227                                                                        $watermarkAlignment, 0, 0));
1228              
1229              /* Check the return code of the composite operation */
1230              if ($ret) {
1231                return array($ret->wrap(__FILE__, __LINE__,
1232                                        "Unable to apply watermark to the video thumbnail image"), null);
1233              }
1234
1235              if(!strcmp($debugOutput,"true")) {
1236                print "\nwatermarked Image: $tmpFile <br>";
1237                print "<hr>";
1238              }
1239                        
1240              /* Update the path of our thumbnail to point to the new watermarked thumbnail instead */
1241              $newTmpFile = $tmpFile;
1242              
1243            }
1244            
1245            /* Make the gallery2 call to add this item to the album */
1246            list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($newTmpFile,
1247                                                                   $fileName,
1248                                                                   $title,
1249                                                                   $summary,
1250                                                                   $description,
1251                                                                   $mimeType,
1252                                                                   $item->getId());
1253            
1254            if ($ret) {
1255                return array($ret, null, null);
1256            }
1257            
1258            $status['addedFiles'][] = array('fileName' => $url,
1259                                            'id' => $newItem->getId(),
1260                                            'warnings' => array());
1261
1262            if(!strcmp($debugOutput,"true")) {
1263                print "\n<br><br><h2>Video Successfully Added to your Gallery Album</h2><br><br><hr>";
1264            }
1265        }
1266        
1267        /* Keep the tmpfiles around if we are in debug mode. Otherwise, remove them. */
1268        if(!strcmp($debugOutput,"false")) {
1269          @$platform->unlink($tmpFile);
1270          @$platform->unlink($newTmpFile);
1271        }
1272        
1273    }
1274    
1275    return array(null, $error, $status);
1276  }
1277
1278  /**
1279   * A simple function to resolve the value of a parameter from
1280   * the default or override value if it exists, or set it
1281   * to the default passed as an argument.
1282   */
1283  function getParameter($params, $name, $default="") {
1284    if(isset($params['override'][$name])) {
1285      /* print "override $name = ".$params['override'][$name]."<br>"; */
1286      return($params['override'][$name]);
1287    } else if(isset($params['default'][$name])) {
1288      /* print "default $name = ".$params['default'][$name] ."<br>"; */
1289      return($params['default'][$name]);
1290    } else {
1291      /* print "$name = $default <br>"; */
1292      return($default);
1293    }
1294  }
1295
1296  /**
1297   * A simple function to get the headers only (no body) for a given URL
1298   * This was taken from GalleryCoreApi::requestWebPage
1299   */
1300  function fetchWebFileHeaders($url, $requestHeaders=array()) {
1301      global $gallery;
1302      
1303      $requestMethod='GET';
1304      $requestBody='';
1305      
1306      /* Convert illegal characters */
1307      $url = str_replace(' ', '%20', $url);
1308      
1309      /* Unescape ampersands, since if the URL comes from form input it will be escaped */
1310      $url = str_replace('&amp;', '&', $url);
1311
1312      $platform =& $gallery->getPlatform();
1313      
1314      $urlComponents = parse_url($url);
1315      if (empty($urlComponents['port'])) {
1316          $urlComponents['port'] = 80;
1317      }
1318      if (empty($urlComponents['path'])) {
1319          $urlComponents['path'] = '/';
1320      }
1321
1322      $handle = @$platform->fsockopen(
1323                                      $urlComponents['host'], $urlComponents['port'], $errno, $errstr, 5);
1324      if (empty($handle)) {
1325          $gallery->debug("Error $errno: '$errstr' requesting $url");
1326          return array(null, null, null);
1327      }
1328      
1329      $requestUri = $urlComponents['path'];
1330      if (!empty($urlComponents['query'])) {
1331          $requestUri .= '?' . $urlComponents['query'];
1332      }
1333      $headerLines = array('Host: ' . $urlComponents['host']);
1334      foreach ($requestHeaders as $key => $value) {
1335          $headerLines[] = $key . ': ' . $value;
1336      }
1337      
1338      $success = $platform->fwrite($handle, sprintf("%s %s HTTP/1.0\r\n%s\r\n\r\n%s",
1339                                                    $requestMethod,
1340                                                    $requestUri,
1341                                                    implode("\r\n", $headerLines),
1342                                                    $requestBody));
1343      if (!$success) {
1344          /* Zero bytes written or false was returned */
1345          $gallery->debug(
1346                          "fwrite failed in requestWebPage($url)" . ($success === false ? ' - false' : ''));
1347          return array(null, null, null);
1348      }
1349      $platform->fflush($handle);
1350      
1351      
1352      /*
1353       * Read the status line.  fgets stops after newlines.  The first line is the protocol
1354       * version followed by a numeric status code and its associated textual phrase.
1355       */
1356      $responseStatus = trim($platform->fgets($handle, 4096));
1357      if (empty($responseStatus)) {
1358          $gallery->debug('Empty http response code, maybe timeout');
1359          return array(null, null, null);
1360      }
1361      
1362      /* Read the headers */
1363      $responseHeaders = array();
1364      while (!$platform->feof($handle)) {
1365          $line = trim($platform->fgets($handle, 4096));
1366          if (empty($line)) {
1367              break;
1368          }
1369        
1370          /* Normalize the line endings */
1371          $line = str_replace("\r", '', $line);
1372          
1373          list ($key, $value) = explode(':', $line, 2);
1374          if (isset($responseHeaders[$key])) {
1375              if (!is_array($responseHeaders[$key])) {
1376                $responseHeaders[$key] = array($responseHeaders[$key]);
1377              }
1378              $responseHeaders[$key][] = trim($value);
1379          } else {
1380              $responseHeaders[$key] = trim($value);
1381          }
1382      }
1383      $platform->fclose($handle);
1384
1385      if(preg_match("/Not found/i", $responseStatus)) {
1386          $success = 0;
1387      }
1388
1389      //print "success: $success <br>responseStatus: $responseStatus <br>responseHeaders: $responseHeaders <br>";
1390      
1391      return array($success, $responseStatus, $responseHeaders);
1392  }
1393  
1394  /**
1395   * @see ItemAdd:loadTemplate
1396   */
1397  function loadTemplate(&$template, &$form, $item) {
1398     global $gallery;
1399     
1400     if ($form['formName'] != 'ItemAddEmbedVideo') {
1401         /* First time around, load the form with item data */
1402         $form['webPage'] = '';
1403         $form['formName'] = 'ItemAddEmbedVideo';
1404     }
1405     
1406     $session =& $gallery->getSession();
1407     
1408     $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
1409     
1410     return array(null,
1411                  'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
1412                  'modules_embedvideo');
1413  }
1414  
1415  /**
1416   * @see ItemAddPlugin::getTitle
1417   */
1418  function getTitle() {
1419     list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
1420     if ($ret) {
1421         return array($ret, null);
1422     }
1423     
1424     return array(null, $module->translate('Embed Video'));
1425  }
1426  
1427 }       
1428 ?>