Fixed a few bugs I introduced this morning when converting hard coded text to variables.
[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 = $this->_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                $contents = $this->_getFeed($url);
167
168                /* Extract the summary from the webpage contents */
169                preg_match('/<meta content="(.+?)\. \w+ \d+, \d+.*" name="description">/i',
170                           $contents, $matches);
171                $summary=$matches[1];
172
173                /* Extract the title from the webpage contents */
174                preg_match('/<title>(.+?)\s+- Google Video<\/title>/i',
175                           $contents, $matches);
176                $title=$matches[1];
177
178                /* Extract the thumbnail URL from the webpage contents */
179                preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i',
180                           $contents, $matches);
181                $thumbnail=$matches[1];
182                $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
183
184                /* Format the description to hold a reference to the embedded video */
185                $description = '<embed FlashVars="autoPlay=true" ';
186                $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
187                $description.= 'type="application/x-shockwave-flash" ';
188                $description.= 'src="'.$googlePlayer.'?docId='.$doc_id.'"> ';
189                $description.= '</embed>';
190                $description.= "<br>$summary";
191          
192            /*
193             **********************************
194             * Embed a remote .flv file
195             **********************************
196             */
197            } else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
198
199                /* Set the title and summary to the name of the file */
200                $title = $matches[1];
201                $summary = $matches[1];
202                
203                /*
204                 * Set the thumbnail to some generic jpg image,
205                 * since we can't extract it from the remote flv file.
206                 * If no parameter is set, set it to a default value.
207                 */
208                if(preg_match("/\w+/", $flvThumbnail)) {
209                  $thumbnail = $flvThumbnail;
210                } else {
211                  $thumbnail = $gallery2_url.$gallery2_flv_thumbnail;
212                }
213
214                /*
215                 * Check to make sure the URL to the remote flv file is valid
216                 * (That the file exists at the URL given)
217                 */
218                if (empty($extraHeaders)) {
219                    $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
220                }
221                list ($successfullyCopied, $response, $headers) =
222                  GalleryCoreApi::fetchWebPage($url, $extraHeaders);
223                if (!$successfullyCopied) {
224                    return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
225                                 "Unable to locate a video at url: $url"),null,null);
226                }                                            
227                
228                /*
229                 * Format the description to hold a reference to the embedded video
230                 * This reference will be embedded using the G2 internal player,
231                 * or an external player if provided by the user.
232                 */
233                if(!$useInternalFlvPlayer) {
234
235                    /*
236                     * The user has indicated they want to use an external flv player
237                     * Make sure one is defined!
238                     */
239                    if(!preg_match("/\w+/",$externalFlvPlayer)) {
240                        return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
241                                    "Invalid/missing external player parameter"),null,null);
242                    }
243
244                    /* Format the description to hold a reference to the embedded video */
245                    $description ='<embed src="'.$externalFlvPlayer.'" ';
246                    $description.= 'width="'.$width.'" height="'.$height.'" ';
247                    $description.= 'bgcolor="#C0C0C0" allowfullscreen="true" ';
248                    $description.= 'type="application/x-shockwave-flash" ';
249                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer" ';
250                    $description.= 'flashvars="file='.$url;
251                    $description.= '&fullscreenpage='.$thumbnail;
252                    $description.= '&linktarget=_Blank&image='.$thumbnail;
253
254                    if(!preg_match("/\w+/",$externalFlvPlayerVars)) {
255                        /* Format the flashvars for the internal G2 flv player */
256                        $description.= '&showdigits=true&autostart=false&showfsbutton=true&';
257                        $description.= '&repeat=false&lightcolor=0x9999FF';
258                        $description.= '&backcolor=0x888888&frontcolor=0x000000"';
259                    } else {
260                        /* Format the flashvars for the external G2 flv player */
261                        $description.= '&'.$externalFlvPlayerVars;
262                    }
263                    $description.=  ' />&nbsp;</p>';
264                
265                /* Internal FLV player */
266                } else {
267                    /* Format the description to hold a reference to the embedded video */
268                    $macromedia_url = "http://download.macromedia.com/pub/shockwave/cabs/flash/";
269                    $description = '<script type="text/javascript">'."\n";
270                    $description.= '// <![CDATA['."\n";
271                    $description.= 'function divResize(id, nw, nh) {'."\n";
272                    $description.= 'var obj = document.getElementById(id);'."\n";
273                    $description.= 'obj.style.width = nw + "px";'."\n";
274                    $description.= 'obj.style.height = nh + "px";'."\n";
275                    $description.= '}'."\n";
276                    $description.= '// ]]>'."\n";
277                    $description.= '</script>'."\n";
278                    $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
279                    $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
280                    $description.= 'codebase="'.$macromedia_url.'swflash.cab#version=8,0,0,0"';
281                    $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
282                    $description.= '<param name="movie" value="'.$gallery2_url.$gallery2_flv_player.'"/>';
283                    $description.= '<param name="FlashVars" value="flvUrl='.$url;
284                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
285                    $description.= '&allowDl=true&thumbUrl='.$thumbnail;
286                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
287                    $description.= '<param name="quality" value="high"/>';
288                    $description.= '<param name="scale" value="noscale"/>';
289                    $description.= '<param name="salign" value="lt"/>';
290                    $description.= '<param name="wmode" value="transparent"/>';
291                    $description.= '<param name="allowScriptAccess" value="always"/>';
292                    $description.= '<embed src="'.$gallery2_url.$gallery2_flv_player.'" ';
293                    $description.= 'flashvars="flvUrl='.$url;
294                    $description.= '&Width='.$width.'&Height='.$height.'&title='.$title;
295                    $description.= '&allowDl=true&thumbUrl='.$thumbnail;
296                    $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" ';
297                    $description.= 'type="application/x-shockwave-flash" ';
298                    $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
299                    $description.= 'wmode="transparent" allowScriptAccess="always" ';
300                    $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
301                    $description.= '</object></div>';
302                }
303                
304           /*
305            **********************************
306            * Unsupported URL to embed
307            **********************************
308            */   
309            } else {
310                return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
311                             "Unable to embed video from: $url"),null,null);
312            }
313            
314
315            /*
316            **********************************
317            * Add the video to Gallery
318            **********************************
319            */
320            
321            /* Get a local tmp file to save the thumbnail URL to */
322            $tmpDir = $gallery->getConfig('data.gallery.tmp');
323            $tmpFile = $platform->tempnam($tmpDir, 'add');
324            $tmpFile.= ".jpg";
325            
326            if($debugOutput) {
327                print "thumbnail: $thumbnail <br>";
328            }
329            
330            /* Fetch the thumbnail and save it to a local file */
331            if (empty($extraHeaders)) {
332                $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
333            }
334            list ($successfullyCopied, $response, $headers) =
335              GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
336            if (!$successfullyCopied) {
337                return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
338                             "Unable to copy thumbnail from url: $url"),null,null);
339            }
340            
341            /* Obtain the mimeType of the thumbnail */
342            list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
343            
344            /* Set the filename for the item we want to add */
345            $fileName = $title;
346            $fileName = preg_replace("/\s+/","_",$fileName);
347            $fileName = preg_replace("/'/","",$fileName);
348            $fileName = preg_replace("/\"/","",$fileName);
349            $fileName = preg_replace("/&#\d+;/","",$fileName);
350            
351            /* General debug output */
352            if($debugOutput) {
353                print "<p><a href=\"".$title."\" target=\"_blank\">";
354                print "<img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
355                print "<p>$description</p>";
356                print "thumbnail: $tmpFile <br>";
357                print "mimeType: $mimeType <br>";
358                print "fileName: $fileName <br>";
359            }
360
361            /* Make the gallery2 call to add this item to the album */
362            list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($tmpFile,
363                                                                   $fileName,
364                                                                   $title,
365                                                                   $summary,
366                                                                   $description,
367                                                                   $mimeType,
368                                                                   $item->getId());
369            
370            if ($ret) {
371                return array($ret, null, null);
372            }
373            
374            $status['addedFiles'][] = array('fileName' => $url,
375                                            'id' => $newItem->getId(),
376                                            'warnings' => array());
377        }
378        @$platform->unlink($tmpFile);
379    }
380    
381    return array(null, $error, $status);
382  }
383
384  /**
385   * @see ItemAdd:loadTemplate
386   */
387  function loadTemplate(&$template, &$form, $item) {
388     global $gallery;
389     
390     if ($form['formName'] != 'ItemAddEmbedVideo') {
391         /* First time around, load the form with item data */
392         $form['webPage'] = '';
393         $form['formName'] = 'ItemAddEmbedVideo';
394     }
395     
396     $session =& $gallery->getSession();
397     
398     $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
399     
400     return array(null,
401                  'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
402                  'modules_embedvideo');
403  }
404  
405  /**
406   * @see ItemAddPlugin::getTitle
407   */
408  function getTitle() {
409     list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
410     if ($ret) {
411         return array($ret, null);
412     }
413     
414     return array(null, $module->translate('Embed Video'));
415  }
416
417
418  /**
419   * ItemAddEmbedVideo::_getFeed
420   */
421  function _getFeed($feed) {
422   
423      /* Open and return Feed with cURL for parsing */
424     $ch = curl_init();
425     $timeout = 0;
426     curl_setopt ($ch, CURLOPT_URL, $feed);
427     curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
428     curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
429     $xml = curl_exec($ch);
430     curl_close($ch);
431     
432     return $xml;    
433  }
434  
435 }       
436 ?>