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