8b5b299461bf912f3e8d13ccbe9eecd399f035f3
[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         $url = $form['webPage']['URL'];
45
46         // Load any stored/set Parameters
47         list ($ret, $params) =
48           GalleryCoreApi::fetchAllPluginParameters('module', 'embedvideo');
49         if ($ret) {
50           return array($ret, null, null);
51         }
52         foreach (array('default', 'override') as $type) {
53           $ItemAddUploadApplet[$type] = array();
54           if (!empty($params['embedvideo' . $type . 'Variables'])) {
55             $variablesArray = explode('|', $params['embedvideo' . $type . 'Variables']);
56             foreach ($variablesArray as $variable) {
57               list ($name, $value) = explode('=', $variable);
58               $ItemAddEmbedVideo[$type][$name] = $value;
59             }
60           }
61         }
62         
63         // Store any Parameters into some simpler, shorter, local variables
64         $debug=0;
65         $use_internal_flv_player = $ItemAddEmbedVideo['default']['useInternalFlvPlayer'];
66         $youtube_dev_id = $ItemAddEmbedVideo['default']['youtubeDevId'];
67         $width=$ItemAddEmbedVideo['default']['width'];
68         $height=$ItemAddEmbedVideo['default']['height'];
69         $external_flv_player = $ItemAddEmbedVideo['default']['externalFlvPlayer'];
70         $external_flv_player_vars = $ItemAddEmbedVideo['default']['externalFlvPlayerVars'];
71
72         ///////////////////////////////
73         // Embed a Youtube Video
74         ///////////////////////////////
75         if(preg_match("/www.youtube.com/",$url)) {
76
77           if(preg_match("/watch\?v=(.*)/",$url,$matches)) {
78             $video_id = $matches[1];
79           } else {
80             return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
81                                                "Unable to extract video id from url: $url"),null,null);
82           }
83           
84           // Youtube Developer ID
85           $dev_id = $youtube_dev_id;
86           if(!preg_match("/\w+/",$dev_id)) {
87             return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
88                                                "Invalid/missing YouTube developer ID: $dev_id"),null,null);
89           }
90           
91           // Youtube api feed
92           $feed = "http://www.youtube.com/api2_rest?method=youtube.videos.get_details&dev_id=$dev_id&video_id=$video_id";
93           
94           //get the feed as a string data source
95           $xml = get_feed($feed);       
96
97           preg_match_all("/\<title\>(.+?)\<\/title\>/smi",$xml, $title);
98           preg_match_all("/\<description\>(.+?)\<\/description\>/smi",$xml, $description);
99           preg_match_all("/\<thumbnail_url\>(.+?)\<\/thumbnail_url\>/smi",$xml, $thumbnail);
100           
101           array_shift($title);
102           array_shift($thumbnail);
103           array_shift($description);
104           
105           // Replace html characters. More can be added but this seems to work for me across the board. 
106           for($i=0;$i<count($description[0]);$i++){       
107             $description[0][$i] = preg_replace("/&#60;/","<",$description[0][$i]);
108             $description[0][$i] = html_entity_decode($description[0][$i],ENT_QUOTES);     
109           }
110           
111           $title = $title[0][0];
112           $summary = $description[0][0];
113           $thumbnail = $thumbnail[0][0];
114           
115           $description = '<object width="'.$width.'" height="'.$height.'">';
116           $description.= '<param name="movie" value="http://www.youtube.com/v/'.$video_id.'"></param>';
117           $description.= '<param name="wmode" value="transparent"></param>';
118           $description.= '<embed src="http://www.youtube.com/v/'.$video_id.'" ';
119           $description.= 'type="application/x-shockwave-flash" wmode="transparent" ';
120           $description.= 'width="'.$width.'" height="'.$height.'"></embed></object>';
121           $description.= "<br>$summary";
122         }
123            
124            
125         ///////////////////////////////////
126         // Embed a Google Video
127         ///////////////////////////////////
128         else if(preg_match("/video.google.com/",$url)) {
129              
130           if(preg_match("/docid=(.*)/",$url,$matches)) {
131             $doc_id = $matches[1];
132           } else {
133             return array(GalleryCoreApi::error(ERROR_BAD_PARAMETER,__FILE__,__LINE__,
134                                                "Unable to extract doc id from url: $url"),null,null);
135           }
136           
137           $link="$url";
138           $contents=file_get_contents($link);
139           preg_match('/<meta content="(.+?)\. \w+ \d+, \d+.*" name="description">/i', $contents, $matches);
140           $summary=$matches[1];
141           preg_match('/<title>(.+?)\s+- Google Video<\/title>/i', $contents, $matches);
142           $title=$matches[1];
143           preg_match('/<img src="(http:\/\/video\.google\.com\/ThumbnailServer2.+?)" /i', $contents, $matches);
144           $thumbnail=$matches[1];
145           $thumbnail=preg_replace("/offsetms=0/","offsetms=0",$thumbnail);
146           
147           $description = '<embed FlashVars="autoPlay=true" ';
148           $description.= 'style="width:'.$width.'px; height:'.$height.'px;" id="VideoPlayback" ';
149           $description.= 'type="application/x-shockwave-flash" ';
150           $description.= 'src="http://video.google.com/googleplayer.swf?docId='.$doc_id.'"> ';
151           $description.= '</embed>';
152           $description.= "<br>$summary";
153          
154         }
155
156         ///////////////////////////
157         // Embed a remote .flv file
158         ///////////////////////////
159         else if(preg_match("/.*\/(.+?)\.flv/i",$url,$matches)) {
160           $title = $matches[1];
161           $summary = $matches[1];
162           $thumbnail = 'http://www.pippins.net/images/flv_thumb.jpg';
163
164           if (empty($extraHeaders)) {
165             $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
166           }
167
168           list ($successfullyCopied, $response, $headers) =
169             GalleryCoreApi::fetchWebPage($url, $extraHeaders);
170           if (!$successfullyCopied) {
171             return array(GalleryCoreApi::error(ERROR_BAD_PATH,__FILE__,__LINE__,
172                                                "Unable to locate a video at url: $url"),null,null);
173           }
174           
175           // External FLV player
176           if(!$use_internal_flv_player) {
177
178             if(!preg_match("/\w+/",$external_flv_player)) {
179               return array(GalleryCoreApi::error(ERROR_CONFIGURATION_REQUIRED,__FILE__,__LINE__,
180                                                "Invalid/missing external player parameter"),null,null);
181             }
182             
183             $description ='<embed src="'.$external_flv_player.'" ';
184             $description.= 'width="'.$width.'" height="'.$height.'" bgcolor="#C0C0C0" allowfullscreen="true" ';
185             $description.= 'type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" ';
186             $description.= 'flashvars="file='.$url.'&fullscreenpage='.$thumbnail.'&linktarget=_Blank&image='.$thumbnail;
187
188             if(!preg_match("/\w+/",$external_flv_player_vars)) {
189               $description.= '&showdigits=true&autostart=false&showfsbutton=true&';
190               $description.= '&repeat=false&lightcolor=0x9999FF&backcolor=0x888888&frontcolor=0x000000"';
191             } else {
192               $description.= '&'.$external_flv_player_vars;
193             }
194             $description.=  ' />&nbsp;</p>';
195           }
196           
197           // Internal FLV player
198           else { 
199             $description = '<script type="text/javascript">'."\n";
200             $description.= '// <![CDATA['."\n";
201             $description.= 'function divResize(id, nw, nh) {'."\n";
202             $description.= 'var obj = document.getElementById(id);'."\n";
203             $description.= 'obj.style.width = nw + "px";'."\n";
204             $description.= 'obj.style.height = nh + "px";'."\n";
205             $description.= '}'."\n";
206             $description.= '// ]]>'."\n";
207             $description.= '</script>'."\n";
208             $description.= '<div id="flashvideo" style="align:left;width:525px;height:392px">'."\n";
209             $description.= '<object classid="clsid:D27CDB6E-AE6D-11CF-96B8-444553540000"';
210             $description.= 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"';
211             $description.= 'width="100%" height="100%" id="IFid1" class="ImageFrame_image">';
212             $description.= '<param name="movie" value="http://www.pippins.net/gallery2/modules/flashvideo/lib/G2flv.swf"/>';
213             $description.= '<param name="FlashVars" value="flvUrl='.$url.'&Width='.$width.'&Height='.$height.'&title='.$title;
214             $description.= '&allowDl=true&thumbUrl='.$thumbnail.'&langDownload=Download&langLarge=Large&langNormal=Normal"/>';
215             $description.= '<param name="quality" value="high"/>';
216             $description.= '<param name="scale" value="noscale"/>';
217             $description.= '<param name="salign" value="lt"/>';
218             $description.= '<param name="wmode" value="transparent"/>';
219             $description.= '<param name="allowScriptAccess" value="always"/>';
220             $description.= '<embed src="http://www.pippins.net/gallery2/modules/flashvideo/lib/G2flv.swf" flashvars="flvUrl='.$url;
221             $description.= '&Width='.$width.'&Height='.$height.'&title='.$title.'&allowDl=true&thumbUrl='.$thumbnail;
222             $description.= '&langDownload=Download&langLarge=Large&langNormal=Normal" type="application/x-shockwave-flash" ';
223             $description.= 'width="100%" height="100%" quality="high" scale="noscale" salign="lt" ';
224             $description.= 'wmode="transparent" allowScriptAccess="always" ';
225             $description.= 'pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
226             $description.= '</object></div>';
227           }
228         }
229         
230         ////////////////////////////
231         // Unsupported URL to embed
232         ////////////////////////////
233         else {
234           return array(GalleryCoreApi::error(ERROR_UNSUPPORTED_FILE_TYPE,__FILE__,__LINE__,
235                                                "Unable to embed video from: $url"),null,null);
236         }
237
238         
239         ////////////////////////////
240         // Add the video to Gallery
241         ////////////////////////////
242         
243         // Get a local tmp file to save the thumbnail to
244         $tmpDir = $gallery->getConfig('data.gallery.tmp');
245         $tmpFile = $platform->tempnam($tmpDir, 'add');
246         $tmpFile.= ".jpg";
247
248         if($debug) {
249           print "thumbnail: $thumbnail <br>";
250         }
251         
252         // Fetch the thumbnail and save it to a local file
253         if (empty($extraHeaders)) {
254           $extraHeaders = array('Referer' => str_replace('&amp;', '&', $url));
255         }
256
257         list ($successfullyCopied, $response, $headers) =
258           GalleryCoreApi::fetchWebFile($thumbnail, $tmpFile, $extraHeaders);
259         if (!$successfullyCopied) {
260           return array(GalleryCoreApi::error(ERROR_STORAGE_FAILURE,__FILE__,__LINE__,
261                                                "Unable to copy thumbnail from url: $url"),null,null);
262         }
263
264         // Obtain the mimeType of the thumbnail
265         list ($ret, $mimeType) = GalleryCoreApi::getMimeType($tmpFile);
266
267         // Set the filename for the item we want to add
268         $fileName = $title;
269         $fileName = preg_replace("/\s+/","_",$fileName);
270         $fileName = preg_replace("/'/","",$fileName);
271         $fileName = preg_replace("/\"/","",$fileName);
272         $fileName = preg_replace("/&#\d+;/","",$fileName);
273         
274         // DEBUG OUTPUT
275         if($debug) {
276           print "<p><a href=\"".$title."\" target=\"_blank\">\n<img src=\"".$thumbnail."\">\n</a>".$summary."</p>";
277           print "<p>$description</p>";
278           print "thumbnail: $tmpFile <br>";
279           print "mimeType: $mimeType <br>";
280           print "fileName: $fileName <br>";
281         }
282         
283         list ($ret, $newItem) = GalleryCoreApi::addItemToAlbum($tmpFile,
284                                                                $fileName,
285                                                                $title,
286                                                                $summary,
287                                                                $description,
288                                                                $mimeType,
289                                                                $item->getId());
290         
291         if ($ret) {
292           return array($ret, null, null);
293         }
294         
295         $status['addedFiles'][] = array('fileName' => $url,
296                                         'id' => $newItem->getId(),
297                                         'warnings' => array());
298       }
299       @$platform->unlink($tmpFile);
300     }
301     
302     return array(null, $error, $status);
303   }
304
305 /**
306  * @see ItemAdd:loadTemplate
307  */
308 function loadTemplate(&$template, &$form, $item) {
309   global $gallery;
310   
311   if ($form['formName'] != 'ItemAddEmbedVideo') {
312     /* First time around, load the form with item data */
313     $form['webPage'] = '';
314     $form['formName'] = 'ItemAddEmbedVideo';
315   }
316       
317   $session =& $gallery->getSession();
318   
319   $template->setVariable('ItemAddEmbedVideo', $ItemAddEmbedVideo);
320   
321   return array(null,
322                'modules/embedvideo/templates/ItemAddEmbedVideo.tpl',
323                'modules_embedvideo');
324 }
325
326 /**
327  * @see ItemAddPlugin::getTitle
328  */
329  function getTitle() {
330    list ($ret, $module) = GalleryCoreApi::loadPlugin('module', 'embedvideo');
331    if ($ret) {
332      return array($ret, null);
333    }
334    
335    return array(null, $module->translate('Embed Video'));
336  }
337 }
338
339
340 function get_feed($feed){
341   
342   //Open and return Feed with cURL for parsing
343   $ch = curl_init();
344   $timeout = 0;
345   curl_setopt ($ch, CURLOPT_URL, $feed);
346   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
347   curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
348   $xml = curl_exec($ch);
349   curl_close($ch);
350   
351   return $xml;
352   
353 }
354         
355 ?>