Added code to remove hardcoded gallery2 server URL.
[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 /**
22  * This plugin will handle the addition of embedded video objects
23  * @package embedVideo
24  * @subpackage UserInterface
25  * @author Alan Pippin <apippin@pippins.net>
26  * @version $Revision: 1.1 $
27  */
28 class ItemAddEmbedVideo extends ItemAddPlugin {
29   
30   /**
31    * @see ItemAddPlugin::handleRequest
32    */
33  function handleRequest($form, &$item) {
34    global $gallery;
35     
36    $status = $error = array();
37    
38    if (isset($form['action']['addEmbedVideoPage'])) {
39      
40        $platform =& $gallery->getPlatform();
41       
42        if(isset($form['webPage']['URL'])) {
43          
44            /* Load any stored/set Parameters */
45            list ($ret, $params) =
46              GalleryCoreApi::fetchAllPluginParameters('module', 'embedvideo');
47            if ($ret) {
48                return array($ret, null, null);
49            }
50            foreach (array('default', 'override') as $type) {
51                $ItemAddUploadApplet[$type] = array();
52                if (!empty($params['embedvideo' . $type . 'Variables'])) {
53                    $variablesArray = explode('|', $params['embedvideo' . $type . 'Variables']);
54                    foreach ($variablesArray as $variable) {
55                        list ($name, $value) = explode('=', $variable);
56                        $ItemAddEmbedVideo[$type][$name] = $value;
57                    }
58                }
59            }
60            
61            /* Store any Parameters into some simpler, shorter, local variables */
62            $debugOutput = $ItemAddEmbedVideo['default']['debugOutput'];
63            $useInternalFlvPlayer = $ItemAddEmbedVideo['default']['useInternalFlvPlayer'];
64            $youtubeDevId = $ItemAddEmbedVideo['default']['youtubeDevId'];
65            $width=$ItemAddEmbedVideo['default']['width'];
66            $height=$ItemAddEmbedVideo['default']['height'];
67            $externalFlvPlayer = $ItemAddEmbedVideo['default']['externalFlvPlayer'];
68            $externalFlvPlayerVars = $ItemAddEmbedVideo['default']['externalFlvPlayerVars'];
69            $flvThumbnail = $ItemAddEmbedVideo['default']['flvThumbnail'];
70
71            /* Store other string constants we'll use later */
72            $youtubeUrlPattern="www.youtube.com";
73            $youtubeApiUrl="http://www.youtube.com/api2_rest";
74            $googleUrlPattern="video.google.com";
75            $googlePlayer="http://video.google.com/googleplayer.swf";
76            
77            /* Gallery2 specific paths and variables */
78            $urlGenerator =& $gallery->getUrlGenerator();
79            $gallery2_url = $urlGenerator->getCurrentUrlDir();
80            $gallery2_flv_thumbnail = "modules/thumbnail/images/G2video.jpg";
81            $gallery2_flv_player = "modules/flashvideo/lib/G2flv.swf";
82            
83            /* Store the passed URL in a shorter local variable */
84            $url = $form['webPage']['URL'];
85
86            /*
87             *****************************
88             * Embed a Youtube Video
89             *****************************
90             */
91            if(preg_match("/$youtubeUrlPattern/",$url)) {
92
93                /* Make sure we can find a video_id in the URL */
94                if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
95                    $video_id = $matches[1];
96                } else {
97                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
98                                 "Unable to extract video id from url: $url"),null,null);
99                }
100                
101                /* Make sure we have a valid youtube developer id */
102                $dev_id = $youtubeDevId;
103                if(!preg_match("/\w+/",$dev_id)) {
104                    return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
105                                 "Invalid/missing YouTube developer ID: $dev_id"),null,null);
106                }
107                
108                /* Youtube api feed */
109                $feed = $youtubeApiUrl.'?method=youtube.videos.get_details';
110                $feed.= "&dev_id=$dev_id&video_id=$video_id";
111                
112                /* Get the youtube xml feed as a string data source */
113                $xml = _getFeed($feed);  
114
115                if($debugOutput) {
116                  print "$xml";
117                }
118                
119                /* Extract certain information from the xml feed */
120                preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
121                preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
122                preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
123                
124                array_shift($title);
125                array_shift($thumbnail);
126                array_shift($description);
127           
128                /* Replace html characters. More can be added but this seems to work */
129                for($i=0;$i<count($description[0]);$i++){          
130                    $description[0][$i] = preg_replace("/&#60;/","<",$description[0][$i]);
131                    $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);      
132                }
133
134                /* Store the information found in some local variables */
135                $title = $title[0][0];
136                $summary = $description[0][0];
137                $thumbnail = $thumbnail[0][0];
138
139                /* Format the description to hold a reference to the embedded video */
140                $description = '<object width="'.$width.'" height="'.$height.'">';
141                $description.= '<param name="movie" ';
142                $description.= 'value="http://www.youtube.com/v/'.$video_id.'"></param>';
143                $description.= '<param name="wmode" value="transparent"></param>';
144                $description.= '<embed src="http://www.youtube.com/v/'.$video_id.'" ';
145                $description.= 'type="application/x-shockwave-flash" wmode="transparent" ';
146                $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
147                $description.= "<br>$summary";
148
149            /*
150             **********************************
151             * Embed a Google Video
152             **********************************
153             */
154            } else if(preg_match("/$googleUrlPattern/",$url)) {
155
156                /* Make sure we can extract a docID */
157                if(preg_match("/docid=(.*)/",$url,$matches)) {
158                    $doc_id = $matches[1];
159                } else {
160                    return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
161                                 "Unable to extract doc id from url: $url"),null,null);
162                }
163
164                /* Grab the contents of the webpage used to display the video on video.google.com */
165                $contents=file_get_contents($url);
166
167                /* Extract the summary from the webpage contents */
168                preg_match('/<meta content="(.+?)\. \w+ \d+, \d+.*" name="description">/i',
169                           $contents, $matches);
170                $summary=$matches[1];
171
172                /* Extract the title from the webpage contents */
173                preg_match('/<title>(.+?)\s+- Google Video<\/title>/i',
174                           $contents, $matches);
175                $title=$matches[1];
176
177                /* Extract the thumbnail URL from the webpage contents */
178                preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
179                           $contents, $matches);
180                $thumbnail=$matches[1];
181                $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
182
183                /* Format the description to hold a reference to the embedded video */
184                $description = '<embed FlashVars="autoPlay=true" ';
185                $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
186                $description.= 'type="application/x-shockwave-flash" ';
187                $description.= 'src="'.$googlePlayer.'"?docId='.$doc_id.'"> ';
188                $description.= '</embed>';
189                $description.= "<br>$summary";
190          
191            /*
192             **********************************
193             * Embed a remote .flv file
194             **********************************
195             */
196            } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
197
198                /* Set the title and summary to the name of the file */
199                $title = $matches[1];
200                $summary = $matches[1];
201                
202                /*
203                 * Set the thumbnail to some generic jpg image,
204                 * since we can't extract it from the remote flv file.
205                 * If no parameter is set, set it to a default value.
206                 */
207                if(preg_match("/\w+/", $flvThumbnail)) {
208                  $thumbnail = $flvThumbnail;
209                } else {
210                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
211                }
212
213                /*
214                 * Check to make sure the URL to the remote flv file is valid
215                 * (That the file exists at the URL given)
216                 */
217                if (empty($extraHeaders)) {
218                    $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
219                }
220                list ($successfullyCopied, $response, $headers) =
221                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
222                if (!$successfullyCopied) {
223                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
224                                 "Unable to locate a video at url: $url"),null,null);
225                }                                            
226                
227                /*
228                 * Format the description to hold a reference to the embedded video
229                 * This reference will be embedded using the G2 internal player,
230                 * or an external player if provided by the user.
231                 */
232                if(!$useInternalFlvPlayer) {
233
234                    /*
235                     * The user has indicated they want to use an external flv player
236                     * Make sure one is defined!
237                     */
238                    if(!preg_match("/\w+/",$externalFlvPlayer)) {
239                        return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
240                                    "Invalid/missing external player parameter"),null,null);
241                    }
242
243                    /* Format the description to hold a reference to the embedded video */
244                    $description ='<embed src="'.$externalFlvPlayer.'" ';
245                    $description.= 'width="'.$width.'" height="'.$height.'" ';
246                    $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
247                    $description.= 'type="application/x-shockwave-flash" ';
248                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
249                    $description.= 'flashvars="file='.$url;
250                    $description.= '&fullscreenpage='.$thumbnail;
251                    $description.= '&linktarget=_Blank&image='.$thumbnail;
252
253                    if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
254                        /* Format the flashvars for the internal G2 flv player */
255                        $description.= '&showdigits=true&autostart=false&showfsbutton=true&';
256                        $description.= '&repeat=false&lightcolor=0x9999FF';
257                        $description.= '&backcolor=0x888888&frontcolor=0x000000"';
258                    } else {
259                        /* Format the flashvars for the external G2 flv player */
260                        $description.= '&'.$externalFlvPlayerVars;
261                    }
262                    $description.=  ' />&nbsp;</p>';
263                
264                /* Internal FLV player */
265                } else {
266                    /* Format the description to hold a reference to the embedded video */
267                    $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
268                    $description = '<script type="text/javascript">'."\n";
269                    $description.= '// <![CDATA['."\n";
270                    $description.= 'function divResize(id, nw, nh) {'."\n";
271                    $description.= 'var obj = document.getElementById(id);'."\n";
272                    $description.= 'obj.style.width = nw + "px";'."\n";
273                    $description.= 'obj.style.height = nh + "px";'."\n";
274                    $description.= '}'."\n";
275                    $description.= '// ]]>'."\n";
276                    $description.= '</script>'."\n";
277                    $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
278                    $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
279                    $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
280                    $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
281                    $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
282                    $description.= '<param name="FlashVars" value="flvUrl='.$url;
283                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
284                    $description.= '&allowDl=true&thumbUrl='.$thumbnail;
285                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
286                    $description.= '<param name="quality" value="high"/>';
287                    $description.= '<param name="scale" value="noscale"/>';
288                    $description.= '<param name="salign" value="lt"/>';
289                    $description.= '<param name="wmode" value="transparent"/>';
290                    $description.= '<param name="allowScriptAccess" value="always"/>';
291                    $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
292                    $description.= 'flashvars="flvUrl='.$url;
293                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
294                    $description.= '&allowDl=true&thumbUrl='.$thumbnail;
295                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
296                    $description.= 'type="application/x-shockwave-flash" ';
297                    $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
298                    $description.= 'wmode="transparent" allowScriptAccess="always" ';
299                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
300                    $description.= '</object></div>';
301                }
302                
303           /*
304            **********************************
305            * Unsupported URL to embed
306            **********************************
307            */   
308            } else {
309                return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
310                             "Unable to embed video from: $url"),null,null);
311            }
312            
313
314            /*
315            **********************************
316            * Add the video to Gallery
317            **********************************
318            */
319            
320            /* Get a local tmp file to save the thumbnail URL to */
321            $tmpDir = $gallery->getConfig('data.gallery.tmp');
322            $tmpFile = $platform->tempnam($tmpDir, 'add');
323            $tmpFile.= ".jpg";
324            
325            if($debugOutput) {
326                print "thumbnail: $thumbnail <br>";
327            }
328            
329            /* Fetch the thumbnail and save it to a local file */
330            if (empty($extraHeaders)) {
331                $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
332            }
333            list ($successfullyCopied, $response, $headers) =
334              GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
335            if (!$successfullyCopied) {
336                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
337                             "Unable to copy thumbnail from url: $url"),null,null);
338            }
339            
340            /* Obtain the mimeType of the thumbnail */
341            list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
342            
343            /* Set the filename for the item we want to add */
344            $fileName = $title;
345            $fileName = preg_replace("/\s+/","_",$fileName);
346            $fileName = preg_replace("/'/","",$fileName);
347            $fileName = preg_replace("/\"/","",$fileName);
348            $fileName = preg_replace("/&#\d+;/","",$fileName);
349            
350            /* General debug output */
351            if($debugOutput) {
352                print "<p><a href=\"".$title."\" target=\"_blank\">";
353                print "<img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
354                print "<p>$description</p>";
355                print "thumbnail: $tmpFile <br>";
356                print "mimeType: $mimeType <br>";
357                print "fileName: $fileName <br>";
358            }
359
360            /* Make the gallery2 call to add this item to the album */
361            list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($tmpFile,
362                                                                   $fileName,
363                                                                   $title,
364                                                                   $summary,
365                                                                   $description,
366                                                                   $mimeType,
367                                                                   $item->getId());
368            
369            if ($ret) {
370                return array($ret, null, null);
371            }
372            
373            $status['addedFiles'][] = array('fileName' => $url,
374                                            'id' => $newItem->getId(),
375                                            'warnings' => array());
376        }
377        @$platform->unlink($tmpFile);
378    }
379    
380    return array(null, $error, $status);
381  }
382
383  /**
384   * @see ItemAdd:loadTemplate
385   */
386  function loadTemplate(&$template, &$form, $item) {
387     global $gallery;
388     
389     if ($form['formName'] != 'ItemAddEmbedVideo') {
390         /* First time around, load the form with item data */
391         $form['webPage'] = '';
392         $form['formName'] = 'ItemAddEmbedVideo';
393     }
394     
395     $session =& $gallery->getSession();
396     
397     $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
398     
399     return array(null,
400                  'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
401                  'modules_embedvideo');
402  }
403  
404  /**
405   * @see ItemAddPlugin::getTitle
406   */
407  function getTitle() {
408     list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
409     if ($ret) {
410         return array($ret, null);
411     }
412     
413     return array(null, $module->translate('Embed Video'));
414  }
415
416
417  /**
418   * ItemAddEmbedVideo::_getFeed
419   */
420  function _getFeed($feed) {
421   
422      /* Open and return Feed with cURL for parsing */
423     $ch = curl_init();
424     $timeout = 0;
425     curl_setopt ($ch, CURLOPT_URL, $feed);
426     curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
427     curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
428     $xml = curl_exec($ch);
429     curl_close($ch);
430     
431     return $xml;    
432  }
433  
434 }       
435 ?>