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