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