Index: extensions/gvideo/include/functions.inc.php
===================================================================
--- extensions/gvideo/include/functions.inc.php	(revision 19213)
+++ extensions/gvideo/include/functions.inc.php	(revision 20804)
@@ -26,6 +26,4 @@
     case 'youtube':
     {
-      $video['type'] = 'youtube';
-
       parse_str($url['query'], $url['query']);
       if (empty($url['query']['v'])) return false;
@@ -36,8 +34,8 @@
     case 'youtu': // youtu.be (short-url service)
     {
+      $video['type'] = 'youtube';
+      
       if (empty($video['video_id']))
       {
-        $video['type'] = 'youtube';
-        
         $url['path'] = explode('/', $url['path']);
         $video['video_id'] = $url['path'][1];
@@ -48,15 +46,21 @@
       if (!$safe_mode)
       {
-        $api_url = 'http://gdata.youtube.com/feeds/api/videos/'.$video['video_id'].'?v=2&alt=json';
-        $json = download_remote_file($api_url, true);
-        if ($json === false or $json == 'file_error') return false;
+        $fields = 'entry(id,author,media:group(media:title(text()),media:description(text()),media:thumbnail(@url),media:keywords))';
+        $api_url = 'http://gdata.youtube.com/feeds/api/videos/'.$video['video_id'].'?v=2&alt=json&fields='.$fields;
+        $json = gvideo_download_remote_file($api_url, true);
+        
+        if ($json===false || $json=='file_error') return false;
         
         $json = json_decode($json, true);
         $video = array_merge($video, array(
-          'title' => $json['entry']['title']['$t'],
+          'title' => $json['entry']['media$group']['media$title']['$t'],
           'description' => $json['entry']['media$group']['media$description']['$t'],
-          'thumbnail' => $json['entry']['media$group']['media$thumbnail'][2]['url'],
+          'thumbnail' => $json['entry']['media$group']['media$thumbnail'][0]['url'],
           'author' => $json['entry']['author'][0]['name']['$t'],
           ));
+        if (!empty($json['entry']['media$group']['media$keywords']['$t']))
+        {
+          $video['tags'] = $json['entry']['media$group']['media$keywords']['$t'];
+        }
       }
       else
@@ -80,16 +84,35 @@
       if (!$safe_mode)
       {
-        $api_url = 'http://vimeo.com/api/v2/video/'.$video['video_id'].'.json';
-        $json = download_remote_file($api_url, true);
-        if ($json === false or $json == 'file_error') return false;
-        
-        $json = json_decode($json, true);
-        $video = array_merge($video, array(
-          'title' => $json[0]['title'],
-          'description' => $json[0]['description'],
-          'thumbnail' => $json[0]['thumbnail_large'],
-          'author' => $json[0]['user_name'],
-          'tags' => array_map('trim', explode(',', $json[0]['tags'])),
-          ));
+        // simple API for public videos
+        $api_url_1 = 'http://vimeo.com/api/v2/video/'.$video['video_id'].'.json';
+        $json = gvideo_download_remote_file($api_url_1, true);
+        
+        if ($json!==false && $json!='file_error' && trim($json)!=$video['video_id'].' not found.')
+        {
+          $json = json_decode($json, true);
+          $video = array_merge($video, array(
+            'title' => $json[0]['title'],
+            'description' => $json[0]['description'],
+            'thumbnail' => $json[0]['thumbnail_large'],
+            'author' => $json[0]['user_name'],
+            'tags' => $json[0]['tags'],
+            ));
+        }
+        else
+        {
+          // oEmbed API, for private videos, doesn't return keywords
+          $api_url_2 = 'http://vimeo.com/api/oembed.json?url='.rawurlencode($video['url']);
+          $json = gvideo_download_remote_file($api_url_2, true);
+          
+          if ($json===false || $json=='file_error') return false;
+          
+          $json = json_decode($json, true);
+          $video = array_merge($video, array(
+            'title' => $json['title'],
+            'description' => $json['description'],
+            'thumbnail' => $json['thumbnail_url'],
+            'author' => $json['author_name'],
+            ));
+        }
       }
       else
@@ -115,6 +138,7 @@
       {
         $api_url = 'https://api.dailymotion.com/video/'.$video['video_id'].'?fields=description,thumbnail_large_url,title,owner.username,tags'; // DM doesn't accept non secure connection
-        $json = download_remote_file($api_url, true);
-        if ($json === false or $json == 'file_error') return false;
+        $json = gvideo_download_remote_file($api_url, true);
+        
+        if ($json===false || $json=='file_error') return false;
         
         $json = json_decode($json, true);
@@ -126,5 +150,5 @@
           'thumbnail' => $json['thumbnail_large_url'],
           'author' => $json['owner.username'],
-          'tags' => $json['tags'],
+          'tags' => implode(',', $json['tags']),
           ));
       }
@@ -143,6 +167,7 @@
       
       // no safe_mode for wat.tv
-      $html = download_remote_file($source_url, true);
-      if ($html === false or $html == 'file_error') return false;
+      $html = gvideo_download_remote_file($source_url, true);
+      
+      if ($html===false || $html=='file_error') return false;
       
       preg_match('#<meta property="og:video" content="http://www.wat.tv/swf2/([^"/>]+)" />#', $html, $matches);
@@ -164,5 +189,5 @@
       
       preg_match_all('#<meta property="video:tag" content="([^">]+)" />#', $html, $matches);
-      $video['tags'] = $matches[1];
+      $video['tags'] = implode(',',  $matches[1]);
       break;
     }
@@ -180,6 +205,7 @@
       if (!$safe_mode)
       {
-        $html = download_remote_file($source_url, true);
-        if ($html === false or $html == 'file_error') return false;
+        $html = gvideo_download_remote_file($source_url, true);
+        
+        if ($html===false || $html=='file_error') return false;
         
         preg_match('#<meta property="og:title" content="([^">]*)" />#', $html, $matches);
@@ -196,5 +222,5 @@
         
         preg_match('#<meta name="keywords" content="([^">]+)" />#', $html, $matches);
-        $video['tags'] = array_map('trim', explode(',', $matches[1]));
+        $video['tags'] = $matches[1];
       }
       else
@@ -211,4 +237,107 @@
   
   return $video;
+}
+
+/**
+ * @params:
+ *  $video (from parse_video_url)
+ *  $config :
+ *    - category, integer
+ *    - add_film_frame, boolean
+ *    - sync_description, boolean
+ *    - sync_tags, boolean
+ *    - with, integer
+ *    - height, integer
+ *    - autoplay, integer (0-1)
+ */
+function add_video($video, $config)
+{
+  global $page, $conf;
+  
+  $query = '
+SELECT picture_id
+  FROM '.GVIDEO_TABLE.'
+  WHERE type = "'.$video['type'].'"
+    AND video_id = "'.$video['video_id'].'"
+;';
+  $result = pwg_query($query);
+  
+  if (pwg_db_num_rows($result))
+  {
+    $page['warnings'][] = l10n('This video was already registered');
+    list($image_id) = pwg_db_fetch_row($result);
+    return $image_id;
+  }
+  
+  include_once(PHPWG_ROOT_PATH . 'admin/include/functions_upload.inc.php');
+  
+  // download thumbnail
+  $thumb_ext = empty($video['thumbnail']) ? 'jpg' : get_extension($video['thumbnail']);
+  $thumb_name = $video['type'].'-'.$video['video_id'].'-'.uniqid().'.'.$thumb_ext;
+  $thumb_source = $conf['data_location'].$thumb_name;
+  if ( empty($video['thumbnail']) or gvideo_download_remote_file($video['thumbnail'], $thumb_source) !== true )
+  {
+    $thumb_source = $conf['data_location'].get_filename_wo_extension($thumb_name).'.jpg';
+    copy(GVIDEO_PATH.'mimetypes/'.$video['type'].'.jpg', $thumb_source);
+  }
+  
+  if ($config['add_film_frame'])
+  {
+    add_film_frame($thumb_source);
+  }
+  
+  // add image and update infos
+  $image_id = add_uploaded_file($thumb_source, $thumb_name, array($config['category']));
+  
+  $updates = array(
+    'name' => pwg_db_real_escape_string($video['title']),
+    'author' => pwg_db_real_escape_string($video['author']),
+    'is_gvideo' => 1,
+    );
+    
+  if ( $config['sync_description'] and !empty($video['description']) )
+  {
+    $updates['comment'] = pwg_db_real_escape_string($video['description']);
+  }
+  
+  if ( $config['sync_tags'] and !empty($video['tags']) )
+  {
+    $tags = pwg_db_real_escape_string($video['tags']);
+    set_tags(get_tag_ids($tags), $image_id);
+  }
+  
+  single_update(
+    IMAGES_TABLE,
+    $updates,
+    array('id' => $image_id),
+    true
+    );
+  
+  // register video
+  if ( !preg_match('#^([0-9]*)$#', $config['width']) or !preg_match('#^([0-9]*)$#', $config['height']) )
+  {
+    $config['width'] = $config['height'] = '';
+  }
+  if ( $config['autoplay']!='0' and $config['autoplay']!='1' )
+  {
+    $config['autoplay'] = '';
+  }
+  
+  $insert = array(
+    'picture_id' => $image_id,
+    'url' => $video['url'],
+    'type' => $video['type'],
+    'video_id' => $video['video_id'],
+    'width' => $config['width'],
+    'height' => $config['height'],
+    'autoplay' => $config['autoplay'],
+    );
+    
+  single_insert(
+    GVIDEO_TABLE,
+    $insert
+    );
+    
+  return $image_id;
 }
 
@@ -233,100 +362,100 @@
  * @param: mixed destination file (if true, file content is returned)
  */
-if (!function_exists('download_remote_file'))
+function gvideo_download_remote_file($src, $dest, $headers=array())
 {
-  function download_remote_file($src, $dest)
-  {
-    if (empty($src))
+  if (empty($src))
+  {
+    return false;
+  }
+  
+  $return = ($dest === true) ? true : false;
+  
+  array_push($headers, 'Accept-language: en');
+  
+  /* curl */
+  if (function_exists('curl_init'))
+  {
+    if (!$return)
+    {
+      $newf = fopen($dest, "wb");
+    }
+    $ch = curl_init();
+    
+    curl_setopt($ch, CURLOPT_URL, $src);
+    curl_setopt($ch, CURLOPT_HEADER, false);
+    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
+    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
+    if (!ini_get('safe_mode'))
+    {
+      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+      curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
+    }
+    if (strpos($src, 'https://') !== false)
+    {
+      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
+      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
+    }
+    if (!$return)
+    {
+      curl_setopt($ch, CURLOPT_FILE, $newf);
+    }
+    else
+    {
+      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+    }
+    
+    $out = curl_exec($ch);
+    curl_close($ch);
+    
+    if ($out === false)
+    {
+      return 'file_error';
+    }
+    else if (!$return)
+    {
+      fclose($newf);
+      return true;
+    }
+    else
+    {
+      return $out;
+    }
+  }
+  /* file get content */
+  else if (ini_get('allow_url_fopen'))
+  {
+    if (strpos($src, 'https://') !== false and !extension_loaded('openssl'))
     {
       return false;
     }
     
-    $return = ($dest === true) ? true : false;
-    
-    /* curl */
-    if (function_exists('curl_init'))
-    {
-      if (!$return)
-      {
-        $newf = fopen($dest, "wb");
-      }
-      $ch = curl_init();
-      
-      curl_setopt($ch, CURLOPT_URL, $src);
-      curl_setopt($ch, CURLOPT_HEADER, false);
-      curl_setopt($ch, CURLOPT_HTTPHEADER, array("Accept-language: en"));
-      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
-      if (!ini_get('safe_mode'))
-      {
-        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
-        curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
-      }
-      if (strpos($src, 'https://') !== false)
-      {
-        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
-        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
-      }
-      if (!$return)
-      {
-        curl_setopt($ch, CURLOPT_FILE, $newf);
-      }
-      else
-      {
-        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-      }
-      
-      $out = curl_exec($ch);
-      curl_close($ch);
-      
-      if ($out === false)
-      {
-        return 'file_error';
-      }
-      else if (!$return)
-      {
-        fclose($newf);
-        return true;
-      }
-      else
-      {
-        return $out;
-      }
-    }
-    /* file get content */
-    else if (ini_get('allow_url_fopen'))
-    {
-      if (strpos($src, 'https://') !== false and !extension_loaded('openssl'))
-      {
-        return false;
-      }
-      
-      $opts = array(
-        'http' => array(
-          'method' => "GET",
-          'user_agent' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
-          'header' => "Accept-language: en",
-        )
-      );
-
-      $context = stream_context_create($opts);
-      
-      if (($file = file_get_contents($src, false, $context)) === false)
-      {
-        return 'file_error';
-      }
-      
-      if (!$return)
-      {
-        file_put_contents($dest, $file);
-        return true;
-      }
-      else
-      {
-        return $file;
-      }
-    }
-    
-    return false;
-  }
+    $opts = array(
+      'http' => array(
+        'method' => "GET",
+        'user_agent' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
+        'header' => implode("\r\n", $headers),
+      )
+    );
+
+    $context = stream_context_create($opts);
+    
+    if (($file = file_get_contents($src, false, $context)) === false)
+    {
+      return 'file_error';
+    }
+    
+    if (!$return)
+    {
+      file_put_contents($dest, $file);
+      return true;
+    }
+    else
+    {
+      return $file;
+    }
+  }
+  
+  return false;
 }
 
