Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Moving files out of application directory to accommodate spark creation

  • Loading branch information...
commit 736c5263b6fc603b243042d34cdc0368ac0e3a65 1 parent d64fa19
Jim authored
View
62 controllers/example.php
@@ -0,0 +1,62 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+
+class Example extends CI_Controller
+{
+ //CALL THIS METHOD FIRST BY GOING TO
+ //www.your_url.com/index.php/request_youtube
+ public function request_youtube()
+ {
+ $params['key'] = 'ENTER YOUR GOOGLE CONSUMER KEY';
+ $params['secret'] = 'ENTER YOUR GOOGLE CONSUMER SECRET';
+ $params['algorithm'] = 'HMAC-SHA1';
+
+ $this->load->library('google_oauth', $params);
+ $data = $this->google_oauth->get_request_token(site_url('example/access_youtube'));
+ $this->session->set_userdata('token_secret', $data['token_secret']);
+ redirect($data['redirect']);
+ }
+
+ //This method will be redirected to automatically
+ //once the user approves access of your application
+ public function access_youtube()
+ {
+ $params['key'] = 'ENTER YOUR GOOGLE CONSUMER KEY';
+ $params['secret'] = 'ENTER YOUR GOOGLE CONSUMER SECRET';
+ $params['algorithm'] = 'HMAC-SHA1';
+
+ $this->load->library('google_oauth', $params);
+
+ $oauth = $this->google_oauth->get_access_token(false, $this->session->userdata('token_secret'));
+
+ $this->session->set_userdata('oauth_token', $oauth['oauth_token']);
+ $this->session->set_userdata('oauth_token_secret', $oauth['oauth_token_secret']);
+ }
+
+ //This method can be called without having
+ //done the oauth steps
+ public function youtube_no_auth()
+ {
+ $params['apikey'] = 'ENTER YOUR GOOGLE YOUTUBE API KEY';
+
+ $this->load->library('youtube', $params);
+ echo $this->youtube->getKeywordVideoFeed('pac man');
+ }
+
+ //This method can be called after you executed
+ //the oauth steps
+ public function youtube_auth()
+ {
+ $params['apikey'] = 'ENTER YOUR GOOGLE YOUTUBE API KEY';
+ $params['oauth']['key'] = 'ENTER YOUR GOOGLE CONSUMER KEY';
+ $params['oauth']['secret'] = 'ENTER YOUR GOOGLE CONSUMER SECRET';
+ $params['oauth']['algorithm'] = 'HMAC-SHA1';
+ $params['oauth']['access_token'] = array('oauth_token'=>urlencode($this->session->userdata('oauth_token')),
+ 'oauth_token_secret'=>urlencode($this->session->userdata('oauth_token_secret')));
+
+ $this->load->library('youtube', $params);
+ echo $this->youtube->getUserUploads();
+ }
+}
+
+/* End of file example.php */
+/* Location: ./application/controllers/example.php */
View
177 helpers/oauth_helper.php
@@ -0,0 +1,177 @@
+<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
+
+/*
+Copyright (C) 2011 by Jim Saunders
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/**
+ * Defines the different OAuth Signing algorithms. You
+ * should use this instead of writing them out each time.
+ */
+class OAUTH_ALGORITHMS
+{
+ const HMAC_SHA1 = 'HMAC-SHA1';
+ const RSA_SHA1 = 'RSA-SHA1';
+}
+
+/**
+ * Signs an array of oauth parameters according to the 1.0 spec using
+ * the hmac-sha1 hasing algorithm
+ *
+ * @param string $method either GET or POST
+ * @param string $baseurl the baseurl we are authenticating againts
+ * @param string $secret the consumer secret key
+ * @param array $parameters all parameters that need to be signed (NOTE: the token secret key should be added here)
+ * @return string the signature
+ */
+function sign_hmac_sha1($method, $baseurl, $secret, array $parameters)
+{
+ $data = $method.'&';
+ $data .= urlencode($baseurl).'&';
+ $oauth = '';
+ ksort($parameters);
+ //Put the token secret in if it does not exist. It
+ //will be empty if it does not exist as per the spec.
+ if(!array_key_exists('oauth_token_secret', $parameters))$parameters['oauth_token_secret'] = '';
+ foreach($parameters as $key => $value)
+ {
+ //Don't include the token secret into the base string
+ if(strtolower($key) != 'oauth_token_secret')$oauth .= "&{$key}={$value}";
+ }
+ $data .= urlencode(substr($oauth, 1));
+ $secret .= '&'.$parameters['oauth_token_secret'];
+
+ return base64_encode(hash_hmac('sha1', $data, $secret, true));
+}
+
+/**
+ * Signs an array of oauth parameters according to the 1.0 spec using
+ * the rsa-sha1 hasing algorithm
+ *
+ * @param string $method either GET or POST
+ * @param string $baseurl the baseurl we are authenticating againts
+ * @param string $certfile the location of your private certificate file
+ * @param array $parameters all parameters that need to be signed
+ * @return string the signature
+ */
+function sign_rsa_sha1($method, $baseurl, $certfile, array $parameters)
+{
+ $fp = fopen($certfile, "r");
+ $private = fread($fp, 8192);
+ fclose($fp);
+
+ $data = $method.'&';
+ $data .= urlencode($baseurl).'&';
+ $oauth = '';
+ ksort($parameters);
+
+ foreach($parameters as $key => $value)
+ $oauth .= "&{$key}={$value}";
+ $data .= urlencode(substr($oauth, 1));
+
+ $keyid = openssl_get_privatekey($private);
+ openssl_sign($data, $signature, $keyid);
+ openssl_free_key($keyid);
+
+ return base64_encode($signature);
+}
+
+/**
+ * Assembles the auth params array into a string that can
+ * be put into an http header request.
+ *
+ * @param array $authparams the oauth parameters
+ * @return string the header authorization portion with trailing \r\n
+ */
+function build_auth_string(array $authparams)
+{
+ $header = "Authorization: OAuth ";
+ $auth = '';
+ foreach($authparams AS $key=>$value)
+ {
+ //Don't include token secret
+ if($key != 'oauth_token_secret')$auth .= ", {$key}=\"{$value}\"";
+ }
+ return $header.substr($auth, 2)."\r\n";
+}
+
+/**
+ * Assemble an associative array with oauth values
+ *
+ * @param string $baseurl the base url we are authenticating against.
+ * @param string $key your consumer key
+ * @param string $secret either your consumer secret key or the file location of your rsa private key.
+ * @param array $extra additional oauth parameters that should be included (you must urlencode, if appropriate, before calling this function)
+ * @param string $method either GET or POST
+ * @param string $algo either HMAC-SHA1 or RSA-SHA1 (NOTE: this affects what you put in for the secret parameter)
+ * @return array of all the oauth parameters
+ */
+function build_auth_array($baseurl, $key, $secret, $extra = array(), $method = 'GET', $algo = OAUTH_ALGORITHMS::RSA_SHA1)
+{
+ $auth['oauth_consumer_key'] = $key;
+ $auth['oauth_signature_method'] = $algo;
+ $auth['oauth_timestamp'] = time();
+ $auth['oauth_nonce'] = md5(uniqid(rand(), true));
+ $auth['oauth_version'] = '1.0';
+
+ $auth = array_merge($auth, $extra);
+
+ //We want to remove any query parameters from the base url
+ $urlsegs = explode("?", $baseurl);
+ $baseurl = $urlsegs[0];
+
+ //If there are any query parameters we need to make sure they
+ //get signed with the rest of the auth data.
+ $signing = $auth;
+ if(count($urlsegs) > 1)
+ {
+ preg_match_all("/([\w\-]+)\=([\w\d\-\%\.\$\+\*]+)\&?/", $urlsegs[1], $matches);
+ $signing = $signing + array_combine($matches[1], $matches[2]);
+ }
+
+ if(strtoupper($algo) == OAUTH_ALGORITHMS::HMAC_SHA1)$auth['oauth_signature'] = sign_hmac_sha1($method, $baseurl, $secret, $signing);
+ else if(strtoupper($algo) == OAUTH_ALGORITHMS::RSA_SHA1)$auth['oauth_signature'] = sign_rsa_sha1 ($method, $baseurl, $secret, $signing);
+
+ $auth['oauth_signature'] = urlencode($auth['oauth_signature']);
+ return $auth;
+}
+
+/**
+ * Creates the authorization portion of a header NOTE: This does not
+ * create a complete http header. Also NOTE: the oauth_token parameter
+ * should be passed in using the $extra array.
+ *
+ * @param string $baseurl the base url we are authenticating against.
+ * @param string $key your consumer key
+ * @param string $secret either your consumer secret key or the file location of your rsa private key.
+ * @param array $extra additional oauth parameters that should be included (you must urlencode a parameter, if appropriate, before calling this function)
+ * @param string $method either GET or POST
+ * @param string $algo either HMAC-SHA1 or RSA-SHA1 (NOTE: this affects what you put in for the secret parameter)
+ * @return string the header authorization portion with trailing \r\n
+ */
+function get_auth_header($baseurl, $key, $secret, $extra = array(), $method = 'GET', $algo = OAUTH_ALGORITHMS::RSA_SHA1)
+{
+ $auth = build_auth_array($baseurl, $key, $secret, $extra, $method, $algo);
+ return build_auth_string($auth);
+}
+
+/* ./application/helpers/oauth_helper.php */
+?>
View
173 libraries/google_oauth.php
@@ -0,0 +1,173 @@
+<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
+
+/*
+Copyright (C) 2011 by Jim Saunders
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+
+/**
+ * This library is meant to get you an oauth access token
+ * for a google service. You can define which service by
+ * changing the SCOPE constant. You will need to pass in
+ * your consumer key and secret upon loading this library.
+ *
+ * I currently use it in my YouTube API but it can be used
+ * for any google service that allows for OAuth.
+ */
+class google_oauth
+{
+ const SCHEME = 'https';
+ const HOST = 'www.google.com';
+ const AUTHORIZE_URI = '/accounts/OAuthAuthorizeToken';
+ const REQUEST_URI = '/accounts/OAuthGetRequestToken';
+ const ACCESS_URI = '/accounts/OAuthGetAccessToken';
+
+ //This should be changed to correspond with the
+ //google service you are authenticating against.
+ const SCOPE = 'https://gdata.youtube.com'; //YouTube
+
+ //Array that should contain the consumer secret and
+ //key which should be passed into the constructor.
+ private $_consumer = false;
+
+ /**
+ * Pass in a parameters array which should look as follows:
+ * array('key'=>'example.com', 'secret'=>'mysecret');
+ * Note that the secret should either be a hash string for
+ * HMAC signatures or a file path string for RSA signatures.
+ *
+ * @param array $params
+ */
+ public function google_oauth($params)
+ {
+ $this->CI =& get_instance();
+ $this->CI->load->helper('oauth');
+ //Set defaults for method and algorithm if they are not specified
+ if(!array_key_exists('method', $params))$params['method'] = 'GET';
+ if(!array_key_exists('algorithm', $params))$params['algorithm'] = OAUTH_ALGORITHMS::RSA_SHA1;
+
+ $this->_consumer = $params;
+ }
+
+ /**
+ * This is called to begin the oauth token exchange. This should only
+ * need to be called once for a user, provided they allow oauth access.
+ * It will return a URL that your site should redirect to, allowing the
+ * user to login and accept your application.
+ *
+ * @param string $callback the page on your site you wish to return to
+ * after the user grants your application access.
+ * @return mixed either the URL to redirect to, or if they specified HMAC
+ * signing an array with the token_secret and the redirect url
+ */
+ public function get_request_token($callback)
+ {
+ $baseurl = self::SCHEME.'://'.self::HOST.self::REQUEST_URI;
+
+ //Generate an array with the initial oauth values we need
+ $auth = build_auth_array($baseurl, $this->_consumer['key'], $this->_consumer['secret'],
+ array('oauth_callback'=>urlencode($callback), 'scope'=>urlencode(self::SCOPE)),
+ $this->_consumer['method'], $this->_consumer['algorithm']);
+ //Create the "Authorization" portion of the header
+ $str = '';
+ foreach($auth AS $key=>$value)
+ if($key != 'scope')$str .= ",{$key}=\"{$value}\"";//Do not include scope in the Authorization string.
+ $str = substr($str, 1);
+ $str = 'Authorization: OAuth '.$str;
+ //Send it
+ $response = $this->_connect("{$baseurl}?scope={$auth['scope']}", $str);
+ //We should get back a request token and secret which
+ //we will add to the redirect url.
+ parse_str($response, $resarray);
+ //Return the full redirect url and let the user decide what to do from there.
+ $redirect = self::SCHEME.'://'.self::HOST.self::AUTHORIZE_URI."?oauth_token={$resarray['oauth_token']}";
+ //If they are using HMAC then we need to return the token secret for them to store.
+ if($this->_consumer['algorithm'] == OAUTH_ALGORITHMS::RSA_SHA1)return $redirect;
+ else return array('token_secret'=>$resarray['oauth_token_secret'], 'redirect'=>$redirect);
+ }
+
+ /**
+ * This is called to finish the oauth token exchange. This too should
+ * only need to be called once for a user. The token returned should
+ * be stored in your database for that particular user.
+ *
+ * @param string $token this is the oauth_token returned with your callback url
+ * @param string $secret this is the token secret supplied from the request (Only required if using HMAC)
+ * @param string $verifier this is the oauth_verifier returned with your callback url
+ * @return array access token and token secret
+ */
+ public function get_access_token($token = false, $secret = false, $verifier = false)
+ {
+ //If no request token was specified then attempt to get one from the url
+ if($token === false && isset($_GET['oauth_token']))$token = $_GET['oauth_token'];
+ if($verifier === false && isset($_GET['oauth_verifier']))$verifier = $_GET['oauth_verifier'];
+ //If all else fails attempt to get it from the request uri.
+ if($token === false && $verifier === false)
+ {
+ $uri = $_SERVER['REQUEST_URI'];
+ $uriparts = explode('?', $uri);
+
+ $authfields = array();
+ parse_str($uriparts[1], $authfields);
+ $token = $authfields['oauth_token'];
+ $verifier = $authfields['oauth_verifier'];
+ }
+
+ $tokenddata = array('oauth_token'=>urlencode($token), 'oauth_verifier'=>urlencode($verifier));
+ if($secret !== false)$tokenddata['oauth_token_secret'] = urlencode($secret);
+
+ $baseurl = self::SCHEME.'://'.self::HOST.self::ACCESS_URI;
+ //Include the token and verifier into the header request.
+ $auth = get_auth_header($baseurl, $this->_consumer['key'], $this->_consumer['secret'],
+ $tokenddata, $this->_consumer['method'], $this->_consumer['algorithm']);
+ $response = $this->_connect($baseurl, $auth);
+ //Parse the response into an array it should contain
+ //both the access token and the secret key. (You only
+ //need the secret key if you use HMAC-SHA1 signatures.)
+ parse_str($response, $oauth);
+ //Return the token and secret for storage
+ return $oauth;
+ }
+
+ /**
+ * Connects to the server and sends the request,
+ * then returns the response from the server.
+ * @param <type> $url
+ * @param <type> $auth
+ * @return <type>
+ */
+ private function _connect($url, $auth)
+ {
+ $ch = curl_init($url);
+ curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
+ curl_setopt($ch, CURLOPT_SSLVERSION,3);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLOPT_HTTPHEADER, array($auth));
+
+ $response = curl_exec($ch);
+ curl_close($ch);
+ return $response;
+ }
+}
+// ./system/application/libraries
+?>
View
558 libraries/youtube.php
@@ -0,0 +1,558 @@
+<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+
+/*
+Copyright (C) 2011 by Jim Saunders
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+class youtube
+{
+ const HTTP_1 = '1.1';
+ const HOST = 'gdata.youtube.com';
+ const PORT = '80';
+ const SCHEME = 'http';
+ const METHOD = 'GET';
+ const LINE_END = "\r\n";
+ const API_VERSION = '2';
+
+ const URI_BASE = 'http://gdata.youtube.com/';
+
+ const DEBUG = false;
+
+ private $_uris = array(
+ 'STANDARD_TOP_RATED_URI' => 'feeds/api/standardfeeds/top_rated',
+ 'STANDARD_MOST_VIEWED_URI' => 'feeds/api/standardfeeds/most_viewed',
+ 'STANDARD_RECENTLY_FEATURED_URI' => 'feeds/api/standardfeeds/recently_featured',
+ 'STANDARD_WATCH_ON_MOBILE_URI' => 'feeds/api/standardfeeds/watch_on_mobile',
+ 'USER_URI' => 'feeds/api/users',
+ 'INBOX_FEED_URI' => 'feeds/api/users/default/inbox',
+ 'VIDEO_URI' => 'feeds/api/videos',
+ 'USER_UPLOADS_REL' => 'schemas/2007#user.uploads',
+ 'USER_PLAYLISTS_REL' => 'schemas/2007#user.playlists',
+ 'USER_SUBSCRIPTIONS_REL' => 'schemas/2007#user.subscriptions',
+ 'USER_CONTACTS_REL' => 'schemas/2007#user.contacts',
+ 'USER_FAVORITES_REL' => 'schemas/2007#user.favorites',
+ 'VIDEO_RESPONSES_REL' => 'schemas/2007#video.responses',
+ 'VIDEO_RATINGS_REL' => 'schemas/2007#video.ratings',
+ 'VIDEO_COMPLAINTS_REL' => 'schemas/2007#video.complaints',
+ 'PLAYLIST_REL' => 'schemas/2007#playlist',
+ 'IN_REPLY_TO_SCHEME' => 'schemas/2007#in-reply-to',
+ 'UPLOAD_TOKEN_REQUEST' => 'action/GetUploadToken'
+ );
+
+ private $_header = array(
+ 'Host'=>self::HOST,
+ 'Connection'=>'close',
+ 'User-Agent'=>'CodeIgniter',
+ 'Accept-encoding'=>'identity',
+ 'GData-Version'=>self::API_VERSION
+ );
+
+ private $_oauth = array();
+ private $_access = false;
+
+ /**
+ * Create YouTube object
+ *
+ * @param string $clientId The clientId issued by the YouTube dashboard
+ * @param string $developerKey The developerKey issued by the YouTube dashboard
+ */
+ public function youtube($params)
+ {
+ if(isset($params['apikey']))$this->_header['X-GData-Key'] = 'key='.$params['apikey'];
+ $this->CI =& get_instance();
+ if(isset($params['oauth']))
+ {
+ $this->_oauth['key'] = $params['oauth']['key'];
+ $this->_oauth['secret'] = $params['oauth']['secret'];
+ $this->_oauth['algorithm'] = $params['oauth']['algorithm'];
+ $this->_access = $params['oauth']['access_token'];
+ }
+ }
+
+ /**
+ * Builds out an http header based on the specified parameters.
+ *
+ * @param $url string the url this header will go to.
+ * @param $prepend any header data that needs to be added to the header before it is built.
+ * @param $append any header data that needs to be added after the header is built.
+ * @param $method the http method to be used 'POST', 'GET', 'PUT' etc.
+ * return string the http header.
+ **/
+ private function _build_header($url = false, $prepend = false, $append = false, $method = self::METHOD)
+ {
+ $str = $prepend === false ? '' : $prepend;
+ foreach($this->_header AS $key=>$value)
+ $str .= $key.": ".$value.self::LINE_END;
+ if($this->_access !== false && $url !== false)
+ {
+ $this->CI->load->helper('oauth_helper');
+ $str .= get_auth_header($url, $this->_oauth['key'], $this->_oauth['secret'], $this->_access, $method, $this->_oauth['algorithm']);
+ }
+ $str .= $append === false ? '' : $append;
+
+ return $str;
+ }
+
+ /**
+ * Connects to the configured server and returns a handle for I/O
+ **/
+ private function _connect($host = self::HOST, $port = self::PORT, $ssl = false)
+ {
+ $connect = $ssl === false ? 'tcp' : 'ssl';
+ $opts = array(self::SCHEME=>array('method'=>self::METHOD, 'header'=>$this->_build_header()));
+ $context = stream_context_create($opts);
+ $handle = stream_socket_client($connect.'://'.$host.':'.$port, $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $context);
+
+ return $handle;
+ }
+
+ /**
+ * Checks that the response from the server after we make our request is good.
+ * If it isn't then we log the response we got and return false.
+ **/
+ private function _check_status($handle)
+ {
+ $gotStatus = false;
+ $response = '';
+ $resparray = array();
+ while(($line = fgets($handle)) !== false && !$this->_timedout($handle))
+ {
+ $gotStatus = $gotStatus || (strpos($line, 'HTTP') !== false);
+ if($gotStatus)
+ {
+ $response .= $line;
+ array_push($resparray, $line);
+ if(rtrim($line) === '')break;
+ }
+ }
+
+ $matches = explode(' ', $resparray[0]);
+ $status = $gotStatus ? intval($matches[1]) : 0;
+ if($status < 200 || $status > 299)
+ {
+ error_log('YouTube library received bad response: '.$response);
+ if(!self::DEBUG)return false;
+ else return $response;
+ }
+ return true;
+ }
+
+ private function _read($handle)
+ {
+ if($this->_check_status($handle) !== true)return false;
+ $response = '';
+ //Get the chunk size
+ $chunksize = rtrim(fgets($handle));
+ //Convert hex chunk size to int
+ if(ctype_xdigit($chunksize))$chunksize = hexdec($chunksize);
+ else $chunksize = 0;
+
+ if(self::DEBUG)error_log("\nCHUNKSIZE: {$chunksize}");
+
+ while($chunksize > 0 && !$this->_timedout($handle))
+ {
+ $line = fgets($handle, $chunksize);
+ //If fgets stops on a newline before reaching
+ //chunksize. Loop till we get to the chunksize.
+ while(strlen($line) < $chunksize)
+ $line .= fgets($handle);
+
+ $response .= rtrim($line);
+ if(self::DEBUG)error_log("\nCHUNK: {$line}");
+
+ $chunksize = rtrim(fgets($handle));
+ //If we have a valid number for chunksize and we
+ //didn't get an error while reading the last line
+ if(ctype_xdigit($chunksize) && $line !== false)$chunksize = hexdec($chunksize);
+ else break;
+
+ if(self::DEBUG)error_log("\nCHUNKSIZE: {$chunksize}");
+ }
+ if(self::DEBUG)error_log("\nRESPONSE: {$response}");
+ return $response;
+ }
+
+ /**
+ * Writes the specified request to the file handle.
+ **/
+ private function _write($handle, $request)
+ {
+ if(self::DEBUG)error_log($request);
+ fwrite($handle, $request);
+ return $request;
+ }
+
+ /**
+ * Checks that the specified file handle hasn't timed out.
+ **/
+ private function _timedout($handle)
+ {
+ if($handle)
+ {
+ $info = stream_get_meta_data($handle);
+ return $info['timed_out'];
+ }
+ return false;
+ }
+
+ /**
+ * Executes a request that does not pass data, and returns the response.
+ *
+ * @param $uri The URI that corresponds to the data we want.
+ * @return the xml response from youtube.
+ **/
+ private function _response_request($uri, array $params = array())
+ {
+ if(!empty($params))$uri .= '?'.http_build_query($params);
+ $request = self::METHOD." {$uri} HTTP/".self::HTTP_1.self::LINE_END;
+
+ $url = self::URI_BASE.substr($uri, 1);
+
+ $fullrequest = $this->_build_header($url, $request, self::LINE_END);
+
+ if(self::DEBUG)error_log($fullrequest);
+
+ $handle = $this->_connect();
+ $this->_write($handle, $fullrequest);
+ $output = $this->_read($handle);
+
+ fclose($handle);
+ $handle = null;
+
+ return $output;
+ }
+
+ /**
+ * Retrieves a specific video entry.
+ *
+ * @param $videoId The ID of the video to retrieve.
+ * @param $fullEntry (optional) Retrieve the full metadata for the entry.
+ * Only possible if entry belongs to currently authenticated user.
+ * @return the xml response from youtube
+ */
+ public function getVideoEntry($videoId, $fullEntry = false, array $params = array())
+ {
+ if($fullEntry)return $this->_response_request("/{$this->_uris['USER_URI']}/default/uploads/{$videoId}", $params);
+ else return $this->_response_request("/{$this->_uris['VIDEO_URI']}/{$videoId}", $params);
+ }
+
+ /**
+ * Retrieves a feed of videos related to the specified video ID.
+ *
+ * @param string $videoId The videoId of interest
+ * @param array $params additional parameters to pass to youtube see: http://code.google.com/apis/youtube/2.0/reference.html#Query_parameter_definitions
+ * @return the xml response from youtube.
+ */
+ public function getRelatedVideoFeed($videoId, array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['VIDEO_URI']}/{$videoId}/related", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ /**
+ * Retrieves a feed of video responses related to the specified video ID.
+ *
+ * @param string $videoId The videoId of interest
+ * @param array $params additional parameters to pass to youtube see: http://code.google.com/apis/youtube/2.0/reference.html#Query_parameter_definitions
+ * @return the xml response from youtube.
+ */
+ public function getVideoResponseFeed($videoId, array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['VIDEO_URI']}/{$videoId}/responses", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ /**
+ * Retrieves a feed of videos based on an array of keywords.
+ *
+ * @param string $keywords Words to search by. Use "" for exact search, - for not and | for or.
+ * @param array $params additional parameters to pass to youtube see: http://code.google.com/apis/youtube/2.0/reference.html#Query_parameter_definitions
+ * @return the xml response from youtube.
+ */
+ public function getKeywordVideoFeed($keywords, array $params = array())
+ {
+ //Only need to convert spaces the rest get converted later.
+ $params['q'] = str_replace(' ', '+', $keywords);
+ return $this->_response_request("/{$this->_uris['VIDEO_URI']}", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ /**
+ * Retrieves a feed of video comments related to the specified video ID.
+ *
+ * @param string $videoId The videoId of interest
+ * @param array $params additional parameters to pass to youtube see: http://code.google.com/apis/youtube/2.0/reference.html#Query_parameter_definitions
+ * @return the xml response from youtube.
+ */
+ public function getVideoCommentFeed($videoId, array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['VIDEO_URI']}/{$videoId}/comments", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getTopRatedVideoFeed(array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['STANDARD_TOP_RATED_URI']}", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getMostViewedVideoFeed(array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['STANDARD_MOST_VIEWED_URI']}", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getRecentlyFeaturedVideoFeed(array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['STANDARD_RECENTLY_FEATURED_URI']}", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getWatchOnMobileVideoFeed(array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['STANDARD_WATCH_ON_MOBILE_URI']}", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getPlaylistListFeed($user = 'default', array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['USER_URI']}/{$user}/playlists", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getSubscriptionFeed($user = 'default', array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['USER_URI']}/{$user}/subscription", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getContactFeed($user = 'default', array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['USER_URI']}/{$user}/contacts", array_merge(array('v'=>self::API_VERSION), $params));
+ }
+
+ /**
+ * Get all of the uploads the specified user has made to youtube.
+ * If no user is specified then the currently authenticated user
+ * is used.
+ *
+ * @param string $user the youtube user name of the user whose uploads you want.
+ * @param array $params additional parameters to pass to youtube see: http://code.google.com/apis/youtube/2.0/reference.html#Query_parameter_definitions
+ * @return the xml response from youtube.
+ **/
+ public function getUserUploads($user = 'default', array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['USER_URI']}/{$user}/uploads", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getUserFavorites($user = 'default', array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['USER_URI']}/{$user}/favorites", array_merge(array('start-index'=>1, 'max-results'=>10), $params));
+ }
+
+ public function getUserProfile($user = 'default')
+ {
+ return $this->_response_request("/{$this->_uris['USER_URI']}/{$user}");
+ }
+
+ public function getUserActivity($user = 'default', array $params = array())
+ {
+ return $this->_response_request("/{$this->_uris['USER_URI']}/{$user}/events", array_merge(array('v'=>self::API_VERSION), $params));
+ }
+
+ /**
+ * Get a feed of the currently authenticated users inbox.
+ *
+ * @return the youtube response xml.
+ **/
+ public function getInboxFeedForCurrentUser()
+ {
+ if($this->_access !== false)return $this->_response_request ("/{$this->_uris['INBOX_FEED_URI']}");
+ else return false;
+ }
+
+ /**
+ * Executes a request and passes metadata, the returns the response.
+ *
+ * @param $uri the URI for this request.
+ * @param $metadata the data to send for this request (usually XML)
+ * @return mixed false if not authroized otherwise the response is returned.
+ **/
+ private function _data_request($uri, $metadata)
+ {
+ if($this->_access !== false)
+ {
+ $header = "POST {$uri} HTTP/".self::HTTP_1.self::LINE_END;
+ $url = self::URI_BASE.substr($uri, 1);
+ $encoding = "UTF-8";
+ $extra = "Content-Type: application/atom+xml; charset={$encoding}".self::LINE_END;
+ $extra .= "GData-Version: 2.0".self::LINE_END;
+ mb_internal_encoding($encoding);
+
+ $extra .= "Content-Length: ".mb_strlen($metadata.self::LINE_END).self::LINE_END.self::LINE_END;
+
+ $fullrequest = $this->_build_header($url, $header, $extra, 'POST');
+ $fullrequest .= $metadata.self::LINE_END;
+
+ $handle = $this->_connect();
+ $this->_write($handle, $fullrequest);
+ $output = $this->_read($handle);
+
+ fclose($handle);
+ $handle = null;
+
+ return $output;
+ }
+ return false;
+ }
+
+ /**
+ * Directly uploads videos stored on your server to the youtube servers.
+ *
+ * @param string $path The path on your server to the video to upload.
+ * @param string $contenttype The mime-type of the video to upload.
+ * @param string $metadata XML information about the video to upload.
+ * @param string (optional) $user the user name whose account this video will go to. Defaults to the authenticated user.
+ **/
+ public function directUpload($path, $contenttype, $metadata, $user = 'default')
+ {
+ if($this->_access !== false)
+ {
+ $uri = "/{$this->_uris['USER_URI']}/{$user}/uploads";
+ $header = "POST {$uri} HTTP/".self::HTTP_1.self::LINE_END;
+ //We use a special host for direct uploads.
+ $host = "uploads.gdata.youtube.com";
+ $url = "http://".$host.$uri;
+ $extra = "GData-Version: 2.0".self::LINE_END;
+ //Add the file name to the slug parameter.
+ $extra .= "Slug: ".basename($path).self::LINE_END;
+ //Create a random boundry string.
+ $this->CI->load->helper('string');
+ $boundry = random_string();
+ $extra .= "Content-Type: multipart/related; boundary=\"{$boundry}\"".self::LINE_END;
+
+ //Build out the data portion of the request
+ $data = "--".$boundry.self::LINE_END;
+ $data .= "Content-Type: application/atom+xml; charset=UTF-8".self::LINE_END.self::LINE_END;
+ $data .= $metadata.self::LINE_END;
+ $data .= "--".$boundry.self::LINE_END;
+ $data .= "Content-Type: ".$contenttype.self::LINE_END;
+ $data .= "Content-Transfer-Encoding: binary".self::LINE_END.self::LINE_END;
+ $data .= file_get_contents($path).self::LINE_END;
+ $data .= "--{$boundry}--".self::LINE_END;
+
+ //Calculate the size of the data portion.
+ $extra .= "Content-Length: ".strlen($data).self::LINE_END.self::LINE_END;
+ $this->_header['Host'] = $host;//Swap the default host
+ $fullrequest = $this->_build_header($url, $header, $extra, 'POST');
+ $this->_header['Host'] = self::HOST;//Revert the default host.
+ $fullrequest .= $data;
+
+ $handle = null;
+ //Connect to the special upload host
+ $handle = $this->_connect($host);
+
+ $this->_write($handle, $fullrequest);
+ $output = $this->_read($handle);
+
+ fclose($handle);
+ $handle = null;
+
+ return $output;
+ }
+ return false;
+ }
+
+
+ /**
+ * Makes a data request for a youtube upload token.
+ * You must provide details for the video prior to
+ * the request. These are specified in xml and are
+ * passed as the metadata field.
+ *
+ * @param string $metadata XML information about the video about to be uploaded.
+ * @return mixed false if not authorized otherwise the response is returned.
+ **/
+ public function getFormUploadToken($metadata)
+ {
+ return $this->_data_request("/{$this->_uris['UPLOAD_TOKEN_REQUEST']}", $metadata);
+ }
+
+ /**
+ * Add a comment to a video or a reply to another comment.
+ * To reply to a comment you must specify the commentId
+ * otherwise it is just a regular comment.
+ *
+ * @param string $videoId the video the comment goes with.
+ * @param string $comment the comment
+ * @param string (optional) $commentId the id of the comment to reply to.
+ * @return mixed false if not authenticated otherwise the http response is returned.
+ **/
+ public function addComment($videoId, $comment, $commentId = false)
+ {
+
+ $uri = "/{$this->_uris['VIDEO_URI']}/{$videoId}/comments";
+ $url = self::URI_BASE.substr($uri, 1);
+
+ $xml = "<?xml version='1.0' encoding='UTF-8'?><entry xmlns='http://www.w3.org/2005/Atom' xmlns:yt='http://gdata.youtube.com/schemas/2007'>";
+ if($commentId !== false)$xml .= "<link rel='http://gdata.youtube.com/schemas/2007#in-reply-to' type='application/atom+xml' href='{$url}/{$commentId}'/>";
+ $xml .= "<content>{$comment}</content></entry>";
+
+ return $this->_data_request($uri, $xml);
+ }
+
+ /**
+ * Add a video response to another video.
+ *
+ * @param string $videoId the youtube id of the video the response is to.
+ * @param string $responseId the youtube id of the video response.
+ * @return mixed false if not authenticated otherwise the http response is returned.
+ **/
+ public function addVideoResponse($videoId, $responseId)
+ {
+ $uri = "/{$this->_uris['VIDEO_URI']}/{$videoId}/responses";
+ $xml = "<?xml version='1.0' encoding='UTF-8'?><entry xmlns='http://www.w3.org/2005/Atom'><id>{$responseId}</id></entry>";
+
+ return $this->_data_request($uri, $xml);
+ }
+
+ /**
+ * Adds a numeric rating between 1 and 5 to the specified video
+ *
+ * @param string $videoId the youtube video id.
+ * @param int $rating the numeric rating between 1 and 5.
+ * @return mixed false if not authenticated otherwise the http response is sent.
+ **/
+ public function addNumericRating($videoId, $rating)
+ {
+ if(is_numeric($rating) && $rating > 0 && $rating < 6)
+ {
+ $xml = "<?xml version='1.0' encoding='UTF-8'?><entry xmlns='http://www.w3.org/2005/Atom' xmlns:gd='http://schemas.google.com/g/2005'><gd:rating value='{$rating}' min='1' max='5'/></entry>";
+ return $this->_data_request("/{$this->_uris['VIDEO_URI']}/{$videoId}/ratings", $xml);
+ }
+ return false;
+ }
+
+ /**
+ * Adds a like or dislike rating to the specified video.
+ *
+ * @param string $videoId the youtube video id.
+ * @param bool $like boolean where true = like and false = dislike.
+ * @return mixed false if not authenticated otherwise the http response is sent.
+ **/
+ public function addLikeDislike($videoId, $like)
+ {
+ $xml = "<?xml version='1.0' encoding='UTF-8'?><entry xmlns='http://www.w3.org/2005/Atom' xmlns:yt='http://gdata.youtube.com/schemas/2007'><yt:rating value='".($like === true ? 'like':'dislike')."'/></entry>";
+ return $this->_data_request("/{$this->_uris['VIDEO_URI']}/{$videoId}/ratings", $xml);
+ }
+}
+// ./system/application/libraries
+?>
Please sign in to comment.
Something went wrong with that request. Please try again.