diff --git a/appnet/AppDotNet.php b/appnet/AppDotNet.php
new file mode 100644
index 0000000..3236131
--- /dev/null
+++ b/appnet/AppDotNet.php
@@ -0,0 +1,1647 @@
+_clientId = $client_id;
+ $this->_clientSecret = $client_secret;
+
+ // if the digicert certificate exists in the same folder as this file,
+ // remember that fact for later
+ if (file_exists(dirname(__FILE__).'/DigiCertHighAssuranceEVRootCA.pem')) {
+ $this->_sslCA = dirname(__FILE__).'/DigiCertHighAssuranceEVRootCA.pem';
+ }
+ }
+
+ /**
+ * Set whether or not to strip Envelope Response (meta) information
+ * This option will be deprecated in the future. Is it to allow
+ * a stepped migration path between code expecting the old behavior
+ * and new behavior. When not stripped, you still can use the proper
+ * method to pull the meta information. Please start converting your code ASAP
+ */
+ public function includeResponseEnvelope() {
+ $this->_stripResponseEnvelope=false;
+ }
+
+ /**
+ * Construct the proper Auth URL for the user to visit and either grant
+ * or not access to your app. Usually you would place this as a link for
+ * the user to client, or a redirect to send them to the auth URL.
+ * Also can be called after authentication for additional scopes
+ * @param string $callbackUri Where you want the user to be directed
+ * after authenticating with App.net. This must be one of the URIs
+ * allowed by your App.net application settings.
+ * @param array $scope An array of scopes (permissions) you wish to obtain
+ * from the user. Currently options are stream, email, write_post, follow,
+ * messages, and export. If you don't specify anything, you'll only receive
+ * access to the user's basic profile (the default).
+ */
+ public function getAuthUrl($callback_uri,$scope=null) {
+
+ // construct an authorization url based on our client id and other data
+ $data = array(
+ 'client_id'=>$this->_clientId,
+ 'response_type'=>'code',
+ 'redirect_uri'=>$callback_uri,
+ );
+
+ $url = $this->_authUrl;
+ if ($this->_accessToken) {
+ $url .= 'authorize?';
+ } else {
+ $url .= 'authenticate?';
+ }
+ $url .= $this->buildQueryString($data);
+
+ if ($scope) {
+ $url .= '&scope='.implode('+',$scope);
+ }
+
+ // return the constructed url
+ return $url;
+ }
+
+ /**
+ * Call this after they return from the auth page, or anytime you need the
+ * token. For example, you could store it in a database and use
+ * setAccessToken() later on to return on behalf of the user.
+ */
+ public function getAccessToken($callback_uri) {
+ // if there's no access token set, and they're returning from
+ // the auth page with a code, use the code to get a token
+ if (!$this->_accessToken && isset($_GET['code']) && $_GET['code']) {
+
+ // construct the necessary elements to get a token
+ $data = array(
+ 'client_id'=>$this->_clientId,
+ 'client_secret'=>$this->_clientSecret,
+ 'grant_type'=>'authorization_code',
+ 'redirect_uri'=>$callback_uri,
+ 'code'=>$_GET['code']
+ );
+
+ // try and fetch the token with the above data
+ $res = $this->httpReq('post',$this->_authUrl.'access_token', $data);
+
+ // store it for later
+ $this->_accessToken = $res['access_token'];
+ $this->_username = $res['username'];
+ $this->_user_id = $res['user_id'];
+ }
+
+ // return what we have (this may be a token, or it may be nothing)
+ return $this->_accessToken;
+ }
+
+ /**
+ * Check the scope of current token to see if it has required scopes
+ * has to be done after a check
+ */
+ public function checkScopes($app_scopes) {
+ if (!count($this->_scopes)) {
+ return -1; // _scope is empty
+ }
+ $missing=array();
+ foreach($app_scopes as $scope) {
+ if (!in_array($scope,$this->_scopes)) {
+ if ($scope=='public_messages') {
+ // messages works for public_messages
+ if (in_array('messages',$this->_scopes)) {
+ // if we have messages in our scopes
+ continue;
+ }
+ }
+ $missing[]=$scope;
+ }
+ }
+ // identify the ones missing
+ if (count($missing)) {
+ // do something
+ return $missing;
+ }
+ return 0; // 0 missing
+ }
+
+ /**
+ * Set the access token (eg: after retrieving it from offline storage)
+ * @param string $token A valid access token you're previously received
+ * from calling getAccessToken().
+ */
+ public function setAccessToken($token) {
+ $this->_accessToken = $token;
+ }
+
+ /**
+ * Deauthorize the current token (delete your authorization from the API)
+ * Generally this is useful for logging users out from a web app, so they
+ * don't get automatically logged back in the next time you redirect them
+ * to the authorization URL.
+ */
+ public function deauthorizeToken() {
+ return $this->httpReq('delete',$this->_baseUrl.'token');
+ }
+
+ /**
+ * Retrieve an app access token from the app.net API. This allows you
+ * to access the API without going through the user access flow if you
+ * just want to (eg) consume global. App access tokens are required for
+ * some actions (like streaming global). DO NOT share the return value
+ * of this function with any user (or save it in a cookie, etc). This
+ * is considered secret info for your app only.
+ * @return string The app access token
+ */
+ public function getAppAccessToken() {
+
+ // construct the necessary elements to get a token
+ $data = array(
+ 'client_id'=>$this->_clientId,
+ 'client_secret'=>$this->_clientSecret,
+ 'grant_type'=>'client_credentials',
+ );
+
+ // try and fetch the token with the above data
+ $res = $this->httpReq('post',$this->_authUrl.'access_token', $data);
+
+ // store it for later
+ $this->_appAccessToken = $res['access_token'];
+ $this->_accessToken = $res['access_token'];
+ $this->_username = null;
+ $this->_user_id = null;
+
+ return $this->_accessToken;
+ }
+
+ /**
+ * Returns the total number of requests you're allowed within the
+ * alloted time period.
+ * @see getRateLimitReset()
+ */
+ public function getRateLimit() {
+ return $this->_rateLimit;
+ }
+
+ /**
+ * The number of requests you have remaining within the alloted time period
+ * @see getRateLimitReset()
+ */
+ public function getRateLimitRemaining() {
+ return $this->_rateLimitRemaining;
+ }
+
+ /**
+ * The number of seconds remaining in the alloted time period.
+ * When this time is up you'll have getRateLimit() available again.
+ */
+ public function getRateLimitReset() {
+ return $this->_rateLimitReset;
+ }
+
+ /**
+ * The scope the user has
+ */
+ public function getScope() {
+ return $this->_scope;
+ }
+
+ /**
+ * Internal function, parses out important information App.net adds
+ * to the headers.
+ */
+ protected function parseHeaders($response) {
+ // take out the headers
+ // set internal variables
+ // return the body/content
+ $this->_rateLimit = null;
+ $this->_rateLimitRemaining = null;
+ $this->_rateLimitReset = null;
+ $this->_scope = null;
+
+ $response = explode("\r\n\r\n",$response,2);
+ $headers = $response[0];
+
+ if($headers == 'HTTP/1.1 100 Continue') {
+ $response = explode("\r\n\r\n",$response[1],2);
+ $headers = $response[0];
+ }
+
+ if (isset($response[1])) {
+ $content = $response[1];
+ }
+ else {
+ $content = null;
+ }
+
+ // this is not a good way to parse http headers
+ // it will not (for example) take into account multiline headers
+ // but what we're looking for is pretty basic, so we can ignore those shortcomings
+ $headers = explode("\r\n",$headers);
+ foreach ($headers as $header) {
+ $header = explode(': ',$header,2);
+ if (count($header)<2) {
+ continue;
+ }
+ list($k,$v) = $header;
+ switch ($k) {
+ case 'X-RateLimit-Remaining':
+ $this->_rateLimitRemaining = $v;
+ break;
+ case 'X-RateLimit-Limit':
+ $this->_rateLimit = $v;
+ break;
+ case 'X-RateLimit-Reset':
+ $this->_rateLimitReset = $v;
+ break;
+ case 'X-OAuth-Scopes':
+ $this->_scope = $v;
+ $this->_scopes=explode(',',$v);
+ break;
+ }
+ }
+ return $content;
+ }
+
+ /**
+ * Internal function. Used to turn things like TRUE into 1, and then
+ * calls http_build_query.
+ */
+ protected function buildQueryString($array) {
+ foreach ($array as $k=>&$v) {
+ if ($v===true) {
+ $v = '1';
+ }
+ elseif ($v===false) {
+ $v = '0';
+ }
+ unset($v);
+ }
+ return http_build_query($array);
+ }
+
+
+ /**
+ * Internal function to handle all
+ * HTTP requests (POST,PUT,GET,DELETE)
+ */
+ protected function httpReq($act, $req, $params=array(),$contentType='application/x-www-form-urlencoded') {
+ $ch = curl_init($req);
+ $headers = array();
+ if($act != 'get') {
+ curl_setopt($ch, CURLOPT_POST, true);
+ // if they passed an array, build a list of parameters from it
+ if (is_array($params) && $act != 'post-raw') {
+ $params = $this->buildQueryString($params);
+ }
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
+ $headers[] = "Content-Type: ".$contentType;
+ }
+ if($act != 'post' && $act != 'post-raw') {
+ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($act));
+ }
+ if($act == 'get' && isset($params['access_token'])) {
+ $headers[] = 'Authorization: Bearer '.$params['access_token'];
+ }
+ else if ($this->_accessToken) {
+ $headers[] = 'Authorization: Bearer '.$this->_accessToken;
+ }
+ curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch, CURLINFO_HEADER_OUT, true);
+ curl_setopt($ch, CURLOPT_HEADER, true);
+ if ($this->_sslCA) {
+ curl_setopt($ch, CURLOPT_CAINFO, $this->_sslCA);
+ }
+ $this->_last_response = curl_exec($ch);
+ $this->_last_request = curl_getinfo($ch,CURLINFO_HEADER_OUT);
+ $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ curl_close($ch);
+ if ($http_status==0) {
+ throw new AppDotNetException('Unable to connect to '.$req);
+ }
+ if ($http_status<200 || $http_status>=300) {
+ throw new AppDotNetException('HTTP error '.$this->_last_response);
+ }
+ if ($this->_last_request===false) {
+ if (!curl_getinfo($ch,CURLINFO_SSL_VERIFYRESULT)) {
+ throw new AppDotNetException('SSL verification failed, connection terminated.');
+ }
+ }
+ $response = $this->parseHeaders($this->_last_response);
+ $response = json_decode($response,true);
+
+ if (isset($response['meta'])) {
+ if (isset($response['meta']['max_id'])) {
+ $this->_maxid=$response['meta']['max_id'];
+ $this->_minid=$response['meta']['min_id'];
+ }
+ if (isset($response['meta']['more'])) {
+ $this->_more=$response['meta']['more'];
+ }
+ if (isset($response['meta']['marker'])) {
+ $this->_last_marker=$response['meta']['marker'];
+ }
+ }
+
+ // look for errors
+ if (isset($response['error'])) {
+ if (is_array($response['error'])) {
+ throw new AppDotNetException($response['error']['message'],
+ $response['error']['code']);
+ }
+ else {
+ throw new AppDotNetException($response['error']);
+ }
+ }
+
+ // look for response migration errors
+ elseif (isset($response['meta']) && isset($response['meta']['error_message'])) {
+ throw new AppDotNetException($response['meta']['error_message'],$response['meta']['code']);
+ }
+
+ // if we've received a migration response, handle it and return data only
+ elseif ($this->_stripResponseEnvelope && isset($response['meta']) && isset($response['data'])) {
+ return $response['data'];
+ }
+
+ // else non response migration response, just return it
+ else {
+ return $response;
+ }
+ }
+
+
+ /**
+ * Get max_id from last meta response data envelope
+ */
+ public function getResponseMaxID() {
+ return $this->_maxid;
+ }
+
+ /**
+ * Get min_id from last meta response data envelope
+ */
+ public function getResponseMinID() {
+ return $this->_minid;
+ }
+
+ /**
+ * Get more from last meta response data envelope
+ */
+ public function getResponseMore() {
+ return $this->_more;
+ }
+
+ /**
+ * Get marker from last meta response data envelope
+ */
+ public function getResponseMarker() {
+ return $this->_last_marker;
+ }
+
+ /**
+ * Fetch API configuration object
+ */
+ public function getConfig() {
+ return $this->httpReq('get',$this->_baseUrl.'config');
+ }
+
+ /**
+ * Return the Filters for the current user.
+ */
+ public function getAllFilters() {
+ return $this->httpReq('get',$this->_baseUrl.'filters');
+ }
+
+ /**
+ * Create a Filter for the current user.
+ * @param string $name The name of the new filter
+ * @param array $filters An associative array of filters to be applied.
+ * This may change as the API evolves, as of this writing possible
+ * values are: user_ids, hashtags, link_domains, and mention_user_ids.
+ * You will need to provide at least one filter name=>value pair.
+ */
+ public function createFilter($name='New filter', $filters=array()) {
+ $filters['name'] = $name;
+ return $this->httpReq('post',$this->_baseUrl.'filters',$filters);
+ }
+
+ /**
+ * Returns a specific Filter object.
+ * @param integer $filter_id The ID of the filter you wish to retrieve.
+ */
+ public function getFilter($filter_id=null) {
+ return $this->httpReq('get',$this->_baseUrl.'filters/'.urlencode($filter_id));
+ }
+
+ /**
+ * Delete a Filter. The Filter must belong to the current User.
+ * @return object Returns the deleted Filter on success.
+ */
+ public function deleteFilter($filter_id=null) {
+ return $this->httpReq('delete',$this->_baseUrl.'filters/'.urlencode($filter_id));
+ }
+
+ /**
+ * Process user description, message or post text.
+ * Mentions and hashtags will be parsed out of the
+ * text, as will bare URLs. To create a link in the text without using a
+ * bare URL, include the anchor text in the object text and include a link
+ * entity in the function call.
+ * @param string $text The text of the description/message/post
+ * @param array $data An associative array of optional post data. This
+ * will likely change as the API evolves, as of this writing allowed keys are:
+ * reply_to, and annotations. "annotations" may be a complex object represented
+ * by an associative array.
+ * @param array $params An associative array of optional data to be included
+ * in the URL (such as 'include_annotations' and 'include_machine')
+ * @return array An associative array representing the post.
+ */
+ public function processText($text=null, $data = array(), $params = array()) {
+ $data['text'] = $text;
+ $json = json_encode($data);
+ $qs = '';
+ if (!empty($params)) {
+ $qs = '?'.$this->buildQueryString($params);
+ }
+ return $this->httpReq('post',$this->_baseUrl.'text/process'.$qs, $json, 'application/json');
+ }
+
+ /**
+ * Create a new Post object. Mentions and hashtags will be parsed out of the
+ * post text, as will bare URLs. To create a link in a post without using a
+ * bare URL, include the anchor text in the post's text and include a link
+ * entity in the post creation call.
+ * @param string $text The text of the post
+ * @param array $data An associative array of optional post data. This
+ * will likely change as the API evolves, as of this writing allowed keys are:
+ * reply_to, and annotations. "annotations" may be a complex object represented
+ * by an associative array.
+ * @param array $params An associative array of optional data to be included
+ * in the URL (such as 'include_annotations' and 'include_machine')
+ * @return array An associative array representing the post.
+ */
+ public function createPost($text=null, $data = array(), $params = array()) {
+ $data['text'] = $text;
+
+ $json = json_encode($data);
+ $qs = '';
+ if (!empty($params)) {
+ $qs = '?'.$this->buildQueryString($params);
+ }
+ return $this->httpReq('post',$this->_baseUrl.'posts'.$qs, $json, 'application/json');
+ }
+
+ /**
+ * Returns a specific Post.
+ * @param integer $post_id The ID of the post to retrieve
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: include_annotations.
+ * @return array An associative array representing the post
+ */
+ public function getPost($post_id=null,$params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id)
+ .'?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Delete a Post. The current user must be the same user who created the Post.
+ * It returns the deleted Post on success.
+ * @param integer $post_id The ID of the post to delete
+ * @param array An associative array representing the post that was deleted
+ */
+ public function deletePost($post_id=null) {
+ return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id));
+ }
+
+ /**
+ * Retrieve the Posts that are 'in reply to' a specific Post.
+ * @param integer $post_id The ID of the post you want to retrieve replies for.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * @return An array of associative arrays, each representing a single post.
+ */
+ public function getPostReplies($post_id=null,$params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id)
+ .'/replies?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Get the most recent Posts created by a specific User in reverse
+ * chronological order (most recent first).
+ * @param mixed $user_id Either the ID of the user you wish to retrieve posts by,
+ * or the string "me", which will retrieve posts for the user you're authenticated
+ * as.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * @return An array of associative arrays, each representing a single post.
+ */
+ public function getUserPosts($user_id='me', $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id)
+ .'/posts?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Get the most recent Posts mentioning by a specific User in reverse
+ * chronological order (newest first).
+ * @param mixed $user_id Either the ID of the user who is being mentioned, or
+ * the string "me", which will retrieve posts for the user you're authenticated
+ * as.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * @return An array of associative arrays, each representing a single post.
+ */
+ public function getUserMentions($user_id='me',$params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'users/'
+ .urlencode($user_id).'/mentions?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Return the 20 most recent posts from the current User and
+ * the Users they follow.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * @return An array of associative arrays, each representing a single post.
+ */
+ public function getUserStream($params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Returns a specific user object.
+ * @param mixed $user_id The ID of the user you want to retrieve, or the string
+ * "me" to retrieve data for the users you're currently authenticated as.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: include_annotations|include_user_annotations.
+ * @return array An associative array representing the user data.
+ */
+ public function getUser($user_id='me', $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id)
+ .'?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Returns multiple users request by an array of user ids
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: include_annotations|include_user_annotations.
+ * @return array An associative array representing the users data.
+ */
+ public function getUsers($user_arr, $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'users?ids='.join(',',$user_arr)
+ .'&'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Add the specified user ID to the list of users followed.
+ * Returns the User object of the user being followed.
+ * @param integer $user_id The user ID of the user to follow.
+ * @return array An associative array representing the user you just followed.
+ */
+ public function followUser($user_id=null) {
+ return $this->httpReq('post',$this->_baseUrl.'users/'.urlencode($user_id).'/follow');
+ }
+
+ /**
+ * Removes the specified user ID to the list of users followed.
+ * Returns the User object of the user being unfollowed.
+ * @param integer $user_id The user ID of the user to unfollow.
+ * @return array An associative array representing the user you just unfollowed.
+ */
+ public function unfollowUser($user_id=null) {
+ return $this->httpReq('delete',$this->_baseUrl.'users/'.urlencode($user_id).'/follow');
+ }
+
+ /**
+ * Returns an array of User objects the specified user is following.
+ * @param mixed $user_id Either the ID of the user being followed, or
+ * the string "me", which will retrieve posts for the user you're authenticated
+ * as.
+ * @return array An array of associative arrays, each representing a single
+ * user following $user_id
+ */
+ public function getFollowing($user_id='me') {
+ return $this->httpReq('get',$this->_baseUrl.'users/'.$user_id.'/following');
+ }
+
+ /**
+ * Returns an array of User objects for users following the specified user.
+ * @param mixed $user_id Either the ID of the user being followed, or
+ * the string "me", which will retrieve posts for the user you're authenticated
+ * as.
+ * @return array An array of associative arrays, each representing a single
+ * user following $user_id
+ */
+ public function getFollowers($user_id='me') {
+ return $this->httpReq('get',$this->_baseUrl.'users/'.$user_id.'/followers');
+ }
+
+ /**
+ * Return Posts matching a specific #hashtag.
+ * @param string $hashtag The hashtag you're looking for.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * @return An array of associative arrays, each representing a single post.
+ */
+ public function searchHashtags($hashtag=null, $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'posts/tag/'
+ .urlencode($hashtag).'?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Retrieve a list of all public Posts on App.net, often referred to as the
+ * global stream.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * @return An array of associative arrays, each representing a single post.
+ */
+ public function getPublicPosts($params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'posts/stream/global?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * List User interactions
+ */
+ public function getMyInteractions($params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'users/me/interactions?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Retrieve a user's user ID by specifying their username.
+ * Now supported by the API. We use the API if we have a token
+ * Otherwise we scrape the alpha.app.net site for the info.
+ * @param string $username The username of the user you want the ID of, without
+ * an @ symbol at the beginning.
+ * @return integer The user's user ID
+ */
+ public function getIdByUsername($username=null) {
+ if ($this->_accessToken) {
+ $res=$this->httpReq('get',$this->_baseUrl.'users/@'.$username);
+ $user_id=$res['data']['id'];
+ } else {
+ $ch = curl_init('https://alpha.app.net/'.urlencode(strtolower($username)));
+ curl_setopt($ch, CURLOPT_POST, false);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($ch,CURLOPT_USERAGENT,
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1');
+ $response = curl_exec($ch);
+ curl_close($ch);
+ $temp = explode('title="User Id ',$response);
+ $temp2 = explode('"',$temp[1]);
+ $user_id = $temp2[0];
+ }
+ return $user_id;
+ }
+
+ /**
+ * Mute a user
+ * @param integer $user_id The user ID to mute
+ */
+ public function muteUser($user_id=null) {
+ return $this->httpReq('post',$this->_baseUrl.'users/'.urlencode($user_id).'/mute');
+ }
+
+ /**
+ * Unmute a user
+ * @param integer $user_id The user ID to unmute
+ */
+ public function unmuteUser($user_id=null) {
+ return $this->httpReq('delete',$this->_baseUrl.'users/'.urlencode($user_id).'/mute');
+ }
+
+ /**
+ * List the users muted by the current user
+ * @return array An array of associative arrays, each representing one muted user.
+ */
+ public function getMuted() {
+ return $this->httpReq('get',$this->_baseUrl.'users/me/muted');
+ }
+
+ /**
+ * Star a post
+ * @param integer $post_id The post ID to star
+ */
+ public function starPost($post_id=null) {
+ return $this->httpReq('post',$this->_baseUrl.'posts/'.urlencode($post_id).'/star');
+ }
+
+ /**
+ * Unstar a post
+ * @param integer $post_id The post ID to unstar
+ */
+ public function unstarPost($post_id=null) {
+ return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id).'/star');
+ }
+
+ /**
+ * List the posts starred by the current user
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * See https://github.com/appdotnet/api-spec/blob/master/resources/posts.md#general-parameters
+ * @return array An array of associative arrays, each representing a single
+ * user who has starred a post
+ */
+ public function getStarred($user_id='me', $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id).'/stars'
+ .'?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * List the users who have starred a post
+ * @param integer $post_id the post ID to get stars from
+ * @return array An array of associative arrays, each representing one user.
+ */
+ public function getStars($post_id=null) {
+ return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id).'/stars');
+ }
+
+ /**
+ * Returns an array of User objects of users who reposted the specified post.
+ * @param integer $post_id the post ID to
+ * @return array An array of associative arrays, each representing a single
+ * user who reposted $post_id
+ */
+ public function getReposters($post_id){
+ return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id).'/reposters');
+ }
+
+ /**
+ * Repost an existing Post object.
+ * @param integer $post_id The id of the post
+ * @return not a clue
+ */
+ public function repost($post_id){
+ return $this->httpReq('post',$this->_baseUrl.'posts/'.urlencode($post_id).'/repost');
+ }
+
+ /**
+ * Delete a post that the user has reposted.
+ * @param integer $post_id The id of the post
+ * @return not a clue
+ */
+ public function deleteRepost($post_id){
+ return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id).'/repost');
+ }
+
+ /**
+ * List the posts who match a specific search term
+ * @param array $params a list of filter, search query, and general Post parameters
+ * see: https://developers.app.net/reference/resources/post/search/
+ * @param string $query The search query. Supports
+ * normal search terms. Searches post text.
+ * @return array An array of associative arrays, each representing one post.
+ * or false on error
+ */
+ public function searchPosts($params = array(), $query='', $order='default') {
+ if (!is_array($params)) {
+ return false;
+ }
+ if (!empty($query)) {
+ $params['query']=$query;
+ }
+ if ($order=='default') {
+ if (!empty($query)) {
+ $params['order']='score';
+ } else {
+ $params['order']='id';
+ }
+ }
+ return $this->httpReq('get',$this->_baseUrl.'posts/search?'.$this->buildQueryString($params));
+ }
+
+
+ /**
+ * List the users who match a specific search term
+ * @param string $search The search query. Supports @username or #tag searches as
+ * well as normal search terms. Searches username, display name, bio information.
+ * Does not search posts.
+ * @return array An array of associative arrays, each representing one user.
+ */
+ public function searchUsers($search="") {
+ return $this->httpReq('get',$this->_baseUrl.'users/search?q='.urlencode($search));
+ }
+
+ /**
+ * Return the 20 most recent posts for a stream using a valid Token
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * @return An array of associative arrays, each representing a single post.
+ */
+ public function getTokenStream($params = array()) {
+ if ($params['access_token']) {
+ return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params),$params);
+ } else {
+ return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params));
+ }
+ }
+
+ /**
+ * Get a user object by username
+ * @param string $name the @name to get
+ * @return array representing one user
+ */
+ public function getUserByName($name=null) {
+ return $this->httpReq('get',$this->_baseUrl.'users/@'.$name);
+ }
+
+ /**
+ * Return the 20 most recent Posts from the current User's personalized stream
+ * and mentions stream merged into one stream.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: count, before_id, since_id, include_muted, include_deleted,
+ * include_directed_posts, and include_annotations.
+ * @return An array of associative arrays, each representing a single post.
+ */
+ public function getUserUnifiedStream($params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'posts/stream/unified?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Update Profile Data via JSON
+ * @data array containing user descriptors
+ */
+ public function updateUserData($data = array(), $params = array()) {
+ $json = json_encode($data);
+ return $this->httpReq('put',$this->_baseUrl.'users/me'.'?'.
+ $this->buildQueryString($params), $json, 'application/json');
+ }
+
+ /**
+ * Update a user image
+ * @which avatar|cover
+ * @image path reference to image
+ */
+ protected function updateUserImage($which = 'avatar', $image = null) {
+ $data = array($which=>"@$image");
+ return $this->httpReq('post-raw',$this->_baseUrl.'users/me/'.$which, $data, 'multipart/form-data');
+ }
+
+ public function updateUserAvatar($avatar = null) {
+ if($avatar != null)
+ return $this->updateUserImage('avatar', $avatar);
+ }
+
+ public function updateUserCover($cover = null) {
+ if($cover != null)
+ return $this->updateUserImage('cover', $cover);
+ }
+
+ /**
+ * update stream marker
+ */
+ public function updateStreamMarker($data = array()) {
+ $json = json_encode($data);
+ return $this->httpReq('post',$this->_baseUrl.'posts/marker', $json, 'application/json');
+ }
+
+ /**
+ * get a page of current user subscribed channels
+ */
+ public function getUserSubscriptions($params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'channels?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * get user channels
+ */
+ public function getMyChannels($params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'channels/me?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * create a channel
+ * note: you cannot create a channel with type=net.app.core.pm (see createMessage)
+ */
+ public function createChannel($data = array()) {
+ $json = json_encode($data);
+ return $this->httpReq('post',$this->_baseUrl.'channels'.($pm?'/pm/messsages':''), $json, 'application/json');
+ }
+
+ /**
+ * get channelid info
+ */
+ public function getChannel($channelid, $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * get multiple channels' info by an array of channelids
+ */
+ public function getChannels($channels, $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'channels?ids='.join(',',$channels).'&'.$this->buildQueryString($params));
+ }
+
+ /**
+ * update channelid
+ */
+ public function updateChannel($channelid, $data = array()) {
+ $json = json_encode($data);
+ return $this->httpReq('put',$this->_baseUrl.'channels/'.$channelid, $json, 'application/json');
+ }
+
+ /**
+ * subscribe from channelid
+ */
+ public function channelSubscribe($channelid) {
+ return $this->httpReq('post',$this->_baseUrl.'channels/'.$channelid.'/subscribe');
+ }
+
+ /**
+ * unsubscribe from channelid
+ */
+ public function channelUnsubscribe($channelid) {
+ return $this->httpReq('delete',$this->_baseUrl.'channels/'.$channelid.'/subscribe');
+ }
+
+ /**
+ * get all user objects subscribed to channelid
+ */
+ public function getChannelSubscriptions($channelid, $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'channel/'.$channelid.'/subscribers?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * get all user IDs subscribed to channelid
+ */
+ public function getChannelSubscriptionsById($channelid) {
+ return $this->httpReq('get',$this->_baseUrl.'channel/'.$channelid.'/subscribers/ids');
+ }
+
+
+ /**
+ * get a page of messages in channelid
+ */
+ public function getMessages($channelid, $params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'/messages?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * create message
+ * @param $channelid numeric or "pm" for auto-chanenl (type=net.app.core.pm)
+ * @param $data array('text'=>'YOUR_MESSAGE') If a type=net.app.core.pm, then "destinations" key can be set to address as an array of people to send this PM too
+ */
+ public function createMessage($channelid,$data) {
+ $json = json_encode($data);
+ return $this->httpReq('post',$this->_baseUrl.'channels/'.$channelid.'/messages', $json, 'application/json');
+ }
+
+ /**
+ * get message
+ */
+ public function getMessage($channelid,$messageid) {
+ return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'/messages/'.$messageid);
+ }
+
+ /**
+ * delete messsage
+ */
+ public function deleteMessage($channelid,$messageid) {
+ return $this->httpReq('delete',$this->_baseUrl.'channels/'.$channelid.'/messages/'.$messageid);
+ }
+
+
+ /**
+ * Get Application Information
+ */
+ public function getAppTokenInfo() {
+ // requires appAccessToken
+ if (!$this->_appAccessToken) {
+ $this->getAppAccessToken();
+ }
+ // ensure request is made with our appAccessToken
+ $params['access_token']=$this->_appAccessToken;
+ return $this->httpReq('get',$this->_baseUrl.'token',$params);
+ }
+
+ /**
+ * Get User Information
+ */
+ public function getUserTokenInfo() {
+ return $this->httpReq('get',$this->_baseUrl.'token');
+ }
+
+ /**
+ * Get Application Authorized User IDs
+ */
+ public function getAppUserIDs() {
+ // requires appAccessToken
+ if (!$this->_appAccessToken) {
+ $this->getAppAccessToken();
+ }
+ // ensure request is made with our appAccessToken
+ $params['access_token']=$this->_appAccessToken;
+ return $this->httpReq('get',$this->_baseUrl.'apps/me/tokens/user_ids',$params);
+ }
+
+ /**
+ * Get Application Authorized User Tokens
+ */
+ public function getAppUserTokens() {
+ // requires appAccessToken
+ if (!$this->_appAccessToken) {
+ $this->getAppAccessToken();
+ }
+ // ensure request is made with our appAccessToken
+ $params['access_token']=$this->_appAccessToken;
+ return $this->httpReq('get',$this->_baseUrl.'apps/me/tokens',$params);
+ }
+
+ public function getLastRequest() {
+ return $this->_last_request;
+ }
+ public function getLastResponse() {
+ return $this->_last_response;
+ }
+
+ /**
+ * Registers your function (or an array of object and method) to be called
+ * whenever an event is received via an open app.net stream. Your function
+ * will receive a single parameter, which is the object wrapper containing
+ * the meta and data.
+ * @param mixed A PHP callback (either a string containing the function name,
+ * or an array where the first element is the class/object and the second
+ * is the method).
+ */
+ public function registerStreamFunction($function) {
+ $this->_streamCallback = $function;
+ }
+
+ /**
+ * Opens a stream that's been created for this user/app and starts sending
+ * events/objects to your defined callback functions. You must define at
+ * least one callback function before opening a stream.
+ * @param mixed $stream Either a stream ID or the endpoint of a stream
+ * you've already created. This stream must exist and must be valid for
+ * your current access token. If you pass a stream ID, the library will
+ * make an API call to get the endpoint.
+ *
+ * This function will return immediately, but your callback functions
+ * will continue to receive events until you call closeStream() or until
+ * App.net terminates the stream from their end with an error.
+ *
+ * If you're disconnected due to a network error, the library will
+ * automatically attempt to reconnect you to the same stream, no action
+ * on your part is necessary for this. However if the app.net API returns
+ * an error, a reconnection attempt will not be made.
+ *
+ * Note there is no closeStream, because once you open a stream you
+ * can't stop it (unless you exit() or die() or throw an uncaught
+ * exception, or something else that terminates the script).
+ * @return boolean True
+ * @see createStream()
+ */
+ public function openStream($stream) {
+ // if there's already a stream running, don't allow another
+ if ($this->_currentStream) {
+ throw new AppDotNetException('There is already a stream being consumed, only one stream can be consumed per AppDotNetStream instance');
+ }
+ // must register a callback (or the exercise is pointless)
+ if (!$this->_streamCallback) {
+ throw new AppDotNetException('You must define your callback function using registerStreamFunction() before calling openStream');
+ }
+ // if the stream is a numeric value, get the stream info from the api
+ if (is_numeric($stream)) {
+ $stream = $this->getStream($stream);
+ $this->_streamUrl = $stream['endpoint'];
+ }
+ else {
+ $this->_streamUrl = $stream;
+ }
+ // continue doing this until we get an error back or something...?
+ $this->httpStream('get',$this->_streamUrl);
+
+ return true;
+ }
+
+ /**
+ * Close the currently open stream.
+ * @return true;
+ */
+ public function closeStream() {
+ if (!$this->_lastStreamActivity) {
+ // never opened
+ return;
+ }
+ if (!$this->_multiStream) {
+ throw new AppDotNetException('You must open a stream before calling closeStream()');
+ }
+ curl_close($this->_currentStream);
+ curl_multi_remove_handle($this->_multiStream,$this->_currentStream);
+ curl_multi_close($this->_multiStream);
+ $this->_currentStream = null;
+ $this->_multiStream = null;
+ }
+
+ /**
+ * Retrieve all streams for the current access token.
+ * @return array An array of stream definitions.
+ */
+ public function getAllStreams() {
+ return $this->httpReq('get',$this->_baseUrl.'streams');
+ }
+
+ /**
+ * Returns a single stream specified by a stream ID. The stream must have been
+ * created with the current access token.
+ * @return array A stream definition
+ */
+ public function getStream($streamId) {
+ return $this->httpReq('get',$this->_baseUrl.'streams/'.urlencode($streamId));
+ }
+
+ /**
+ * Creates a stream for the current app access token.
+ *
+ * @param array $objectTypes The objects you want to retrieve data for from the
+ * stream. At time of writing these can be 'post', 'star', and/or 'user_follow'.
+ * If you don't specify, all events will be retrieved.
+ */
+ public function createStream($objectTypes=null) {
+ // default object types to everything
+ if (is_null($objectTypes)) {
+ $objectTypes = array('post','star','user_follow');
+ }
+ $data = array(
+ 'object_types'=>$objectTypes,
+ 'type'=>'long_poll',
+ );
+ $data = json_encode($data);
+ $response = $this->httpReq('post',$this->_baseUrl.'streams',$data,'application/json');
+ return $response;
+ }
+
+ /**
+ * Update stream for the current app access token
+ *
+ * @param integer $streamId The stream ID to update. This stream must have been
+ * created by the current access token.
+ * @param array $data allows object_types, type, filter_id and key to be updated. filter_id/key can be omitted
+ */
+ public function updateStream($streamId,$data) {
+ // objectTypes is likely required
+ if (is_null($data['object_types'])) {
+ $data['object_types'] = array('post','star','user_follow');
+ }
+ // type can still only be long_poll
+ if (is_null($data['type'])) {
+ $data['type']='long_poll';
+ }
+ $data = json_encode($data);
+ $response = $this->httpReq('put',$this->_baseUrl.'streams/'.urlencode($streamId),$data,'application/json');
+ return $response;
+ }
+
+ /**
+ * Deletes a stream if you no longer need it.
+ *
+ * @param integer $streamId The stream ID to delete. This stream must have been
+ * created by the current access token.
+ */
+ public function deleteStream($streamId) {
+ return $this->httpReq('delete',$this->_baseUrl.'streams/'.urlencode($streamId));
+ }
+
+ /**
+ * Deletes all streams created by the current access token.
+ */
+ public function deleteAllStreams() {
+ return $this->httpReq('delete',$this->_baseUrl.'streams');
+ }
+
+ /**
+ * Internal function used to process incoming chunks from the stream. This is only
+ * public because it needs to be accessed by CURL. Do not call or use this function
+ * in your own code.
+ * @ignore
+ */
+ public function httpStreamReceive($ch,$data) {
+ $this->_lastStreamActivity = time();
+ $this->_streamBuffer .= $data;
+ if (!$this->_streamHeaders) {
+ $pos = strpos($this->_streamBuffer,"\r\n\r\n");
+ if ($pos!==false) {
+ $this->_streamHeaders = substr($this->_streamBuffer,0,$pos);
+ $this->_streamBuffer = substr($this->_streamBuffer,$pos+4);
+ }
+ }
+ else {
+ $pos = strpos($this->_streamBuffer,"\r\n");
+ while ($pos!==false) {
+ $command = substr($this->_streamBuffer,0,$pos);
+ $this->_streamBuffer = substr($this->_streamBuffer,$pos+2);
+ $command = json_decode($command,true);
+ if ($command) {
+ call_user_func($this->_streamCallback,$command);
+ }
+ $pos = strpos($this->_streamBuffer,"\r\n");
+ }
+ }
+ return strlen($data);
+ }
+
+ /**
+ * Opens a long lived HTTP connection to the app.net servers, and sends data
+ * received to the httpStreamReceive function. As a general rule you should not
+ * directly call this method, it's used by openStream().
+ */
+ protected function httpStream($act, $req, $params=array(),$contentType='application/x-www-form-urlencoded') {
+ if ($this->_currentStream) {
+ throw new AppDotNetException('There is already an open stream, you must close the existing one before opening a new one');
+ }
+ $headers = array();
+ $this->_streamBuffer = '';
+ if ($this->_accessToken) {
+ $headers[] = 'Authorization: Bearer '.$this->_accessToken;
+ }
+ $this->_currentStream = curl_init($req);
+ curl_setopt($this->_currentStream, CURLOPT_HTTPHEADER, $headers);
+ curl_setopt($this->_currentStream, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($this->_currentStream, CURLINFO_HEADER_OUT, true);
+ curl_setopt($this->_currentStream, CURLOPT_HEADER, true);
+ if ($this->_sslCA) {
+ curl_setopt($this->_currentStream, CURLOPT_CAINFO, $this->_sslCA);
+ }
+ // every time we receive a chunk of data, forward it to httpStreamReceive
+ curl_setopt($this->_currentStream, CURLOPT_WRITEFUNCTION, array($this, "httpStreamReceive"));
+
+ // curl_exec($ch);
+ // return;
+
+ $this->_multiStream = curl_multi_init();
+ $this->_lastStreamActivity = time();
+ curl_multi_add_handle($this->_multiStream,$this->_currentStream);
+ }
+
+ public function reconnectStream() {
+ $this->closeStream();
+ $this->_connectFailCounter++;
+ // if we've failed a few times, back off
+ if ($this->_connectFailCounter>1) {
+ $sleepTime = pow(2,$this->_connectFailCounter);
+ // don't sleep more than 60 seconds
+ if ($sleepTime>60) {
+ $sleepTime = 60;
+ }
+ sleep($sleepTime);
+ }
+ $this->httpStream('get',$this->_streamUrl);
+ }
+
+ /**
+ * Process an open stream for x microseconds, then return. This is useful if you want
+ * to be doing other things while processing the stream. If you just want to
+ * consume the stream without other actions, you can call processForever() instead.
+ * @param float @microseconds The number of microseconds to process for before
+ * returning. There are 1,000,000 microseconds in a second.
+ *
+ * @return void
+ */
+ public function processStream($microseconds=null) {
+ if (!$this->_multiStream) {
+ throw new AppDotNetException('You must open a stream before calling processStream()');
+ }
+ $start = microtime(true);
+ $active = null;
+ $inQueue = null;
+ $sleepFor = 0;
+ do {
+ // if we haven't received anything within 5.5 minutes, reconnect
+ // keepalives are sent every 5 minutes (measured on 2013-3-12 by @ryantharp)
+ if (time()-$this->_lastStreamActivity>=330) {
+ $this->reconnectStream();
+ }
+ curl_multi_exec($this->_multiStream, $active);
+ if (!$active) {
+ $httpCode = curl_getinfo($this->_currentStream,CURLINFO_HTTP_CODE);
+ // don't reconnect on 400 errors
+ if ($httpCode>=400 && $httpCode<=499) {
+ throw new AppDotNetException('Received HTTP error '.$httpCode.' check your URL and credentials before reconnecting');
+ }
+ $this->reconnectStream();
+ }
+ // sleep for a max of 2/10 of a second
+ $timeSoFar = (microtime(true)-$start)*1000000;
+ $sleepFor = $this->streamingSleepFor;
+ if ($timeSoFar+$sleepFor>$microseconds) {
+ $sleepFor = $microseconds - $timeSoFar;
+ }
+
+ if ($sleepFor>0) {
+ usleep($sleepFor);
+ }
+ } while ($timeSoFar+$sleepFor<$microseconds);
+ }
+
+ /**
+ * Process an open stream forever. This function will never return, if you
+ * want to perform other actions while consuming the stream, you should use
+ * processFor() instead.
+ * @return void This function will never return
+ * @see processFor();
+ */
+ public function processStreamForever() {
+ while (true) {
+ $this->processStream(600);
+ }
+ }
+
+
+ /**
+ * Upload a file to a user's file store
+ * @param string $file A string containing the path of the file to upload.
+ * @param array $data Additional data about the file you're uploading. At the
+ * moment accepted keys are: mime-type, kind, type, name, public and annotations.
+ * - If you don't specify mime-type, ADNPHP will attempt to guess the mime type
+ * based on the file, however this isn't always reliable.
+ * - If you don't specify kind ADNPHP will attempt to determine if the file is
+ * an image or not.
+ * - If you don't specify name, ADNPHP will use the filename of the first
+ * parameter.
+ * - If you don't specify public, your file will be uploaded as a private file.
+ * - Type is REQUIRED.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: include_annotations|include_file_annotations.
+ * @return array An associative array representing the file
+ */
+ public function createFile($file, $data, $params=array()) {
+ if (!$file) {
+ throw new AppDotNetException('You must specify a path to a file');
+ }
+ if (!file_exists($file)) {
+ throw new AppDotNetException('File path specified does not exist');
+ }
+ if (!is_readable($file)) {
+ throw new AppDotNetException('File path specified is not readable');
+ }
+
+ if (!$data) {
+ $data = array();
+ }
+
+ if (!array_key_exists('type',$data) || !$data['type']) {
+ throw new AppDotNetException('Type is required when creating a file');
+ }
+
+ if (!array_key_exists('name',$data)) {
+ $data['name'] = basename($file);
+ }
+
+ if (array_key_exists('mime-type',$data)) {
+ $mimeType = $data['mime-type'];
+ unset($data['mime-type']);
+ }
+ else {
+ $mimeType = null;
+ }
+ if (!array_key_exists('kind',$data)) {
+ $test = @getimagesize($path);
+ if ($test && array_key_exists('mime',$test)) {
+ $data['kind'] = 'image';
+ if (!$mimeType) {
+ $mimeType = $test['mime'];
+ }
+ }
+ else {
+ $data['kind'] = 'other';
+ }
+ }
+ if (!$mimeType) {
+ $finfo = finfo_open(FILEINFO_MIME_TYPE);
+ $mimeType = finfo_file($finfo, $file);
+ finfo_close($finfo);
+ }
+ if (!$mimeType) {
+ throw new AppDotNetException('Unable to determine mime type of file, try specifying it explicitly');
+ }
+ if (!array_key_exists('public',$data) || !$data['public']) {
+ $public = false;
+ }
+ else {
+ $public = true;
+ }
+
+ $data['content'] = "@$file;type=$mimeType";
+ return $this->httpReq('post-raw',$this->_baseUrl.'files', $data, 'multipart/form-data');
+ }
+
+
+ public function createFilePlaceholder($file = null, $params=array()) {
+ $name = basename($file);
+ $data = array('annotations' => $params['annotations'], 'kind' => $params['kind'],
+ 'name' => $name, 'type' => $params['metadata']);
+ $json = json_encode($data);
+ return $this->httpReq('post',$this->_baseUrl.'files', $json, 'application/json');
+ }
+
+ public function updateFileContent($fileid, $file) {
+
+ $data = file_get_contents($file);
+ $finfo = finfo_open(FILEINFO_MIME_TYPE);
+ $mime = finfo_file($finfo, $file);
+ finfo_close($finfo);
+
+ return $this->httpReq('put',$this->_baseUrl.'files/' . $fileid
+ .'/content', $data, $mime);
+ }
+
+ /**
+ * Allows for file rename and annotation changes.
+ * @param integer $file_id The ID of the file to update
+ * @param array $params An associative array of file parameters.
+ * @return array An associative array representing the updated file
+ */
+ public function updateFile($file_id=null, $params=array()) {
+ $data = array('annotations' => $params['annotations'] , 'name' => $params['name']);
+ $json = json_encode($data);
+ return $this->httpReq('put',$this->_baseUrl.'files/'.urlencode($file_id), $json, 'application/json');
+ }
+
+ /**
+ * Returns a specific File.
+ * @param integer $file_id The ID of the file to retrieve
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: include_annotations|include_file_annotations.
+ * @return array An associative array representing the file
+ */
+ public function getFile($file_id=null,$params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id)
+ .'?'.$this->buildQueryString($params));
+ }
+
+ public function getFileContent($file_id=null,$params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id)
+ .'/content?'.$this->buildQueryString($params));
+ }
+
+ /** $file_key : derived_file_key */
+ public function getDerivedFileContent($file_id=null,$file_key=null,$params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id)
+ .'/content/'.urlencode($file_key)
+ .'?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Returns file objects.
+ * @param array $file_ids The IDs of the files to retrieve
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: include_annotations|include_file_annotations.
+ * @return array An associative array representing the file data.
+ */
+ public function getFiles($file_ids=array(), $params = array()) {
+ $ids = '';
+ foreach($file_ids as $id) {
+ $ids .= $id . ',';
+ }
+ $params['ids'] = substr($ids, 0, -1);
+ return $this->httpReq('get',$this->_baseUrl.'files'
+ .'?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Returns a user's file objects.
+ * @param array $params An associative array of optional general parameters.
+ * This will likely change as the API evolves, as of this writing allowed keys
+ * are: include_annotations|include_file_annotations|include_user_annotations.
+ * @return array An associative array representing the file data.
+ */
+ public function getUserFiles($params = array()) {
+ return $this->httpReq('get',$this->_baseUrl.'users/me/files'
+ .'?'.$this->buildQueryString($params));
+ }
+
+ /**
+ * Delete a File. The current user must be the same user who created the File.
+ * It returns the deleted File on success.
+ * @param integer $file_id The ID of the file to delete
+ * @return array An associative array representing the file that was deleted
+ */
+ public function deleteFile($file_id=null) {
+ return $this->httpReq('delete',$this->_baseUrl.'files/'.urlencode($file_id));
+ }
+
+}
+
+class AppDotNetException extends Exception {}
diff --git a/appnet/DigiCertHighAssuranceEVRootCA.pem b/appnet/DigiCertHighAssuranceEVRootCA.pem
new file mode 100644
index 0000000..9e6810a
--- /dev/null
+++ b/appnet/DigiCertHighAssuranceEVRootCA.pem
@@ -0,0 +1,23 @@
+-----BEGIN CERTIFICATE-----
+MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs
+MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3
+d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j
+ZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL
+MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3
+LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug
+RVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm
++9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW
+PNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM
+xChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB
+Ik5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3
+hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg
+EsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF
+MAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA
+FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec
+nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z
+eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF
+hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2
+Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe
+vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep
++OkuE6N36B9K
+-----END CERTIFICATE-----
diff --git a/appnet/README.md b/appnet/README.md
new file mode 100644
index 0000000..ec24753
--- /dev/null
+++ b/appnet/README.md
@@ -0,0 +1,15 @@
+App.net Plugin
+==============
+
+With this addon to friendica you can give your users the possibility to post their *public* messages to App.net and
+to import their timeline. The messages will be strapped their rich context and shortened to 256 characters length if
+necessary.
+
+Installation
+------------
+
+If you have an developer account you can create an Application for all of your users at
+[https://account.app.net/developer/apps/](https://account.app.net/developer/apps/). Add the redirect uri
+"https://your.server.name/appnet/connect" (Replace "your.server.name" with the hostname of your server)
+
+If you can't create an application (because you only have a free account) this addon still works, but your users have to create individual applications on their own.
diff --git a/appnet/appnet.css b/appnet/appnet.css
new file mode 100755
index 0000000..b1d8d27
--- /dev/null
+++ b/appnet/appnet.css
@@ -0,0 +1,29 @@
+#appnet-import-label, #appnet-disconnect-label, #appnet-token-label,
+#appnet-enable-label, #appnet-bydefault-label,
+#appnet-clientid-label, #appnet-clientsecret-label {
+ float: left;
+ width: 200px;
+ margin-top: 10px;
+}
+
+#appnet-import, #appnet-disconnect, #appnet-token,
+#appnet-checkbox, #appnet-bydefault,
+#appnet-clientid, #appnet-clientsecret {
+ float: left;
+ margin-top: 10px;
+}
+
+#appnet-submit {
+ margin-top: 15px;
+}
+
+#appnet-avatar {
+ float: left;
+ width: 48px;
+ height: 48px;
+ padding: 2px;
+}
+#appnet-info-block {
+ height: 52px;
+ vertical-align: middle;
+}
diff --git a/appnet/appnet.php b/appnet/appnet.php
new file mode 100644
index 0000000..151a81e
--- /dev/null
+++ b/appnet/appnet.php
@@ -0,0 +1,1358 @@
+
+ * Status: Unsupported
+ */
+
+/*
+ To-Do:
+ - Use embedded pictures for the attachment information (large attachment)
+ - Sound links must be handled
+ - https://alpha.app.net/sr_rolando/post/32365203 - double pictures
+ - https://alpha.app.net/opendev/post/34396399 - location data
+*/
+
+require_once('include/enotify.php');
+require_once("include/socgraph.php");
+
+define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
+
+function appnet_install() {
+ register_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
+ register_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
+ register_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
+ register_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
+ register_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
+ register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post');
+ register_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body');
+ register_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification');
+}
+
+
+function appnet_uninstall() {
+ unregister_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
+ unregister_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
+ unregister_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
+ unregister_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
+ unregister_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
+ unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
+ unregister_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body');
+ unregister_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification');
+}
+
+function appnet_module() {}
+
+function appnet_content(&$a) {
+ if(! local_user()) {
+ notice( t('Permission denied.') . EOL);
+ return '';
+ }
+
+ require_once("mod/settings.php");
+ settings_init($a);
+
+ if (isset($a->argv[1]))
+ switch ($a->argv[1]) {
+ case "connect":
+ $o = appnet_connect($a);
+ break;
+ default:
+ $o = print_r($a->argv, true);
+ break;
+ }
+ else
+ $o = appnet_connect($a);
+
+ return $o;
+}
+
+function appnet_check_item_notification($a, &$notification_data) {
+ $own_id = get_pconfig($notification_data["uid"], 'appnet', 'ownid');
+
+ $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
+ intval($notification_data["uid"]),
+ dbesc("adn::".$own_id)
+ );
+
+ if ($own_user)
+ $notification_data["profiles"][] = $own_user[0]["url"];
+}
+
+function appnet_plugin_admin(&$a, &$o){
+ $t = get_markup_template( "admin.tpl", "addon/appnet/" );
+
+ $o = replace_macros($t, array(
+ '$submit' => t('Save Settings'),
+ // name, label, value, help, [extra values]
+ '$clientid' => array('clientid', t('Client ID'), get_config('appnet', 'clientid' ), ''),
+ '$clientsecret' => array('clientsecret', t('Client Secret'), get_config('appnet', 'clientsecret' ), ''),
+ ));
+}
+
+function appnet_plugin_admin_post(&$a){
+ $clientid = ((x($_POST,'clientid')) ? notags(trim($_POST['clientid'])) : '');
+ $clientsecret = ((x($_POST,'clientsecret')) ? notags(trim($_POST['clientsecret'])): '');
+ set_config('appnet','clientid',$clientid);
+ set_config('appnet','clientsecret',$clientsecret);
+ info( t('Settings updated.'). EOL );
+}
+
+function appnet_connect(&$a) {
+ require_once 'addon/appnet/AppDotNet.php';
+
+ $clientId = get_config('appnet','clientid');
+ $clientSecret = get_config('appnet','clientsecret');
+
+ if (($clientId == "") || ($clientSecret == "")) {
+ $clientId = get_pconfig(local_user(),'appnet','clientid');
+ $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
+ }
+
+ $app = new AppDotNet($clientId, $clientSecret);
+
+ try {
+ $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
+
+ logger("appnet_connect: authenticated");
+ $o .= t("You are now authenticated to app.net. ");
+ set_pconfig(local_user(),'appnet','token', $token);
+ }
+ catch (AppDotNetException $e) {
+ $o .= t("
First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. ');
+ $s .= sprintf(t("Use '%s' as Redirect URI
"
+msgstr ""
+
+#: appnet.php:80
+msgid "return to the connector page"
+msgstr ""
+
+#: appnet.php:94
+msgid "Post to app.net"
+msgstr ""
+
+#: appnet.php:125 appnet.php:129
+msgid "App.net Export"
+msgstr ""
+
+#: appnet.php:142
+msgid "Currently connected to: "
+msgstr ""
+
+#: appnet.php:144
+msgid "Enable App.net Post Plugin"
+msgstr ""
+
+#: appnet.php:149
+msgid "Post to App.net by default"
+msgstr ""
+
+#: appnet.php:153
+msgid "Import the remote timeline"
+msgstr ""
+
+#: appnet.php:159
+msgid ""
+"
Error fetching user profile. Please clear the configuration and try again."
+"
"
+msgstr ""
+
+#: appnet.php:164
+msgid "
You have two ways to connect to App.net.
"
+msgstr ""
+
+#: appnet.php:166
+msgid ""
+"
First way: Register an application at https://account.app.net/developer/apps/ and enter "
+"Client ID and Client Secret. "
+msgstr ""
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
První možnost: Registrovat svou žádost na https://account.app.net/developer/apps/ a zadat Client ID and Client Secret. "
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
Druhá možnost: vložit token do http://dev-lite.jonathonduerig.com/. "
+
+#: appnet.php:178
+msgid ""
+"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', "
+"'Messages'.
"
+msgstr "Nastavte tyto rámce: 'Základní', 'Stream', 'Psaní příspěvků, 'Veřejné zprávy', 'Zprávy'."
+
+#: appnet.php:180
+msgid "Token"
+msgstr "Token"
+
+#: appnet.php:192
+msgid "Sign in using App.net"
+msgstr "Přihlásit se s použitím App.net"
+
+#: appnet.php:197
+msgid "Clear OAuth configuration"
+msgstr "Vymazat konfiguraci OAuth"
+
+#: appnet.php:204
+msgid "Save Settings"
+msgstr "Uložit Nastavení"
diff --git a/appnet/lang/cs/strings.php b/appnet/lang/cs/strings.php
new file mode 100644
index 0000000..4bc4542
--- /dev/null
+++ b/appnet/lang/cs/strings.php
@@ -0,0 +1,29 @@
+=2 && $n<=4) ? 1 : 2;;
+}}
+;
+$a->strings["Permission denied."] = "Přístup odmítnut.";
+$a->strings["You are now authenticated to app.net. "] = "Nyní jste přihlášen k app.net.";
+$a->strings["
Error fetching token. Please try again.
"] = "
Chyba v přenesení tokenu. Prosím zkuste to znovu.
";
+$a->strings["return to the connector page"] = "návrat ke stránce konektor";
+$a->strings["Post to app.net"] = "Poslat příspěvek na app.net";
+$a->strings["App.net Export"] = "App.net Export";
+$a->strings["Currently connected to: "] = "V současné době připojen k:";
+$a->strings["Enable App.net Post Plugin"] = "Aktivovat App.net Post Plugin";
+$a->strings["Post to App.net by default"] = "Defaultně poslat na App.net";
+$a->strings["Import the remote timeline"] = "Importovat vzdálenou časovou osu";
+$a->strings["
Error fetching user profile. Please clear the configuration and try again.
"] = "
Chyba v přenesení uživatelského profilu. Prosím zkuste smazat konfiguraci a zkusit to znovu.
První možnost: Registrovat svou žádost na https://account.app.net/developer/apps/ a zadat Client ID and Client Secret. ";
+$a->strings["Use '%s' as Redirect URI
Erster Weg: Registriere eine Anwendung unter https://account.app.net/developer/apps/ und wähle eine Client ID und ein Client Secret."
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
Erster Weg: Registriere eine Anwendung unter https://account.app.net/developer/apps/ und wähle eine Client ID und ein Client Secret.";
+$a->strings["Use '%s' as Redirect URI
Zweiter Weg: Beantrage ein Token unter http://dev-lite.jonathonduerig.com/. ";
+$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.
"] = "Verwende folgende Scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.";
+$a->strings["Token"] = "Token";
+$a->strings["Sign in using App.net"] = "Per App.net anmelden";
+$a->strings["Clear OAuth configuration"] = "OAuth Konfiguration löschen";
+$a->strings["Save Settings"] = "Einstellungen speichern";
diff --git a/appnet/lang/es/messages.po b/appnet/lang/es/messages.po
new file mode 100644
index 0000000..a44089d
--- /dev/null
+++ b/appnet/lang/es/messages.po
@@ -0,0 +1,118 @@
+# ADDON appnet
+# Copyright (C)
+# This file is distributed under the same license as the Friendica appnet addon package.
+#
+#
+# Translators:
+# Alberto Díaz Tormo , 2016
+msgid ""
+msgstr ""
+"Project-Id-Version: friendica\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-06-22 11:47+0200\n"
+"PO-Revision-Date: 2016-10-13 21:25+0000\n"
+"Last-Translator: Alberto Díaz Tormo \n"
+"Language-Team: Spanish (http://www.transifex.com/Friendica/friendica/language/es/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: es\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+
+#: appnet.php:39
+msgid "Permission denied."
+msgstr "Permiso denegado"
+
+#: appnet.php:73
+msgid "You are now authenticated to app.net. "
+msgstr "Ahora está autenticado en app.net."
+
+#: appnet.php:77
+msgid "
Error fetching token. Please try again.
"
+msgstr "
Advertencia de error. Por favor inténtelo de nuevo.
"
+
+#: appnet.php:80
+msgid "return to the connector page"
+msgstr "vuelva a pa página de conexón"
+
+#: appnet.php:94
+msgid "Post to app.net"
+msgstr "Publique en app.net"
+
+#: appnet.php:125 appnet.php:129
+msgid "App.net Export"
+msgstr "Exportar a app.net"
+
+#: appnet.php:142
+msgid "Currently connected to: "
+msgstr "Actualmente conectado a:"
+
+#: appnet.php:144
+msgid "Enable App.net Post Plugin"
+msgstr "Habilitar el plugin de publicación de App.net"
+
+#: appnet.php:149
+msgid "Post to App.net by default"
+msgstr "Publicar en App.net por defecto"
+
+#: appnet.php:153
+msgid "Import the remote timeline"
+msgstr "Importar la línea de tiempo remota"
+
+#: appnet.php:159
+msgid ""
+"
Error fetching user profile. Please clear the configuration and try "
+"again.
"
+msgstr "
Advertencia de error de perfil. Por favor borre la configuración e inténtelo de nuevo.
Primera forma: Registrar una aplicación en https://account.app.net/developer/apps/ y seleccionar Client ID y Client Secret. "
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
Segunda manera: traiga un símbolo a http://dev-lite.jonathonduerig.com/"
+
+#: appnet.php:178
+msgid ""
+"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', "
+"'Messages'.
"
+msgstr "Seleccione estas posibilidades: 'Básico', 'Continuo', 'Escribir entrada', 'Mensajes públicos', 'Mensajes'."
+
+#: appnet.php:180
+msgid "Token"
+msgstr "Símbolo"
+
+#: appnet.php:192
+msgid "Sign in using App.net"
+msgstr "Regístrese usando App.net"
+
+#: appnet.php:197
+msgid "Clear OAuth configuration"
+msgstr "Borre la configuración OAuth"
+
+#: appnet.php:204
+msgid "Save Settings"
+msgstr "Guardar los ajustes"
diff --git a/appnet/lang/es/strings.php b/appnet/lang/es/strings.php
new file mode 100644
index 0000000..020c6f3
--- /dev/null
+++ b/appnet/lang/es/strings.php
@@ -0,0 +1,29 @@
+strings["Permission denied."] = "Permiso denegado";
+$a->strings["You are now authenticated to app.net. "] = "Ahora está autenticado en app.net.";
+$a->strings["
Error fetching token. Please try again.
"] = "
Advertencia de error. Por favor inténtelo de nuevo.
";
+$a->strings["return to the connector page"] = "vuelva a pa página de conexón";
+$a->strings["Post to app.net"] = "Publique en app.net";
+$a->strings["App.net Export"] = "Exportar a app.net";
+$a->strings["Currently connected to: "] = "Actualmente conectado a:";
+$a->strings["Enable App.net Post Plugin"] = "Habilitar el plugin de publicación de App.net";
+$a->strings["Post to App.net by default"] = "Publicar en App.net por defecto";
+$a->strings["Import the remote timeline"] = "Importar la línea de tiempo remota";
+$a->strings["
Error fetching user profile. Please clear the configuration and try again.
"] = "
Advertencia de error de perfil. Por favor borre la configuración e inténtelo de nuevo.
Primera forma: Registrar una aplicación en https://account.app.net/developer/apps/ y seleccionar Client ID y Client Secret. ";
+$a->strings["Use '%s' as Redirect URI
"] = "Use '%s' como Redirigir URI";
+$a->strings["Client ID"] = "ID de cliente";
+$a->strings["Client Secret"] = "Secreto de cliente";
+$a->strings["
Segunda manera: traiga un símbolo a http://dev-lite.jonathonduerig.com/";
+$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.
"] = "Seleccione estas posibilidades: 'Básico', 'Continuo', 'Escribir entrada', 'Mensajes públicos', 'Mensajes'.";
+$a->strings["Token"] = "Símbolo";
+$a->strings["Sign in using App.net"] = "Regístrese usando App.net";
+$a->strings["Clear OAuth configuration"] = "Borre la configuración OAuth";
+$a->strings["Save Settings"] = "Guardar los ajustes";
diff --git a/appnet/lang/fr/messages.po b/appnet/lang/fr/messages.po
new file mode 100644
index 0000000..6f5f299
--- /dev/null
+++ b/appnet/lang/fr/messages.po
@@ -0,0 +1,119 @@
+# ADDON appnet
+# Copyright (C)
+# This file is distributed under the same license as the Friendica appnet addon package.
+#
+#
+# Translators:
+# Hypolite Petovan , 2016
+# Jak , 2014
+msgid ""
+msgstr ""
+"Project-Id-Version: friendica\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-06-22 11:47+0200\n"
+"PO-Revision-Date: 2016-09-24 02:12+0000\n"
+"Last-Translator: Hypolite Petovan \n"
+"Language-Team: French (http://www.transifex.com/Friendica/friendica/language/fr/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: fr\n"
+"Plural-Forms: nplurals=2; plural=(n > 1);\n"
+
+#: appnet.php:39
+msgid "Permission denied."
+msgstr "Autorisation refusée"
+
+#: appnet.php:73
+msgid "You are now authenticated to app.net. "
+msgstr "Vous êtes maintenant authentifié sur app.net"
+
+#: appnet.php:77
+msgid "
Error fetching token. Please try again.
"
+msgstr "
Impossible d'obtenir le jeton, merci de réessayer.
"
+
+#: appnet.php:80
+msgid "return to the connector page"
+msgstr "revenir à la page du connecteur"
+
+#: appnet.php:94
+msgid "Post to app.net"
+msgstr "Publier sur app.net"
+
+#: appnet.php:125 appnet.php:129
+msgid "App.net Export"
+msgstr "Export App.net"
+
+#: appnet.php:142
+msgid "Currently connected to: "
+msgstr "Actuellement connecté à :"
+
+#: appnet.php:144
+msgid "Enable App.net Post Plugin"
+msgstr "Activer le plugin de publication app.net"
+
+#: appnet.php:149
+msgid "Post to App.net by default"
+msgstr "Publier sur App.net par défaut"
+
+#: appnet.php:153
+msgid "Import the remote timeline"
+msgstr "Importer la timeline distante"
+
+#: appnet.php:159
+msgid ""
+"
Error fetching user profile. Please clear the configuration and try "
+"again.
"
+msgstr "
Impossible d'obtenir le profil utilisateur. Merci de réinitialiser la configuration et de réessayer.
"
+
+#: appnet.php:164
+msgid "
You have two ways to connect to App.net.
"
+msgstr "
Vous avez deux possibilités pour vous connecter à App.net.
Première méthode: Enregistrer une application sur App.net [en] et entrez l'ID Client et le Secret Client. "
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
Deuxième méthode: obtenez un jeton ur http://dev-lite.jonathonduerig.com/ [en]. "
+
+#: appnet.php:178
+msgid ""
+"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', "
+"'Messages'.
"
+msgstr "Cochez les \"scopes\" suivant: \"Basic\", \"Stream\", \"Write Post\", \"Public Messages\", \"Messages\"."
+
+#: appnet.php:180
+msgid "Token"
+msgstr "Jeton"
+
+#: appnet.php:192
+msgid "Sign in using App.net"
+msgstr "Se connecter avec App.net"
+
+#: appnet.php:197
+msgid "Clear OAuth configuration"
+msgstr "Effacer la configuration OAuth"
+
+#: appnet.php:204
+msgid "Save Settings"
+msgstr "Sauvegarder les paramètres"
diff --git a/appnet/lang/fr/strings.php b/appnet/lang/fr/strings.php
new file mode 100644
index 0000000..ef9fc9e
--- /dev/null
+++ b/appnet/lang/fr/strings.php
@@ -0,0 +1,29 @@
+ 1);;
+}}
+;
+$a->strings["Permission denied."] = "Autorisation refusée";
+$a->strings["You are now authenticated to app.net. "] = "Vous êtes maintenant authentifié sur app.net";
+$a->strings["
Error fetching token. Please try again.
"] = "
Impossible d'obtenir le jeton, merci de réessayer.
";
+$a->strings["return to the connector page"] = "revenir à la page du connecteur";
+$a->strings["Post to app.net"] = "Publier sur app.net";
+$a->strings["App.net Export"] = "Export App.net";
+$a->strings["Currently connected to: "] = "Actuellement connecté à :";
+$a->strings["Enable App.net Post Plugin"] = "Activer le plugin de publication app.net";
+$a->strings["Post to App.net by default"] = "Publier sur App.net par défaut";
+$a->strings["Import the remote timeline"] = "Importer la timeline distante";
+$a->strings["
Error fetching user profile. Please clear the configuration and try again.
"] = "
Impossible d'obtenir le profil utilisateur. Merci de réinitialiser la configuration et de réessayer.
";
+$a->strings["
You have two ways to connect to App.net.
"] = "
Vous avez deux possibilités pour vous connecter à App.net.
Deuxième méthode: obtenez un jeton ur http://dev-lite.jonathonduerig.com/ [en]. ";
+$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.
"] = "Cochez les \"scopes\" suivant: \"Basic\", \"Stream\", \"Write Post\", \"Public Messages\", \"Messages\".";
+$a->strings["Token"] = "Jeton";
+$a->strings["Sign in using App.net"] = "Se connecter avec App.net";
+$a->strings["Clear OAuth configuration"] = "Effacer la configuration OAuth";
+$a->strings["Save Settings"] = "Sauvegarder les paramètres";
diff --git a/appnet/lang/it/messages.po b/appnet/lang/it/messages.po
new file mode 100644
index 0000000..17b933f
--- /dev/null
+++ b/appnet/lang/it/messages.po
@@ -0,0 +1,118 @@
+# ADDON appnet
+# Copyright (C)
+# This file is distributed under the same license as the Friendica appnet addon package.
+#
+#
+# Translators:
+# fabrixxm , 2014
+msgid ""
+msgstr ""
+"Project-Id-Version: friendica\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-06-22 11:47+0200\n"
+"PO-Revision-Date: 2014-09-10 10:18+0000\n"
+"Last-Translator: fabrixxm \n"
+"Language-Team: Italian (http://www.transifex.com/Friendica/friendica/language/it/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: it\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+
+#: appnet.php:39
+msgid "Permission denied."
+msgstr "Permesso negato."
+
+#: appnet.php:73
+msgid "You are now authenticated to app.net. "
+msgstr "Sei autenticato su app.net"
+
+#: appnet.php:77
+msgid "
Error fetching token. Please try again.
"
+msgstr "
Errore recuperando il token. Prova di nuovo
"
+
+#: appnet.php:80
+msgid "return to the connector page"
+msgstr "ritorna alla pagina del connettore"
+
+#: appnet.php:94
+msgid "Post to app.net"
+msgstr "Invia ad app.net"
+
+#: appnet.php:125 appnet.php:129
+msgid "App.net Export"
+msgstr "Esporta App.net"
+
+#: appnet.php:142
+msgid "Currently connected to: "
+msgstr "Al momento connesso con:"
+
+#: appnet.php:144
+msgid "Enable App.net Post Plugin"
+msgstr "Abilita il plugin di invio ad App.net"
+
+#: appnet.php:149
+msgid "Post to App.net by default"
+msgstr "Invia sempre ad App.net"
+
+#: appnet.php:153
+msgid "Import the remote timeline"
+msgstr "Importa la timeline remota"
+
+#: appnet.php:159
+msgid ""
+"
Error fetching user profile. Please clear the configuration and try "
+"again.
"
+msgstr "
Errore recuperando il profilo utente. Svuota la configurazione e prova di nuovo.
Registrare un'applicazione su https://account.app.net/developer/apps/ e inserire Client ID e Client Secret."
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
Oppure puoi recuperare un token su http://dev-lite.jonathonduerig.com/."
+
+#: appnet.php:178
+msgid ""
+"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', "
+"'Messages'.
"
+msgstr "Imposta gli ambiti 'Basic', 'Stream', 'Scrivi Post', 'Messaggi Pubblici', 'Messaggi'."
+
+#: appnet.php:180
+msgid "Token"
+msgstr "Token"
+
+#: appnet.php:192
+msgid "Sign in using App.net"
+msgstr "Autenticati con App.net"
+
+#: appnet.php:197
+msgid "Clear OAuth configuration"
+msgstr "Pulisci configurazione OAuth"
+
+#: appnet.php:204
+msgid "Save Settings"
+msgstr "Salva Impostazioni"
diff --git a/appnet/lang/it/strings.php b/appnet/lang/it/strings.php
new file mode 100644
index 0000000..01c5652
--- /dev/null
+++ b/appnet/lang/it/strings.php
@@ -0,0 +1,29 @@
+strings["Permission denied."] = "Permesso negato.";
+$a->strings["You are now authenticated to app.net. "] = "Sei autenticato su app.net";
+$a->strings["
Error fetching token. Please try again.
"] = "
Errore recuperando il token. Prova di nuovo
";
+$a->strings["return to the connector page"] = "ritorna alla pagina del connettore";
+$a->strings["Post to app.net"] = "Invia ad app.net";
+$a->strings["App.net Export"] = "Esporta App.net";
+$a->strings["Currently connected to: "] = "Al momento connesso con:";
+$a->strings["Enable App.net Post Plugin"] = "Abilita il plugin di invio ad App.net";
+$a->strings["Post to App.net by default"] = "Invia sempre ad App.net";
+$a->strings["Import the remote timeline"] = "Importa la timeline remota";
+$a->strings["
Error fetching user profile. Please clear the configuration and try again.
"] = "
Errore recuperando il profilo utente. Svuota la configurazione e prova di nuovo.
Oppure puoi recuperare un token su http://dev-lite.jonathonduerig.com/.";
+$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.
"] = "Imposta gli ambiti 'Basic', 'Stream', 'Scrivi Post', 'Messaggi Pubblici', 'Messaggi'.";
+$a->strings["Token"] = "Token";
+$a->strings["Sign in using App.net"] = "Autenticati con App.net";
+$a->strings["Clear OAuth configuration"] = "Pulisci configurazione OAuth";
+$a->strings["Save Settings"] = "Salva Impostazioni";
diff --git a/appnet/lang/nl/messages.po b/appnet/lang/nl/messages.po
new file mode 100644
index 0000000..74653c7
--- /dev/null
+++ b/appnet/lang/nl/messages.po
@@ -0,0 +1,118 @@
+# ADDON appnet
+# Copyright (C)
+# This file is distributed under the same license as the Friendica appnet addon package.
+#
+#
+# Translators:
+# Jeroen S , 2016
+msgid ""
+msgstr ""
+"Project-Id-Version: friendica\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-06-22 11:47+0200\n"
+"PO-Revision-Date: 2016-06-23 19:52+0000\n"
+"Last-Translator: Jeroen S \n"
+"Language-Team: Dutch (http://www.transifex.com/Friendica/friendica/language/nl/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: nl\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+
+#: appnet.php:39
+msgid "Permission denied."
+msgstr "Toegang geweigerd"
+
+#: appnet.php:73
+msgid "You are now authenticated to app.net. "
+msgstr "Je bent nu aangemeld bij app.net."
+
+#: appnet.php:77
+msgid "
Error fetching token. Please try again.
"
+msgstr "
Fout tijdens token fetching. Probeer het nogmaals.
"
+
+#: appnet.php:80
+msgid "return to the connector page"
+msgstr "ga terug naar de connector pagina"
+
+#: appnet.php:94
+msgid "Post to app.net"
+msgstr "Post naar app.net."
+
+#: appnet.php:125 appnet.php:129
+msgid "App.net Export"
+msgstr "App.net Export"
+
+#: appnet.php:142
+msgid "Currently connected to: "
+msgstr "Momenteel verbonden met:"
+
+#: appnet.php:144
+msgid "Enable App.net Post Plugin"
+msgstr "App.net Post Plugin inschakelen"
+
+#: appnet.php:149
+msgid "Post to App.net by default"
+msgstr "Naar App.net posten als standaard instellen"
+
+#: appnet.php:153
+msgid "Import the remote timeline"
+msgstr "The tijdlijn op afstand importeren"
+
+#: appnet.php:159
+msgid ""
+"
Error fetching user profile. Please clear the configuration and try "
+"again.
"
+msgstr "
Fout tijdens het ophalen van gebruikersprofiel. Leeg de configuratie en probeer het opnieuw.
"
+
+#: appnet.php:164
+msgid "
You have two ways to connect to App.net.
"
+msgstr "
Er zijn twee manieren om met App.net te verbinden.
"
+
+#: appnet.php:166
+msgid ""
+"
First way: Register an application at https://account.app.net/developer/apps/"
+" and enter Client ID and Client Secret. "
+msgstr ""
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "
+msgstr ""
+
+#: appnet.php:178
+msgid ""
+"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', "
+"'Messages'.
"
+msgstr ""
+
+#: appnet.php:180
+msgid "Token"
+msgstr ""
+
+#: appnet.php:192
+msgid "Sign in using App.net"
+msgstr ""
+
+#: appnet.php:197
+msgid "Clear OAuth configuration"
+msgstr ""
+
+#: appnet.php:204
+msgid "Save Settings"
+msgstr ""
diff --git a/appnet/lang/nl/strings.php b/appnet/lang/nl/strings.php
new file mode 100644
index 0000000..ba72e36
--- /dev/null
+++ b/appnet/lang/nl/strings.php
@@ -0,0 +1,29 @@
+strings["Permission denied."] = "Toegang geweigerd";
+$a->strings["You are now authenticated to app.net. "] = "Je bent nu aangemeld bij app.net.";
+$a->strings["
Error fetching token. Please try again.
"] = "
Fout tijdens token fetching. Probeer het nogmaals.
";
+$a->strings["return to the connector page"] = "ga terug naar de connector pagina";
+$a->strings["Post to app.net"] = "Post naar app.net.";
+$a->strings["App.net Export"] = "App.net Export";
+$a->strings["Currently connected to: "] = "Momenteel verbonden met:";
+$a->strings["Enable App.net Post Plugin"] = "App.net Post Plugin inschakelen";
+$a->strings["Post to App.net by default"] = "Naar App.net posten als standaard instellen";
+$a->strings["Import the remote timeline"] = "The tijdlijn op afstand importeren";
+$a->strings["
Error fetching user profile. Please clear the configuration and try again.
"] = "
Fout tijdens het ophalen van gebruikersprofiel. Leeg de configuratie en probeer het opnieuw.
";
+$a->strings["
You have two ways to connect to App.net.
"] = "
Er zijn twee manieren om met App.net te verbinden.
";
+$a->strings["
First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "";
+$a->strings["Use '%s' as Redirect URI
Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "";
+$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.
"] = "";
+$a->strings["Token"] = "";
+$a->strings["Sign in using App.net"] = "";
+$a->strings["Clear OAuth configuration"] = "";
+$a->strings["Save Settings"] = "";
diff --git a/appnet/lang/pt-br/messages.po b/appnet/lang/pt-br/messages.po
new file mode 100644
index 0000000..c279c7d
--- /dev/null
+++ b/appnet/lang/pt-br/messages.po
@@ -0,0 +1,119 @@
+# ADDON appnet
+# Copyright (C)
+# This file is distributed under the same license as the Friendica appnet addon package.
+#
+#
+# Translators:
+# Beatriz Vital , 2016
+# Calango Jr , 2014
+msgid ""
+msgstr ""
+"Project-Id-Version: friendica\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-06-22 11:47+0200\n"
+"PO-Revision-Date: 2016-08-19 20:37+0000\n"
+"Last-Translator: Beatriz Vital \n"
+"Language-Team: Portuguese (Brazil) (http://www.transifex.com/Friendica/friendica/language/pt_BR/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: pt_BR\n"
+"Plural-Forms: nplurals=2; plural=(n > 1);\n"
+
+#: appnet.php:39
+msgid "Permission denied."
+msgstr "Permissão negada."
+
+#: appnet.php:73
+msgid "You are now authenticated to app.net. "
+msgstr "Você está autenticado no app.net."
+
+#: appnet.php:77
+msgid "
Error fetching token. Please try again.
"
+msgstr "Erro ocorrido na obtenção do token. Tente novamente."
+
+#: appnet.php:80
+msgid "return to the connector page"
+msgstr "Volte a página de conectores."
+
+#: appnet.php:94
+msgid "Post to app.net"
+msgstr "Publicar no App.net"
+
+#: appnet.php:125 appnet.php:129
+msgid "App.net Export"
+msgstr "App.net exportar"
+
+#: appnet.php:142
+msgid "Currently connected to: "
+msgstr "Atualmente conectado em: "
+
+#: appnet.php:144
+msgid "Enable App.net Post Plugin"
+msgstr "Habilitar plug-in para publicar no App.net"
+
+#: appnet.php:149
+msgid "Post to App.net by default"
+msgstr "Publicar em App.net por padrão"
+
+#: appnet.php:153
+msgid "Import the remote timeline"
+msgstr "Importar a linha do tempo remota"
+
+#: appnet.php:159
+msgid ""
+"
Error fetching user profile. Please clear the configuration and try "
+"again.
"
+msgstr "Erro na obtenção do perfil do usuário. Confira as configurações e tente novamente."
+
+#: appnet.php:164
+msgid "
1º Método: Registre uma aplicação em https://account.app.net/developer/apps/ e entre o Client ID e Client Secret"
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
2º Método: obtenha um token em http://dev-lite.jonathonduerig.com/. "
+
+#: appnet.php:178
+msgid ""
+"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', "
+"'Messages'.
"
+msgstr "Adicione valor as estas saídas: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'."
+
+#: appnet.php:180
+msgid "Token"
+msgstr "Token"
+
+#: appnet.php:192
+msgid "Sign in using App.net"
+msgstr "Entre usando o App.net"
+
+#: appnet.php:197
+msgid "Clear OAuth configuration"
+msgstr "Limpar configuração OAuth"
+
+#: appnet.php:204
+msgid "Save Settings"
+msgstr "Salvar Configurações"
diff --git a/appnet/lang/pt-br/strings.php b/appnet/lang/pt-br/strings.php
new file mode 100644
index 0000000..b8e1112
--- /dev/null
+++ b/appnet/lang/pt-br/strings.php
@@ -0,0 +1,29 @@
+ 1);;
+}}
+;
+$a->strings["Permission denied."] = "Permissão negada.";
+$a->strings["You are now authenticated to app.net. "] = "Você está autenticado no app.net.";
+$a->strings["
Error fetching token. Please try again.
"] = "Erro ocorrido na obtenção do token. Tente novamente.";
+$a->strings["return to the connector page"] = "Volte a página de conectores.";
+$a->strings["Post to app.net"] = "Publicar no App.net";
+$a->strings["App.net Export"] = "App.net exportar";
+$a->strings["Currently connected to: "] = "Atualmente conectado em: ";
+$a->strings["Enable App.net Post Plugin"] = "Habilitar plug-in para publicar no App.net";
+$a->strings["Post to App.net by default"] = "Publicar em App.net por padrão";
+$a->strings["Import the remote timeline"] = "Importar a linha do tempo remota";
+$a->strings["
Error fetching user profile. Please clear the configuration and try again.
"] = "Erro na obtenção do perfil do usuário. Confira as configurações e tente novamente.";
+$a->strings["
Prima modalitate: Înregistrați o cerere pe https://account.app.net/developer/apps/ şi introduceți ID Client şi Cheia Secretă Client."
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
"
+msgstr "Utilizați '%s' ca URI de Redirecţionare
A doua cale: autorizați un indicativ de acces token de pe http://dev-lite.jonathonduerig.com/ ."
+
+#: appnet.php:178
+msgid ""
+"Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', "
+"'Messages'.
Eroare la procesarea token-ului. Vă rugăm să reîncercați.
";
+$a->strings["return to the connector page"] = "revenire la pagina de conectare";
+$a->strings["Post to app.net"] = "Postați pe App.net";
+$a->strings["App.net Export"] = "Exportare pe App.net";
+$a->strings["Currently connected to: "] = "Conectat curent la:";
+$a->strings["Enable App.net Post Plugin"] = "Activare Modul Postare pe App.net";
+$a->strings["Post to App.net by default"] = "Postați implicit pe App.net";
+$a->strings["Import the remote timeline"] = "Importare cronologie la distanță";
+$a->strings["
Error fetching user profile. Please clear the configuration and try again.
"] = "
Eroare la procesarea profilului de utilizator. Vă rugăm să ștergeți configurarea şi apoi reîncercați.
Prima modalitate: Înregistrați o cerere pe https://account.app.net/developer/apps/ şi introduceți ID Client şi Cheia Secretă Client.";
+$a->strings["Use '%s' as Redirect URI
A doua cale: autorizați un indicativ de acces token de pe http://dev-lite.jonathonduerig.com/ .";
+$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.
"] = "Stabiliți aceste scopuri: 'De Bază', 'Flux', 'Scriere Postare', 'Mesaje Publice', 'Mesaje'.";
+$a->strings["Token"] = "Token";
+$a->strings["Sign in using App.net"] = "Autentificați-vă utilizând App.net";
+$a->strings["Clear OAuth configuration"] = "Ștergeți configurările OAuth";
+$a->strings["Save Settings"] = "Salvare Configurări";
diff --git a/appnet/lang/ru/messages.po b/appnet/lang/ru/messages.po
new file mode 100644
index 0000000..a5755ca
--- /dev/null
+++ b/appnet/lang/ru/messages.po
@@ -0,0 +1,118 @@
+# ADDON appnet
+# Copyright (C)
+# This file is distributed under the same license as the Friendica appnet addon package.
+#
+#
+# Translators:
+# Stanislav N. , 2017
+msgid ""
+msgstr ""
+"Project-Id-Version: friendica\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2014-06-22 11:47+0200\n"
+"PO-Revision-Date: 2017-04-08 05:32+0000\n"
+"Last-Translator: Stanislav N. \n"
+"Language-Team: Russian (http://www.transifex.com/Friendica/friendica/language/ru/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: ru\n"
+"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);\n"
+
+#: appnet.php:39
+msgid "Permission denied."
+msgstr "Доступ запрещен."
+
+#: appnet.php:73
+msgid "You are now authenticated to app.net. "
+msgstr "Вы аутентифицированы на app.net"
+
+#: appnet.php:77
+msgid "
Error fetching token. Please try again.
"
+msgstr "
Ошибка получения токена. Попробуйте еще раз.
"
+
+#: appnet.php:80
+msgid "return to the connector page"
+msgstr "вернуться на страницу коннектора"
+
+#: appnet.php:94
+msgid "Post to app.net"
+msgstr "Отправить на app.net"
+
+#: appnet.php:125 appnet.php:129
+msgid "App.net Export"
+msgstr "Экспорт app.net"
+
+#: appnet.php:142
+msgid "Currently connected to: "
+msgstr "В настоящее время соединены с: "
+
+#: appnet.php:144
+msgid "Enable App.net Post Plugin"
+msgstr "Включить плагин App.net"
+
+#: appnet.php:149
+msgid "Post to App.net by default"
+msgstr "Отправлять сообщения на App.net по-умолчанию"
+
+#: appnet.php:153
+msgid "Import the remote timeline"
+msgstr "Импортировать удаленные сообщения"
+
+#: appnet.php:159
+msgid ""
+"
Error fetching user profile. Please clear the configuration and try "
+"again.
"
+msgstr "
Ошибка при получении профиля пользователя. Сбросьте конфигурацию и попробуйте еще раз.
Первый способ: зарегистрируйте приложение на https://account.app.net/developer/apps/ и введите Client ID и Client Secret"
+
+#: appnet.php:167
+#, php-format
+msgid "Use '%s' as Redirect URI
";
+$a->strings["return to the connector page"] = "вернуться на страницу коннектора";
+$a->strings["Post to app.net"] = "Отправить на app.net";
+$a->strings["App.net Export"] = "Экспорт app.net";
+$a->strings["Currently connected to: "] = "В настоящее время соединены с: ";
+$a->strings["Enable App.net Post Plugin"] = "Включить плагин App.net";
+$a->strings["Post to App.net by default"] = "Отправлять сообщения на App.net по-умолчанию";
+$a->strings["Import the remote timeline"] = "Импортировать удаленные сообщения";
+$a->strings["
Error fetching user profile. Please clear the configuration and try again.
"] = "
Ошибка при получении профиля пользователя. Сбросьте конфигурацию и попробуйте еще раз.
Первый способ: зарегистрируйте приложение на https://account.app.net/developer/apps/ и введите Client ID и Client Secret";
+$a->strings["Use '%s' as Redirect URI
Второй путь: получите токен на http://dev-lite.jonathonduerig.com/. ";
+$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.
"] = "Выберите области: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.";
+$a->strings["Token"] = "Токен";
+$a->strings["Sign in using App.net"] = "Войти через App.net";
+$a->strings["Clear OAuth configuration"] = "Удалить конфигурацию OAuth";
+$a->strings["Save Settings"] = "Сохранить настройки";
diff --git a/appnet/lastid.txt b/appnet/lastid.txt
new file mode 100644
index 0000000..959417e
--- /dev/null
+++ b/appnet/lastid.txt
@@ -0,0 +1 @@
+36406925
\ No newline at end of file
diff --git a/appnet/sync.php b/appnet/sync.php
new file mode 100644
index 0000000..5da79dd
--- /dev/null
+++ b/appnet/sync.php
@@ -0,0 +1,514 @@
+set_baseurl(get_config('system','url'));
+
+//require_once("addon/appnet/appnet.php");
+
+$uid = 1;
+appnet_fetchstream($a, $uid);
+
+function appnet_fetchstream($a, $uid) {
+ require_once("addon/appnet/AppDotNet.php");
+ require_once('include/items.php');
+
+ $token = get_pconfig($uid,'appnet','token');
+ $clientId = get_pconfig($uid,'appnet','clientid');
+ $clientSecret = get_pconfig($uid,'appnet','clientsecret');
+
+ $app = new AppDotNet($clientId, $clientSecret);
+ $app->setAccessToken($token);
+
+ $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
+ intval($uid));
+
+ if(count($r))
+ $me = $r[0];
+ else {
+ logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
+ return;
+ }
+
+ $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
+ intval($uid)
+ );
+
+ if(count($user))
+ $user = $user[0];
+ else {
+ logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
+ return;
+ }
+
+ $ownid = get_pconfig($uid,'appnet','ownid');
+
+ $param = array("include_annotations" => true);
+ $post = $app->getPost(32189565, $param);
+ //$post = $app->getPost(32166492, $param);
+ //$post = $app->getPost(32166065, $param);
+ //$post = $app->getPost(32161780, $param);
+ $postarray = appnet2_createpost($a, $uid, $post, $me, $user, $ownid, false);
+print_r($postarray);
+// $item = item_store($postarray);
+ die();
+
+
+ // Fetch stream
+ $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, "include_html" => false, "include_annotations" => true);
+
+ $lastid = get_pconfig($uid, 'appnet', 'laststreamid');
+
+ if ($lastid <> "")
+ $param["since_id"] = $lastid;
+
+ try {
+ $stream = $app->getUserStream($param);
+ }
+ catch (AppDotNetException $e) {
+ logger("appnet_fetchstream: Error fetching stream for user ".$uid);
+ }
+
+ $stream = array_reverse($stream);
+ foreach ($stream AS $post) {
+ $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
+
+ $item = item_store($postarray);
+ logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
+
+ $lastid = $post["id"];
+
+ if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
+ $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
+ INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
+ WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
+
+ if (count($r)) {
+ require_once('include/enotify.php');
+ notification(array(
+ 'type' => NOTIFY_COMMENT,
+ 'notify_flags' => $user['notify-flags'],
+ 'language' => $user['language'],
+ 'to_name' => $user['username'],
+ 'to_email' => $user['email'],
+ 'uid' => $user['uid'],
+ 'item' => $postarray,
+ 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
+ 'source_name' => $postarray['author-name'],
+ 'source_link' => $postarray['author-link'],
+ 'source_photo' => $postarray['author-avatar'],
+ 'verb' => ACTIVITY_POST,
+ 'otype' => 'item',
+ 'parent' => $r[0]["parent"],
+ ));
+ }
+ }
+ }
+
+ set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
+
+ // Fetch mentions
+ $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, "include_html" => false, "include_annotations" => true);
+
+ $lastid = get_pconfig($uid, 'appnet', 'lastmentionid');
+
+ if ($lastid <> "")
+ $param["since_id"] = $lastid;
+
+ try {
+ $mentions = $app->getUserMentions("me", $param);
+ }
+ catch (AppDotNetException $e) {
+ logger("appnet_fetchstream: Error fetching mentions for user ".$uid);
+ }
+
+ $mentions = array_reverse($mentions);
+ foreach ($mentions AS $post) {
+ $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
+
+ if (isset($postarray["id"]))
+ $item = $postarray["id"];
+ elseif (isset($postarray["body"])) {
+ $item = item_store($postarray);
+ logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
+ } else
+ $item = 0;
+
+ $lastid = $post["id"];
+
+ if ($item != 0) {
+ require_once('include/enotify.php');
+ notification(array(
+ 'type' => NOTIFY_TAGSELF,
+ 'notify_flags' => $user['notify-flags'],
+ 'language' => $user['language'],
+ 'to_name' => $user['username'],
+ 'to_email' => $user['email'],
+ 'uid' => $user['uid'],
+ 'item' => $postarray,
+ 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
+ 'source_name' => $postarray['author-name'],
+ 'source_link' => $postarray['author-link'],
+ 'source_photo' => $postarray['author-avatar'],
+ 'verb' => ACTIVITY_TAG,
+ 'otype' => 'item'
+ ));
+ }
+ }
+
+ set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
+
+
+/* To-Do
+ $param = array("interaction_actions" => "star");
+ $interactions = $app->getMyInteractions($param);
+ foreach ($interactions AS $interaction)
+ appnet_dolike($a, $uid, $interaction);
+*/
+}
+
+function appnet2_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true) {
+ require_once('include/items.php');
+
+ if ($post["machine_only"])
+ return;
+
+ if ($post["is_deleted"])
+ return;
+
+ $postarray = array();
+ $postarray['gravity'] = 0;
+ $postarray['uid'] = $uid;
+ $postarray['wall'] = 0;
+ $postarray['verb'] = ACTIVITY_POST;
+ $postarray['network'] = dbesc(NETWORK_APPNET);
+ $postarray['uri'] = "adn::".$post["id"];
+
+ $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+ dbesc($postarray['uri']),
+ intval($uid)
+ );
+
+// if (count($r))
+// return($r[0]);
+
+ $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
+ dbesc($postarray['uri']),
+ intval($uid)
+ );
+
+// if (count($r))
+// return($r[0]);
+
+ $postarray['parent-uri'] = "adn::".$post["thread_id"];
+ if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
+ $postarray['thr-parent'] = "adn::".$post["reply_to"];
+
+ // Complete the thread if the parent doesn't exists
+ if ($threadcompletion) {
+ $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
+ dbesc($postarray['thr-parent']),
+ intval($uid)
+ );
+ if (!count($r)) {
+ require_once("addon/appnet/AppDotNet.php");
+
+ $token = get_pconfig($uid,'appnet','token');
+ $clientId = get_pconfig($uid,'appnet','clientid');
+ $clientSecret = get_pconfig($uid,'appnet','clientsecret');
+
+ $app = new AppDotNet($clientId, $clientSecret);
+ $app->setAccessToken($token);
+
+ $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, "include_html" => false, "include_annotations" => true);
+ try {
+ $thread = $app->getPostReplies($post["thread_id"], $param);
+ }
+ catch (AppDotNetException $e) {
+ logger("appnet_createpost: Error fetching thread for user ".$uid);
+ }
+ $thread = array_reverse($thread);
+ foreach ($thread AS $tpost) {
+ $threadpost = appnet2_createpost($a, $uid, $tpost, $me, $user, $ownid, $createuser, false);
+ $item = item_store($threadpost);
+ }
+ }
+ }
+ } else
+ $postarray['thr-parent'] = $postarray['uri'];
+
+ $postarray['plink'] = $post["canonical_url"];
+
+ if ($post["user"]["id"] != $ownid) {
+ $postarray['owner-name'] = $post["user"]["name"];
+ $postarray['owner-link'] = $post["user"]["canonical_url"];
+ $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
+ $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
+ } else {
+ $postarray['owner-name'] = $me["name"];
+ $postarray['owner-link'] = $me["url"];
+ $postarray['owner-avatar'] = $me["thumb"];
+ $postarray['contact-id'] = $me["id"];
+ }
+
+ $links = array();
+
+ if (is_array($post["repost_of"])) {
+ $postarray['author-name'] = $post["repost_of"]["user"]["name"];
+ $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
+ $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
+
+ $content = $post["repost_of"];
+ } else {
+ $postarray['author-name'] = $postarray['owner-name'];
+ $postarray['author-link'] = $postarray['owner-link'];
+ $postarray['author-avatar'] = $postarray['owner-avatar'];
+
+ $content = $post;
+ }
+
+ if (is_array($content["entities"])) {
+ $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
+ $postarray['body'] = $converted["body"];
+ $postarray['tag'] = $converted["tags"];
+ } else
+ $postarray['body'] = $content["text"];
+
+ if (is_array($content["annotations"]))
+ $postarray['body'] = appnet_expand_annotations($a, $postarray['body'], $content["annotations"]);
+
+ if (sizeof($content["entities"]["links"]))
+ foreach($content["entities"]["links"] AS $link) {
+ $url = normalise_link($link["url"]);
+ $links[$url] = $url;
+ }
+
+ if (sizeof($content["annotations"]))
+ foreach($content["annotations"] AS $annotation) {
+ if (isset($annotation["value"]["embeddable_url"])) {
+ $url = normalise_link($annotation["value"]["embeddable_url"]);
+ if (isset($links[$url]))
+ unset($links[$url]);
+ }
+ }
+
+ if (sizeof($links)) {
+ $link = array_pop($links);
+ $url = "[url=".$link."]".$link."[/url]";
+
+ $removedlink = trim(str_replace($url, "", $postarray['body']));
+
+ if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
+ $postarray['body'] = $removedlink;
+
+ $postarray['body'] .= add_page_info($link);
+ }
+
+ $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
+ $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
+
+ $postarray['app'] = $post["source"]["name"];
+
+ return($postarray);
+ //print_r($postarray);
+ //print_r($post);
+}
+
+function appnet_expand_entities($a, $body, $entities) {
+
+ if (!function_exists('substr_unicode')) {
+ function substr_unicode($str, $s, $l = null) {
+ return join("", array_slice(
+ preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
+ }
+ }
+
+ $tags_arr = array();
+ $replace = array();
+
+ foreach ($entities["mentions"] AS $mention) {
+ $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
+ $tags_arr["@".$mention["name"]] = $url;
+ $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
+ }
+
+ foreach ($entities["hashtags"] AS $hashtag) {
+ $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
+ $tags_arr["#".$hashtag["name"]] = $url;
+ $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
+ }
+
+ foreach ($entities["links"] AS $links) {
+ $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
+ $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
+ }
+
+
+ if (sizeof($replace)) {
+ krsort($replace);
+ foreach ($replace AS $entity) {
+ $pre = substr_unicode($body, 0, $entity["pos"]);
+ $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
+
+ $body = $pre.$entity["replace"].$post;
+ }
+ }
+
+ return(array("body" => $body, "tags" => implode($tags_arr, ",")));
+}
+
+function appnet_expand_annotations($a, $body, $annotations) {
+ foreach ($annotations AS $annotation) {
+ if ($annotation["value"]["type"] == "photo") {
+ if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
+ $body .= "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
+ elseif ($annotation["value"]["url"] != "")
+ $body .= "\n[img]".$annotation["value"]["url"]."[/img]";
+ }
+ }
+ return $body;
+}
+
+function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
+ $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
+ intval($uid), dbesc("adn::".$contact["id"]));
+
+ if(!count($r) AND !$create_user)
+ return($me);
+
+
+ if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
+ logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
+ return(-1);
+ }
+
+ if(!count($r)) {
+ // create contact record
+ q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
+ `name`, `nick`, `photo`, `network`, `rel`, `priority`,
+ `writable`, `blocked`, `readonly`, `pending` )
+ VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
+ intval($uid),
+ dbesc(datetime_convert()),
+ dbesc($contact["canonical_url"]),
+ dbesc(normalise_link($contact["canonical_url"])),
+ dbesc($contact["username"]."@app.net"),
+ dbesc("adn::".$contact["id"]),
+ dbesc(''),
+ dbesc("adn::".$contact["id"]),
+ dbesc($contact["name"]),
+ dbesc($contact["username"]),
+ dbesc($contact["avatar_image"]["url"]),
+ dbesc(NETWORK_APPNET),
+ intval(CONTACT_IS_FRIEND),
+ intval(1),
+ intval(1)
+ );
+
+ $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
+ dbesc("adn::".$contact["id"]),
+ intval($uid)
+ );
+
+ if(! count($r))
+ return(false);
+
+ $contact_id = $r[0]['id'];
+
+ $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
+ intval($uid)
+ );
+
+ if($g && intval($g[0]['def_gid'])) {
+ require_once('include/group.php');
+ group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
+ }
+
+ require_once("Photo.php");
+
+ $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
+
+ q("UPDATE `contact` SET `photo` = '%s',
+ `thumb` = '%s',
+ `micro` = '%s',
+ `name-date` = '%s',
+ `uri-date` = '%s',
+ `avatar-date` = '%s'
+ WHERE `id` = %d",
+ dbesc($photos[0]),
+ dbesc($photos[1]),
+ dbesc($photos[2]),
+ dbesc(datetime_convert()),
+ dbesc(datetime_convert()),
+ dbesc(datetime_convert()),
+ intval($contact_id)
+ );
+
+ } else {
+ // update profile photos once every two weeks as we have no notification of when they change.
+
+ //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
+ $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
+
+ // check that we have all the photos, this has been known to fail on occasion
+
+ if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
+
+ logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
+
+ require_once("Photo.php");
+
+ $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
+
+ q("UPDATE `contact` SET `photo` = '%s',
+ `thumb` = '%s',
+ `micro` = '%s',
+ `name-date` = '%s',
+ `uri-date` = '%s',
+ `avatar-date` = '%s',
+ `url` = '%s',
+ `nurl` = '%s',
+ `addr` = '%s',
+ `name` = '%s',
+ `nick` = '%s'
+ WHERE `id` = %d",
+ dbesc($photos[0]),
+ dbesc($photos[1]),
+ dbesc($photos[2]),
+ dbesc(datetime_convert()),
+ dbesc(datetime_convert()),
+ dbesc(datetime_convert()),
+ dbesc($contact["canonical_url"]),
+ dbesc(normalise_link($contact["canonical_url"])),
+ dbesc($contact["username"]."@app.net"),
+ dbesc($contact["username"]),
+ dbesc($contact["name"]),
+ intval($r[0]['id'])
+ );
+ }
+ }
+
+ return($r[0]["id"]);
+}
+
+// starPost
+// unstarPost
+// repost
+// deleteRepost
diff --git a/appnet/templates/admin.tpl b/appnet/templates/admin.tpl
new file mode 100644
index 0000000..a933f3d
--- /dev/null
+++ b/appnet/templates/admin.tpl
@@ -0,0 +1,3 @@
+{{include file="field_input.tpl" field=$clientid}}
+{{include file="field_input.tpl" field=$clientsecret}}
+
diff --git a/appnet/test.php b/appnet/test.php
new file mode 100644
index 0000000..6e1b071
--- /dev/null
+++ b/appnet/test.php
@@ -0,0 +1,256 @@
+set_baseurl(get_config('system','url'));
+
+require_once("addon/appnet/appnet.php");
+require_once("include/plaintext.php");
+
+$b['uid'] = 1;
+
+$token = get_pconfig($b['uid'],'appnet','token');
+
+require_once 'addon/appnet/AppDotNet.php';
+
+$clientId = get_pconfig($b["uid"],'appnet','clientid');
+$clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
+
+$app = new AppDotNet($clientId, $clientSecret);
+$app->setAccessToken($token);
+
+//$param = array("include_annotations" => true);
+//$param = array("include_muted" => true, "include_directed_posts" => true);
+$param = array("include_muted" => true, "include_deleted" => false, "include_directed_posts" => true,
+ "include_html" => false, "include_post_annotations" => true);
+
+
+//$param = array("include_post_annotations" => true, "include_muted" => true, "include_directed_posts" => true);
+//$post = $app->getPost(37154801, $param);
+$post = $app->getPost(37189594, $param);
+//$post = $app->getPost(36892980, $param);
+//$post = $app->getPost(36837961, $param);
+//$post = $app->getPost(36843534, $param);
+
+print_r($post);
+die();
+
+$r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
+ intval($b['uid']));
+
+if(count($r))
+ $me = $r[0];
+
+$ownid = get_pconfig($b['uid'],'appnet','ownid');
+
+$user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
+ intval($b['uid'])
+ );
+
+ if(count($user))
+ $user = $user[0];
+
+$test = appnet_createpost($a, $b['uid'], $post, $me, $user, $ownid, true, false, true);
+
+print_r($test);
+
+die();
+
+
+
+/*
+$recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
+
+$post = "♲ AdoraBelle (_Adora_Belle_@twitter.com): They are a little tied up... *rofl* @Shysarah2009 @AldiCustCare";
+
+$post = str_replace($recycle, ">> ", $post);
+//$post = preg_replace("=".$recycle." (.*) \((.*)@(.*)\)=ism", ">> $1 ($2@$3)", $ppost);
+//$post = preg_replace("=".$recycle."(.*)=ism", ">> $1", $ppost);
+
+die($post);
+*/
+$b["uid"] = 1;
+$b["plink"] = "https://pirati.ca/display/heluecht/2834617";
+//$b["title"] = "Wenn sich Microsoft per Telefon meldet, sollte man stutzig werden.";
+
+// Image
+$b["body"] = "Nur ein kleiner Test, bitte ignorieren. (wird sowieso sofort wieder gelöscht)
+[url=https://lh3.googleusercontent.com/-5J1tGHGvELQ/U2EL_6RuAHI/AAAAAAAAX5U/71dlHNFUjXw/30.04.14%2B-%2B1][img=479x640]https://lh3.googleusercontent.com/-5J1tGHGvELQ/U2EL_6RuAHI/AAAAAAAAX5U/71dlHNFUjXw/w506-h750/30.04.14%2B-%2B1[/img]
+[/url]";
+
+/*
+$b["body"] = "Übrigens: Früher #[url=http://www.dabo.de]war[/url] alles besser.
+
+[bookmark=https://www.youtube.com/watch?v=-8yF9zqlpR4]SALTATIO MORTIS - Früher war alles besser | Napalm Records[/bookmark]";
+*/
+$b["body"] = "Umfrageergebnisse aus der [url=http://www.heise.de]Hölle.[/url] In [url=http://www.heise.de]Deutschland[/url] wäre das Ergebnis sicherlich ähnlich.
+[class=type-link][bookmark=http://www.zeit.de/gesellschaft/zeitgeschehen/2014-05/oesterreich-studie-fuehrer]Studie: Ein Drittel der Österreicher will einen starken Führer[/bookmark]
+[img]http://images.zeit.de/politik/ausland/2014-05/oesterreich-umfrage/oesterreich-umfrage-540x304.jpg[/img]
+[quote]Wahlen? Parlament? Nicht so wichtig, sagen viele Österreicher laut einer Umfrage. Sie wollen einen Führer, der sich um Demokratie nicht kümmern muss.[/quote]
+[/class]";
+
+$b['postopts'] = "appnet";
+/*
+$b["body"] = "Dies ist ein Testposting, dass wieder gelöscht werden wird.";
+*/
+$b["body"] = "\"This is the end ...\"
+
+[url=https://pirati.ca/photos/heluecht/image/4ccfc897bf2ab350e0fcce93078365f5][img]https://pirati.ca/photo/4ccfc897bf2ab350e0fcce93078365f5-2.jpg[/img][/url]";
+
+$b["body"] = "[share author='Lukas' profile='https://alpha.app.net/phasenkasper' avatar='https://d2rfichhc2fb9n.cloudfront.net/image/5/1kT9xKMb9JyBVTCBnDHEaHLRUnd7InMiOiJzMyIsImIiOiJhZG4tdXNlci1hc3NldHMiLCJrIjoiYXNzZXRzL3VzZXIvZjkvM2EvNjAvZjkzYTYwMDAwMDAwMDAwMC5wbmciLCJvIjoiIn0' link='https://alpha.app.net/phasenkasper/post/32422435' posted='2014-06-12 11:42:18']
+Ich bin immer wieder begeistern wie toll mein Windows läuft. [url=https://photos.app.net/32422435/1]photos.app.net/32422435/1[/url]
+[img]https://files.app.net/1/1304673/aHwho5GfB2iXEXGGET4V3lOZVUZ5gyfFNI_CChgQ_iHYTs9sooUCIIMa3MPjLx4DHeFm3qCqEyIlo3ucFM2GDgr5SAHhJcXplNPqYGCzBxx4WP0rKxQAY65YE_tgBTaaxR5f6yMM3RzMBV6ooSH0y6zEmF0yRc6EEgn1WFaddqrSRb5XzT8ThiIspzQOy9b6m[/img][/share]";
+
+$b["body"] = "Ein A380 ist jetzt nicht unbedingt das unwendigste Flugzeug, habe ich das Gefühl.
+[share author='Javier Salgado' profile='https://plus.google.com/101295635357824725690' avatar='https://lh6.googleusercontent.com/-uE1alnITTco/AAAAAAAAAAI/AAAAAAAAAcc/jXjCG51oQfg/photo.jpg?sz=50' link='https://plus.google.com/101295635357824725690/posts/CjLEs9pSWFV']Unbelievable Airbus A380 vertical Take-off + Amaz…: http://youtu.be/RJxnwF-MPi0
+[class=type-video][bookmark=http://youtu.be/RJxnwF-MPi0]Unbelievable Airbus A380 vertical Take-off + Amazing Air Show ( HD ) Paris Air show 2013[/bookmark]
+[/class][/share]";
+
+/*
+ require_once("include/plaintext.php");
+
+$post = plaintext($a, $b, 256, false, 6);
+
+print_r($post);
+
+die();
+*/
+
+/*
+$url = "https://pirati.ca/photos/heluecht/image/54d898d7e1a8e9ba032a5fa352f51862";
+
+require_once("mod/parse_url.php");
+$data = parseurl_getsiteinfo($url, true);
+
+print_r($data);
+
+die();
+*/
+
+//$id = 3949352;
+$id = 3949512;
+$r = q("SELECT * FROM `item` WHERE `id` = %d", intval($id));
+$b = $r[0];
+
+$b['postopts'] = "appnet";
+
+//$data = get_attached_data($b["body"]);
+//print_r($data);
+
+$post = plaintext($a, $b, 256, false, 6);
+
+print_r($post);
+
+$data = appnet_create_entities($a, $b, $post);
+
+print_r($data);
+
+die();
+
+appnet_send($a, $b);
+die();
+
+
+$token = get_pconfig($b['uid'],'appnet','token');
+
+require_once 'addon/appnet/AppDotNet.php';
+
+$clientId = get_pconfig($b["uid"],'appnet','clientid');
+$clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
+
+$app = new AppDotNet($clientId, $clientSecret);
+$app->setAccessToken($token);
+
+//$param = array("include_annotations" => true);
+$param = array("include_muted" => true, "include_directed_posts" => true);
+//$param = array("include_post_annotations" => true, "include_muted" => true, "include_directed_posts" => true);
+//$post = $app->getPost(32236571, $param);
+//$post = $app->getPost(32237235, $param);
+//$post = $app->getPost(32217767, $param);
+//$post = $app->getPost(32203349, $param);
+//$post = $app->getPost(32239275, $param);
+//$post = $app->getPost(32261367, $param);
+//$post = $app->getPost(32306954, $param);
+$post = $app->getPost(32926285, $param);
+
+print_r($post);
+
+die();
+
+$lastid = @file_get_contents("addon/appnet/lastid.txt");
+$clients = @file_get_contents("addon/appnet/clients.txt");
+$users = @file_get_contents("addon/appnet/users.txt");
+
+if ($lastid != "")
+ $param["since_id"] = $lastid;
+
+$posts = $app->getPublicPosts($param);
+
+foreach ($posts AS $post) {
+ $lastid = $post["id"];
+
+ if ((count($post["entities"]["mentions"]) == 0) AND !strstr($clients, $post["source"]["client_id"]))
+ continue;
+
+ if ((count($post["entities"]["mentions"]) > 0) AND !strstr($clients, $post["source"]["client_id"]))
+ $clients .= $post["source"]["client_id"]." - ".$post["source"]["link"]." - ".$post["source"]["name"]."\n";
+
+ if (!strstr($userss, $post["user"]["canonical_url"]))
+ $users .= $post["user"]["canonical_url"]." - ".$post["user"]["username"]."\n";
+
+ echo $post["source"]["link"]." ".$post["source"]["name"]."\n";
+ echo $post["user"]["username"]."\n";
+ echo $post["text"]."\n";
+ //print_r($post["entities"]["mentions"]);
+ echo $post["id"]."\n";
+ echo "---------------------------------\n";
+}
+
+file_put_contents("addon/appnet/lastid.txt", $lastid);
+file_put_contents("addon/appnet/clients.txt", $clients);
+file_put_contents("addon/appnet/users.txt", $users);
+
+/*
+ try {
+$post = $app->getPost(323069541111, $param);
+ }
+ catch (AppDotNetException $e) {
+ print_r(appnet_error($e->getMessage()));
+ }
+*/
+
+//print_r($post);
+die();
+
+$data = array();
+$data["annotations"][] = array(
+ "type" => "net.app.core.crosspost",
+ "value" => array(
+ "canonical_url" => $b["plink"]
+ )
+ );
+
+$data["annotations"][] = array(
+ "type" => "com.friendica.post",
+ "value" => array(
+ "raw" => $b["body2"]
+ )
+ );
+
+$ret = $app->createPost($b["body"], $data);
+
+print_r($ret);
diff --git a/appnet/test/ADNRecipes.php b/appnet/test/ADNRecipes.php
new file mode 100644
index 0000000..f34bd42
--- /dev/null
+++ b/appnet/test/ADNRecipes.php
@@ -0,0 +1,254 @@
+_adn = new AppDotNet(null, null);
+ }
+
+ public function setAccessToken($access_token) {
+ $this->_adn->setAccessToken($access_token);
+ }
+}
+
+class ADNBroadcastMessageBuilder extends ADNRecipe {
+ // stores the channel ID for this message
+ private $_channel_id = null;
+
+ // stores the headline
+ private $_headline = null;
+
+ // stores the body text
+ private $_text = null;
+
+ // should we parse markdown links?
+ private $_parseMarkdownLinks = false;
+
+ // should we parse URLs out of the text body?
+ private $_parseLinks = false;
+
+ // stores the read more link
+ private $_readMoreLink = null;
+
+ // stores the photo filename
+ private $_photo = null;
+
+ // stores the attachment filename
+ private $_attachment = null;
+
+ /**
+ * Sets the destination channel ID. Required.
+ * @param string $channel_id The App.net Channel ID to send to. Get this
+ * from the web publisher tools if you don't have one.
+ */
+ public function setChannelID($channel_id) {
+ $this->_channel_id = $channel_id;
+
+ return $this;
+ }
+
+ public function getChannelID() {
+ return $this->_channel_id;
+ }
+
+ /**
+ * Sets the broadcast headline. This string shows up in the push
+ * notifications which are sent to mobile apps, and is the title
+ * displayed in the UI.
+ * @param string $headline A short string for a headline.
+ */
+ public function setHeadline($headline) {
+ $this->_headline = $headline;
+
+ return $this;
+ }
+
+ public function getHeadline() {
+ return $this->_headline;
+ }
+
+ /**
+ * Sets the broadcast text. This string shows up as a description
+ * on the broadcast detail page and in the "card" view in the
+ * mobile apps. Can contain links.
+ * @param string $text Broadcast body text.
+ */
+ public function setText($text) {
+ $this->_text = $text;
+
+ return $this;
+ }
+
+ public function getText() {
+ return $this->_text;
+ }
+
+ /**
+ * Sets a flag which allows links to be parsed out of body text in
+ * [Markdown](http://daringfireball.net/projects/markdown/)
+ * format.
+ * @param bool $parseMarkdownLinks Parse markdown links.
+ */
+ public function setParseMarkdownLinks($parseMarkdownLinks) {
+ $this->_parseMarkdownLinks = $parseMarkdownLinks;
+
+ return $this;
+ }
+
+ public function getParseMarkdownLinks() {
+ return $this->_parseMarkdownLinks;
+ }
+
+ /**
+ * Sets a flag which causes bare URLs in body text to be linkified.
+ * @param bool $parseLinks Parse links.
+ */
+ public function setParseLinks($parseLinks) {
+ $this->_parseLinks = $parseLinks;
+
+ return $this;
+ }
+
+ public function getParseLinks() {
+ return $this->_parseLinks;
+ }
+
+ /**
+ * Sets the URL the broadcast should link to.
+ * @param string $readMoreLink Read more link URL.
+ */
+ public function setReadMoreLink($readMoreLink) {
+ $this->_readMoreLink = $readMoreLink;
+
+ return $this;
+ }
+
+ public function getReadMoreLink() {
+ return $this->_readMoreLink;
+ }
+
+ /**
+ * Sets the filename of a photo associated with a broadcast.
+ * Probably requires the php-imagick extension. File will be
+ * uploaded to App.net.
+ * @param string $photo Photo filename.
+ */
+ public function setPhoto($photo) {
+ $this->_photo = $photo;
+
+ return $this;
+ }
+
+ public function getPhoto() {
+ return $this->_photo;
+ }
+
+ /**
+ * Sets the filename of a attachment associated with a broadcast.
+ * File will be uploaded to App.net.
+ * @param string $attachment Attachment filename.
+ */
+ public function setAttachment($attachment) {
+ $this->_attachment = $attachment;
+
+ return $this;
+ }
+
+ public function getAttachment() {
+ return $this->_attachment;
+ }
+
+ /**
+ * Sends the built-up broadcast.
+ */
+ public function send() {
+ $parseLinks = $this->_parseLinks || $this->_parseMarkdownLinks;
+ $message = array(
+ "annotations" => array(),
+ "entities" => array(
+ "parse_links" => $parseLinks,
+ "parse_markdown_links" => $this->_parseMarkdownLinks,
+ ),
+ );
+
+ if (isset($this->_photo)) {
+ $photoFile = $this->_adn->createFile($this->_photo, array(
+ type => "com.github.jdolitsky.appdotnetphp.photo",
+ ));
+
+ $message["annotations"][] = array(
+ "type" => "net.app.core.oembed",
+ "value" => array(
+ "+net.app.core.file" => array(
+ "file_id" => $photoFile["id"],
+ "file_token" => $photoFile["file_token"],
+ "format" => "oembed",
+ ),
+ ),
+ );
+ }
+
+ if (isset($this->_attachment)) {
+ if (isset($this->_attachment)) {
+ $attachmentFile = $this->_adn->createFile($this->_attachment, array(
+ type => "com.github.jdolitsky.appdotnetphp.attachment",
+ ));
+
+ $message["annotations"][] = array(
+ "type" => "net.app.core.oembed",
+ "value" => array(
+ "+net.app.core.file" => array(
+ "file_id" => $attachmentFile["id"],
+ "file_token" => $attachmentFile["file_token"],
+ "format" => "metadata",
+ ),
+ ),
+ );
+ }
+ }
+
+ if (isset($this->_text)) {
+ $message["text"] = $this->_text;
+ } else {
+ $message["machine_only"] = true;
+ }
+
+ if (isset($this->_headline)) {
+ $message["annotations"][] = array(
+ "type" => "net.app.core.broadcast.message.metadata",
+ "value" => array(
+ "subject" => $this->_headline,
+ ),
+ );
+ }
+
+ if (isset($this->_readMoreLink)) {
+ $message["annotations"][] = array(
+ "type" => "net.app.core.crosspost",
+ "value" => array(
+ "canonical_url" => $this->_readMoreLink,
+ ),
+ );
+ }
+
+ return $this->_adn->createMessage($this->_channel_id, $message);
+ }
+}
+
+
+
+
+
+
+
+?>
diff --git a/appnet/test/ConsumeStream.php b/appnet/test/ConsumeStream.php
new file mode 100755
index 0000000..2b7e6b0
--- /dev/null
+++ b/appnet/test/ConsumeStream.php
@@ -0,0 +1,94 @@
+getAppAccessToken();
+
+// getting a 400 error
+// 1. first check to make sure you set your app_clientId & app_clientSecret correctly
+// if that doesn't fix it, try this
+// 2. It's possible you have hit your stream limit (5 stream per app)
+// uncomment this to clear all the streams you've previously created
+//$app->deleteAllStreams();
+
+// create a stream
+// if you already have a stream you can skip this step
+// this stream is going to consume posts and stars (but not follows)
+$stream = $app->createStream(array('post','star','user_follow'));
+
+// you might want to save $stream['endpoint'] or $stream['id'] for later so
+// you don't have to re-create the stream
+print "stream id [".$stream['id']."]\n";
+//$stream = $app->getStream(XXX);
+
+// we need to create a callback function that will do something with posts/stars
+// when they're received from the stream. This function should accept one single
+// parameter that will be the php object containing the meta / data for the event.
+
+/*
+ [meta] => Array
+ (
+ [timestamp] => 1352147672891
+ [type] => post/star/etc...
+ [id] => 1399341
+ )
+ // data is as you would expect it
+*/
+function handleEvent($event) {
+ global $counters;
+ $json=json_encode($event['data']);
+ $counters[$event['meta']['type']]++;
+ switch ($event['meta']['type']) {
+ case 'post':
+ print $event['meta']['is_deleted']?'p':'P';
+ break;
+ case 'star':
+ print $event['meta']['is_deleted']?'_':'*';
+ break;
+ case 'user_follow':
+ print $event['meta']['is_deleted']?'f':'F';
+ break;
+ case 'stream_marker':
+ print $event['meta']['is_deleted']?'/':'=';
+ break;
+ case 'message':
+ print $event['meta']['is_deleted']?'m':'M';
+ break;
+ case 'channel':
+ print $event['meta']['is_deleted']?'c':'C';
+ break;
+ case 'channel_subscription':
+ print $event['meta']['is_deleted']?'f':'F';
+ break;
+ default:
+ print "Unknwon type [".$event['meta']['type']."]\n";
+ break;
+ }
+}
+
+// register that function as the stream handler
+$app->registerStreamFunction('handleEvent');
+
+// open the stream for reading
+$app->openStream($stream['endpoint']);
+
+// now we want to process the stream. We have two options. If all we're doing
+// in this script is processing the stream, we can just call:
+// $app->processStreamForever();
+// otherwise you can create a loop, and call $app->processStream($milliseconds)
+// intermittently, like:
+while (true) {
+ $counters=array('post'=>0,'star'=>0,'user_follow'=>0,'stream_marker'=>0,'message'=>0,'channel'=>0,'channel_subscription'=>0);
+ // now we're going to process the stream for awhile (60 seconds)
+ $app->processStream(60*1000000);
+ echo "\n";
+ // show some stats
+ echo date('H:i')." [",$counters['post'],"]posts [",$counters['star'],"]stars [",$counters['user_follow'],"]follow [",$counters['stream_marker'],"]mrkrs [",$counters['message'],"]msgs /min\n";
+ // then do something else...
+}
+?>
\ No newline at end of file
diff --git a/appnet/test/EZAppDotNet.php b/appnet/test/EZAppDotNet.php
new file mode 100644
index 0000000..fe7e617
--- /dev/null
+++ b/appnet/test/EZAppDotNet.php
@@ -0,0 +1,235 @@
+registerStreamFunction(array($this,'streamEZCallback'));
+
+ // make sure we cleanup/destroy any streams when we exit
+ register_shutdown_function(array($this,'stopStreaming'));
+ }
+
+ public function getAuthUrl($redirectUri=null,$scope=null) {
+ global $app_redirectUri,$app_scope;
+
+ if (is_null($redirectUri)) {
+ $redirectUri = $app_redirectUri;
+ }
+ if (is_null($scope)) {
+ $scope = $app_scope;
+ }
+ return parent::getAuthUrl($redirectUri,$scope);
+ }
+
+ // user login
+ public function setSession($cookie=0,$callback=null) {
+
+ if (!isset($callback)) {
+ global $app_redirectUri;
+ $cb=$app_redirectUri;
+ } else {
+ $cb=$callback;
+ }
+
+ // try and set the token the original way (eg: if they're logging in)
+ $token = $this->getAccessToken($cb);
+
+ // if that didn't work, check to see if there's an existing token stored somewhere
+ if (!$token) {
+ $token = $this->getSession();
+ }
+
+ $_SESSION['AppDotNetPHPAccessToken']=$token;
+
+ // if they want to stay logged in via a cookie, set the cookie
+ if ($token && $cookie) {
+ $cookie_lifetime = time()+(60*60*24*7);
+ setcookie('AppDotNetPHPAccessToken',$token,$cookie_lifetime);
+ }
+
+ return $token;
+ }
+
+ // check if user is logged in
+ public function getSession() {
+
+ // first check for cookie
+ if (isset($_COOKIE['AppDotNetPHPAccessToken']) && $_COOKIE['AppDotNetPHPAccessToken'] != 'expired') {
+ $this->setAccessToken($_COOKIE['AppDotNetPHPAccessToken']);
+ return $_COOKIE['AppDotNetPHPAccessToken'];
+ }
+
+ // else check the session for the token (from a previous page load)
+ else if (isset($_SESSION['AppDotNetPHPAccessToken'])) {
+ $this->setAccessToken($_SESSION['AppDotNetPHPAccessToken']);
+ return $_SESSION['AppDotNetPHPAccessToken'];
+ }
+
+ return false;
+ }
+
+ // log the user out
+ public function deleteSession() {
+ // clear the session
+ unset($_SESSION['AppDotNetPHPAccessToken']);
+
+ // unset the cookie
+ setcookie('AppDotNetPHPAccessToken', null, 1);
+
+ // clear the access token
+ $this->setAccessToken(null);
+
+ // done!
+ return true;
+ }
+
+ /**
+ * Registers a callback function to be called whenever an event of a certain
+ * type is received from the app.net streaming API. Your function will recieve
+ * a PHP associative array containing an app.net object. You must register at
+ * least one callback function before starting to stream (otherwise your data
+ * would simply be discarded). You can register multiple event types and even
+ * multiple functions per event (just call this method as many times as needed).
+ * If you register multiple functions for a single event, each will be called
+ * every time an event of that type is received.
+ *
+ * Note you should not be doing any significant processing in your callback
+ * functions. Doing so could cause your scripts to fall behind the stream and
+ * risk getting disconnected. Ideally your callback functions should simply
+ * drop the data into a file or database to be collected and processed by
+ * another program.
+ * @param string $type The type of even your callback would like to recieve.
+ * At time of writing the possible options are 'post', 'star', 'user_follow'.
+ */
+ public function registerStreamCallback($type,$callback) {
+ switch ($type) {
+ case 'post':
+ case 'star':
+ case 'user_follow':
+ if (!array_key_exists($type,$this->_callbacks)) {
+ $this->_callbacks[$type] = array();
+ }
+ $this->_callbacks[$type][] = $callback;
+ return true;
+ break;
+ default:
+ throw new AppDotNetException('Unknown callback type: '.$type);
+ }
+ }
+
+ /**
+ * This is the easy way to start streaming. Register some callback functions
+ * using registerCallback(), then call startStreaming(). Every time the stream
+ * gets sent a type of object you have a callback for, your callback function(s)
+ * will be called with the proper data. When your script exits the streams will
+ * be cleaned up (deleted).
+ *
+ * Do not use this method if you want to spread out streams across multiple
+ * processes or multiple servers, since the first script that exits/crashes will
+ * delete the streams for everyone else. Instead use createStream() and openStream().
+ * @return true
+ * @see AppDotNetStream::stopStreaming()
+ * @see AppDotNetStream::createStream()
+ * @see AppDotNetStream::openStream()
+ */
+ public function startStreaming() {
+ // only listen for object types that we have registered callbacks for
+ if (!$this->_callbacks) {
+ throw new AppDotNetException('You must register at least one callback function before calling startStreaming');
+ }
+ // if there's already a stream running, don't allow another
+ if ($this->_currentStream) {
+ throw new AppDotNetException('There is already a stream being consumed, only one stream can be consumed per AppDotNetStream instance');
+ }
+ $stream = $this->createStream(array_keys($this->_callbacks));
+ // when the script exits, delete this stream (if it's still around)
+ $this->_autoShutdownStreams[] = $response['id'];
+ // start consuming
+ $this->openStream($response['id']);
+ return true;
+ }
+
+ /**
+ * This is the easy way to stop streaming and cleans up the no longer needed stream.
+ * This method will be called automatically if you started streaming using
+ * startStreaming().
+ *
+ * Do not use this method if you want to spread out streams across multiple
+ * processes or multiple servers, since it will delete the streams for everyone
+ * else. Instead use closeStream().
+ * @return true
+ * @see AppDotNetStream::startStreaming()
+ * @see AppDotNetStream::deleteStream()
+ * @see AppDotNetStream::closeStream()
+ */
+ public function stopStreaming() {
+ $this->closeStream();
+ // delete any auto streams
+ foreach ($this->_autoShutdownStreams as $streamId) {
+ $this->deleteStream($streamId);
+ }
+ return true;
+ }
+
+ /**
+ * Internal function used to make your streaming easier. I hope.
+ */
+ protected function streamEZCallback($type,$data) {
+ // if there are defined callbacks for this object type, then...
+ if (array_key_exists($type,$this->_callbacks)) {
+ // loop through the callbacks notifying each one in turn
+ foreach ($this->_callbacks[$type] as $callback) {
+ call_user_func($callback,$data);
+ }
+ }
+ }
+
+}
diff --git a/appnet/test/EZsettings.php b/appnet/test/EZsettings.php
new file mode 100644
index 0000000..15321f0
--- /dev/null
+++ b/appnet/test/EZsettings.php
@@ -0,0 +1,25 @@
+debug = true;
+ $client->debug_http = true;
+ $client->server = '';
+
+ $client->oauth_version = '2.0';
+ $client->dialog_url = 'https://account.app.net/oauth/authenticate?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&response_type=code&state={STATE}';
+ $client->access_token_url = 'https://account.app.net/oauth/access_token';
+
+ $client->redirect_uri = 'https://'.$_SERVER['HTTP_HOST'].
+ dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/appnet.php';
+
+ $client->client_id = 'js4qF6UN4fwXTK87Ax9Bjf3DhEQuK5hA'; $application_line = __LINE__;
+ $client->client_secret = 'Z4hsLHh82d5cQAwNVD2uZtNg3WqFxLXF ';
+
+ if(strlen($client->client_id) == 0
+ || strlen($client->client_secret) == 0)
+ die('Please create an application in App.net Apps page '.
+ 'https://bufferapp.com/developers/apps/create '.
+ ' and in the line '.$application_line.
+ ' set the client_id to Client ID and client_secret with Client'.
+ ' Secret');
+
+ //$client->access_token = 'AQAAAAAACzfmWzVa5o69CFJrV-fBt9PLkV9sd9_0BnnHTI02_NGvvsZDCgz-38eA5_yAgu9AwaFcUzFp0qdCj4y2svy6qUl42g';
+
+ /* API permissions
+ */
+ $client->scope = '';
+ if(($success = $client->Initialize()))
+ {
+ if(($success = $client->Process()))
+ {
+ if(strlen($client->access_token))
+ {;
+ $success = $client->CallAPI(
+ 'https://api.app.net/users/me',
+ 'GET', array(), array('FailOnAccessError'=>true, 'RequestBody'=>true), $user);
+/*
+ $params["text"] = "Nur ein Test";
+ $params["profile_ids"][] = "52b844df9db82271330000b8";
+ //$params["profile_ids"][] = "5280e86b5b3c91d77b0000dd";
+ //$params["profile_ids"][] = "52b844ed9db82271330000bc";
+ //$params["profile_ids"][] = "52b8463d9db822db340000e1";
+ $params["shorten"] = false;
+ $params["now"] = false;
+print_r($params);
+ $success = $client->CallAPI(
+ 'https://api.bufferapp.com/1/updates/create.json',
+ 'POST', $params, array('FailOnAccessError'=>true, 'RequestContentType'=>'application/json'), $user);
+*/
+ }
+ }
+ $success = $client->Finalize($success);
+ }
+ if($client->exit)
+ exit;
+
+ if($success)
+ {
+?>
+
+
+
+App.net OAuth client results
+
+
+', HtmlSpecialChars($user->name),
+ ' you have logged in successfully with App.net!';
+ echo '
', HtmlSpecialChars(print_r($user, 1)), '
';
+?>
+
+
+
+
+
+
+OAuth client error
+
+
+
OAuth client error
+
Error: error); ?>
+
+
+
diff --git a/appnet/test/backup/http.php b/appnet/test/backup/http.php
new file mode 100644
index 0000000..aba8b46
--- /dev/null
+++ b/appnet/test/backup/http.php
@@ -0,0 +1,2122 @@
+"01",
+ "Feb"=>"02",
+ "Mar"=>"03",
+ "Apr"=>"04",
+ "May"=>"05",
+ "Jun"=>"06",
+ "Jul"=>"07",
+ "Aug"=>"08",
+ "Sep"=>"09",
+ "Oct"=>"10",
+ "Nov"=>"11",
+ "Dec"=>"12");
+ var $session='';
+ var $connection_close=0;
+ var $force_close = 0;
+ var $connected_host = '';
+ var $connected_port = -1;
+ var $connected_ssl = 0;
+
+ /* Private methods - DO NOT CALL */
+
+ Function Tokenize($string,$separator="")
+ {
+ if(!strcmp($separator,""))
+ {
+ $separator=$string;
+ $string=$this->next_token;
+ }
+ for($character=0;$characternext_token=substr($string,$found+1);
+ return(substr($string,0,$found));
+ }
+ else
+ {
+ $this->next_token="";
+ return($string);
+ }
+ }
+
+ Function CookieEncode($value, $name)
+ {
+ return($name ? str_replace("=", "%25", $value) : str_replace(";", "%3B", $value));
+ }
+
+ Function SetError($error, $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR)
+ {
+ $this->error_code = $error_code;
+ return($this->error=$error);
+ }
+
+ Function SetPHPError($error, &$php_error_message, $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR)
+ {
+ if(IsSet($php_error_message)
+ && strlen($php_error_message))
+ $error.=": ".$php_error_message;
+ return($this->SetError($error, $error_code));
+ }
+
+ Function SetDataAccessError($error,$check_connection=0)
+ {
+ $this->error=$error;
+ $this->error_code = HTTP_CLIENT_ERROR_COMMUNICATION_FAILURE;
+ if(!$this->use_curl
+ && function_exists("socket_get_status"))
+ {
+ $status=socket_get_status($this->connection);
+ if($status["timed_out"])
+ $this->error.=": data access time out";
+ elseif($status["eof"])
+ {
+ if($check_connection)
+ $this->error="";
+ else
+ $this->error.=": the server disconnected";
+ }
+ }
+ }
+
+ Function OutputDebug($message)
+ {
+ if($this->log_debug)
+ error_log($message);
+ else
+ {
+ $message.="\n";
+ if($this->html_debug)
+ $message=str_replace("\n"," \n",HtmlEntities($message));
+ echo $message;
+ flush();
+ }
+ }
+
+ Function GetLine()
+ {
+ for($line="";;)
+ {
+ if($this->use_curl)
+ {
+ $eol=strpos($this->response,"\n",$this->read_response);
+ $data=($eol ? substr($this->response,$this->read_response,$eol+1-$this->read_response) : "");
+ $this->read_response+=strlen($data);
+ }
+ else
+ {
+ if(feof($this->connection))
+ {
+ $this->SetDataAccessError("reached the end of data while reading from the HTTP server connection");
+ return(0);
+ }
+ $data=fgets($this->connection,100);
+ }
+ if(GetType($data)!="string"
+ || strlen($data)==0)
+ {
+ $this->SetDataAccessError("it was not possible to read line from the HTTP server");
+ return(0);
+ }
+ $line.=$data;
+ $length=strlen($line);
+ if($length
+ && !strcmp(substr($line,$length-1,1),"\n"))
+ {
+ $length-=(($length>=2 && !strcmp(substr($line,$length-2,1),"\r")) ? 2 : 1);
+ $line=substr($line,0,$length);
+ if($this->debug)
+ $this->OutputDebug("S $line");
+ return($line);
+ }
+ }
+ }
+
+ Function PutLine($line)
+ {
+ if($this->debug)
+ $this->OutputDebug("C $line");
+ if(!fputs($this->connection,$line."\r\n"))
+ {
+ $this->SetDataAccessError("it was not possible to send a line to the HTTP server");
+ return(0);
+ }
+ return(1);
+ }
+
+ Function PutData($data)
+ {
+ if(strlen($data))
+ {
+ if($this->debug)
+ $this->OutputDebug('C '.$data);
+ if(!fputs($this->connection,$data))
+ {
+ $this->SetDataAccessError("it was not possible to send data to the HTTP server");
+ return(0);
+ }
+ }
+ return(1);
+ }
+
+ Function FlushData()
+ {
+ if(!fflush($this->connection))
+ {
+ $this->SetDataAccessError("it was not possible to send data to the HTTP server");
+ return(0);
+ }
+ return(1);
+ }
+
+ Function ReadChunkSize()
+ {
+ if($this->remaining_chunk==0)
+ {
+ $debug=$this->debug;
+ if(!$this->debug_response_body)
+ $this->debug=0;
+ $line=$this->GetLine();
+ $this->debug=$debug;
+ if(GetType($line)!="string")
+ return($this->SetError("could not read chunk start: ".$this->error, $this->error_code));
+ $this->remaining_chunk=hexdec($line);
+ if($this->remaining_chunk == 0)
+ {
+ if(!$this->debug_response_body)
+ $this->debug=0;
+ $line=$this->GetLine();
+ $this->debug=$debug;
+ if(GetType($line)!="string")
+ return($this->SetError("could not read chunk end: ".$this->error, $this->error_code));
+ }
+ }
+ return("");
+ }
+
+ Function ReadBytes($length)
+ {
+ if($this->use_curl)
+ {
+ $bytes=substr($this->response,$this->read_response,min($length,strlen($this->response)-$this->read_response));
+ $this->read_response+=strlen($bytes);
+ if($this->debug
+ && $this->debug_response_body
+ && strlen($bytes))
+ $this->OutputDebug("S ".$bytes);
+ }
+ else
+ {
+ if($this->chunked)
+ {
+ for($bytes="",$remaining=$length;$remaining;)
+ {
+ if(strlen($this->ReadChunkSize()))
+ return("");
+ if($this->remaining_chunk==0)
+ {
+ $this->last_chunk_read=1;
+ break;
+ }
+ $ask=min($this->remaining_chunk,$remaining);
+ $chunk=@fread($this->connection,$ask);
+ $read=strlen($chunk);
+ if($read==0)
+ {
+ $this->SetDataAccessError("it was not possible to read data chunk from the HTTP server");
+ return("");
+ }
+ if($this->debug
+ && $this->debug_response_body)
+ $this->OutputDebug("S ".$chunk);
+ $bytes.=$chunk;
+ $this->remaining_chunk-=$read;
+ $remaining-=$read;
+ if($this->remaining_chunk==0)
+ {
+ if(feof($this->connection))
+ return($this->SetError("reached the end of data while reading the end of data chunk mark from the HTTP server", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ $data=@fread($this->connection,2);
+ if(strcmp($data,"\r\n"))
+ {
+ $this->SetDataAccessError("it was not possible to read end of data chunk from the HTTP server");
+ return("");
+ }
+ }
+ }
+ }
+ else
+ {
+ $bytes=@fread($this->connection,$length);
+ if(strlen($bytes))
+ {
+ if($this->debug
+ && $this->debug_response_body)
+ $this->OutputDebug("S ".$bytes);
+ }
+ else
+ $this->SetDataAccessError("it was not possible to read data from the HTTP server", $this->connection_close);
+ }
+ }
+ return($bytes);
+ }
+
+ Function EndOfInput()
+ {
+ if($this->use_curl)
+ return($this->read_response>=strlen($this->response));
+ if($this->chunked)
+ return($this->last_chunk_read);
+ if($this->content_length_set)
+ return($this->content_length <= $this->read_length);
+ return(feof($this->connection));
+ }
+
+ Function Resolve($domain, &$ip, $server_type)
+ {
+ if(preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$domain))
+ $ip=$domain;
+ else
+ {
+ if($this->debug)
+ $this->OutputDebug('Resolving '.$server_type.' server domain "'.$domain.'"...');
+ if(!strcmp($ip=@gethostbyname($domain),$domain))
+ $ip="";
+ }
+ if(strlen($ip)==0
+ || (strlen($this->exclude_address)
+ && !strcmp(@gethostbyname($this->exclude_address),$ip)))
+ return($this->SetError("could not resolve the host domain \"".$domain."\"", HTTP_CLIENT_ERROR_INVALID_SERVER_ADDRESS));
+ return('');
+ }
+
+ Function Connect($host_name, $host_port, $ssl, $server_type = 'HTTP')
+ {
+ $domain=$host_name;
+ $port = $host_port;
+ if(strlen($error = $this->Resolve($domain, $ip, $server_type)))
+ return($error);
+ if(strlen($this->socks_host_name))
+ {
+ switch($this->socks_version)
+ {
+ case '4':
+ $version = 4;
+ break;
+ case '5':
+ $version = 5;
+ break;
+ default:
+ return('it was not specified a supported SOCKS protocol version');
+ break;
+ }
+ $host_ip = $ip;
+ $port = $this->socks_host_port;
+ $host_server_type = $server_type;
+ $server_type = 'SOCKS';
+ if(strlen($error = $this->Resolve($this->socks_host_name, $ip, $server_type)))
+ return($error);
+ }
+ if($this->debug)
+ $this->OutputDebug('Connecting to '.$server_type.' server IP '.$ip.' port '.$port.'...');
+ if($ssl)
+ $ip="ssl://".$host_name;
+ if(($this->connection=($this->timeout ? @fsockopen($ip, $port, $errno, $error, $this->timeout) : @fsockopen($ip, $port, $errno)))==0)
+ {
+ $error_code = HTTP_CLIENT_ERROR_CANNOT_CONNECT;
+ switch($errno)
+ {
+ case -3:
+ return($this->SetError("socket could not be created", $error_code));
+ case -4:
+ return($this->SetError("dns lookup on hostname \"".$host_name."\" failed", $error_code));
+ case -5:
+ return($this->SetError("connection refused or timed out", $error_code));
+ case -6:
+ return($this->SetError("fdopen() call failed", $error_code));
+ case -7:
+ return($this->SetError("setvbuf() call failed", $error_code));
+ default:
+ return($this->SetPHPError($errno." could not connect to the host \"".$host_name."\"",$php_errormsg, $error_code));
+ }
+ }
+ else
+ {
+ if($this->data_timeout
+ && function_exists("socket_set_timeout"))
+ socket_set_timeout($this->connection,$this->data_timeout,0);
+ if(strlen($this->socks_host_name))
+ {
+ if($this->debug)
+ $this->OutputDebug('Connected to the SOCKS server '.$this->socks_host_name);
+ $send_error = 'it was not possible to send data to the SOCKS server';
+ $receive_error = 'it was not possible to receive data from the SOCKS server';
+ switch($version)
+ {
+ case 4:
+ $command = 1;
+ $user = '';
+ if(!fputs($this->connection, chr($version).chr($command).pack('nN', $host_port, ip2long($host_ip)).$user.Chr(0)))
+ $error = $this->SetDataAccessError($send_error);
+ else
+ {
+ $response = fgets($this->connection, 9);
+ if(strlen($response) != 8)
+ $error = $this->SetDataAccessError($receive_error);
+ else
+ {
+ $socks_errors = array(
+ "\x5a"=>'',
+ "\x5b"=>'request rejected',
+ "\x5c"=>'request failed because client is not running identd (or not reachable from the server)',
+ "\x5d"=>'request failed because client\'s identd could not confirm the user ID string in the request',
+ );
+ $error_code = $response[1];
+ $error = (IsSet($socks_errors[$error_code]) ? $socks_errors[$error_code] : 'unknown');
+ if(strlen($error))
+ $error = 'SOCKS error: '.$error;
+ }
+ }
+ break;
+ case 5:
+ if($this->debug)
+ $this->OutputDebug('Negotiating the authentication method ...');
+ $methods = 1;
+ $method = 0;
+ if(!fputs($this->connection, chr($version).chr($methods).chr($method)))
+ $error = $this->SetDataAccessError($send_error);
+ else
+ {
+ $response = fgets($this->connection, 3);
+ if(strlen($response) != 2)
+ $error = $this->SetDataAccessError($receive_error);
+ elseif(Ord($response[1]) != $method)
+ $error = 'the SOCKS server requires an authentication method that is not yet supported';
+ else
+ {
+ if($this->debug)
+ $this->OutputDebug('Connecting to '.$host_server_type.' server IP '.$host_ip.' port '.$host_port.'...');
+ $command = 1;
+ $address_type = 1;
+ if(!fputs($this->connection, chr($version).chr($command)."\x00".chr($address_type).pack('Nn', ip2long($host_ip), $host_port)))
+ $error = $this->SetDataAccessError($send_error);
+ else
+ {
+ $response = fgets($this->connection, 11);
+ if(strlen($response) != 10)
+ $error = $this->SetDataAccessError($receive_error);
+ else
+ {
+ $socks_errors = array(
+ "\x00"=>'',
+ "\x01"=>'general SOCKS server failure',
+ "\x02"=>'connection not allowed by ruleset',
+ "\x03"=>'Network unreachable',
+ "\x04"=>'Host unreachable',
+ "\x05"=>'Connection refused',
+ "\x06"=>'TTL expired',
+ "\x07"=>'Command not supported',
+ "\x08"=>'Address type not supported'
+ );
+ $error_code = $response[1];
+ $error = (IsSet($socks_errors[$error_code]) ? $socks_errors[$error_code] : 'unknown');
+ if(strlen($error))
+ $error = 'SOCKS error: '.$error;
+ }
+ }
+ }
+ }
+ break;
+ default:
+ $error = 'support for SOCKS protocol version '.$this->socks_version.' is not yet implemented';
+ break;
+ }
+ if(strlen($error))
+ {
+ fclose($this->connection);
+ return($error);
+ }
+ }
+ if($this->debug)
+ $this->OutputDebug("Connected to $host_name");
+ if(strlen($this->proxy_host_name)
+ && !strcmp(strtolower($this->protocol), 'https'))
+ {
+ if(function_exists('stream_socket_enable_crypto')
+ && in_array('ssl', stream_get_transports()))
+ $this->state = "ConnectedToProxy";
+ else
+ {
+ $this->OutputDebug("It is not possible to start SSL after connecting to the proxy server. If the proxy refuses to forward the SSL request, you may need to upgrade to PHP 5.1 or later with OpenSSL support enabled.");
+ $this->state="Connected";
+ }
+ }
+ else
+ $this->state="Connected";
+ return("");
+ }
+ }
+
+ Function Disconnect()
+ {
+ if($this->debug)
+ $this->OutputDebug("Disconnected from ".$this->connected_host);
+ if($this->use_curl)
+ {
+ curl_close($this->connection);
+ $this->response="";
+ }
+ else
+ fclose($this->connection);
+ $this->state="Disconnected";
+ return("");
+ }
+
+ /* Public methods */
+
+ Function GetRequestArguments($url, &$arguments)
+ {
+ $this->error = '';
+ $this->error_code = HTTP_CLIENT_ERROR_NO_ERROR;
+ $arguments=array();
+ $url = str_replace(' ', '%20', $url);
+ $parameters=@parse_url($url);
+ if(!$parameters)
+ return($this->SetError("it was not specified a valid URL", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ if(!IsSet($parameters["scheme"]))
+ return($this->SetError("it was not specified the protocol type argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ switch(strtolower($parameters["scheme"]))
+ {
+ case "http":
+ case "https":
+ $arguments["Protocol"]=$parameters["scheme"];
+ break;
+ default:
+ return($parameters["scheme"]." connection scheme is not yet supported");
+ }
+ if(!IsSet($parameters["host"]))
+ return($this->SetError("it was not specified the connection host argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ $arguments["HostName"]=$parameters["host"];
+ $arguments["Headers"]=array("Host"=>$parameters["host"].(IsSet($parameters["port"]) ? ":".$parameters["port"] : ""));
+ if(IsSet($parameters["user"]))
+ {
+ $arguments["AuthUser"]=UrlDecode($parameters["user"]);
+ if(!IsSet($parameters["pass"]))
+ $arguments["AuthPassword"]="";
+ }
+ if(IsSet($parameters["pass"]))
+ {
+ if(!IsSet($parameters["user"]))
+ $arguments["AuthUser"]="";
+ $arguments["AuthPassword"]=UrlDecode($parameters["pass"]);
+ }
+ if(IsSet($parameters["port"]))
+ {
+ if(strcmp($parameters["port"],strval(intval($parameters["port"]))))
+ return($this->SetError("it was not specified a valid connection host argument", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ $arguments["HostPort"]=intval($parameters["port"]);
+ }
+ else
+ $arguments["HostPort"]=0;
+ $arguments["RequestURI"]=(IsSet($parameters["path"]) ? $parameters["path"] : "/").(IsSet($parameters["query"]) ? "?".$parameters["query"] : "");
+ if(strlen($this->user_agent))
+ $arguments["Headers"]["User-Agent"]=$this->user_agent;
+ if(strlen($this->accept))
+ $arguments["Headers"]["Accept"]=$this->accept;
+ return("");
+ }
+
+ Function Open($arguments)
+ {
+ if(strlen($this->error))
+ return($this->error);
+ $error_code = HTTP_CLIENT_ERROR_UNSPECIFIED_ERROR;
+ if(IsSet($arguments["HostName"]))
+ $this->host_name=$arguments["HostName"];
+ if(IsSet($arguments["HostPort"]))
+ $this->host_port=$arguments["HostPort"];
+ if(IsSet($arguments["ProxyHostName"]))
+ $this->proxy_host_name=$arguments["ProxyHostName"];
+ if(IsSet($arguments["ProxyHostPort"]))
+ $this->proxy_host_port=$arguments["ProxyHostPort"];
+ if(IsSet($arguments["SOCKSHostName"]))
+ $this->socks_host_name=$arguments["SOCKSHostName"];
+ if(IsSet($arguments["SOCKSHostPort"]))
+ $this->socks_host_port=$arguments["SOCKSHostPort"];
+ if(IsSet($arguments["SOCKSVersion"]))
+ $this->socks_version=$arguments["SOCKSVersion"];
+ if(IsSet($arguments["Protocol"]))
+ $this->protocol=$arguments["Protocol"];
+ switch(strtolower($this->protocol))
+ {
+ case "http":
+ $default_port=80;
+ break;
+ case "https":
+ $default_port=443;
+ break;
+ default:
+ return($this->SetError("it was not specified a valid connection protocol", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ }
+ if(strlen($this->proxy_host_name)==0)
+ {
+ if(strlen($this->host_name)==0)
+ return($this->SetError("it was not specified a valid hostname", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ $host_name=$this->host_name;
+ $host_port=($this->host_port ? $this->host_port : $default_port);
+ $server_type = 'HTTP';
+ }
+ else
+ {
+ $host_name=$this->proxy_host_name;
+ $host_port=$this->proxy_host_port;
+ $server_type = 'HTTP proxy';
+ }
+ $ssl=(strtolower($this->protocol)=="https" && strlen($this->proxy_host_name)==0);
+ if($ssl
+ && strlen($this->socks_host_name))
+ return($this->SetError('establishing SSL connections via a SOCKS server is not yet supported', HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ $this->use_curl=($ssl && $this->prefer_curl && function_exists("curl_init"));
+ switch($this->state)
+ {
+ case 'Connected':
+ if(!strcmp($host_name, $this->connected_host)
+ && intval($host_port) == $this->connected_port
+ && intval($ssl) == $this->connected_ssl)
+ {
+ if($this->debug)
+ $this->OutputDebug("Reusing connection to ".$this->connected_host);
+ return('');
+ }
+ if(strlen($error = $this->Disconnect()))
+ return($error);
+ case "Disconnected":
+ break;
+ default:
+ return("1 already connected");
+ }
+ if($this->debug)
+ $this->OutputDebug("Connecting to ".$this->host_name);
+ if($this->use_curl)
+ {
+ $error=(($this->connection=curl_init($this->protocol."://".$this->host_name.($host_port==$default_port ? "" : ":".strval($host_port))."/")) ? "" : "Could not initialize a CURL session");
+ if(strlen($error)==0)
+ {
+ if(IsSet($arguments["SSLCertificateFile"]))
+ curl_setopt($this->connection,CURLOPT_SSLCERT,$arguments["SSLCertificateFile"]);
+ if(IsSet($arguments["SSLCertificatePassword"]))
+ curl_setopt($this->connection,CURLOPT_SSLCERTPASSWD,$arguments["SSLCertificatePassword"]);
+ if(IsSet($arguments["SSLKeyFile"]))
+ curl_setopt($this->connection,CURLOPT_SSLKEY,$arguments["SSLKeyFile"]);
+ if(IsSet($arguments["SSLKeyPassword"]))
+ curl_setopt($this->connection,CURLOPT_SSLKEYPASSWD,$arguments["SSLKeyPassword"]);
+ }
+ $this->state="Connected";
+ }
+ else
+ {
+ $error="";
+ if(strlen($this->proxy_host_name)
+ && (IsSet($arguments["SSLCertificateFile"])
+ || IsSet($arguments["SSLCertificateFile"])))
+ $error="establishing SSL connections using certificates or private keys via non-SSL proxies is not supported";
+ else
+ {
+ if($ssl)
+ {
+ if(IsSet($arguments["SSLCertificateFile"]))
+ $error="establishing SSL connections using certificates is only supported when the cURL extension is enabled";
+ elseif(IsSet($arguments["SSLKeyFile"]))
+ $error="establishing SSL connections using a private key is only supported when the cURL extension is enabled";
+ else
+ {
+ $version=explode(".",function_exists("phpversion") ? phpversion() : "3.0.7");
+ $php_version=intval($version[0])*1000000+intval($version[1])*1000+intval($version[2]);
+ if($php_version<4003000)
+ $error="establishing SSL connections requires at least PHP version 4.3.0 or having the cURL extension enabled";
+ elseif(!function_exists("extension_loaded")
+ || !extension_loaded("openssl"))
+ $error="establishing SSL connections requires the OpenSSL extension enabled";
+ }
+ }
+ if(strlen($error)==0)
+ {
+ $error=$this->Connect($host_name, $host_port, $ssl, $server_type);
+ $error_code = $this->error_code;
+ }
+ }
+ }
+ if(strlen($error))
+ return($this->SetError($error, $error_code));
+ $this->session=md5(uniqid(""));
+ $this->connected_host = $host_name;
+ $this->connected_port = intval($host_port);
+ $this->connected_ssl = intval($ssl);
+ return("");
+ }
+
+ Function Close($force = 0)
+ {
+ if($this->state=="Disconnected")
+ return("1 already disconnected");
+ if(!$this->force_close
+ && $this->keep_alive
+ && !$force
+ && $this->state == 'ResponseReceived')
+ {
+ if($this->debug)
+ $this->OutputDebug('Keeping the connection alive to '.$this->connected_host);
+ $this->state = 'Connected';
+ return('');
+ }
+ return($this->Disconnect());
+ }
+
+ Function PickCookies(&$cookies,$secure)
+ {
+ if(IsSet($this->cookies[$secure]))
+ {
+ $now=gmdate("Y-m-d H-i-s");
+ for($domain=0,Reset($this->cookies[$secure]);$domaincookies[$secure]);Next($this->cookies[$secure]),$domain++)
+ {
+ $domain_pattern=Key($this->cookies[$secure]);
+ $match=strlen($this->request_host)-strlen($domain_pattern);
+ if($match>=0
+ && !strcmp($domain_pattern,substr($this->request_host,$match))
+ && ($match==0
+ || $domain_pattern[0]=="."
+ || $this->request_host[$match-1]=="."))
+ {
+ for(Reset($this->cookies[$secure][$domain_pattern]),$path_part=0;$path_partcookies[$secure][$domain_pattern]);Next($this->cookies[$secure][$domain_pattern]),$path_part++)
+ {
+ $path=Key($this->cookies[$secure][$domain_pattern]);
+ if(strlen($this->request_uri)>=strlen($path)
+ && substr($this->request_uri,0,strlen($path))==$path)
+ {
+ for(Reset($this->cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookiecookies[$secure][$domain_pattern][$path]);Next($this->cookies[$secure][$domain_pattern][$path]),$cookie++)
+ {
+ $cookie_name=Key($this->cookies[$secure][$domain_pattern][$path]);
+ $expires=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]["expires"];
+ if($expires==""
+ || strcmp($now,$expires)<0)
+ $cookies[$cookie_name]=$this->cookies[$secure][$domain_pattern][$path][$cookie_name];
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Function GetFileDefinition($file, &$definition)
+ {
+ $name="";
+ if(IsSet($file["FileName"]))
+ $name=basename($file["FileName"]);
+ if(IsSet($file["Name"]))
+ $name=$file["Name"];
+ if(strlen($name)==0)
+ return("it was not specified the file part name");
+ if(IsSet($file["Content-Type"]))
+ {
+ $content_type=$file["Content-Type"];
+ $type=$this->Tokenize(strtolower($content_type),"/");
+ $sub_type=$this->Tokenize("");
+ switch($type)
+ {
+ case "text":
+ case "image":
+ case "audio":
+ case "video":
+ case "application":
+ case "message":
+ break;
+ case "automatic":
+ switch($sub_type)
+ {
+ case "name":
+ switch(GetType($dot=strrpos($name,"."))=="integer" ? strtolower(substr($name,$dot)) : "")
+ {
+ case ".xls":
+ $content_type="application/excel";
+ break;
+ case ".hqx":
+ $content_type="application/macbinhex40";
+ break;
+ case ".doc":
+ case ".dot":
+ case ".wrd":
+ $content_type="application/msword";
+ break;
+ case ".pdf":
+ $content_type="application/pdf";
+ break;
+ case ".pgp":
+ $content_type="application/pgp";
+ break;
+ case ".ps":
+ case ".eps":
+ case ".ai":
+ $content_type="application/postscript";
+ break;
+ case ".ppt":
+ $content_type="application/powerpoint";
+ break;
+ case ".rtf":
+ $content_type="application/rtf";
+ break;
+ case ".tgz":
+ case ".gtar":
+ $content_type="application/x-gtar";
+ break;
+ case ".gz":
+ $content_type="application/x-gzip";
+ break;
+ case ".php":
+ case ".php3":
+ $content_type="application/x-httpd-php";
+ break;
+ case ".js":
+ $content_type="application/x-javascript";
+ break;
+ case ".ppd":
+ case ".psd":
+ $content_type="application/x-photoshop";
+ break;
+ case ".swf":
+ case ".swc":
+ case ".rf":
+ $content_type="application/x-shockwave-flash";
+ break;
+ case ".tar":
+ $content_type="application/x-tar";
+ break;
+ case ".zip":
+ $content_type="application/zip";
+ break;
+ case ".mid":
+ case ".midi":
+ case ".kar":
+ $content_type="audio/midi";
+ break;
+ case ".mp2":
+ case ".mp3":
+ case ".mpga":
+ $content_type="audio/mpeg";
+ break;
+ case ".ra":
+ $content_type="audio/x-realaudio";
+ break;
+ case ".wav":
+ $content_type="audio/wav";
+ break;
+ case ".bmp":
+ $content_type="image/bitmap";
+ break;
+ case ".gif":
+ $content_type="image/gif";
+ break;
+ case ".iff":
+ $content_type="image/iff";
+ break;
+ case ".jb2":
+ $content_type="image/jb2";
+ break;
+ case ".jpg":
+ case ".jpe":
+ case ".jpeg":
+ $content_type="image/jpeg";
+ break;
+ case ".jpx":
+ $content_type="image/jpx";
+ break;
+ case ".png":
+ $content_type="image/png";
+ break;
+ case ".tif":
+ case ".tiff":
+ $content_type="image/tiff";
+ break;
+ case ".wbmp":
+ $content_type="image/vnd.wap.wbmp";
+ break;
+ case ".xbm":
+ $content_type="image/xbm";
+ break;
+ case ".css":
+ $content_type="text/css";
+ break;
+ case ".txt":
+ $content_type="text/plain";
+ break;
+ case ".htm":
+ case ".html":
+ $content_type="text/html";
+ break;
+ case ".xml":
+ $content_type="text/xml";
+ break;
+ case ".mpg":
+ case ".mpe":
+ case ".mpeg":
+ $content_type="video/mpeg";
+ break;
+ case ".qt":
+ case ".mov":
+ $content_type="video/quicktime";
+ break;
+ case ".avi":
+ $content_type="video/x-ms-video";
+ break;
+ case ".eml":
+ $content_type="message/rfc822";
+ break;
+ default:
+ $content_type="application/octet-stream";
+ break;
+ }
+ break;
+ default:
+ return($content_type." is not a supported automatic content type detection method");
+ }
+ break;
+ default:
+ return($content_type." is not a supported file content type");
+ }
+ }
+ else
+ $content_type="application/octet-stream";
+ $definition=array(
+ "Content-Type"=>$content_type,
+ "NAME"=>$name
+ );
+ if(IsSet($file["FileName"]))
+ {
+ if(GetType($length=@filesize($file["FileName"]))!="integer")
+ {
+ $error="it was not possible to determine the length of the file ".$file["FileName"];
+ if(IsSet($php_errormsg)
+ && strlen($php_errormsg))
+ $error.=": ".$php_errormsg;
+ if(!file_exists($file["FileName"]))
+ $error="it was not possible to access the file ".$file["FileName"];
+ return($error);
+ }
+ $definition["FILENAME"]=$file["FileName"];
+ $definition["Content-Length"]=$length;
+ }
+ elseif(IsSet($file["Data"]))
+ $definition["Content-Length"]=strlen($definition["DATA"]=$file["Data"]);
+ else
+ return("it was not specified a valid file name");
+ return("");
+ }
+
+ Function ConnectFromProxy($arguments, &$headers)
+ {
+ if(!$this->PutLine('CONNECT '.$this->host_name.':'.($this->host_port ? $this->host_port : 443).' HTTP/1.0')
+ || (strlen($this->user_agent)
+ && !$this->PutLine('User-Agent: '.$this->user_agent))
+ || (strlen($this->accept)
+ && !$this->PutLine('Accept: '.$this->accept))
+ || (IsSet($arguments['Headers']['Proxy-Authorization'])
+ && !$this->PutLine('Proxy-Authorization: '.$arguments['Headers']['Proxy-Authorization']))
+ || !$this->PutLine(''))
+ {
+ $this->Disconnect();
+ return($this->error);
+ }
+ $this->state = "ConnectSent";
+ if(strlen($error=$this->ReadReplyHeadersResponse($headers)))
+ return($error);
+ $proxy_authorization="";
+ while(!strcmp($this->response_status, "100"))
+ {
+ $this->state="ConnectSent";
+ if(strlen($error=$this->ReadReplyHeadersResponse($headers)))
+ return($error);
+ }
+ switch($this->response_status)
+ {
+ case "200":
+ if(!@stream_socket_enable_crypto($this->connection, 1, STREAM_CRYPTO_METHOD_SSLv23_CLIENT))
+ {
+ $this->SetPHPError('it was not possible to start a SSL encrypted connection via this proxy', $php_errormsg, HTTP_CLIENT_ERROR_COMMUNICATION_FAILURE);
+ $this->Disconnect();
+ return($this->error);
+ }
+ $this->state = "Connected";
+ break;
+ case "407":
+ if(strlen($error=$this->Authenticate($headers, -1, $proxy_authorization, $this->proxy_request_user, $this->proxy_request_password, $this->proxy_request_realm, $this->proxy_request_workstation)))
+ return($error);
+ break;
+ default:
+ return($this->SetError("unable to send request via proxy", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ }
+ return("");
+ }
+
+ Function SendRequest($arguments)
+ {
+ if(strlen($this->error))
+ return($this->error);
+ if(IsSet($arguments["ProxyUser"]))
+ $this->proxy_request_user=$arguments["ProxyUser"];
+ elseif(IsSet($this->proxy_user))
+ $this->proxy_request_user=$this->proxy_user;
+ if(IsSet($arguments["ProxyPassword"]))
+ $this->proxy_request_password=$arguments["ProxyPassword"];
+ elseif(IsSet($this->proxy_password))
+ $this->proxy_request_password=$this->proxy_password;
+ if(IsSet($arguments["ProxyRealm"]))
+ $this->proxy_request_realm=$arguments["ProxyRealm"];
+ elseif(IsSet($this->proxy_realm))
+ $this->proxy_request_realm=$this->proxy_realm;
+ if(IsSet($arguments["ProxyWorkstation"]))
+ $this->proxy_request_workstation=$arguments["ProxyWorkstation"];
+ elseif(IsSet($this->proxy_workstation))
+ $this->proxy_request_workstation=$this->proxy_workstation;
+ switch($this->state)
+ {
+ case "Disconnected":
+ return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "Connected":
+ $connect = 0;
+ break;
+ case "ConnectedToProxy":
+ if(strlen($error = $this->ConnectFromProxy($arguments, $headers)))
+ return($error);
+ $connect = 1;
+ break;
+ default:
+ return($this->SetError("can not send request in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ }
+ if(IsSet($arguments["RequestMethod"]))
+ $this->request_method=$arguments["RequestMethod"];
+ if(IsSet($arguments["User-Agent"]))
+ $this->user_agent=$arguments["User-Agent"];
+ if(!IsSet($arguments["Headers"]["User-Agent"])
+ && strlen($this->user_agent))
+ $arguments["Headers"]["User-Agent"]=$this->user_agent;
+ if(IsSet($arguments["KeepAlive"]))
+ $this->keep_alive=intval($arguments["KeepAlive"]);
+ if(!IsSet($arguments["Headers"]["Connection"])
+ && $this->keep_alive)
+ $arguments["Headers"]["Connection"]='Keep-Alive';
+ if(IsSet($arguments["Accept"]))
+ $this->user_agent=$arguments["Accept"];
+ if(!IsSet($arguments["Headers"]["Accept"])
+ && strlen($this->accept))
+ $arguments["Headers"]["Accept"]=$this->accept;
+ if(strlen($this->request_method)==0)
+ return($this->SetError("it was not specified a valid request method", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ if(IsSet($arguments["RequestURI"]))
+ $this->request_uri=$arguments["RequestURI"];
+ if(strlen($this->request_uri)==0
+ || substr($this->request_uri,0,1)!="/")
+ return($this->SetError("it was not specified a valid request URI", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ $this->request_arguments=$arguments;
+ $this->request_headers=(IsSet($arguments["Headers"]) ? $arguments["Headers"] : array());
+ $body_length=0;
+ $this->request_body="";
+ $get_body=1;
+ if($this->request_method=="POST"
+ || $this->request_method=="PUT")
+ {
+ if(IsSet($arguments['StreamRequest']))
+ {
+ $get_body = 0;
+ $this->request_headers["Transfer-Encoding"]="chunked";
+ }
+ elseif(IsSet($arguments["PostFiles"])
+ || ($this->force_multipart_form_post
+ && IsSet($arguments["PostValues"])))
+ {
+ $boundary="--".md5(uniqid(time()));
+ $this->request_headers["Content-Type"]="multipart/form-data; boundary=".$boundary.(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : "");
+ $post_parts=array();
+ if(IsSet($arguments["PostValues"]))
+ {
+ $values=$arguments["PostValues"];
+ if(GetType($values)!="array")
+ return($this->SetError("it was not specified a valid POST method values array", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ for(Reset($values),$value=0;$value$headers,"DATA"=>$data);
+ $body_length+=strlen($headers)+strlen($data)+strlen("\r\n");
+ }
+ }
+ $body_length+=strlen("--".$boundary."--\r\n");
+ $files=(IsSet($arguments["PostFiles"]) ? $arguments["PostFiles"] : array());
+ Reset($files);
+ $end=(GetType($input=Key($files))!="string");
+ for(;!$end;)
+ {
+ if(strlen($error=$this->GetFileDefinition($files[$input],$definition)))
+ return("3 ".$error);
+ $headers="--".$boundary."\r\nContent-Disposition: form-data; name=\"".$input."\"; filename=\"".$definition["NAME"]."\"\r\nContent-Type: ".$definition["Content-Type"]."\r\n\r\n";
+ $part=count($post_parts);
+ $post_parts[$part]=array("HEADERS"=>$headers);
+ if(IsSet($definition["FILENAME"]))
+ {
+ $post_parts[$part]["FILENAME"]=$definition["FILENAME"];
+ $data="";
+ }
+ else
+ $data=$definition["DATA"];
+ $post_parts[$part]["DATA"]=$data;
+ $body_length+=strlen($headers)+$definition["Content-Length"]+strlen("\r\n");
+ Next($files);
+ $end=(GetType($input=Key($files))!="string");
+ }
+ $get_body=0;
+ }
+ elseif(IsSet($arguments["PostValues"]))
+ {
+ $values=$arguments["PostValues"];
+ if(GetType($values)!="array")
+ return($this->SetError("it was not specified a valid POST method values array", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ for(Reset($values),$value=0;$value0)
+ $this->request_body.="&";
+ $this->request_body.=UrlEncode($k)."=".UrlEncode($values[$k][$v]);
+ }
+ }
+ else
+ {
+ if($value>0)
+ $this->request_body.="&";
+ $this->request_body.=UrlEncode($k)."=".UrlEncode($values[$k]);
+ }
+ }
+ $this->request_headers["Content-Type"]="application/x-www-form-urlencoded".(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : "");
+ $get_body=0;
+ }
+ }
+ if($get_body
+ && (IsSet($arguments["Body"])
+ || IsSet($arguments["BodyStream"])))
+ {
+ if(IsSet($arguments["Body"]))
+ $this->request_body=$arguments["Body"];
+ else
+ {
+ $stream=$arguments["BodyStream"];
+ $this->request_body="";
+ for($part=0; $partrequest_body.=$stream[$part]["Data"];
+ elseif(IsSet($stream[$part]["File"]))
+ {
+ if(!($file=@fopen($stream[$part]["File"],"rb")))
+ return($this->SetPHPError("could not open upload file ".$stream[$part]["File"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE));
+ while(!feof($file))
+ {
+ if(GetType($block=@fread($file,$this->file_buffer_length))!="string")
+ {
+ $error=$this->SetPHPError("could not read body stream file ".$stream[$part]["File"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE);
+ fclose($file);
+ return($error);
+ }
+ $this->request_body.=$block;
+ }
+ fclose($file);
+ }
+ else
+ return("5 it was not specified a valid file or data body stream element at position ".$part);
+ }
+ }
+ if(!IsSet($this->request_headers["Content-Type"]))
+ $this->request_headers["Content-Type"]="application/octet-stream".(IsSet($arguments["CharSet"]) ? "; charset=".$arguments["CharSet"] : "");
+ }
+ if(IsSet($arguments["AuthUser"]))
+ $this->request_user=$arguments["AuthUser"];
+ elseif(IsSet($this->user))
+ $this->request_user=$this->user;
+ if(IsSet($arguments["AuthPassword"]))
+ $this->request_password=$arguments["AuthPassword"];
+ elseif(IsSet($this->password))
+ $this->request_password=$this->password;
+ if(IsSet($arguments["AuthRealm"]))
+ $this->request_realm=$arguments["AuthRealm"];
+ elseif(IsSet($this->realm))
+ $this->request_realm=$this->realm;
+ if(IsSet($arguments["AuthWorkstation"]))
+ $this->request_workstation=$arguments["AuthWorkstation"];
+ elseif(IsSet($this->workstation))
+ $this->request_workstation=$this->workstation;
+ if(strlen($this->proxy_host_name)==0
+ || $connect)
+ $request_uri=$this->request_uri;
+ else
+ {
+ switch(strtolower($this->protocol))
+ {
+ case "http":
+ $default_port=80;
+ break;
+ case "https":
+ $default_port=443;
+ break;
+ }
+ $request_uri=strtolower($this->protocol)."://".$this->host_name.(($this->host_port==0 || $this->host_port==$default_port) ? "" : ":".$this->host_port).$this->request_uri;
+ }
+ if($this->use_curl)
+ {
+ $version=(GetType($v=curl_version())=="array" ? (IsSet($v["version"]) ? $v["version"] : "0.0.0") : (preg_match("/^libcurl\\/([0-9]+\\.[0-9]+\\.[0-9]+)/",$v,$m) ? $m[1] : "0.0.0"));
+ $curl_version=100000*intval($this->Tokenize($version,"."))+1000*intval($this->Tokenize("."))+intval($this->Tokenize(""));
+ $protocol_version=($curl_version<713002 ? "1.0" : $this->protocol_version);
+ }
+ else
+ $protocol_version=$this->protocol_version;
+ $this->request=$this->request_method." ".$request_uri." HTTP/".$protocol_version;
+ if($body_length
+ || ($body_length=strlen($this->request_body))
+ || !strcmp($this->request_method, 'POST'))
+ $this->request_headers["Content-Length"]=$body_length;
+ for($headers=array(),$host_set=0,Reset($this->request_headers),$header=0;$headerrequest_headers);Next($this->request_headers),$header++)
+ {
+ $header_name=Key($this->request_headers);
+ $header_value=$this->request_headers[$header_name];
+ if(GetType($header_value)=="array")
+ {
+ for(Reset($header_value),$value=0;$valuerequest_headers))=="host")
+ {
+ $this->request_host=strtolower($header_value);
+ $host_set=1;
+ }
+ }
+ if(!$host_set)
+ {
+ $headers[]="Host: ".$this->host_name;
+ $this->request_host=strtolower($this->host_name);
+ }
+ if(count($this->cookies))
+ {
+ $cookies=array();
+ $this->PickCookies($cookies,0);
+ if(strtolower($this->protocol)=="https")
+ $this->PickCookies($cookies,1);
+ if(count($cookies))
+ {
+ $h=count($headers);
+ $headers[$h]="Cookie:";
+ for(Reset($cookies),$cookie=0;$cookieuse_curl)
+ {
+ if(IsSet($arguments['StreamRequest']))
+ return($this->SetError("Streaming request data is not supported when using Curl", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ if($body_length
+ && strlen($this->request_body)==0)
+ {
+ for($request_body="",$success=1,$part=0;$partSetPHPError("could not open upload file ".$post_parts[$part]["FILENAME"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE);
+ $success=0;
+ break;
+ }
+ while(!feof($file))
+ {
+ if(GetType($block=@fread($file,$this->file_buffer_length))!="string")
+ {
+ $this->SetPHPError("could not read upload file", $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE);
+ $success=0;
+ break;
+ }
+ $request_body.=$block;
+ }
+ fclose($file);
+ if(!$success)
+ break;
+ }
+ $request_body.="\r\n";
+ }
+ $request_body.="--".$boundary."--\r\n";
+ }
+ else
+ $request_body=$this->request_body;
+ curl_setopt($this->connection,CURLOPT_HEADER,1);
+ curl_setopt($this->connection,CURLOPT_RETURNTRANSFER,1);
+ if($this->timeout)
+ curl_setopt($this->connection,CURLOPT_TIMEOUT,$this->timeout);
+ curl_setopt($this->connection,CURLOPT_SSL_VERIFYPEER,0);
+ curl_setopt($this->connection,CURLOPT_SSL_VERIFYHOST,0);
+ $request=$this->request."\r\n".implode("\r\n",$headers)."\r\n\r\n".$request_body;
+ curl_setopt($this->connection,CURLOPT_CUSTOMREQUEST,$request);
+ if($this->debug)
+ $this->OutputDebug("C ".$request);
+ if(!($success=(strlen($this->response=curl_exec($this->connection))!=0)))
+ {
+ $error=curl_error($this->connection);
+ $this->SetError("Could not execute the request".(strlen($error) ? ": ".$error : ""), HTTP_CLIENT_ERROR_PROTOCOL_FAILURE);
+ }
+ }
+ else
+ {
+ if(($success=$this->PutLine($this->request)))
+ {
+ for($header=0;$headerPutLine($headers[$header]))
+ break;
+ }
+ if($success
+ && ($success=$this->PutLine("")))
+ {
+ if(IsSet($arguments['StreamRequest']))
+ $next_state = "SendingRequestBody";
+ elseif($body_length)
+ {
+ if(strlen($this->request_body))
+ $success=$this->PutData($this->request_body);
+ else
+ {
+ for($part=0;$partPutData($post_parts[$part]["HEADERS"]))
+ || !($success=$this->PutData($post_parts[$part]["DATA"])))
+ break;
+ if(IsSet($post_parts[$part]["FILENAME"]))
+ {
+ if(!($file=@fopen($post_parts[$part]["FILENAME"],"rb")))
+ {
+ $this->SetPHPError("could not open upload file ".$post_parts[$part]["FILENAME"], $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE);
+ $success=0;
+ break;
+ }
+ while(!feof($file))
+ {
+ if(GetType($block=@fread($file,$this->file_buffer_length))!="string")
+ {
+ $this->SetPHPError("could not read upload file", $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE);
+ $success=0;
+ break;
+ }
+ if(!($success=$this->PutData($block)))
+ break;
+ }
+ fclose($file);
+ if(!$success)
+ break;
+ }
+ if(!($success=$this->PutLine("")))
+ break;
+ }
+ if($success)
+ $success=$this->PutLine("--".$boundary."--");
+ }
+ if($success)
+ $sucess=$this->FlushData();
+ }
+ }
+ }
+ }
+ if(!$success)
+ return($this->SetError("could not send the HTTP request: ".$this->error, $this->error_code));
+ $this->state=$next_state;
+ return("");
+ }
+
+ Function SetCookie($name, $value, $expires="" , $path="/" , $domain="" , $secure=0, $verbatim=0)
+ {
+ if(strlen($this->error))
+ return($this->error);
+ if(strlen($name)==0)
+ return($this->SetError("it was not specified a valid cookie name", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ if(strlen($path)==0
+ || strcmp($path[0],"/"))
+ return($this->SetError($path." is not a valid path for setting cookie ".$name, HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ if($domain==""
+ || !strpos($domain,".",$domain[0]=="." ? 1 : 0))
+ return($this->SetError($domain." is not a valid domain for setting cookie ".$name, HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ $domain=strtolower($domain);
+ if(!strcmp($domain[0],"."))
+ $domain=substr($domain,1);
+ if(!$verbatim)
+ {
+ $name=$this->CookieEncode($name,1);
+ $value=$this->CookieEncode($value,0);
+ }
+ $secure=intval($secure);
+ $this->cookies[$secure][$domain][$path][$name]=array(
+ "name"=>$name,
+ "value"=>$value,
+ "domain"=>$domain,
+ "path"=>$path,
+ "expires"=>$expires,
+ "secure"=>$secure
+ );
+ return("");
+ }
+
+ Function SendRequestBody($data, $end_of_data)
+ {
+ if(strlen($this->error))
+ return($this->error);
+ switch($this->state)
+ {
+ case "Disconnected":
+ return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "Connected":
+ case "ConnectedToProxy":
+ return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "SendingRequestBody":
+ break;
+ case "RequestSent":
+ return($this->SetError("request body was already sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ default:
+ return($this->SetError("can not send the request body in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ }
+ $length = strlen($data);
+ if($length)
+ {
+ $size = dechex($length)."\r\n";
+ if(!$this->PutData($size)
+ || !$this->PutData($data))
+ return($this->error);
+ }
+ if($end_of_data)
+ {
+ $size = "0\r\n";
+ if(!$this->PutData($size))
+ return($this->error);
+ $this->state = "RequestSent";
+ }
+ return("");
+ }
+
+ Function ReadReplyHeadersResponse(&$headers)
+ {
+ $headers=array();
+ if(strlen($this->error))
+ return($this->error);
+ switch($this->state)
+ {
+ case "Disconnected":
+ return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "Connected":
+ return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "ConnectedToProxy":
+ return($this->SetError("connection from the remote server from the proxy was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "SendingRequestBody":
+ return($this->SetError("request body data was not completely sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "ConnectSent":
+ $connect = 1;
+ break;
+ case "RequestSent":
+ $connect = 0;
+ break;
+ default:
+ return($this->SetError("can not get request headers in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ }
+ $this->content_length=$this->read_length=$this->read_response=$this->remaining_chunk=0;
+ $this->content_length_set=$this->chunked=$this->last_chunk_read=$chunked=0;
+ $this->force_close = $this->connection_close=0;
+ for($this->response_status="";;)
+ {
+ $line=$this->GetLine();
+ if(GetType($line)!="string")
+ return($this->SetError("could not read request reply: ".$this->error, $this->error_code));
+ if(strlen($this->response_status)==0)
+ {
+ if(!preg_match($match="/^http\\/[0-9]+\\.[0-9]+[ \t]+([0-9]+)[ \t]*(.*)\$/i",$line,$matches))
+ return($this->SetError("it was received an unexpected HTTP response status", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ $this->response_status=$matches[1];
+ $this->response_message=$matches[2];
+ }
+ if($line=="")
+ {
+ if(strlen($this->response_status)==0)
+ return($this->SetError("it was not received HTTP response status", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ $this->state=($connect ? "GotConnectHeaders" : "GotReplyHeaders");
+ break;
+ }
+ $header_name=strtolower($this->Tokenize($line,":"));
+ $header_value=Trim(Chop($this->Tokenize("\r\n")));
+ if(IsSet($headers[$header_name]))
+ {
+ if(GetType($headers[$header_name])=="string")
+ $headers[$header_name]=array($headers[$header_name]);
+ $headers[$header_name][]=$header_value;
+ }
+ else
+ $headers[$header_name]=$header_value;
+ if(!$connect)
+ {
+ switch($header_name)
+ {
+ case "content-length":
+ $this->content_length=intval($headers[$header_name]);
+ $this->content_length_set=1;
+ break;
+ case "transfer-encoding":
+ $encoding=$this->Tokenize($header_value,"; \t");
+ if(!$this->use_curl
+ && !strcmp($encoding,"chunked"))
+ $chunked=1;
+ break;
+ case "set-cookie":
+ if($this->support_cookies)
+ {
+ if(GetType($headers[$header_name])=="array")
+ $cookie_headers=$headers[$header_name];
+ else
+ $cookie_headers=array($headers[$header_name]);
+ for($cookie=0;$cookieTokenize($cookie_headers[$cookie],"="));
+ $cookie_value=$this->Tokenize(";");
+ $domain=$this->request_host;
+ $path="/";
+ $expires="";
+ $secure=0;
+ while(($name = strtolower(trim(UrlDecode($this->Tokenize("=")))))!="")
+ {
+ $value=UrlDecode($this->Tokenize(";"));
+ switch($name)
+ {
+ case "domain":
+ $domain=$value;
+ break;
+ case "path":
+ $path=$value;
+ break;
+ case "expires":
+ if(preg_match("/^((Mon|Monday|Tue|Tuesday|Wed|Wednesday|Thu|Thursday|Fri|Friday|Sat|Saturday|Sun|Sunday), )?([0-9]{2})\\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\-([0-9]{2,4}) ([0-9]{2})\\:([0-9]{2})\\:([0-9]{2}) GMT\$/",$value,$matches))
+ {
+ $year=intval($matches[5]);
+ if($year<1900)
+ $year+=($year<70 ? 2000 : 1900);
+ $expires="$year-".$this->months[$matches[4]]."-".$matches[3]." ".$matches[6].":".$matches[7].":".$matches[8];
+ }
+ break;
+ case "secure":
+ $secure=1;
+ break;
+ }
+ }
+ if(strlen($this->SetCookie($cookie_name, $cookie_value, $expires, $path , $domain, $secure, 1)))
+ $this->error="";
+ }
+ }
+ break;
+ case "connection":
+ $this->force_close = $this->connection_close=!strcmp(strtolower($header_value),"close");
+ break;
+ }
+ }
+ }
+ $this->chunked=$chunked;
+ if($this->content_length_set)
+ $this->connection_close=0;
+ return("");
+ }
+
+ Function Redirect(&$headers)
+ {
+ if($this->follow_redirect)
+ {
+ if(!IsSet($headers["location"])
+ || (GetType($headers["location"])!="array"
+ && strlen($location=$headers["location"])==0)
+ || (GetType($headers["location"])=="array"
+ && strlen($location=$headers["location"][0])==0))
+ return($this->SetError("it was received a redirect without location URL", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ if(strcmp($location[0],"/"))
+ {
+ if(!($location_arguments=@parse_url($location)))
+ return($this->SetError("the server did not return a valid redirection location URL", HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ if(!IsSet($location_arguments["scheme"]))
+ $location=((GetType($end=strrpos($this->request_uri,"/"))=="integer" && $end>1) ? substr($this->request_uri,0,$end) : "")."/".$location;
+ }
+ if(!strcmp($location[0],"/"))
+ $location=$this->protocol."://".$this->host_name.($this->host_port ? ":".$this->host_port : "").$location;
+ $error=$this->GetRequestArguments($location,$arguments);
+ if(strlen($error))
+ return($this->SetError("could not process redirect url: ".$error, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ $arguments["RequestMethod"]="GET";
+ if(strlen($error=$this->Close())==0
+ && strlen($error=$this->Open($arguments))==0
+ && strlen($error=$this->SendRequest($arguments))==0)
+ {
+ $this->redirection_level++;
+ if($this->redirection_level>$this->redirection_limit)
+ {
+ $error="it was exceeded the limit of request redirections";
+ $this->error_code = HTTP_CLIENT_ERROR_PROTOCOL_FAILURE;
+ }
+ else
+ $error=$this->ReadReplyHeaders($headers);
+ $this->redirection_level--;
+ }
+ if(strlen($error))
+ return($this->SetError($error, $this->error_code));
+ }
+ return("");
+ }
+
+ Function Authenticate(&$headers, $proxy, &$proxy_authorization, &$user, &$password, &$realm, &$workstation)
+ {
+ if($proxy)
+ {
+ $authenticate_header="proxy-authenticate";
+ $authorization_header="Proxy-Authorization";
+ $authenticate_status="407";
+ $authentication_mechanism=$this->proxy_authentication_mechanism;
+ }
+ else
+ {
+ $authenticate_header="www-authenticate";
+ $authorization_header="Authorization";
+ $authenticate_status="401";
+ $authentication_mechanism=$this->authentication_mechanism;
+ }
+ if(IsSet($headers[$authenticate_header])
+ && $this->sasl_authenticate)
+ {
+ if(function_exists("class_exists")
+ && !class_exists("sasl_client_class"))
+ return($this->SetError("the SASL client class needs to be loaded to be able to authenticate".($proxy ? " with the proxy server" : "")." and access this site", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ if(GetType($headers[$authenticate_header])=="array")
+ $authenticate=$headers[$authenticate_header];
+ else
+ $authenticate=array($headers[$authenticate_header]);
+ for($response="", $mechanisms=array(),$m=0;$mTokenize($authenticate[$m]," ");
+ $response=$this->Tokenize("");
+ if(strlen($authentication_mechanism))
+ {
+ if(!strcmp($authentication_mechanism,$mechanism))
+ {
+ $mechanisms[]=$mechanism;
+ break;
+ }
+ }
+ else
+ $mechanisms[]=$mechanism;
+ }
+ $sasl=new sasl_client_class;
+ if(IsSet($user))
+ $sasl->SetCredential("user",$user);
+ if(IsSet($password))
+ $sasl->SetCredential("password",$password);
+ if(IsSet($realm))
+ $sasl->SetCredential("realm",$realm);
+ if(IsSet($workstation))
+ $sasl->SetCredential("workstation",$workstation);
+ $sasl->SetCredential("uri",$this->request_uri);
+ $sasl->SetCredential("method",$this->request_method);
+ $sasl->SetCredential("session",$this->session);
+ do
+ {
+ $status=$sasl->Start($mechanisms,$message,$interactions);
+ }
+ while($status==SASL_INTERACT);
+ switch($status)
+ {
+ case SASL_CONTINUE:
+ break;
+ case SASL_NOMECH:
+ return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".(strlen($authentication_mechanism) ? "authentication mechanism ".$authentication_mechanism." may not be used: " : "").$sasl->error, HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ default:
+ return($this->SetError("Could not start the SASL ".($proxy ? "proxy " : "")."authentication client: ".$sasl->error, HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ }
+ if($proxy >= 0)
+ {
+ for(;;)
+ {
+ if(strlen($error=$this->ReadReplyBody($body,$this->file_buffer_length)))
+ return($error);
+ if(strlen($body)==0)
+ break;
+ }
+ }
+ $authorization_value=$sasl->mechanism.(IsSet($message) ? " ".($sasl->encode_response ? base64_encode($message) : $message) : "");
+ $request_arguments=$this->request_arguments;
+ $arguments=$request_arguments;
+ $arguments["Headers"][$authorization_header]=$authorization_value;
+ if(!$proxy
+ && strlen($proxy_authorization))
+ $arguments["Headers"]["Proxy-Authorization"]=$proxy_authorization;
+ if(strlen($error=$this->Close())
+ || strlen($error=$this->Open($arguments)))
+ return($this->SetError($error, $this->error_code));
+ $authenticated=0;
+ if(IsSet($message))
+ {
+ if($proxy < 0)
+ {
+ if(strlen($error=$this->ConnectFromProxy($arguments, $headers)))
+ return($this->SetError($error, $this->error_code));
+ }
+ else
+ {
+ if(strlen($error=$this->SendRequest($arguments))
+ || strlen($error=$this->ReadReplyHeadersResponse($headers)))
+ return($this->SetError($error, $this->error_code));
+ }
+ if(!IsSet($headers[$authenticate_header]))
+ $authenticate=array();
+ elseif(GetType($headers[$authenticate_header])=="array")
+ $authenticate=$headers[$authenticate_header];
+ else
+ $authenticate=array($headers[$authenticate_header]);
+ for($mechanism=0;$mechanismTokenize($authenticate[$mechanism]," "),$sasl->mechanism))
+ {
+ $response=$this->Tokenize("");
+ break;
+ }
+ }
+ switch($this->response_status)
+ {
+ case $authenticate_status:
+ break;
+ case "301":
+ case "302":
+ case "303":
+ case "307":
+ if($proxy >= 0)
+ return($this->Redirect($headers));
+ default:
+ if(intval($this->response_status/100)==2)
+ {
+ if($proxy)
+ $proxy_authorization=$authorization_value;
+ $authenticated=1;
+ break;
+ }
+ if($proxy
+ && !strcmp($this->response_status,"401"))
+ {
+ $proxy_authorization=$authorization_value;
+ $authenticated=1;
+ break;
+ }
+ return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".$this->response_status." ".$this->response_message, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ }
+ }
+ for(;!$authenticated;)
+ {
+ do
+ {
+ $status=$sasl->Step($response,$message,$interactions);
+ }
+ while($status==SASL_INTERACT);
+ switch($status)
+ {
+ case SASL_CONTINUE:
+ $authorization_value=$sasl->mechanism.(IsSet($message) ? " ".($sasl->encode_response ? base64_encode($message) : $message) : "");
+ $arguments=$request_arguments;
+ $arguments["Headers"][$authorization_header]=$authorization_value;
+ if(!$proxy
+ && strlen($proxy_authorization))
+ $arguments["Headers"]["Proxy-Authorization"]=$proxy_authorization;
+ if($proxy < 0)
+ {
+ if(strlen($error=$this->ConnectFromProxy($arguments, $headers)))
+ return($this->SetError($error, $this->error_code));
+ }
+ else
+ {
+ if(strlen($error=$this->SendRequest($arguments))
+ || strlen($error=$this->ReadReplyHeadersResponse($headers)))
+ return($this->SetError($error, $this->error_code));
+ }
+ switch($this->response_status)
+ {
+ case $authenticate_status:
+ if(GetType($headers[$authenticate_header])=="array")
+ $authenticate=$headers[$authenticate_header];
+ else
+ $authenticate=array($headers[$authenticate_header]);
+ for($response="",$mechanism=0;$mechanismTokenize($authenticate[$mechanism]," "),$sasl->mechanism))
+ {
+ $response=$this->Tokenize("");
+ break;
+ }
+ }
+ if($proxy >= 0)
+ {
+ for(;;)
+ {
+ if(strlen($error=$this->ReadReplyBody($body,$this->file_buffer_length)))
+ return($error);
+ if(strlen($body)==0)
+ break;
+ }
+ }
+ $this->state="Connected";
+ break;
+ case "301":
+ case "302":
+ case "303":
+ case "307":
+ if($proxy >= 0)
+ return($this->Redirect($headers));
+ default:
+ if(intval($this->response_status/100)==2)
+ {
+ if($proxy)
+ $proxy_authorization=$authorization_value;
+ $authenticated=1;
+ break;
+ }
+ if($proxy
+ && !strcmp($this->response_status,"401"))
+ {
+ $proxy_authorization=$authorization_value;
+ $authenticated=1;
+ break;
+ }
+ return($this->SetError(($proxy ? "proxy " : "")."authentication error: ".$this->response_status." ".$this->response_message));
+ }
+ break;
+ default:
+ return($this->SetError("Could not process the SASL ".($proxy ? "proxy " : "")."authentication step: ".$sasl->error, HTTP_CLIENT_ERROR_PROTOCOL_FAILURE));
+ }
+ }
+ }
+ return("");
+ }
+
+ Function ReadReplyHeaders(&$headers)
+ {
+ if(strlen($error=$this->ReadReplyHeadersResponse($headers)))
+ return($error);
+ $proxy_authorization="";
+ while(!strcmp($this->response_status, "100"))
+ {
+ $this->state="RequestSent";
+ if(strlen($error=$this->ReadReplyHeadersResponse($headers)))
+ return($error);
+ }
+ switch($this->response_status)
+ {
+ case "301":
+ case "302":
+ case "303":
+ case "307":
+ if(strlen($error=$this->Redirect($headers)))
+ return($error);
+ break;
+ case "407":
+ if(strlen($error=$this->Authenticate($headers, 1, $proxy_authorization, $this->proxy_request_user, $this->proxy_request_password, $this->proxy_request_realm, $this->proxy_request_workstation)))
+ return($error);
+ if(strcmp($this->response_status,"401"))
+ return("");
+ case "401":
+ return($this->Authenticate($headers, 0, $proxy_authorization, $this->request_user, $this->request_password, $this->request_realm, $this->request_workstation));
+ }
+ return("");
+ }
+
+ Function ReadReplyBody(&$body,$length)
+ {
+ $body="";
+ if(strlen($this->error))
+ return($this->error);
+ switch($this->state)
+ {
+ case "Disconnected":
+ return($this->SetError("connection was not yet established", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "Connected":
+ case "ConnectedToProxy":
+ return($this->SetError("request was not sent", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ case "RequestSent":
+ if(($error=$this->ReadReplyHeaders($headers))!="")
+ return($error);
+ break;
+ case "GotReplyHeaders":
+ break;
+ case 'ResponseReceived':
+ $body = '';
+ return('');
+ default:
+ return($this->SetError("can not get request headers in the current connection state", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ }
+ if($this->content_length_set)
+ $length=min($this->content_length-$this->read_length,$length);
+ $body = '';
+ if($length>0)
+ {
+ if(!$this->EndOfInput()
+ && ($body=$this->ReadBytes($length))=="")
+ {
+ if(strlen($this->error))
+ return($this->SetError("could not get the request reply body: ".$this->error, $this->error_code));
+ }
+ $this->read_length+=strlen($body);
+ if($this->EndOfInput())
+ $this->state = 'ResponseReceived';
+ }
+ return("");
+ }
+
+ Function ReadWholeReplyBody(&$body)
+ {
+ $body = '';
+ for(;;)
+ {
+ if(strlen($error = $this->ReadReplyBody($block, $this->file_buffer_length)))
+ return($error);
+ if(strlen($block) == 0)
+ return('');
+ $body .= $block;
+ }
+ }
+
+ Function ReadWholeReplyIntoTemporaryFile(&$file)
+ {
+ if(!($file = tmpfile()))
+ return $this->SetPHPError('could not create the temporary file to save the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE);
+ for(;;)
+ {
+ if(strlen($error = $this->ReadReplyBody($block, $this->file_buffer_length)))
+ {
+ fclose($file);
+ return($error);
+ }
+ if(strlen($block) == 0)
+ {
+ if(@fseek($file, 0) != 0)
+ {
+ $error = $this->SetPHPError('could not seek to the beginning of temporary file with the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE);
+ fclose($file);
+ return $error;
+ }
+ return('');
+ }
+ if(!@fwrite($file, $block))
+ {
+ $error = $this->SetPHPError('could not write to the temporary file to save the response', $php_errormsg, HTTP_CLIENT_ERROR_CANNOT_ACCESS_LOCAL_FILE);
+ fclose($file);
+ return $error;
+ }
+ }
+ }
+
+ Function SaveCookies(&$cookies, $domain='', $secure_only=0, $persistent_only=0)
+ {
+ $now=gmdate("Y-m-d H-i-s");
+ $cookies=array();
+ for($secure_cookies=0,Reset($this->cookies);$secure_cookiescookies);Next($this->cookies),$secure_cookies++)
+ {
+ $secure=Key($this->cookies);
+ if(!$secure_only
+ || $secure)
+ {
+ for($cookie_domain=0,Reset($this->cookies[$secure]);$cookie_domaincookies[$secure]);Next($this->cookies[$secure]),$cookie_domain++)
+ {
+ $domain_pattern=Key($this->cookies[$secure]);
+ $match=strlen($domain)-strlen($domain_pattern);
+ if(strlen($domain)==0
+ || ($match>=0
+ && !strcmp($domain_pattern,substr($domain,$match))
+ && ($match==0
+ || $domain_pattern[0]=="."
+ || $domain[$match-1]==".")))
+ {
+ for(Reset($this->cookies[$secure][$domain_pattern]),$path_part=0;$path_partcookies[$secure][$domain_pattern]);Next($this->cookies[$secure][$domain_pattern]),$path_part++)
+ {
+ $path=Key($this->cookies[$secure][$domain_pattern]);
+ for(Reset($this->cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookiecookies[$secure][$domain_pattern][$path]);Next($this->cookies[$secure][$domain_pattern][$path]),$cookie++)
+ {
+ $cookie_name=Key($this->cookies[$secure][$domain_pattern][$path]);
+ $expires=$this->cookies[$secure][$domain_pattern][$path][$cookie_name]["expires"];
+ if((!$persistent_only
+ && strlen($expires)==0)
+ || (strlen($expires)
+ && strcmp($now,$expires)<0))
+ $cookies[$secure][$domain_pattern][$path][$cookie_name]=$this->cookies[$secure][$domain_pattern][$path][$cookie_name];
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Function SavePersistentCookies(&$cookies, $domain='', $secure_only=0)
+ {
+ $this->SaveCookies($cookies, $domain, $secure_only, 1);
+ }
+
+ Function GetPersistentCookies(&$cookies, $domain='', $secure_only=0)
+ {
+ $this->SavePersistentCookies($cookies, $domain, $secure_only);
+ }
+
+ Function RestoreCookies($cookies, $clear=1)
+ {
+ $new_cookies=($clear ? array() : $this->cookies);
+ for($secure_cookies=0, Reset($cookies); $secure_cookiesSetError("invalid cookie secure value type (".serialize($secure).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ for($cookie_domain=0,Reset($cookies[$secure]);$cookie_domainSetError("invalid cookie domain value type (".serialize($domain_pattern).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ for(Reset($cookies[$secure][$domain_pattern]),$path_part=0;$path_partSetError("invalid cookie path value type (".serialize($path).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ for(Reset($cookies[$secure][$domain_pattern][$path]),$cookie=0;$cookieSetError("invalid cookie expiry value type (".serialize($expires).")", HTTP_CLIENT_ERROR_INVALID_PARAMETERS));
+ $new_cookies[$secure][$domain_pattern][$path][$cookie_name]=array(
+ "name"=>$cookie_name,
+ "value"=>$value,
+ "domain"=>$domain_pattern,
+ "path"=>$path,
+ "expires"=>$expires,
+ "secure"=>$secure
+ );
+ }
+ }
+ }
+ }
+ $this->cookies=$new_cookies;
+ return("");
+ }
+};
+
+?>
\ No newline at end of file
diff --git a/appnet/test/backup/oauth_client.php b/appnet/test/backup/oauth_client.php
new file mode 100644
index 0000000..e21e980
--- /dev/null
+++ b/appnet/test/backup/oauth_client.php
@@ -0,0 +1,2486 @@
+
+
+
+ net.manuellemos.oauth
+
+ @(#) $Id: oauth_client.php,v 1.97 2014/04/29 01:16:28 mlemos Exp $
+ Copyright (C) Manuel Lemos 2012
+ OAuth client
+ Manuel Lemos
+ mlemos-at-acm.org
+
+
+ en
+ This class serves two main purposes:
+ 1) Implement the OAuth protocol to retrieve a token from a server to
+ authorize the access to an API on behalf of the current
+ user.
+ 2) Perform calls to a Web services API using a token previously
+ obtained using this class or a token provided some other way by the
+ Web services provider.
+ Regardless of your purposes, you always need to start calling
+ the class Initialize function after
+ initializing setup variables. After you are done with the class,
+ always call the Finalize function at
+ the end.
+ This class supports either OAuth protocol versions 1.0, 1.0a and
+ 2.0. It abstracts the differences between these protocol versions,
+ so the class usage is the same independently of the OAuth
+ version of the server.
+ The class also provides built-in support to several popular OAuth
+ servers, so you do not have to manually configure all the details to
+ access those servers. Just set the
+ server variable to configure the class
+ to access one of the built-in supported servers.
+ If you need to access one type of server that is not yet directly
+ supported by the class, you need to configure it explicitly setting
+ the variables: oauth_version,
+ url_parameters,
+ authorization_header,
+ request_token_url,
+ dialog_url,
+ offline_dialog_url,
+ append_state_to_redirect_uri and
+ access_token_url.
+ Before proceeding to the actual OAuth authorization process, you
+ need to have registered your application with the OAuth server. The
+ registration provides you values to set the variables
+ client_id and
+ client_secret. Some servers also
+ provide an additional value to set the
+ api_key variable.
+ You also need to set the variables
+ redirect_uri and
+ scope before calling the
+ Process function to make the class
+ perform the necessary interactions with the OAuth
+ server.
+ The OAuth protocol involves multiple steps that include redirection
+ to the OAuth server. There it asks permission to the current user to
+ grant your application access to APIs on his/her behalf. When there
+ is a redirection, the class will set the
+ exit variable to
+ 1. Then your script should exit
+ immediately without outputting anything.
+ When the OAuth access token is successfully obtained, the following
+ variables are set by the class with the obtained values:
+ access_token,
+ access_token_secret,
+ access_token_expiry,
+ access_token_type. You may want to
+ store these values to use them later when calling the server
+ APIs.
+ If there was a problem during OAuth authorization process, check the
+ variable authorization_error to
+ determine the reason.
+ Once you get the access token, you can call the server APIs using
+ the CallAPI function. Check the
+ access_token_error variable to
+ determine if there was an error when trying to to call the
+ API.
+ If for some reason the user has revoked the access to your
+ application, you need to ask the user to authorize your application
+ again. First you may need to call the function
+ ResetAccessToken to reset the value of
+ the access token that may be cached in session variables.
+
+
+{/metadocument}
+*/
+
+class oauth_client_class
+{
+/*
+{metadocument}
+
+ error
+ STRING
+
+
+ Store the message that is returned when an error
+ occurs.
+ Check this variable to understand what happened when a call to
+ any of the class functions has failed.
+ This class uses cumulative error handling. This means that if one
+ class functions that may fail is called and this variable was
+ already set to an error message due to a failure in a previous call
+ to the same or other function, the function will also fail and does
+ not do anything.
+ This allows programs using this class to safely call several
+ functions that may fail and only check the failure condition after
+ the last function call.
+ Just set this variable to an empty string to clear the error
+ condition.
+
+
+{/metadocument}
+*/
+ var $error = '';
+
+/*
+{metadocument}
+
+ debug
+ BOOLEAN
+ 0
+
+ Control whether debug output is enabled
+ Set this variable to 1 if you
+ need to check what is going on during calls to the class. When
+ enabled, the debug output goes either to the variable
+ debug_output and the PHP error log.
+
+
+{/metadocument}
+*/
+ var $debug = false;
+
+/*
+{metadocument}
+
+ debug_http
+ BOOLEAN
+ 0
+
+ Control whether the dialog with the remote Web server
+ should also be logged.
+ Set this variable to 1 if you
+ want to inspect the data exchange with the OAuth server.
+
+
+{/metadocument}
+*/
+ var $debug_http = false;
+
+/*
+{metadocument}
+
+ exit
+ BOOLEAN
+ 0
+
+ Determine if the current script should be exited.
+ Check this variable after calling the
+ Process function and exit your script
+ immediately if the variable is set to
+ 1.
+
+
+{/metadocument}
+*/
+ var $exit = false;
+
+/*
+{metadocument}
+
+ debug_output
+ STRING
+
+
+ Capture the debug output generated by the class
+ Inspect this variable if you need to see what happened during
+ the class function calls.
+
+
+{/metadocument}
+*/
+ var $debug_output = '';
+
+/*
+{metadocument}
+
+ debug_prefix
+ STRING
+ OAuth client:
+
+ Mark the lines of the debug output to identify actions
+ performed by this class.
+ Change this variable if you prefer the debug output lines to
+ be prefixed with a different text.
+
+
+{/metadocument}
+*/
+ var $debug_prefix = 'OAuth client: ';
+
+/*
+{metadocument}
+
+ server
+ STRING
+
+
+ Identify the type of OAuth server to access.
+ The class provides built-in support to several types of OAuth
+ servers. This means that the class can automatically initialize
+ several configuration variables just by setting this server
+ variable.
+ Currently it supports the following servers:
+ 37Signals,
+ Amazon,
+ Bitbucket,
+ Box,
+ Buffer,
+ Dailymotion,
+ Discogs,
+ Disqus,
+ Dropbox (Dropbox with OAuth 1.0),
+ Dropbox2 (Dropbox with OAuth 2.0),
+ Etsy,
+ Eventful,
+ Facebook,
+ Fitbit,
+ Flickr,
+ Foursquare,
+ github,
+ Google,
+ Google1 (Google with OAuth 1.0),
+ Instagram,
+ LinkedIn,
+ Microsoft,
+ Rdio,
+ Reddit,
+ Salesforce,
+ Scoop.it,
+ StockTwits,
+ SurveyMonkey,
+ Tumblr,
+ Twitter,
+ Vimeo,
+ VK,
+ Withings,
+ Wordpress,
+ Xero,
+ XING and
+ Yahoo. Please contact the author if you
+ would like to ask to add built-in support for other types of OAuth
+ servers.
+ If you want to access other types of OAuth servers that are not
+ yet supported, set this variable to an empty string and configure
+ other variables with values specific to those servers.
+
+
+{/metadocument}
+*/
+ var $server = '';
+
+/*
+{metadocument}
+
+ configuration_file
+ STRING
+ oauth_configuration.json
+
+ Specify the path of the configuration file that defines the
+ properties of additional OAuth server types.
+ Change the path in this variable if you are accessing a type
+ of server without support built-in the class and you need to put
+ the configuration file path in a different directory.
+
+
+{/metadocument}
+*/
+ var $configuration_file = 'oauth_configuration.json';
+
+/*
+{metadocument}
+
+ request_token_url
+ STRING
+
+
+ URL of the OAuth server to request the initial token for
+ OAuth 1.0 and 1.0a servers.
+ Set this variable to the OAuth request token URL when you are
+ not accessing one of the built-in supported OAuth
+ servers.
+ For OAuth 1.0 and 1.0a servers, the request token URL can have
+ certain marks that will act as template placeholders which will be
+ replaced with given values before requesting the authorization
+ token. Currently it supports the following placeholder
+ marks:
+ {SCOPE} - scope of the requested permissions to the granted by the
+ OAuth server with the user permissions
+
+
+{/metadocument}
+*/
+ var $request_token_url = '';
+
+/*
+{metadocument}
+
+ dialog_url
+ STRING
+
+
+ URL of the OAuth server to redirect the browser so the user
+ can grant access to your application.
+ Set this variable to the OAuth request token URL when you are
+ not accessing one of the built-in supported OAuth servers.
+ For OAuth 1.0a servers that return the login dialog URL
+ automatically, set this variable to
+ automatic
+ For certain servers, the dialog URL can have certain marks that
+ will act as template placeholders which will be replaced with
+ values defined before redirecting the users browser. Currently it
+ supports the following placeholder marks:
+ {REDIRECT_URI} - URL to redirect when returning from the OAuth
+ server authorization page
+ {CLIENT_ID} - client application identifier registered at the
+ server
+ {SCOPE} - scope of the requested permissions to the granted by the
+ OAuth server with the user permissions
+ {STATE} - identifier of the OAuth session state
+ {API_KEY} - API key to access the server
+
+
+{/metadocument}
+*/
+ var $dialog_url = '';
+
+/*
+{metadocument}
+
+ offline_dialog_url
+ STRING
+
+
+ URL of the OAuth server to redirect the browser so the user
+ can grant access to your application when offline access is
+ requested.
+ Set this variable to the OAuth request token URL when you are
+ not accessing one of the built-in supported OAuth servers and the
+ OAuth server supports offline access.
+ It should have the same format as the
+ dialog_url variable.
+
+
+{/metadocument}
+*/
+ var $offline_dialog_url = '';
+
+/*
+{metadocument}
+
+ append_state_to_redirect_uri
+ STRING
+
+
+ Pass the OAuth session state in a variable with a different
+ name to work around implementation bugs of certain OAuth
+ servers
+ Set this variable when you are not accessing one of the
+ built-in supported OAuth servers if the OAuth server has a bug
+ that makes it not pass back the OAuth state identifier in a
+ request variable named state.
+
+
+{/metadocument}
+*/
+ var $append_state_to_redirect_uri = '';
+
+/*
+{metadocument}
+
+ access_token_url
+ STRING
+
+
+ OAuth server URL that will return the access token
+ URL.
+ Set this variable to the OAuth access token URL when you are
+ not accessing one of the built-in supported OAuth servers.
+
+
+{/metadocument}
+*/
+ var $access_token_url = '';
+
+
+/*
+{metadocument}
+
+ oauth_version
+ STRING
+ 2.0
+
+ Version of the protocol version supported by the OAuth
+ server.
+ Set this variable to the OAuth server protocol version when
+ you are not accessing one of the built-in supported OAuth
+ servers.
+
+
+{/metadocument}
+*/
+ var $oauth_version = '2.0';
+
+/*
+{metadocument}
+
+ url_parameters
+ BOOLEAN
+ 0
+
+ Determine if the API call parameters should be moved to the
+ call URL.
+ Set this variable to 1 if the
+ API you need to call requires that the call parameters always be
+ passed via the API URL.
+
+
+{/metadocument}
+*/
+ var $url_parameters = false;
+
+/*
+{metadocument}
+
+ authorization_header
+ BOOLEAN
+ 1
+
+ Determine if the OAuth parameters should be passed via HTTP
+ Authorization request header.
+ Set this variable to 1 if the
+ OAuth server requires that the OAuth parameters be passed using
+ the HTTP Authorization instead of the request URI parameters.
+
+
+{/metadocument}
+*/
+ var $authorization_header = true;
+
+/*
+{metadocument}
+
+ token_request_method
+ STRING
+ GET
+
+ Define the HTTP method that should be used to request
+ tokens from the server.
+ Set this variable to POST if the
+ OAuth server does not support requesting tokens using the HTTP GET
+ method.
+
+
+{/metadocument}
+*/
+ var $token_request_method = 'GET';
+
+/*
+{metadocument}
+
+ signature_method
+ STRING
+ HMAC-SHA1
+
+ Define the method to generate the signature for API request
+ parameters values.
+ Currently it supports PLAINTEXT
+ and HMAC-SHA1.
+
+
+{/metadocument}
+*/
+ var $signature_method = 'HMAC-SHA1';
+
+/*
+{metadocument}
+
+ redirect_uri
+ STRING
+
+
+ URL of the current script page that is calling this
+ class
+ Set this variable to the current script page URL before
+ proceeding the the OAuth authorization process.
+
+
+{/metadocument}
+*/
+ var $redirect_uri = '';
+
+/*
+{metadocument}
+
+ client_id
+ STRING
+
+
+ Identifier of your application registered with the OAuth
+ server
+ Set this variable to the application identifier that is
+ provided by the OAuth server when you register the
+ application.
+
+
+{/metadocument}
+*/
+ var $client_id = '';
+
+/*
+{metadocument}
+
+ client_secret
+ STRING
+
+
+ Secret value assigned to your application when it is
+ registered with the OAuth server.
+ Set this variable to the application secret that is provided
+ by the OAuth server when you register the application.
+
+
+{/metadocument}
+*/
+ var $client_secret = '';
+
+/*
+{metadocument}
+
+ api_key
+ STRING
+
+
+ Identifier of your API key provided by the OAuth
+ server
+ Set this variable to the API key if the OAuth server requires
+ one.
+
+
+{/metadocument}
+*/
+ var $api_key = '';
+
+/*
+{metadocument}
+
+ get_token_with_api_key
+ BOOLEAN
+ 0
+
+ Option to determine if the access token should be retrieved
+ using the API key value instead of the client secret.
+ Set this variable to 1 if the
+ OAuth server requires that the client secret be set to the API key
+ when retrieving the OAuth token.
+
+
+{/metadocument}
+*/
+ var $get_token_with_api_key = false;
+
+/*
+{metadocument}
+
+ scope
+ STRING
+
+
+ Permissions that your application needs to call the OAuth
+ server APIs
+ Check the documentation of the APIs that your application
+ needs to call to set this variable with the identifiers of the
+ permissions that the user needs to grant to your application.
+
+
+{/metadocument}
+*/
+ var $scope = '';
+
+/*
+{metadocument}
+
+ offline
+ BOOLEAN
+ 0
+
+ Specify whether it will be necessary to call the API when
+ the user is not present and the server supports renewing expired
+ access tokens using refresh tokens.
+ Set this variable to 1 if the
+ server supports renewing expired tokens automatically when the
+ user is not present.
+
+
+{/metadocument}
+*/
+ var $offline = false;
+
+/*
+{metadocument}
+
+ access_token
+ STRING
+
+
+ Access token obtained from the OAuth server
+ Check this variable to get the obtained access token upon
+ successful OAuth authorization.
+
+
+{/metadocument}
+*/
+ var $access_token = '';
+
+/*
+{metadocument}
+
+ access_token_secret
+ STRING
+
+
+ Access token secret obtained from the OAuth server
+ If the OAuth protocol version is 1.0 or 1.0a, check this
+ variable to get the obtained access token secret upon successful
+ OAuth authorization.
+
+
+{/metadocument}
+*/
+ var $access_token_secret = '';
+
+/*
+{metadocument}
+
+ access_token_expiry
+ STRING
+
+
+ Timestamp of the expiry of the access token obtained from
+ the OAuth server.
+ Check this variable to get the obtained access token expiry
+ time upon successful OAuth authorization. If this variable is
+ empty, that means no expiry time was set.
+
+
+{/metadocument}
+*/
+ var $access_token_expiry = '';
+
+/*
+{metadocument}
+
+ access_token_type
+ STRING
+
+
+ Type of access token obtained from the OAuth server.
+ Check this variable to get the obtained access token type
+ upon successful OAuth authorization.
+
+
+{/metadocument}
+*/
+ var $access_token_type = '';
+
+/*
+{metadocument}
+
+ default_access_token_type
+ STRING
+
+
+ Type of access token to be assumed when the OAuth server
+ does not specify an access token type.
+ Set this variable if the server requires a certain type of
+ access token to be used but it does not specify a token type
+ when the access token is returned.
+
+
+{/metadocument}
+*/
+ var $default_access_token_type = '';
+
+
+/*
+{metadocument}
+
+ access_token_parameter
+ STRING
+
+
+ Name of the access token parameter to be passed in API call
+ requests.
+ Set this variable to a non-empty string to override the
+ default name for the access token parameter which is
+ oauth_token of OAuth 1 and
+ access_token for OAuth 2.
+
+
+{/metadocument}
+*/
+ var $access_token_parameter = '';
+
+
+/*
+{metadocument}
+
+ access_token_response
+ ARRAY
+
+ The original response for the access token request
+ Check this variable if the OAuth server returns custom
+ parameters in the request to obtain the access token.
+
+
+{/metadocument}
+*/
+ var $access_token_response;
+
+/*
+{metadocument}
+
+ store_access_token_response
+ BOOLEAN
+ 0
+
+ Option to determine if the original response for the access
+ token request should be stored in the
+ access_token_response
+ variable.
+ Set this variable to 1 if the
+ OAuth server returns custom parameters in the request to obtain
+ the access token that may be needed in subsequent API calls.
+
+
+{/metadocument}
+*/
+ var $store_access_token_response = false;
+
+/*
+{metadocument}
+
+ access_token_authentication
+ STRING
+
+
+ Option to determine if the requests to obtain a new access
+ token should use authentication to pass the application client ID
+ and secret.
+ Set this variable to basic if the
+ OAuth server requires that the the client ID and secret be passed
+ using HTTP basic authentication headers when retrieving a new
+ token.
+
+
+{/metadocument}
+*/
+ var $access_token_authentication = '';
+
+/*
+{metadocument}
+
+ refresh_token
+ STRING
+
+
+ Refresh token obtained from the OAuth server
+ Check this variable to get the obtained refresh token upon
+ successful OAuth authorization.
+
+
+{/metadocument}
+*/
+ var $refresh_token = '';
+
+/*
+{metadocument}
+
+ access_token_error
+ STRING
+
+
+ Error message returned when a call to the API fails.
+ Check this variable to determine if there was an error while
+ calling the Web services API when using the
+ CallAPI function.
+
+
+{/metadocument}
+*/
+ var $access_token_error = '';
+
+/*
+{metadocument}
+
+ authorization_error
+ STRING
+
+
+ Error message returned when it was not possible to obtain
+ an OAuth access token
+ Check this variable to determine if there was an error while
+ trying to obtain the OAuth access token.
+
+
+{/metadocument}
+*/
+ var $authorization_error = '';
+
+/*
+{metadocument}
+
+ response_status
+ INTEGER
+ 0
+
+ HTTP response status returned by the server when calling an
+ API
+ Check this variable after calling the
+ CallAPI function if the API calls and you
+ need to process the error depending the response status.
+ 200 means no error.
+ 0 means the server response was not
+ retrieved.
+
+
+{/metadocument}
+*/
+ var $response_status = 0;
+
+ var $oauth_user_agent = 'PHP-OAuth-API (http://www.phpclasses.org/oauth-api $Revision: 1.97 $)';
+
+ Function SetError($error)
+ {
+ $this->error = $error;
+ if($this->debug)
+ $this->OutputDebug('Error: '.$error);
+ return(false);
+ }
+
+ Function SetPHPError($error, &$php_error_message)
+ {
+ if(IsSet($php_error_message)
+ && strlen($php_error_message))
+ $error.=": ".$php_error_message;
+ return($this->SetError($error));
+ }
+
+ Function OutputDebug($message)
+ {
+ if($this->debug)
+ {
+ $message = $this->debug_prefix.$message;
+ $this->debug_output .= $message."\n";;
+echo $message; error_log($message);
+ }
+ return(true);
+ }
+
+ Function GetRequestTokenURL(&$request_token_url)
+ {
+ $request_token_url = $this->request_token_url;
+ return(true);
+ }
+
+ Function GetDialogURL(&$url, $redirect_uri = '', $state = '')
+ {
+ $url = (($this->offline && strlen($this->offline_dialog_url)) ? $this->offline_dialog_url : $this->dialog_url);
+ if(strlen($url) === 0)
+ return $this->SetError('the dialog URL '.($this->offline ? 'for offline access ' : '').'is not defined for this server');
+ $url = str_replace(
+ '{REDIRECT_URI}', UrlEncode($redirect_uri), str_replace(
+ '{STATE}', UrlEncode($state), str_replace(
+ '{CLIENT_ID}', UrlEncode($this->client_id), str_replace(
+ '{API_KEY}', UrlEncode($this->api_key), str_replace(
+ '{SCOPE}', UrlEncode($this->scope),
+ $url)))));
+ return(true);
+ }
+
+ Function GetAccessTokenURL(&$access_token_url)
+ {
+ $access_token_url = str_replace('{API_KEY}', $this->api_key, $this->access_token_url);
+ return(true);
+ }
+
+ Function GetStoredState(&$state)
+ {
+ if(!function_exists('session_start'))
+ return $this->SetError('Session variables are not accessible in this PHP environment');
+ if(session_id() === ''
+ && !session_start())
+ return($this->SetPHPError('it was not possible to start the PHP session', $php_errormsg));
+
+ if(IsSet($_SESSION['OAUTH_STATE']))
+ $state = $_SESSION['OAUTH_STATE'];
+ else
+ $state = $_SESSION['OAUTH_STATE'] = time().'-'.substr(md5(rand().time()), 0, 6);
+ return(true);
+ }
+
+ Function GetRequestState(&$state)
+ {
+ $check = (strlen($this->append_state_to_redirect_uri) ? $this->append_state_to_redirect_uri : 'state');
+ $state = (IsSet($_GET[$check]) ? $_GET[$check] : null);
+ return(true);
+ }
+
+ Function GetRequestCode(&$code)
+ {
+ $code = (IsSet($_GET['code']) ? $_GET['code'] : null);
+ return(true);
+ }
+
+ Function GetRequestError(&$error)
+ {
+ $error = (IsSet($_GET['error']) ? $_GET['error'] : null);
+ return(true);
+ }
+
+ Function GetRequestDenied(&$denied)
+ {
+ $denied = (IsSet($_GET['denied']) ? $_GET['denied'] : null);
+ return(true);
+ }
+
+ Function GetRequestToken(&$token, &$verifier)
+ {
+ $token = (IsSet($_GET['oauth_token']) ? $_GET['oauth_token'] : null);
+ $verifier = (IsSet($_GET['oauth_verifier']) ? $_GET['oauth_verifier'] : null);
+ return(true);
+ }
+
+ Function GetRedirectURI(&$redirect_uri)
+ {
+ if(strlen($this->redirect_uri))
+ $redirect_uri = $this->redirect_uri;
+ else
+ $redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
+ return true;
+ }
+
+/*
+{metadocument}
+
+ Redirect
+ VOID
+
+ Redirect the user browser to a given page.
+ This function is meant to be only be called from inside the
+ class. By default it issues HTTP 302 response status and sets the
+ redirection location to a given URL. Sub-classes may override this
+ function to implement a different way to redirect the user
+ browser.
+
+
+ url
+ STRING
+
+ String with the full URL of the page to redirect.
+
+
+
+{/metadocument}
+*/
+ Function Redirect($url)
+ {
+ Header('HTTP/1.0 302 OAuth Redirection');
+ Header('Location: '.$url);
+ }
+/*
+{metadocument}
+
+
+{/metadocument}
+*/
+
+/*
+{metadocument}
+
+ StoreAccessToken
+ BOOLEAN
+
+ Store the values of the access token when it is succefully
+ retrieved from the OAuth server.
+ This function is meant to be only be called from inside the
+ class. By default it stores access tokens in a session variable
+ named OAUTH_ACCESS_TOKEN.
+ Actual implementations should create a sub-class and override this
+ function to make the access token values be stored in other types
+ of containers, like for instance databases.
+ This function should return
+ 1 if the access token was stored
+ successfully.
+
+
+ access_token
+ HASH
+
+ Associative array with properties of the access token.
+ The array may have set the following
+ properties:
+ value: string value of the access
+ token
+ authorized: boolean value that
+ determines if the access token was obtained
+ successfully
+ expiry: (optional) timestamp in ISO
+ format relative to UTC time zone of the access token expiry
+ time
+ type: (optional) type of OAuth token
+ that may determine how it should be used when sending API call
+ requests.
+ refresh: (optional) token that some
+ servers may set to allowing refreshing access tokens when they
+ expire.
+
+
+
+{/metadocument}
+*/
+ Function StoreAccessToken($access_token)
+ {
+ if(!function_exists('session_start'))
+ return $this->SetError('Session variables are not accessible in this PHP environment');
+ if(session_id() === ''
+ && !session_start())
+ return($this->SetPHPError('it was not possible to start the PHP session', $php_errormsg));
+ if(!$this->GetAccessTokenURL($access_token_url))
+ return false;
+ $_SESSION['OAUTH_ACCESS_TOKEN'][$access_token_url] = $access_token;
+ return true;
+ }
+/*
+{metadocument}
+
+
+{/metadocument}
+*/
+
+/*
+{metadocument}
+
+ GetAccessToken
+ BOOLEAN
+
+ Retrieve the OAuth access token if it was already
+ previously stored by the
+ StoreAccessToken function.
+ This function is meant to be only be called from inside the
+ class. By default it retrieves access tokens stored in a session
+ variable named
+ OAUTH_ACCESS_TOKEN.
+ Actual implementations should create a sub-class and override this
+ function to retrieve the access token values from other types of
+ containers, like for instance databases.
+ This function should return
+ 1 if the access token was retrieved
+ successfully.
+
+
+ access_token
+ STRING
+
+
+ Return the properties of the access token in an
+ associative array. If the access token was not yet stored, it
+ returns an empty array. Otherwise, the properties it may return
+ are the same that may be passed to the
+ StoreAccessToken.
+
+
+
+{/metadocument}
+*/
+ Function GetAccessToken(&$access_token)
+ {
+ if(!function_exists('session_start'))
+ return $this->SetError('Session variables are not accessible in this PHP environment');
+ if(session_id() === ''
+ && !session_start())
+ return($this->SetPHPError('it was not possible to start the PHP session', $php_errormsg));
+ if(!$this->GetAccessTokenURL($access_token_url))
+ return false;
+ if(IsSet($_SESSION['OAUTH_ACCESS_TOKEN'][$access_token_url]))
+ $access_token = $_SESSION['OAUTH_ACCESS_TOKEN'][$access_token_url];
+ else
+ $access_token = array();
+ return true;
+ }
+/*
+{metadocument}
+
+
+{/metadocument}
+*/
+
+/*
+{metadocument}
+
+ ResetAccessToken
+ BOOLEAN
+
+ Reset the access token to a state back when the user has
+ not yet authorized the access to the OAuth server API.
+ Call this function if for some reason the token to access
+ the API was revoked and you need to ask the user to authorize
+ the access again.
+ By default the class stores and retrieves access tokens in a
+ session variable named
+ OAUTH_ACCESS_TOKEN.
+ This function must be called when the user is accessing your site
+ pages, so it can reset the information stored in session variables
+ that cache the state of a previously retrieved access
+ token.
+ Actual implementations should create a sub-class and override this
+ function to reset the access token state when it is stored in
+ other types of containers, like for instance databases.
+ This function should return
+ 1 if the access token was resetted
+ successfully.
+
+
+{/metadocument}
+*/
+ Function ResetAccessToken()
+ {
+ if(!$this->GetAccessTokenURL($access_token_url))
+ return false;
+ if($this->debug)
+ $this->OutputDebug('Resetting the access token status for OAuth server located at '.$access_token_url);
+ if(!function_exists('session_start'))
+ return $this->SetError('Session variables are not accessible in this PHP environment');
+ if(session_id() === ''
+ && !session_start())
+ return($this->SetPHPError('it was not possible to start the PHP session', $php_errormsg));
+ if(IsSet($_SESSION['OAUTH_ACCESS_TOKEN'][$access_token_url]))
+ Unset($_SESSION['OAUTH_ACCESS_TOKEN'][$access_token_url]);
+ return true;
+ }
+/*
+{metadocument}
+
+
+{/metadocument}
+*/
+
+ Function Encode($value)
+ {
+ return(is_array($value) ? $this->EncodeArray($value) : str_replace('%7E', '~', str_replace('+',' ', RawURLEncode($value))));
+ }
+
+ Function EncodeArray($array)
+ {
+ foreach($array as $key => $value)
+ $array[$key] = $this->Encode($value);
+ return $array;
+ }
+
+ Function HMAC($function, $data, $key)
+ {
+ switch($function)
+ {
+ case 'sha1':
+ $pack = 'H40';
+ break;
+ default:
+ if($this->debug)
+ $this->OutputDebug($function.' is not a supported an HMAC hash type');
+ return('');
+ }
+ if(strlen($key) > 64)
+ $key = pack($pack, $function($key));
+ if(strlen($key) < 64)
+ $key = str_pad($key, 64, "\0");
+ return(pack($pack, $function((str_repeat("\x5c", 64) ^ $key).pack($pack, $function((str_repeat("\x36", 64) ^ $key).$data)))));
+ }
+
+ Function SendAPIRequest($url, $method, $parameters, $oauth, $options, &$response)
+ {
+ $this->response_status = 0;
+ $http = new http_class;
+ $http->debug = ($this->debug && $this->debug_http);
+ $http->log_debug = true;
+ $http->sasl_authenticate = 0;
+ $http->user_agent = $this->oauth_user_agent;
+ $http->redirection_limit = (IsSet($options['FollowRedirection']) ? intval($options['FollowRedirection']) : 0);
+ $http->follow_redirect = ($http->redirection_limit != 0);
+ if($this->debug)
+ $this->OutputDebug('Accessing the '.$options['Resource'].' at '.$url);
+ $post_files = array();
+ $method = strtoupper($method);
+ $authorization = '';
+ $type = (IsSet($options['RequestContentType']) ? strtolower(trim(strtok($options['RequestContentType'], ';'))) : (($method === 'POST' || IsSet($oauth)) ? 'application/x-www-form-urlencoded' : ''));
+ if(IsSet($oauth))
+ {
+ $values = array(
+ 'oauth_consumer_key'=>$this->client_id,
+ 'oauth_nonce'=>md5(uniqid(rand(), true)),
+ 'oauth_signature_method'=>$this->signature_method,
+ 'oauth_timestamp'=>time(),
+ 'oauth_version'=>'1.0',
+ );
+ $files = (IsSet($options['Files']) ? $options['Files'] : array());
+ if(count($files))
+ {
+ foreach($files as $name => $value)
+ {
+ if(!IsSet($parameters[$name]))
+ return($this->SetError('it was specified an file parameters named '.$name));
+ $file = array();
+ switch(IsSet($value['Type']) ? $value['Type'] : 'FileName')
+ {
+ case 'FileName':
+ $file['FileName'] = $parameters[$name];
+ break;
+ case 'Data':
+ $file['Data'] = $parameters[$name];
+ break;
+ default:
+ return($this->SetError($value['Type'].' is not a valid type for file '.$name));
+ }
+ $file['Content-Type'] = (IsSet($value['ContentType']) ? $value['ContentType'] : 'automatic/name');
+ $post_files[$name] = $file;
+ }
+ UnSet($parameters[$name]);
+ if($method !== 'POST')
+ {
+ $this->OutputDebug('For uploading files the method should be POST not '.$method);
+ $method = 'POST';
+ }
+ if($type !== 'multipart/form-data')
+ {
+ if(IsSet($options['RequestContentType']))
+ return($this->SetError('the request content type for uploading files should be multipart/form-data'));
+ $type = 'multipart/form-data';
+ }
+ $value_parameters = array();
+ }
+ else
+ {
+ if($this->url_parameters
+ && $type === 'application/x-www-form-urlencoded'
+ && count($parameters))
+ {
+ $first = (strpos($url, '?') === false);
+ foreach($parameters as $parameter => $value)
+ {
+ $url .= ($first ? '?' : '&').UrlEncode($parameter).'='.UrlEncode($value);
+ $first = false;
+ }
+ $parameters = array();
+ }
+ $value_parameters = (($type !== 'application/x-www-form-urlencoded') ? array() : $parameters);
+ }
+ $header_values = ($method === 'GET' ? array_merge($values, $oauth, $value_parameters) : array_merge($values, $oauth));
+ $values = array_merge($values, $oauth, $value_parameters);
+ $key = $this->Encode($this->client_secret).'&'.$this->Encode($this->access_token_secret);
+ switch($this->signature_method)
+ {
+ case 'PLAINTEXT':
+ $values['oauth_signature'] = $key;
+ break;
+ case 'HMAC-SHA1':
+ $uri = strtok($url, '?');
+ $sign = $method.'&'.$this->Encode($uri).'&';
+ $first = true;
+ $sign_values = $values;
+ $u = parse_url($url);
+ if(IsSet($u['query']))
+ {
+ parse_str($u['query'], $q);
+ foreach($q as $parameter => $value)
+ $sign_values[$parameter] = $value;
+ }
+ KSort($sign_values);
+ foreach($sign_values as $parameter => $value)
+ {
+ $sign .= $this->Encode(($first ? '' : '&').$parameter.'='.$this->Encode($value));
+ $first = false;
+ }
+ $header_values['oauth_signature'] = $values['oauth_signature'] = base64_encode($this->HMAC('sha1', $sign, $key));
+ break;
+ default:
+ return $this->SetError($this->signature_method.' signature method is not yet supported');
+ }
+ if($this->authorization_header)
+ {
+ $authorization = 'OAuth';
+ $first = true;
+ foreach($header_values as $parameter => $value)
+ {
+ $authorization .= ($first ? ' ' : ',').$parameter.'="'.$this->Encode($value).'"';
+ $first = false;
+ }
+ $post_values = $parameters;
+ }
+ else
+ {
+ if($method === 'GET'
+ || (IsSet($options['PostValuesInURI'])
+ && $options['PostValuesInURI']))
+ {
+ $first = (strcspn($url, '?') == strlen($url));
+ foreach($values as $parameter => $value)
+ {
+ $url .= ($first ? '?' : '&').$parameter.'='.$this->Encode($value);
+ $first = false;
+ }
+ $post_values = array();
+ }
+ else
+ $post_values = $values;
+ }
+ }
+ else
+ {
+ $post_values = $parameters;
+ if(count($parameters))
+ {
+ switch($type)
+ {
+ case 'application/x-www-form-urlencoded':
+ case 'multipart/form-data':
+ case 'application/json':
+ break;
+ default:
+ $first = (strpos($url, '?') === false);
+ foreach($parameters as $name => $value)
+ {
+ if(GetType($value) === 'array')
+ {
+ foreach($value as $index => $value)
+ {
+ $url .= ($first ? '?' : '&').$name.'='.UrlEncode($value);
+ $first = false;
+ }
+ }
+ else
+ {
+ $url .= ($first ? '?' : '&').$name.'='.UrlEncode($value);
+ $first = false;
+ }
+ }
+ }
+ }
+ }
+ if(strlen($authorization) === 0
+ && !strcasecmp($this->access_token_type, 'Bearer'))
+ $authorization = 'Bearer '.$this->access_token;
+ if(strlen($error = $http->GetRequestArguments($url, $arguments)))
+ return($this->SetError('it was not possible to open the '.$options['Resource'].' URL: '.$error));
+ if(strlen($error = $http->Open($arguments)))
+ return($this->SetError('it was not possible to open the '.$options['Resource'].' URL: '.$error));
+ if(count($post_files))
+ $arguments['PostFiles'] = $post_files;
+ $arguments['RequestMethod'] = $method;
+ switch($type)
+ {
+ case 'application/x-www-form-urlencoded':
+ case 'multipart/form-data':
+ if(IsSet($options['RequestBody']))
+ return($this->SetError('the request body is defined automatically from the parameters'));
+ $arguments['PostValues'] = $post_values;
+ break;
+ case 'application/json':
+ $arguments['Headers']['Content-Type'] = $options['RequestContentType'];
+ $arguments['Body'] = (IsSet($options['RequestBody']) ? $options['RequestBody'] : json_encode($parameters));
+ break;
+ default:
+ if(!IsSet($options['RequestBody']))
+ return($this->SetError('it was not specified the body value of the of the API call request'));
+ $arguments['Headers']['Content-Type'] = $options['RequestContentType'];
+ $arguments['Body'] = $options['RequestBody'];
+ break;
+ }
+ $arguments['Headers']['Accept'] = (IsSet($options['Accept']) ? $options['Accept'] : '*/*'); /* */
+ switch(IsSet($options['AccessTokenAuthentication']) ? strtolower($options['AccessTokenAuthentication']) : '')
+ {
+ case 'basic':
+ $arguments['Headers']['Authorization'] = 'Basic '.base64_encode($this->client_id.':'.($this->get_token_with_api_key ? $this->api_key : $this->client_secret));
+ break;
+ case '':
+ if(strlen($authorization))
+ $arguments['Headers']['Authorization'] = $authorization;
+ break;
+ default:
+ return($this->SetError($this->access_token_authentication.' is not a supported authentication mechanism to retrieve an access token'));
+ }
+ if(strlen($error = $http->SendRequest($arguments))
+ || strlen($error = $http->ReadReplyHeaders($headers)))
+ {
+ $http->Close();
+ return($this->SetError('it was not possible to retrieve the '.$options['Resource'].': '.$error));
+ }
+ $error = $http->ReadWholeReplyBody($data);
+ $http->Close();
+ if(strlen($error))
+ {
+ return($this->SetError('it was not possible to access the '.$options['Resource'].': '.$error));
+ }
+ $this->response_status = intval($http->response_status);
+ $content_type = (IsSet($options['ResponseContentType']) ? $options['ResponseContentType'] : (IsSet($headers['content-type']) ? strtolower(trim(strtok($headers['content-type'], ';'))) : 'unspecified'));
+ $content_type = preg_replace('/^(.+\\/).+\\+(.+)$/', '\\1\\2', $content_type);
+ switch($content_type)
+ {
+ case 'text/javascript':
+ case 'application/json':
+ if(!function_exists('json_decode'))
+ return($this->SetError('the JSON extension is not available in this PHP setup'));
+ $object = json_decode($data);
+ switch(GetType($object))
+ {
+ case 'object':
+ if(!IsSet($options['ConvertObjects'])
+ || !$options['ConvertObjects'])
+ $response = $object;
+ else
+ {
+ $response = array();
+ foreach($object as $property => $value)
+ $response[$property] = $value;
+ }
+ break;
+ case 'array':
+ $response = $object;
+ break;
+ default:
+ if(!IsSet($object))
+ return($this->SetError('it was not returned a valid JSON definition of the '.$options['Resource'].' values'));
+ $response = $object;
+ break;
+ }
+ break;
+ case 'application/x-www-form-urlencoded':
+ case 'text/plain':
+ case 'text/html':
+ parse_str($data, $response);
+ break;
+ case 'text/xml':
+ if(IsSet($options['DecodeXMLResponse']))
+ {
+ switch(strtolower($options['DecodeXMLResponse']))
+ {
+ case 'simplexml':
+ if($this->debug)
+ $this->OutputDebug('Decoding XML response with simplexml');
+ try
+ {
+ $response = @new SimpleXMLElement($data);
+ }
+ catch(Exception $exception)
+ {
+ return $this->SetError('Could not parse XML response: '.$exception->getMessage());
+ }
+ break 2;
+ default:
+ return $this->SetError($options['DecodeXML'].' is not a supported method to decode XML responses');
+ }
+ }
+ default:
+ $response = $data;
+ break;
+ }
+ if($this->response_status >= 200
+ && $this->response_status < 300)
+ $this->access_token_error = '';
+ else
+ {
+ $this->access_token_error = 'it was not possible to access the '.$options['Resource'].': it was returned an unexpected response status '.$http->response_status.' Response: '.$data;
+ if($this->debug)
+ $this->OutputDebug('Could not retrieve the OAuth access token. Error: '.$this->access_token_error);
+ if(IsSet($options['FailOnAccessError'])
+ && $options['FailOnAccessError'])
+ {
+ $this->error = $this->access_token_error;
+ return false;
+ }
+ }
+ return true;
+ }
+
+ Function ProcessToken($code, $refresh)
+ {
+ if(!$this->GetRedirectURI($redirect_uri))
+ return false;
+ if($refresh)
+ {
+ $values = array(
+ 'refresh_token'=>$this->refresh_token,
+ 'grant_type'=>'refresh_token',
+ 'scope'=>$this->scope,
+ );
+ }
+ else
+ {
+ $values = array(
+ 'code'=>$code,
+ 'redirect_uri'=>$redirect_uri,
+ 'grant_type'=>'authorization_code'
+ );
+ }
+ $options = array(
+ 'Resource'=>'OAuth '.($refresh ? 'refresh' : 'access').' token',
+ 'ConvertObjects'=>true
+ );
+ switch(strtolower($this->access_token_authentication))
+ {
+ case 'basic':
+ $options['AccessTokenAuthentication'] = $this->access_token_authentication;
+ $values['redirect_uri'] = $redirect_uri;
+ break;
+ case '':
+ $values['client_id'] = $this->client_id;
+ $values['client_secret'] = ($this->get_token_with_api_key ? $this->api_key : $this->client_secret);
+ break;
+ default:
+ return($this->SetError($this->access_token_authentication.' is not a supported authentication mechanism to retrieve an access token'));
+ }
+ if(!$this->GetAccessTokenURL($access_token_url))
+ return false;
+ if(!$this->SendAPIRequest($access_token_url, 'POST', $values, null, $options, $response))
+ return false;
+ if(strlen($this->access_token_error))
+ {
+ $this->authorization_error = $this->access_token_error;
+ return true;
+ }
+ if(!IsSet($response['access_token']))
+ {
+ if(IsSet($response['error']))
+ {
+ $this->authorization_error = 'it was not possible to retrieve the access token: it was returned the error: '.$response['error'];
+ return true;
+ }
+ return($this->SetError('OAuth server did not return the access token'));
+ }
+ $access_token = array(
+ 'value'=>($this->access_token = $response['access_token']),
+ 'authorized'=>true,
+ );
+ if($this->store_access_token_response)
+ $access_token['response'] = $this->access_token_response = $response;
+ if($this->debug)
+ $this->OutputDebug('Access token: '.$this->access_token);
+ if(IsSet($response['expires_in'])
+ && $response['expires_in'] == 0)
+ {
+ if($this->debug)
+ $this->OutputDebug('Ignoring access token expiry set to 0');
+ $this->access_token_expiry = '';
+ }
+ elseif(IsSet($response['expires'])
+ || IsSet($response['expires_in']))
+ {
+ $expires = (IsSet($response['expires']) ? $response['expires'] : $response['expires_in']);
+ if(strval($expires) !== strval(intval($expires))
+ || $expires <= 0)
+ return($this->SetError('OAuth server did not return a supported type of access token expiry time'));
+ $this->access_token_expiry = gmstrftime('%Y-%m-%d %H:%M:%S', time() + $expires);
+ if($this->debug)
+ $this->OutputDebug('Access token expiry: '.$this->access_token_expiry.' UTC');
+ $access_token['expiry'] = $this->access_token_expiry;
+ }
+ else
+ $this->access_token_expiry = '';
+ if(IsSet($response['token_type']))
+ {
+ $this->access_token_type = $response['token_type'];
+ if(strlen($this->access_token_type)
+ && $this->debug)
+ $this->OutputDebug('Access token type: '.$this->access_token_type);
+ $access_token['type'] = $this->access_token_type;
+ }
+ else
+ {
+ $this->access_token_type = $this->default_access_token_type;
+ if(strlen($this->access_token_type)
+ && $this->debug)
+ $this->OutputDebug('Assumed the default for OAuth access token type which is '.$this->access_token_type);
+ }
+ if(IsSet($response['refresh_token']))
+ {
+ $this->refresh_token = $response['refresh_token'];
+ if($this->debug)
+ $this->OutputDebug('New refresh token: '.$this->refresh_token);
+ $access_token['refresh'] = $this->refresh_token;
+ }
+ elseif(strlen($this->refresh_token))
+ {
+ if($this->debug)
+ $this->OutputDebug('Reusing previous refresh token: '.$this->refresh_token);
+ $access_token['refresh'] = $this->refresh_token;
+ }
+ if(!$this->StoreAccessToken($access_token))
+ return false;
+ return true;
+ }
+
+ Function RetrieveToken(&$valid)
+ {
+ $valid = false;
+ if(!$this->GetAccessToken($access_token))
+ return false;
+ if(IsSet($access_token['value']))
+ {
+ $this->access_token_expiry = '';
+ $expired = (IsSet($access_token['expiry']) && strcmp($this->access_token_expiry = $access_token['expiry'], gmstrftime('%Y-%m-%d %H:%M:%S')) < 0);
+ if($expired)
+ {
+ if($this->debug)
+ $this->OutputDebug('The OAuth access token expired in '.$this->access_token_expiry);
+ }
+ $this->access_token = $access_token['value'];
+ if(!$expired
+ && $this->debug)
+ $this->OutputDebug('The OAuth access token '.$this->access_token.' is valid');
+ if(IsSet($access_token['type']))
+ {
+ $this->access_token_type = $access_token['type'];
+ if(strlen($this->access_token_type)
+ && !$expired
+ && $this->debug)
+ $this->OutputDebug('The OAuth access token is of type '.$this->access_token_type);
+ }
+ else
+ {
+ $this->access_token_type = $this->default_access_token_type;
+ if(strlen($this->access_token_type)
+ && !$expired
+ && $this->debug)
+ $this->OutputDebug('Assumed the default for OAuth access token type which is '.$this->access_token_type);
+ }
+ if(IsSet($access_token['secret']))
+ {
+ $this->access_token_secret = $access_token['secret'];
+ if($this->debug
+ && !$expired)
+ $this->OutputDebug('The OAuth access token secret is '.$this->access_token_secret);
+ }
+ if(IsSet($access_token['refresh']))
+ $this->refresh_token = $access_token['refresh'];
+ else
+ $this->refresh_token = '';
+ $this->access_token_response = (($this->store_access_token_response && IsSet($access_token['response'])) ? $access_token['response'] : null);
+ $valid = true;
+ }
+ return true;
+ }
+/*
+{metadocument}
+
+ CallAPI
+ BOOLEAN
+
+ Send a HTTP request to the Web services API using a
+ previously obtained authorization token via OAuth.
+ This function can be used to call an API after having
+ previously obtained an access token through the OAuth protocol
+ using the Process function, or by
+ directly setting the variables
+ access_token, as well as
+ access_token_secret in case of using
+ OAuth 1.0 or 1.0a services.
+ This function returns 1 if
+ the call was done successfully.
+
+
+ url
+ STRING
+
+ URL of the API where the HTTP request will be sent.
+
+
+
+ method
+ STRING
+
+ HTTP method that will be used to send the request. It can
+ be GET,
+ POST,
+ DELETE, PUT,
+ etc..
+
+
+
+ parameters
+ HASH
+
+ Associative array with the names and values of the API
+ call request parameters.
+
+
+
+ options
+ HASH
+
+ Associative array with additional options to configure
+ the request. Currently it supports the following
+ options:
+ 2Legged: boolean option that
+ determines if the API request should be 2 legged. The default
+ value is 0.
+ Accept: content type value of the
+ Accept HTTP header to be sent in the API call HTTP request.
+ Some APIs require that a certain value be sent to specify
+ which version of the API is being called. The default value is
+ */*.
+ ConvertObjects: boolean option that
+ determines if objects should be converted into arrays when the
+ response is returned in JSON format. The default value is
+ 0.
+ DecodeXMLResponse: name of the method
+ to decode XML responses. Currently only
+ simplexml is supported. It makes a
+ XML response be parsed and returned as a SimpleXMLElement
+ object.
+ FailOnAccessError: boolean option
+ that determines if this functions should fail when the server
+ response status is not between 200 and 299. The default value
+ is 0.
+ Files: associative array with
+ details of the parameters that must be passed as file uploads.
+ The array indexes must have the same name of the parameters
+ to be sent as files. The respective array entry values must
+ also be associative arrays with the parameters for each file.
+ Currently it supports the following parameters:
+ - Type - defines how the parameter value should be
+ treated. It can be 'FileName' if the parameter value is
+ is the name of a local file to be uploaded. It may also be
+ 'Data' if the parameter value is the actual data of
+ the file to be uploaded.
+ - Default: 'FileName'
+ - ContentType - MIME value of the content type of the
+ file. It can be 'automatic/name' if the content type
+ should be determine from the file name extension.
+ - Default: 'automatic/name'
+ PostValuesInURI: boolean option to
+ determine that a POST request should pass the request values
+ in the URI. The default value is
+ 0.
+ FollowRedirection: limit number of
+ times that HTTP response redirects will be followed. If it is
+ set to 0, redirection responses
+ fail in error. The default value is
+ 0.
+ RequestBody: request body data of a
+ custom type. The RequestContentType
+ option must be specified, so the
+ RequestBody option is considered.
+ RequestContentType: content type that
+ should be used to send the request values. It can be either
+ application/x-www-form-urlencoded
+ for sending values like from Web forms, or
+ application/json for sending the
+ values encoded in JSON format. Other types are accepted if the
+ RequestBody option is specified.
+ The default value is
+ application/x-www-form-urlencoded.
+ RequestBody: request body data of a
+ custom type. The RequestContentType
+ option must be specified, so the
+ RequestBody option is considered.
+ Resource: string with a label that
+ will be used in the error messages and debug log entries to
+ identify what operation the request is performing. The default
+ value is API call.
+ ResponseContentType: content type
+ that should be considered when decoding the API request
+ response. This overrides the Content-Type header
+ returned by the server. If the content type is
+ application/x-www-form-urlencoded
+ the function will parse the data returning an array of
+ key-value pairs. If the content type is
+ application/json the response will
+ be decode as a JSON-encoded data type. Other content type
+ values will make the function return the original response
+ value as it was returned from the server. The default value
+ for this option is to use what the server returned in the
+ Content-Type header.
+
+
+
+ response
+ STRING
+
+
+ Return the value of the API response. If the value is
+ JSON encoded, this function will decode it and return the value
+ converted to respective types. If the value is form encoded,
+ this function will decode the response and return it as an
+ array. Otherwise, the class will return the value as a
+ string.
+
+
+
+{/metadocument}
+*/
+ Function CallAPI($url, $method, $parameters, $options, &$response)
+ {
+ if(!IsSet($options['Resource']))
+ $options['Resource'] = 'API call';
+ if(!IsSet($options['ConvertObjects']))
+ $options['ConvertObjects'] = false;
+ if(strlen($this->access_token) === 0)
+ {
+ if(!$this->RetrieveToken($valid))
+ return false;
+ if(!$valid)
+ return $this->SetError('the access token is not set to a valid value');
+ }
+ switch(intval($this->oauth_version))
+ {
+ case 1:
+ $oauth = array(
+ (strlen($this->access_token_parameter) ? $this->access_token_parameter : 'oauth_token')=>((IsSet($options['2Legged']) && $options['2Legged']) ? '' : $this->access_token)
+ );
+ break;
+
+ case 2:
+ if(strlen($this->access_token_expiry)
+ && strcmp($this->access_token_expiry, gmstrftime('%Y-%m-%d %H:%M:%S')) <= 0)
+ {
+ if(strlen($this->refresh_token) === 0)
+ return($this->SetError('the access token expired and no refresh token is available'));
+ if($this->debug)
+ $this->OutputDebug('Refreshing the OAuth access token');
+ if(!$this->ProcessToken(null, true))
+ return false;
+ if(IsSet($options['FailOnAccessError'])
+ && $options['FailOnAccessError']
+ && strlen($this->authorization_error))
+ {
+ $this->error = $this->authorization_error;
+ return false;
+ }
+ }
+ $oauth = null;
+ if(strcasecmp($this->access_token_type, 'Bearer'))
+ $url .= (strcspn($url, '?') < strlen($url) ? '&' : '?').(strlen($this->access_token_parameter) ? $this->access_token_parameter : 'access_token').'='.UrlEncode($this->access_token);
+ break;
+
+ default:
+ return($this->SetError($this->oauth_version.' is not a supported version of the OAuth protocol'));
+ }
+ return($this->SendAPIRequest($url, $method, $parameters, $oauth, $options, $response));
+ }
+/*
+{metadocument}
+
+
+{/metadocument}
+*/
+
+/*
+{metadocument}
+
+ Initialize
+ BOOLEAN
+
+ Initialize the class variables and internal state. It must
+ be called before calling other class functions.
+ Set the server variable before
+ calling this function to let it initialize the class variables to
+ work with the specified server type. Alternatively, you can set
+ other class variables manually to make it work with servers that
+ are not yet built-in supported.
+ This function returns 1 if
+ it was able to successfully initialize the class for the specified
+ server type.
+
+
+{/metadocument}
+*/
+ Function Initialize()
+ {
+ if(strlen($this->server) === 0)
+ return true;
+ $this->oauth_version =
+ $this->dialog_url =
+ $this->access_token_url =
+ $this->request_token_url =
+ $this->append_state_to_redirect_uri = '';
+ $this->authorization_header = true;
+ $this->url_parameters = false;
+ $this->token_request_method = 'GET';
+ $this->signature_method = 'HMAC-SHA1';
+ $this->access_token_authentication = '';
+ $this->access_token_parameter = '';
+ $this->default_access_token_type = '';
+ $this->store_access_token_response = false;
+ switch($this->server)
+ {
+ case 'Facebook':
+ $this->oauth_version = '2.0';
+ $this->dialog_url = 'https://www.facebook.com/dialog/oauth?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&state={STATE}';
+ $this->access_token_url = 'https://graph.facebook.com/oauth/access_token';
+ break;
+
+ case 'github':
+ $this->oauth_version = '2.0';
+ $this->dialog_url = 'https://github.com/login/oauth/authorize?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&state={STATE}';
+ $this->access_token_url = 'https://github.com/login/oauth/access_token';
+ break;
+
+ case 'Google':
+ $this->oauth_version = '2.0';
+ $this->dialog_url = 'https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&state={STATE}';
+ $this->offline_dialog_url = 'https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&state={STATE}&access_type=offline&approval_prompt=force';
+ $this->access_token_url = 'https://accounts.google.com/o/oauth2/token';
+ break;
+
+ case 'LinkedIn':
+ $this->oauth_version = '1.0a';
+ $this->request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken?scope={SCOPE}';
+ $this->dialog_url = 'https://api.linkedin.com/uas/oauth/authenticate';
+ $this->access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken';
+ $this->url_parameters = true;
+ break;
+
+ case 'Microsoft':
+ $this->oauth_version = '2.0';
+ $this->dialog_url = 'https://login.live.com/oauth20_authorize.srf?client_id={CLIENT_ID}&scope={SCOPE}&response_type=code&redirect_uri={REDIRECT_URI}&state={STATE}';
+ $this->access_token_url = 'https://login.live.com/oauth20_token.srf';
+ break;
+
+ case 'Twitter':
+ $this->oauth_version = '1.0a';
+ $this->request_token_url = 'https://api.twitter.com/oauth/request_token';
+ $this->dialog_url = 'https://api.twitter.com/oauth/authenticate';
+ $this->access_token_url = 'https://api.twitter.com/oauth/access_token';
+ $this->url_parameters = false;
+ break;
+
+ case 'Yahoo':
+ $this->oauth_version = '1.0a';
+ $this->request_token_url = 'https://api.login.yahoo.com/oauth/v2/get_request_token';
+ $this->dialog_url = 'https://api.login.yahoo.com/oauth/v2/request_auth';
+ $this->access_token_url = 'https://api.login.yahoo.com/oauth/v2/get_token';
+ $this->authorization_header = false;
+ break;
+
+ default:
+ if(!($json = @file_get_contents($this->configuration_file)))
+ {
+ if(!file_exists($this->configuration_file))
+ return $this->SetError('the OAuth server configuration file '.$this->configuration_file.' does not exist');
+ return $this->SetPHPError('could not read the OAuth server configuration file '.$this->configuration_file, $php_errormsg);
+ }
+ $oauth_server = json_decode($json);
+ if(!IsSet($oauth_server))
+ return $this->SetPHPError('It was not possible to decode the OAuth server configuration file '.$this->configuration_file.' eventually due to incorrect format', $php_errormsg);
+ if(GetType($oauth_server) !== 'object')
+ return $this->SetError('It was not possible to decode the OAuth server configuration file '.$this->configuration_file.' because it does not correctly define a JSON object');
+ if(!IsSet($oauth_server->servers)
+ || GetType($oauth_server->servers) !== 'object')
+ return $this->SetError('It was not possible to decode the OAuth server configuration file '.$this->configuration_file.' because it does not correctly define a JSON object for servers');
+ if(!IsSet($oauth_server->servers->{$this->server}))
+ return($this->SetError($this->server.' is not yet a supported type of OAuth server. Please send a request in this class support forum (preferred) http://www.phpclasses.org/oauth-api , or if it is a security or private matter, contact the author Manuel Lemos mlemos@acm.org to request adding built-in support to this type of OAuth server.'));
+ $properties = $oauth_server->servers->{$this->server};
+ if(GetType($properties) !== 'object')
+ return $this->SetError('The OAuth server configuration file '.$this->configuration_file.' for the "'.$this->server.'" server does not correctly define a JSON object');
+ $types = array(
+ 'oauth_version'=>'string',
+ 'request_token_url'=>'string',
+ 'dialog_url'=>'string',
+ 'offline_dialog_url'=>'string',
+ 'access_token_url'=>'string',
+ 'append_state_to_redirect_uri'=> 'string',
+ 'authorization_header'=>'boolean',
+ 'url_parameters' => 'boolean',
+ 'token_request_method'=>'string',
+ 'signature_method'=>'string',
+ 'access_token_authentication'=>'string',
+ 'access_token_parameter'=>'string',
+ 'default_access_token_type'=>'string',
+ 'store_access_token_response'=>'boolean'
+ );
+ $required = array(
+ 'oauth_version'=>array(),
+ 'request_token_url'=>array('1.0', '1.0a'),
+ 'dialog_url'=>array(),
+ 'access_token_url'=>array(),
+ );
+ foreach($properties as $property => $value)
+ {
+ if(!IsSet($types[$property]))
+ return $this->SetError($property.' is not a supported property for the "'.$this->server.'" server in the OAuth server configuration file '.$this->configuration_file);
+ $type = GetType($value);
+ $expected = $types[$property];
+ if($type !== $expected)
+ return $this->SetError(' the property "'.$property.'" for the "'.$this->server.'" server is not of type "'.$expected.'", it is of type "'.$type.'", in the OAuth server configuration file '.$this->configuration_file);
+ $this->{$property} = $value;
+ UnSet($required[$property]);
+ }
+ foreach($required as $property => $value)
+ {
+ if(count($value)
+ && in_array($this->oauth_version, $value))
+ return $this->SetError('the property "'.$property.'" is not defined for the "'.$this->server.'" server in the OAuth server configuration file '.$this->configuration_file);
+ }
+ break;
+ }
+ return(true);
+ }
+/*
+{metadocument}
+
+
+{/metadocument}
+*/
+
+/*
+{metadocument}
+
+ Process
+ BOOLEAN
+
+ Process the OAuth protocol interaction with the OAuth
+ server.
+ Call this function when you need to retrieve the OAuth access
+ token. Check the access_token to
+ determine if the access token was obtained successfully.
+ This function returns 1 if
+ the OAuth protocol was processed without errors.
+
+
+{/metadocument}
+*/
+ Function Process()
+ {
+ switch(intval($this->oauth_version))
+ {
+ case 1:
+ $one_a = ($this->oauth_version === '1.0a');
+ if($this->debug)
+ $this->OutputDebug('Checking the OAuth token authorization state');
+ if(!$this->GetAccessToken($access_token))
+ return false;
+ if(IsSet($access_token['authorized'])
+ && IsSet($access_token['value']))
+ {
+ $expired = (IsSet($access_token['expiry']) && strcmp($access_token['expiry'], gmstrftime('%Y-%m-%d %H:%M:%S')) <= 0);
+ if(!$access_token['authorized']
+ || $expired)
+ {
+ if($this->debug)
+ {
+ if($expired)
+ $this->OutputDebug('The OAuth token expired on '.$access_token['expiry'].'UTC');
+ else
+ $this->OutputDebug('The OAuth token is not yet authorized');
+ $this->OutputDebug('Checking the OAuth token and verifier');
+ }
+ if(!$this->GetRequestToken($token, $verifier))
+ return false;
+ if(!IsSet($token)
+ || ($one_a
+ && !IsSet($verifier)))
+ {
+ if(!$this->GetRequestDenied($denied))
+ return false;
+ if(IsSet($denied)
+ && $denied === $access_token['value'])
+ {
+ if($this->debug)
+ $this->OutputDebug('The authorization request was denied');
+ $this->authorization_error = 'the request was denied';
+ return true;
+ }
+ else
+ {
+ if($this->debug)
+ $this->OutputDebug('Reset the OAuth token state because token and verifier are not both set');
+ $access_token = array();
+ }
+ }
+ elseif($token !== $access_token['value'])
+ {
+ if($this->debug)
+ $this->OutputDebug('Reset the OAuth token state because token does not match what as previously retrieved');
+ $access_token = array();
+ }
+ else
+ {
+ if(!$this->GetAccessTokenURL($url))
+ return false;
+ $oauth = array(
+ 'oauth_token'=>$token,
+ );
+ if($one_a)
+ $oauth['oauth_verifier'] = $verifier;
+ $this->access_token_secret = $access_token['secret'];
+ $options = array('Resource'=>'OAuth access token');
+ $method = strtoupper($this->token_request_method);
+ switch($method)
+ {
+ case 'GET':
+ break;
+ case 'POST':
+ $options['PostValuesInURI'] = true;
+ break;
+ default:
+ $this->error = $method.' is not a supported method to request tokens';
+ break;
+ }
+ if(!$this->SendAPIRequest($url, $method, array(), $oauth, $options, $response))
+ return false;
+ if(strlen($this->access_token_error))
+ {
+ $this->authorization_error = $this->access_token_error;
+ return true;
+ }
+ if(!IsSet($response['oauth_token'])
+ || !IsSet($response['oauth_token_secret']))
+ {
+ $this->authorization_error= 'it was not returned the access token and secret';
+ return true;
+ }
+ $access_token = array(
+ 'value'=>$response['oauth_token'],
+ 'secret'=>$response['oauth_token_secret'],
+ 'authorized'=>true
+ );
+ if(IsSet($response['oauth_expires_in'])
+ && $response['oauth_expires_in'] == 0)
+ {
+ if($this->debug)
+ $this->OutputDebug('Ignoring access token expiry set to 0');
+ $this->access_token_expiry = '';
+ }
+ elseif(IsSet($response['oauth_expires_in']))
+ {
+ $expires = $response['oauth_expires_in'];
+ if(strval($expires) !== strval(intval($expires))
+ || $expires <= 0)
+ return($this->SetError('OAuth server did not return a supported type of access token expiry time'));
+ $this->access_token_expiry = gmstrftime('%Y-%m-%d %H:%M:%S', time() + $expires);
+ if($this->debug)
+ $this->OutputDebug('Access token expiry: '.$this->access_token_expiry.' UTC');
+ $access_token['expiry'] = $this->access_token_expiry;
+ }
+ else
+ $this->access_token_expiry = '';
+
+ if(!$this->StoreAccessToken($access_token))
+ return false;
+ if($this->debug)
+ $this->OutputDebug('The OAuth token was authorized');
+ }
+ }
+ elseif($this->debug)
+ $this->OutputDebug('The OAuth token was already authorized');
+ if(IsSet($access_token['authorized'])
+ && $access_token['authorized'])
+ {
+ $this->access_token = $access_token['value'];
+ $this->access_token_secret = $access_token['secret'];
+ return true;
+ }
+ }
+ else
+ {
+ if($this->debug)
+ $this->OutputDebug('The OAuth access token is not set');
+ $access_token = array();
+ }
+ if(!IsSet($access_token['authorized']))
+ {
+ if($this->debug)
+ $this->OutputDebug('Requesting the unauthorized OAuth token');
+ if(!$this->GetRequestTokenURL($url))
+ return false;
+ $url = str_replace('{SCOPE}', UrlEncode($this->scope), $url);
+ if(!$this->GetRedirectURI($redirect_uri))
+ return false;
+ $oauth = array(
+ 'oauth_callback'=>$redirect_uri,
+ );
+ $options = array(
+ 'Resource'=>'OAuth request token',
+ 'FailOnAccessError'=>true
+ );
+ $method = strtoupper($this->token_request_method);
+ switch($method)
+ {
+ case 'GET':
+ break;
+ case 'POST':
+ $options['PostValuesInURI'] = true;
+ break;
+ default:
+ $this->error = $method.' is not a supported method to request tokens';
+ break;
+ }
+ if(!$this->SendAPIRequest($url, $method, array(), $oauth, $options, $response))
+ return false;
+ if(strlen($this->access_token_error))
+ {
+ $this->authorization_error = $this->access_token_error;
+ return true;
+ }
+ if(!IsSet($response['oauth_token'])
+ || !IsSet($response['oauth_token_secret']))
+ {
+ $this->authorization_error = 'it was not returned the requested token';
+ return true;
+ }
+ $access_token = array(
+ 'value'=>$response['oauth_token'],
+ 'secret'=>$response['oauth_token_secret'],
+ 'authorized'=>false
+ );
+ if(IsSet($response['login_url']))
+ $access_token['login_url'] = $response['login_url'];
+ if(!$this->StoreAccessToken($access_token))
+ return false;
+ }
+ if(!$this->GetDialogURL($url))
+ return false;
+ if($url === 'automatic')
+ {
+ if(!IsSet($access_token['login_url']))
+ return($this->SetError('The request token response did not automatically the login dialog URL as expected'));
+ if($this->debug)
+ $this->OutputDebug('Dialog URL obtained automatically from the request token response: '.$url);
+ $url = $access_token['login_url'];
+ }
+ else
+ $url .= (strpos($url, '?') === false ? '?' : '&').'oauth_token='.$access_token['value'];
+ if(!$one_a)
+ {
+ if(!$this->GetRedirectURI($redirect_uri))
+ return false;
+ $url .= '&oauth_callback='.UrlEncode($redirect_uri);
+ }
+ if($this->debug)
+ $this->OutputDebug('Redirecting to OAuth authorize page '.$url);
+ $this->Redirect($url);
+ $this->exit = true;
+ return true;
+
+ case 2:
+ if($this->debug)
+ {
+ if(!$this->GetAccessTokenURL($access_token_url))
+ return false;
+ $this->OutputDebug('Checking if OAuth access token was already retrieved from '.$access_token_url);
+ }
+ if(!$this->RetrieveToken($valid))
+ return false;
+ if($valid)
+ return true;
+ if($this->debug)
+ $this->OutputDebug('Checking the authentication state in URI '.$_SERVER['REQUEST_URI']);
+ if(!$this->GetStoredState($stored_state))
+ return false;
+ if(strlen($stored_state) == 0)
+ return($this->SetError('it was not set the OAuth state'));
+ if(!$this->GetRequestState($state))
+ return false;
+ if($state === $stored_state)
+ {
+ if($this->debug)
+ $this->OutputDebug('Checking the authentication code');
+ if(!$this->GetRequestCode($code))
+ return false;
+ if(strlen($code) == 0)
+ {
+ if(!$this->GetRequestError($this->authorization_error))
+ return false;
+ if(IsSet($this->authorization_error))
+ {
+ if($this->debug)
+ $this->OutputDebug('Authorization failed with error code '.$this->authorization_error);
+ switch($this->authorization_error)
+ {
+ case 'invalid_request':
+ case 'unauthorized_client':
+ case 'access_denied':
+ case 'unsupported_response_type':
+ case 'invalid_scope':
+ case 'server_error':
+ case 'temporarily_unavailable':
+ case 'user_denied':
+ return true;
+ default:
+ return($this->SetError('it was returned an unknown OAuth error code'));
+ }
+ }
+ return($this->SetError('it was not returned the OAuth dialog code'));
+ }
+ if(!$this->ProcessToken($code, false))
+ return false;
+ }
+ else
+ {
+ if(!$this->GetRedirectURI($redirect_uri))
+ return false;
+ if(strlen($this->append_state_to_redirect_uri))
+ $redirect_uri .= (strpos($redirect_uri, '?') === false ? '?' : '&').$this->append_state_to_redirect_uri.'='.$stored_state;
+ if(!$this->GetDialogURL($url, $redirect_uri, $stored_state))
+ return false;
+ if(strlen($url) == 0)
+ return($this->SetError('it was not set the OAuth dialog URL'));
+ if($this->debug)
+ $this->OutputDebug('Redirecting to OAuth Dialog '.$url);
+ $this->Redirect($url);
+ $this->exit = true;
+ }
+ break;
+
+ default:
+ return($this->SetError($this->oauth_version.' is not a supported version of the OAuth protocol'));
+ }
+ return(true);
+ }
+/*
+{metadocument}
+
+
+{/metadocument}
+*/
+
+/*
+{metadocument}
+
+ Finalize
+ BOOLEAN
+
+ Cleanup any resources that may have been used during the
+ OAuth protocol processing or execution of API calls.
+ Always call this function as the last step after calling the
+ functions Process or
+ CallAPI.
+ This function returns 1 if
+ the function cleaned up any resources successfully.
+
+
+ success
+ BOOLEAN
+
+ Pass the last success state returned by the class or any
+ external code processing the class function results.
+
+
+
+{/metadocument}
+*/
+ Function Finalize($success)
+ {
+ return($success);
+ }
+/*
+{metadocument}
+
+
+{/metadocument}
+*/
+
+/*
+{metadocument}
+
+ Output
+ VOID
+
+ Display the results of the OAuth protocol processing.
+ Only call this function if you are debugging the OAuth
+ authorization process and you need to view what was its
+ results.
+
+
+{/metadocument}
+*/
+ Function Output()
+ {
+ if(strlen($this->authorization_error)
+ || strlen($this->access_token_error)
+ || strlen($this->access_token))
+ {
+?>
+
+
+
+OAuth client result
+
+
+
OAuth client result
+authorization_error))
+ {
+?>
+
It was not possible to authorize the application.debug)
+ {
+?>
+ Authorization error: authorization_error);
+ }
+?>
+access_token_error))
+ {
+?>
+
It was not possible to use the application access token.
+debug)
+ {
+?>
+ Error: access_token_error);
+ }
+?>