KyleMassacre

untitled.php

Jul 30th, 2013
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 74.46 KB | None | 0 0
  1. <?php
  2. /*
  3.  * oauth_client.php
  4.  *
  5.  * @(#) $Id: oauth_client.php,v 1.66 2013/07/06 11:35:56 mlemos Exp $
  6.  *
  7.  */
  8.  
  9. /*
  10. {metadocument}<?xml version="1.0" encoding="ISO-8859-1" ?>
  11. <class>
  12.  
  13.     <package>net.manuellemos.oauth</package>
  14.  
  15.     <version>@(#) $Id: oauth_client.php,v 1.66 2013/07/06 11:35:56 mlemos Exp $</version>
  16.     <copyright>Copyright ? (C) Manuel Lemos 2012</copyright>
  17.     <title>OAuth client</title>
  18.     <author>Manuel Lemos</author>
  19.     <authoraddress>mlemos-at-acm.org</authoraddress>
  20.  
  21.     <documentation>
  22.         <idiom>en</idiom>
  23.         <purpose>This class serves two main purposes:<paragraphbreak />
  24.             1) Implement the OAuth protocol to retrieve a token from a server to
  25.             authorize the access to an API on behalf of the current
  26.             user.<paragraphbreak />
  27.             2) Perform calls to a Web services API using a token previously
  28.             obtained using this class or a token provided some other way by the
  29.             Web services provider.</purpose>
  30.         <usage>Regardless of your purposes, you always need to start calling
  31.             the class <functionlink>Initialize</functionlink> function after
  32.             initializing setup variables. After you are done with the class,
  33.             always call the <functionlink>Finalize</functionlink> function at
  34.             the end.<paragraphbreak />
  35.             This class supports either OAuth protocol versions 1.0, 1.0a and
  36.             2.0. It abstracts the differences between these protocol versions,
  37.             so the class usage is the same independently of the OAuth
  38.             version of the server.<paragraphbreak />
  39.             The class also provides built-in support to several popular OAuth
  40.             servers, so you do not have to manually configure all the details to
  41.             access those servers. Just set the
  42.             <variablelink>server</variablelink> variable to configure the class
  43.             to access one of the built-in supported servers.<paragraphbreak />
  44.             If you need to access one type of server that is not yet directly
  45.             supported by the class, you need to configure it explicitly setting
  46.             the variables: <variablelink>oauth_version</variablelink>,
  47.             <variablelink>url_parameters</variablelink>,
  48.             <variablelink>authorization_header</variablelink>,
  49.             <variablelink>request_token_url</variablelink>,
  50.             <variablelink>dialog_url</variablelink>,
  51.             <variablelink>offline_dialog_url</variablelink>,
  52.             <variablelink>append_state_to_redirect_uri</variablelink> and
  53.             <variablelink>access_token_url</variablelink>.<paragraphbreak />
  54.             Before proceeding to the actual OAuth authorization process, you
  55.             need to have registered your application with the OAuth server. The
  56.             registration provides you values to set the variables
  57.             <variablelink>client_id</variablelink> and
  58.             <variablelink>client_secret</variablelink>.<paragraphbreak />
  59.             You also need to set the variables
  60.             <variablelink>redirect_uri</variablelink> and
  61.             <variablelink>scope</variablelink> before calling the
  62.             <functionlink>Process</functionlink> function to make the class
  63.             perform the necessary interactions with the OAuth
  64.             server.<paragraphbreak />
  65.             The OAuth protocol involves multiple steps that include redirection
  66.             to the OAuth server. There it asks permission to the current user to
  67.             grant your application access to APIs on his/her behalf. When there
  68.             is a redirection, the class will set the
  69.             <variablelink>exit</variablelink> variable to
  70.             <booleanvalue>1</booleanvalue>. Then your script should exit
  71.             immediately without outputting anything.<paragraphbreak />
  72.             When the OAuth access token is successfully obtained, the following
  73.             variables are set by the class with the obtained values:
  74.             <variablelink>access_token</variablelink>,
  75.             <variablelink>access_token_secret</variablelink>,
  76.             <variablelink>access_token_expiry</variablelink>,
  77.             <variablelink>access_token_type</variablelink>. You may want to
  78.             store these values to use them later when calling the server
  79.             APIs.<paragraphbreak />
  80.             If there was a problem during OAuth authorization process, check the
  81.             variable <variablelink>authorization_error</variablelink> to
  82.             determine the reason.<paragraphbreak />
  83.             Once you get the access token, you can call the server APIs using
  84.             the <functionlink>CallAPI</functionlink> function. Check the
  85.             <variablelink>access_token_error</variablelink> variable to
  86.             determine if there was an error when trying to to call the
  87.             API.<paragraphbreak />
  88.             If for some reason the user has revoked the access to your
  89.             application, you need to ask the user to authorize your application
  90.             again. First you may need to call the function
  91.             <functionlink>ResetAccessToken</functionlink> to reset the value of
  92.             the access token that may be cached in session variables.</usage>
  93.     </documentation>
  94.  
  95. {/metadocument}
  96. */
  97.  
  98. class oauth_client_class
  99. {
  100. /*
  101. {metadocument}
  102.     <variable>
  103.         <name>error</name>
  104.         <type>STRING</type>
  105.         <value></value>
  106.         <documentation>
  107.             <purpose>Store the message that is returned when an error
  108.                 occurs.</purpose>
  109.             <usage>Check this variable to understand what happened when a call to
  110.                 any of the class functions has failed.<paragraphbreak />
  111.                 This class uses cumulative error handling. This means that if one
  112.                 class functions that may fail is called and this variable was
  113.                 already set to an error message due to a failure in a previous call
  114.                 to the same or other function, the function will also fail and does
  115.                 not do anything.<paragraphbreak />
  116.                 This allows programs using this class to safely call several
  117.                 functions that may fail and only check the failure condition after
  118.                 the last function call.<paragraphbreak />
  119.                 Just set this variable to an empty string to clear the error
  120.                 condition.</usage>
  121.         </documentation>
  122.     </variable>
  123. {/metadocument}
  124. */
  125.     var $error = '';
  126.  
  127. /*
  128. {metadocument}
  129.     <variable>
  130.         <name>debug</name>
  131.         <type>BOOLEAN</type>
  132.         <value>0</value>
  133.         <documentation>
  134.             <purpose>Control whether debug output is enabled</purpose>
  135.             <usage>Set this variable to <booleanvalue>1</booleanvalue> if you
  136.                 need to check what is going on during calls to the class. When
  137.                 enabled, the debug output goes either to the variable
  138.                 <variablelink>debug_output</variablelink> and the PHP error log.</usage>
  139.         </documentation>
  140.     </variable>
  141. {/metadocument}
  142. */
  143.     var $debug = false;
  144.  
  145. /*
  146. {metadocument}
  147.     <variable>
  148.         <name>debug_http</name>
  149.         <type>BOOLEAN</type>
  150.         <value>0</value>
  151.         <documentation>
  152.             <purpose>Control whether the dialog with the remote Web server
  153.                 should also be logged.</purpose>
  154.             <usage>Set this variable to <booleanvalue>1</booleanvalue> if you
  155.                 want to inspect the data exchange with the OAuth server.</usage>
  156.         </documentation>
  157.     </variable>
  158. {/metadocument}
  159. */
  160.     var $debug_http = false;
  161.  
  162. /*
  163. {metadocument}
  164.     <variable>
  165.         <name>exit</name>
  166.         <type>BOOLEAN</type>
  167.         <value>0</value>
  168.         <documentation>
  169.             <purpose>Determine if the current script should be exited.</purpose>
  170.             <usage>Check this variable after calling the
  171.                 <functionlink>Process</functionlink> function and exit your script
  172.                 immediately if the variable is set to
  173.                 <booleanvalue>1</booleanvalue>.</usage>
  174.         </documentation>
  175.     </variable>
  176. {/metadocument}
  177. */
  178.     var $exit = false;
  179.  
  180. /*
  181. {metadocument}
  182.     <variable>
  183.         <name>debug_output</name>
  184.         <type>STRING</type>
  185.         <value></value>
  186.         <documentation>
  187.             <purpose>Capture the debug output generated by the class</purpose>
  188.             <usage>Inspect this variable if you need to see what happened during
  189.                 the class function calls.</usage>
  190.         </documentation>
  191.     </variable>
  192. {/metadocument}
  193. */
  194.     var $debug_output = '';
  195.  
  196. /*
  197. {metadocument}
  198.     <variable>
  199.         <name>debug_prefix</name>
  200.         <type>STRING</type>
  201.         <value>OAuth client: </value>
  202.         <documentation>
  203.             <purpose>Mark the lines of the debug output to identify actions
  204.                 performed by this class.</purpose>
  205.             <usage>Change this variable if you prefer the debug output lines to
  206.                 be prefixed with a different text.</usage>
  207.         </documentation>
  208.     </variable>
  209. {/metadocument}
  210. */
  211.     var $debug_prefix = 'OAuth client: ';
  212.  
  213. /*
  214. {metadocument}
  215.     <variable>
  216.         <name>server</name>
  217.         <type>STRING</type>
  218.         <value></value>
  219.         <documentation>
  220.             <purpose>Identify the type of OAuth server to access.</purpose>
  221.             <usage>The class provides built-in support to several types of OAuth
  222.                 servers. This means that the class can automatically initialize
  223.                 several configuration variables just by setting this server
  224.                 variable.<paragraphbreak />
  225.                 Currently it supports the following servers:
  226.                 <stringvalue>Bitbucket</stringvalue>,
  227.                 <stringvalue>Box</stringvalue>,
  228.                 <stringvalue>Dropbox</stringvalue>,
  229.                 <stringvalue>Eventful</stringvalue>,
  230.                 <stringvalue>Facebook</stringvalue>,
  231.                 <stringvalue>Fitbit</stringvalue>,
  232.                 <stringvalue>Flickr</stringvalue>,
  233.                 <stringvalue>Foursquare</stringvalue>,
  234.                 <stringvalue>github</stringvalue>,
  235.                 <stringvalue>Google</stringvalue>,
  236.                 <stringvalue>Instagram</stringvalue>,
  237.                 <stringvalue>LinkedIn</stringvalue>,
  238.                 <stringvalue>Microsoft</stringvalue>,
  239.                 <stringvalue>Scoop.it</stringvalue>,
  240.                 <stringvalue>StockTwits</stringvalue>,
  241.                 <stringvalue>Tumblr</stringvalue>,
  242.                 <stringvalue>Twitter</stringvalue>,
  243.                 <stringvalue>XING</stringvalue> and
  244.                 <stringvalue>Yahoo</stringvalue>. Please contact the author if you
  245.                 would like to ask to add built-in support for other types of OAuth
  246.                 servers.<paragraphbreak />
  247.                 If you want to access other types of OAuth servers that are not
  248.                 yet supported, set this variable to an empty string and configure
  249.                 other variables with values specific to those servers.</usage>
  250.         </documentation>
  251.     </variable>
  252. {/metadocument}
  253. */
  254.     var $server = '';
  255.  
  256. /*
  257. {metadocument}
  258.     <variable>
  259.         <name>request_token_url</name>
  260.         <type>STRING</type>
  261.         <value></value>
  262.         <documentation>
  263.             <purpose>URL of the OAuth server to request the initial token for
  264.                 OAuth 1.0 and 1.0a servers.</purpose>
  265.             <usage>Set this variable to the OAuth request token URL when you are
  266.                 not accessing one of the built-in supported OAuth
  267.                 servers.<paragraphbreak />
  268.                 For OAuth 1.0 and 1.0a servers, the request token URL can have
  269.                 certain marks that will act as template placeholders which will be
  270.                 replaced with given values before requesting the authorization
  271.                 token. Currently it supports the following placeholder
  272.                 marks:<paragraphbreak />
  273.                 {SCOPE} - scope of the requested permissions to the granted by the
  274.                 OAuth server with the user permissions</usage>
  275.         </documentation>
  276.     </variable>
  277. {/metadocument}
  278. */
  279.     var $request_token_url = '';
  280.  
  281. /*
  282. {metadocument}
  283.     <variable>
  284.         <name>dialog_url</name>
  285.         <type>STRING</type>
  286.         <value></value>
  287.         <documentation>
  288.             <purpose>URL of the OAuth server to redirect the browser so the user
  289.                 can grant access to your application.</purpose>
  290.             <usage>Set this variable to the OAuth request token URL when you are
  291.                 not accessing one of the built-in supported OAuth servers.<paragraphbreak />
  292.                 For certain servers, the dialog URL can have certain marks that
  293.                 will act as template placeholders which will be replaced with
  294.                 values defined before redirecting the users browser. Currently it
  295.                 supports the following placeholder marks:<paragraphbreak />
  296.                 {REDIRECT_URI} - URL to redirect when returning from the OAuth
  297.                 server authorization page<paragraphbreak />
  298.                 {CLIENT_ID} - client application identifier registered at the
  299.                 server<paragraphbreak />
  300.                 {SCOPE} - scope of the requested permissions to the granted by the
  301.                 OAuth server with the user permissions<paragraphbreak />
  302.                 {STATE} - identifier of the OAuth session state</usage>
  303.         </documentation>
  304.     </variable>
  305. {/metadocument}
  306. */
  307.     var $dialog_url = '';
  308.  
  309. /*
  310. {metadocument}
  311.     <variable>
  312.         <name>offline_dialog_url</name>
  313.         <type>STRING</type>
  314.         <value></value>
  315.         <documentation>
  316.             <purpose>URL of the OAuth server to redirect the browser so the user
  317.                 can grant access to your application when offline access is
  318.                 requested.</purpose>
  319.             <usage>Set this variable to the OAuth request token URL when you are
  320.                 not accessing one of the built-in supported OAuth servers and the
  321.                 OAuth server supports offline access.<paragraphbreak />
  322.                 It should have the same format as the
  323.                 <variablelink>dialog_url</variablelink> variable.</usage>
  324.         </documentation>
  325.     </variable>
  326. {/metadocument}
  327. */
  328.     var $offline_dialog_url = '';
  329.  
  330. /*
  331. {metadocument}
  332.     <variable>
  333.         <name>append_state_to_redirect_uri</name>
  334.         <type>STRING</type>
  335.         <value></value>
  336.         <documentation>
  337.             <purpose>Pass the OAuth session state in a variable with a different
  338.                 name to work around implementation bugs of certain OAuth
  339.                 servers</purpose>
  340.             <usage>Set this variable  when you are not accessing one of the
  341.                 built-in supported OAuth servers if the OAuth server has a bug
  342.                 that makes it not pass back the OAuth state identifier in a
  343.                 request variable named state.</usage>
  344.         </documentation>
  345.     </variable>
  346. {/metadocument}
  347. */
  348.     var $append_state_to_redirect_uri = '';
  349.  
  350. /*
  351. {metadocument}
  352.     <variable>
  353.         <name>access_token_url</name>
  354.         <type>STRING</type>
  355.         <value></value>
  356.         <documentation>
  357.             <purpose>OAuth server URL that will return the access token
  358.                 URL.</purpose>
  359.             <usage>Set this variable to the OAuth access token URL when you are
  360.                 not accessing one of the built-in supported OAuth servers.</usage>
  361.         </documentation>
  362.     </variable>
  363. {/metadocument}
  364. */
  365.     var $access_token_url = '';
  366.  
  367.  
  368. /*
  369. {metadocument}
  370.     <variable>
  371.         <name>oauth_version</name>
  372.         <type>STRING</type>
  373.         <value>2.0</value>
  374.         <documentation>
  375.             <purpose>Version of the protocol version supported by the OAuth
  376.                 server.</purpose>
  377.             <usage>Set this variable to the OAuth server protocol version when
  378.                 you are not accessing one of the built-in supported OAuth
  379.                 servers.</usage>
  380.         </documentation>
  381.     </variable>
  382. {/metadocument}
  383. */
  384.     var $oauth_version = '2.0';
  385.  
  386. /*
  387. {metadocument}
  388.     <variable>
  389.         <name>url_parameters</name>
  390.         <type>BOOLEAN</type>
  391.         <value>0</value>
  392.         <documentation>
  393.             <purpose>Determine if the API call parameters should be moved to the
  394.                 call URL.</purpose>
  395.             <usage>Set this variable to <booleanvalue>1</booleanvalue> if the
  396.                 API you need to call requires that the call parameters always be
  397.                 passed via the API URL.</usage>
  398.         </documentation>
  399.     </variable>
  400. {/metadocument}
  401. */
  402.     var $url_parameters = false;
  403.  
  404. /*
  405. {metadocument}
  406.     <variable>
  407.         <name>authorization_header</name>
  408.         <type>BOOLEAN</type>
  409.         <value>1</value>
  410.         <documentation>
  411.             <purpose>Determine if the OAuth parameters should be passed via HTTP
  412.                 Authorization request header.</purpose>
  413.             <usage>Set this variable to <booleanvalue>1</booleanvalue> if the
  414.                 OAuth server requires that the OAuth parameters be passed using
  415.                 the HTTP Authorization instead of the request URI parameters.</usage>
  416.         </documentation>
  417.     </variable>
  418. {/metadocument}
  419. */
  420.     var $authorization_header = true;
  421.  
  422. /*
  423. {metadocument}
  424.     <variable>
  425.         <name>token_request_method</name>
  426.         <type>STRING</type>
  427.         <value>GET</value>
  428.         <documentation>
  429.             <purpose>Define the HTTP method that should be used to request
  430.                 tokens from the server.</purpose>
  431.             <usage>Set this variable to <stringvalue>POST</stringvalue> if the
  432.                 OAuth server does not support requesting tokens using the HTTP GET
  433.                 method.</usage>
  434.         </documentation>
  435.     </variable>
  436. {/metadocument}
  437. */
  438.     var $token_request_method = 'GET';
  439.  
  440. /*
  441. {metadocument}
  442.     <variable>
  443.         <name>signature_method</name>
  444.         <type>STRING</type>
  445.         <value>HMAC-SHA1</value>
  446.         <documentation>
  447.             <purpose>Define the method to generate the signature for API request
  448.                 parameters values.</purpose>
  449.             <usage>Currently it supports <stringvalue>PLAINTEXT</stringvalue>
  450.                 and <stringvalue>HMAC-SHA1</stringvalue>.</usage>
  451.         </documentation>
  452.     </variable>
  453. {/metadocument}
  454. */
  455.     var $signature_method = 'HMAC-SHA1';
  456.  
  457. /*
  458. {metadocument}
  459.     <variable>
  460.         <name>redirect_uri</name>
  461.         <type>STRING</type>
  462.         <value></value>
  463.         <documentation>
  464.             <purpose>URL of the current script page that is calling this
  465.                 class</purpose>
  466.             <usage>Set this variable to the current script page URL before
  467.                 proceeding the the OAuth authorization process.</usage>
  468.         </documentation>
  469.     </variable>
  470. {/metadocument}
  471. */
  472.     var $redirect_uri = '';
  473.  
  474. /*
  475. {metadocument}
  476.     <variable>
  477.         <name>client_id</name>
  478.         <type>STRING</type>
  479.         <value></value>
  480.         <documentation>
  481.             <purpose>Identifier of your application registered with the OAuth
  482.                 server</purpose>
  483.             <usage>Set this variable to the application identifier that is
  484.                 provided by the OAuth server when you register the
  485.                 application.</usage>
  486.         </documentation>
  487.     </variable>
  488. {/metadocument}
  489. */
  490.     var $client_id = '';
  491.  
  492. /*
  493. {metadocument}
  494.     <variable>
  495.         <name>client_secret</name>
  496.         <type>STRING</type>
  497.         <value></value>
  498.         <documentation>
  499.             <purpose>Secret value assigned to your application when it is
  500.                 registered with the OAuth server.</purpose>
  501.             <usage>Set this variable to the application secret that is provided
  502.                 by the OAuth server when you register the application.</usage>
  503.         </documentation>
  504.     </variable>
  505. {/metadocument}
  506. */
  507.     var $client_secret = '';
  508.  
  509. /*
  510. {metadocument}
  511.     <variable>
  512.         <name>scope</name>
  513.         <type>STRING</type>
  514.         <value></value>
  515.         <documentation>
  516.             <purpose>Permissions that your application needs to call the OAuth
  517.                 server APIs</purpose>
  518.             <usage>Check the documentation of the APIs that your application
  519.                 needs to call to set this variable with the identifiers of the
  520.                 permissions that the user needs to grant to your application.</usage>
  521.         </documentation>
  522.     </variable>
  523. {/metadocument}
  524. */
  525.     var $scope = '';
  526.  
  527. /*
  528. {metadocument}
  529.     <variable>
  530.         <name>offline</name>
  531.         <type>BOOLEAN</type>
  532.         <value>0</value>
  533.         <documentation>
  534.             <purpose>Specify whether it will be necessary to call the API when
  535.                 the user is not present and the server supports renewing expired
  536.                 access tokens using refresh tokens.</purpose>
  537.             <usage>Set this variable to <booleanvalue>1</booleanvalue> if the
  538.                 server supports renewing expired tokens automatically when the
  539.                 user is not present.</usage>
  540.         </documentation>
  541.     </variable>
  542. {/metadocument}
  543. */
  544.     var $offline = false;
  545.  
  546. /*
  547. {metadocument}
  548.     <variable>
  549.         <name>access_token</name>
  550.         <type>STRING</type>
  551.         <value></value>
  552.         <documentation>
  553.             <purpose>Access token obtained from the OAuth server</purpose>
  554.             <usage>Check this variable to get the obtained access token upon
  555.                 successful OAuth authorization.</usage>
  556.         </documentation>
  557.     </variable>
  558. {/metadocument}
  559. */
  560.     var $access_token = '';
  561.  
  562. /*
  563. {metadocument}
  564.     <variable>
  565.         <name>access_token_secret</name>
  566.         <type>STRING</type>
  567.         <value></value>
  568.         <documentation>
  569.             <purpose>Access token secret obtained from the OAuth server</purpose>
  570.             <usage>If the OAuth protocol version is 1.0 or 1.0a, check this
  571.                 variable to get the obtained access token secret upon successful
  572.                 OAuth authorization.</usage>
  573.         </documentation>
  574.     </variable>
  575. {/metadocument}
  576. */
  577.     var $access_token_secret = '';
  578.  
  579. /*
  580. {metadocument}
  581.     <variable>
  582.         <name>access_token_expiry</name>
  583.         <type>STRING</type>
  584.         <value></value>
  585.         <documentation>
  586.             <purpose>Timestamp of the expiry of the access token obtained from
  587.                 the OAuth server.</purpose>
  588.             <usage>Check this variable to get the obtained access token expiry
  589.                 time upon successful OAuth authorization. If this variable is
  590.                 empty, that means no expiry time was set.</usage>
  591.         </documentation>
  592.     </variable>
  593. {/metadocument}
  594. */
  595.     var $access_token_expiry = '';
  596.  
  597. /*
  598. {metadocument}
  599.     <variable>
  600.         <name>access_token_type</name>
  601.         <type>STRING</type>
  602.         <value></value>
  603.         <documentation>
  604.             <purpose>Type of access token obtained from the OAuth server.</purpose>
  605.             <usage>Check this variable to get the obtained access token type
  606.                 upon successful OAuth authorization.</usage>
  607.         </documentation>
  608.     </variable>
  609. {/metadocument}
  610. */
  611.     var $access_token_type = '';
  612.  
  613. /*
  614. {metadocument}
  615.     <variable>
  616.         <name>default_access_token_type</name>
  617.         <type>STRING</type>
  618.         <value></value>
  619.         <documentation>
  620.             <purpose>Type of access token to be assumed when the OAuth server
  621.                 does not specify an access token type.</purpose>
  622.             <usage>Set this variable if the server requires a certain type of
  623.                 access token to be used but it does not specify a token type
  624.                 when the access token is returned.</usage>
  625.         </documentation>
  626.     </variable>
  627. {/metadocument}
  628. */
  629.     var $default_access_token_type = '';
  630.  
  631. /*
  632. {metadocument}
  633.     <variable>
  634.         <name>access_token_response</name>
  635.         <type>ARRAY</type>
  636.         <documentation>
  637.             <purpose>The original response for the access token request</purpose>
  638.             <usage>Check this variable if the OAuth server returns custom
  639.                 parameters in the request to obtain the access token.</usage>
  640.         </documentation>
  641.     </variable>
  642. {/metadocument}
  643. */
  644.     var $access_token_response;
  645.  
  646. /*
  647. {metadocument}
  648.     <variable>
  649.         <name>store_access_token_response</name>
  650.         <type>ARRAY</type>
  651.         <documentation>
  652.             <purpose>Option to determine if the original response for the access
  653.                 token request should be stored in the
  654.                 <variablelink>access_token_response</variablelink>
  655.                 variable.</purpose>
  656.             <usage>Set this variable to <booleanvalue>1</booleanvalue> if the
  657.                 OAuth server returns custom parameters in the request to obtain
  658.                 the access token that may be needed in subsequent API calls.</usage>
  659.         </documentation>
  660.     </variable>
  661. {/metadocument}
  662. */
  663.     var $store_access_token_response = false;
  664.  
  665. /*
  666. {metadocument}
  667.     <variable>
  668.         <name>refresh_token</name>
  669.         <type>STRING</type>
  670.         <value></value>
  671.         <documentation>
  672.             <purpose>Refresh token obtained from the OAuth server</purpose>
  673.             <usage>Check this variable to get the obtained refresh token upon
  674.                 successful OAuth authorization.</usage>
  675.         </documentation>
  676.     </variable>
  677. {/metadocument}
  678. */
  679.     var $refresh_token = '';
  680.  
  681. /*
  682. {metadocument}
  683.     <variable>
  684.         <name>access_token_error</name>
  685.         <type>STRING</type>
  686.         <value></value>
  687.         <documentation>
  688.             <purpose>Error message returned when a call to the API fails.</purpose>
  689.             <usage>Check this variable to determine if there was an error while
  690.                 calling the Web services API when using the
  691.                 <functionlink>CallAPI</functionlink> function.</usage>
  692.         </documentation>
  693.     </variable>
  694. {/metadocument}
  695. */
  696.     var $access_token_error = '';
  697.  
  698. /*
  699. {metadocument}
  700.     <variable>
  701.         <name>authorization_error</name>
  702.         <type>STRING</type>
  703.         <value></value>
  704.         <documentation>
  705.             <purpose>Error message returned when it was not possible to obtain
  706.                 an OAuth access token</purpose>
  707.             <usage>Check this variable to determine if there was an error while
  708.                 trying to obtain the OAuth access token.</usage>
  709.         </documentation>
  710.     </variable>
  711. {/metadocument}
  712. */
  713.     var $authorization_error = '';
  714.  
  715. /*
  716. {metadocument}
  717.     <variable>
  718.         <name>response_status</name>
  719.         <type>INTEGER</type>
  720.         <value>0</value>
  721.         <documentation>
  722.             <purpose>HTTP response status returned by the server when calling an
  723.                 API</purpose>
  724.             <usage>Check this variable after calling the
  725.                 <functionlink>CallAPI</functionlink> function if the API calls and you
  726.                 need to process the error depending the response status.
  727.                 <integervalue>200</integervalue> means no error.
  728.                 <integervalue>0</integervalue> means the server response was not
  729.                 retrieved.</usage>
  730.         </documentation>
  731.     </variable>
  732. {/metadocument}
  733. */
  734.     var $response_status = 0;
  735.  
  736.     var $oauth_user_agent = 'PHP-OAuth-API (http://www.phpclasses.org/oauth-api $Revision: 1.66 $)';
  737.     var $session_started = false;
  738.  
  739.     Function SetError($error)
  740.     {
  741.         $this->error = $error;
  742.         if($this->debug)
  743.             $this->OutputDebug('Error: '.$error);
  744.         return(false);
  745.     }
  746.  
  747.     Function SetPHPError($error, &$php_error_message)
  748.     {
  749.         if(IsSet($php_error_message)
  750.         && strlen($php_error_message))
  751.             $error.=": ".$php_error_message;
  752.         return($this->SetError($error));
  753.     }
  754.  
  755.     Function OutputDebug($message)
  756.     {
  757.         if($this->debug)
  758.         {
  759.             $message = $this->debug_prefix.$message;
  760.             $this->debug_output .= $message."\n";;
  761.             error_log($message);
  762.         }
  763.         return(true);
  764.     }
  765.  
  766.     Function GetRequestTokenURL(&$request_token_url)
  767.     {
  768.         $request_token_url = $this->request_token_url;
  769.         return(true);
  770.     }
  771.  
  772.     Function GetDialogURL(&$url, $redirect_uri = '', $state = '')
  773.     {
  774.         $url = (($this->offline && strlen($this->offline_dialog_url)) ? $this->offline_dialog_url : $this->dialog_url);
  775.         if(strlen($url) === 0)
  776.             return $this->SetError('the dialog URL '.($this->offline ? 'for offline access ' : '').'is not defined for this server');
  777.         $url = str_replace(
  778.             '{REDIRECT_URI}', UrlEncode($redirect_uri), str_replace(
  779.             '{STATE}', UrlEncode($state), str_replace(
  780.             '{CLIENT_ID}', UrlEncode($this->client_id), str_replace(
  781.             '{SCOPE}', UrlEncode($this->scope),
  782.             $url))));
  783.         return(true);
  784.     }
  785.  
  786.     Function GetAccessTokenURL(&$access_token_url)
  787.     {
  788.         $access_token_url = $this->access_token_url;
  789.         return(true);
  790.     }
  791.  
  792.     Function GetStoredState(&$state)
  793.     {
  794.         if(!$this->session_started)
  795.         {
  796.             if(!function_exists('session_start'))
  797.                 return $this->SetError('Session variables are not accessible in this PHP environment');
  798.         }
  799.         if(IsSet($_SESSION['OAUTH_STATE']))
  800.             $state = $_SESSION['OAUTH_STATE'];
  801.         else
  802.             $state = $_SESSION['OAUTH_STATE'] = time().'-'.substr(md5(rand().time()), 0, 6);
  803.         return(true);
  804.     }
  805.  
  806.     Function GetRequestState(&$state)
  807.     {
  808.         $check = (strlen($this->append_state_to_redirect_uri) ? $this->append_state_to_redirect_uri : 'state');
  809.         $state = (IsSet($_GET[$check]) ? $_GET[$check] : null);
  810.         return(true);
  811.     }
  812.  
  813.     Function GetRequestCode(&$code)
  814.     {
  815.         $code = (IsSet($_GET['code']) ? $_GET['code'] : null);
  816.         return(true);
  817.     }
  818.  
  819.     Function GetRequestError(&$error)
  820.     {
  821.         $error = (IsSet($_GET['error']) ? $_GET['error'] : null);
  822.         return(true);
  823.     }
  824.  
  825.     Function GetRequestDenied(&$denied)
  826.     {
  827.         $denied = (IsSet($_GET['denied']) ? $_GET['denied'] : null);
  828.         return(true);
  829.     }
  830.  
  831.     Function GetRequestToken(&$token, &$verifier)
  832.     {
  833.         $token = (IsSet($_GET['oauth_token']) ? $_GET['oauth_token'] : null);
  834.         $verifier = (IsSet($_GET['oauth_verifier']) ? $_GET['oauth_verifier'] : null);
  835.         return(true);
  836.     }
  837.  
  838.     Function GetRedirectURI(&$redirect_uri)
  839.     {
  840.         if(strlen($this->redirect_uri))
  841.             $redirect_uri = $this->redirect_uri;
  842.         else
  843.             $redirect_uri = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  844.         return true;
  845.     }
  846.  
  847. /*
  848. {metadocument}
  849.     <function>
  850.         <name>StoreAccessToken</name>
  851.         <type>BOOLEAN</type>
  852.         <documentation>
  853.             <purpose>Store the values of the access token when it is succefully
  854.                 retrieved from the OAuth server.</purpose>
  855.             <usage>This function is meant to be only be called from inside the
  856.                 class. By default it stores access tokens in a session variable
  857.                 named <stringvalue>OAUTH_ACCESS_TOKEN</stringvalue>.<paragraphbreak />
  858.                 Actual implementations should create a sub-class and override this
  859.                 function to make the access token values be stored in other types
  860.                 of containers, like for instance databases.</usage>
  861.             <returnvalue>This function should return
  862.                 <booleanvalue>1</booleanvalue> if the access token was stored
  863.                 successfully.</returnvalue>
  864.         </documentation>
  865.         <argument>
  866.             <name>access_token</name>
  867.             <type>HASH</type>
  868.             <documentation>
  869.                 <purpose>Associative array with properties of the access token.
  870.                     The array may have set the following
  871.                     properties:<paragraphbreak />
  872.                     <stringvalue>value</stringvalue>: string value of the access
  873.                         token<paragraphbreak />
  874.                     <stringvalue>authorized</stringvalue>: boolean value that
  875.                         determines if the access token was obtained
  876.                         successfully<paragraphbreak />
  877.                     <stringvalue>expiry</stringvalue>: (optional) timestamp in ISO
  878.                         format relative to UTC time zone of the access token expiry
  879.                         time<paragraphbreak />
  880.                     <stringvalue>type</stringvalue>: (optional) type of OAuth token
  881.                         that may determine how it should be used when sending API call
  882.                         requests.<paragraphbreak />
  883.                     <stringvalue>refresh</stringvalue>: (optional) token that some
  884.                         servers may set to allowing refreshing access tokens when they
  885.                         expire.</purpose>
  886.             </documentation>
  887.         </argument>
  888.         <do>
  889. {/metadocument}
  890. */
  891.     Function StoreAccessToken($access_token)
  892.     {
  893.         if(!$this->session_started)
  894.         {
  895.             if(!function_exists('session_start'))
  896.                 return $this->SetError('Session variables are not accessible in this PHP environment');
  897.         }
  898.         $_SESSION['OAUTH_ACCESS_TOKEN'][$this->access_token_url] = $access_token;
  899.         return true;
  900.     }
  901. /*
  902. {metadocument}
  903.         </do>
  904.     </function>
  905. {/metadocument}
  906. */
  907.  
  908. /*
  909. {metadocument}
  910.     <function>
  911.         <name>GetAccessToken</name>
  912.         <type>BOOLEAN</type>
  913.         <documentation>
  914.             <purpose>Retrieve the OAuth access token if it was already
  915.                 previously stored by the
  916.                 <functionlink>StoreAccessToken</functionlink> function.</purpose>
  917.             <usage>This function is meant to be only be called from inside the
  918.                 class. By default it retrieves access tokens stored in a session
  919.                 variable named
  920.                 <stringvalue>OAUTH_ACCESS_TOKEN</stringvalue>.<paragraphbreak />
  921.                 Actual implementations should create a sub-class and override this
  922.                 function to retrieve the access token values from other types of
  923.                 containers, like for instance databases.</usage>
  924.             <returnvalue>This function should return
  925.                 <booleanvalue>1</booleanvalue> if the access token was retrieved
  926.                 successfully.</returnvalue>
  927.         </documentation>
  928.         <argument>
  929.             <name>access_token</name>
  930.             <type>STRING</type>
  931.             <out />
  932.             <documentation>
  933.                 <purpose>Return the properties of the access token in an
  934.                     associative array. If the access token was not yet stored, it
  935.                     returns an empty array. Otherwise, the properties it may return
  936.                     are the same that may be passed to the
  937.                     <functionlink>StoreAccessToken</functionlink>.</purpose>
  938.             </documentation>
  939.         </argument>
  940.         <do>
  941. {/metadocument}
  942. */
  943.     Function GetAccessToken(&$access_token)
  944.     {
  945.         if(!$this->session_started)
  946.         {
  947.             if(!function_exists('session_start'))
  948.                 return $this->SetError('Session variables are not accessible in this PHP environment');
  949.             if(!session_start())
  950.                 return($this->SetPHPError('it was not possible to start the PHP session', $php_error_message));
  951.             $this->session_started = true;
  952.         }
  953.         if(IsSet($_SESSION['OAUTH_ACCESS_TOKEN'][$this->access_token_url]))
  954.             $access_token = $_SESSION['OAUTH_ACCESS_TOKEN'][$this->access_token_url];
  955.         else
  956.             $access_token = array();
  957.         return true;
  958.     }
  959. /*
  960. {metadocument}
  961.         </do>
  962.     </function>
  963. {/metadocument}
  964. */
  965.  
  966. /*
  967. {metadocument}
  968.     <function>
  969.         <name>ResetAccessToken</name>
  970.         <type>BOOLEAN</type>
  971.         <documentation>
  972.             <purpose>Reset the access token to a state back when the user has
  973.                 not yet authorized the access to the OAuth server API.</purpose>
  974.             <usage>Call this function if for some reason the token to access
  975.                 the API was revoked and you need to ask the user to authorize
  976.                 the access again.<paragraphbreak />
  977.                 By default the class stores and retrieves access tokens in a
  978.                 session variable named
  979.                 <stringvalue>OAUTH_ACCESS_TOKEN</stringvalue>.<paragraphbreak />
  980.                 This function must be called when the user is accessing your site
  981.                 pages, so it can reset the information stored in session variables
  982.                 that cache the state of a previously retrieved access
  983.                 token.<paragraphbreak />
  984.                 Actual implementations should create a sub-class and override this
  985.                 function to reset the access token state when it is stored in
  986.                 other types of containers, like for instance databases.</usage>
  987.             <returnvalue>This function should return
  988.                 <booleanvalue>1</booleanvalue> if the access token was resetted
  989.                 successfully.</returnvalue>
  990.         </documentation>
  991.         <do>
  992. {/metadocument}
  993. */
  994.     Function ResetAccessToken()
  995.     {
  996.         if($this->debug)
  997.             $this->OutputDebug('Resetting the access token status for OAuth server located at '.$this->access_token_url);
  998.         if(!$this->session_started)
  999.         {
  1000.             if(!function_exists('session_start'))
  1001.                 return $this->SetError('Session variables are not accessible in this PHP environment');
  1002.             if(!session_start())
  1003.                 return($this->SetPHPError('it was not possible to start the PHP session', $php_error_message));
  1004.         }
  1005.         $this->session_started = true;
  1006.         if(IsSet($_SESSION['OAUTH_ACCESS_TOKEN'][$this->access_token_url]))
  1007.             Unset($_SESSION['OAUTH_ACCESS_TOKEN'][$this->access_token_url]);
  1008.         return true;
  1009.     }
  1010. /*
  1011. {metadocument}
  1012.         </do>
  1013.     </function>
  1014. {/metadocument}
  1015. */
  1016.  
  1017.     Function Encode($value)
  1018.     {
  1019.         return(is_array($value) ? $this->EncodeArray($value) : str_replace('%7E', '~', str_replace('+',' ', RawURLEncode($value))));
  1020.     }
  1021.  
  1022.     Function EncodeArray($array)
  1023.     {
  1024.         foreach($array as $key => $value)
  1025.             $array[$key] = $this->Encode($value);
  1026.         return $array;
  1027.     }
  1028.  
  1029.     Function HMAC($function, $data, $key)
  1030.     {
  1031.         switch($function)
  1032.         {
  1033.             case 'sha1':
  1034.                 $pack = 'H40';
  1035.                 break;
  1036.             default:
  1037.                 if($this->debug)
  1038.                     $this->OutputDebug($function.' is not a supported an HMAC hash type');
  1039.                 return('');
  1040.         }
  1041.         if(strlen($key) > 64)
  1042.             $key = pack($pack, $function($key));
  1043.         if(strlen($key) < 64)
  1044.             $key = str_pad($key, 64, "\0");
  1045.         return(pack($pack, $function((str_repeat("\x5c", 64) ^ $key).pack($pack, $function((str_repeat("\x36", 64) ^ $key).$data)))));
  1046.     }
  1047.  
  1048.     Function SendAPIRequest($url, $method, $parameters, $oauth, $options, &$response)
  1049.     {
  1050.         $this->response_status = 0;
  1051.         $http = new http_class;
  1052.         $http->debug = ($this->debug && $this->debug_http);
  1053.         $http->log_debug = true;
  1054.         $http->sasl_authenticate = 0;
  1055.         $http->user_agent = $this->oauth_user_agent;
  1056.         $http->redirection_limit = (IsSet($options['FollowRedirection']) ? intval($options['FollowRedirection']) : 0);
  1057.         $http->follow_redirect = ($http->redirection_limit != 0);
  1058.         if($this->debug)
  1059.             $this->OutputDebug('Accessing the '.$options['Resource'].' at '.$url);
  1060.         $post_files = array();
  1061.         $method = strtoupper($method);
  1062.         $authorization = '';
  1063.         $type = (IsSet($options['RequestContentType']) ? strtolower(trim(strtok($options['RequestContentType'], ';'))) : 'application/x-www-form-urlencoded');
  1064.         if(IsSet($oauth))
  1065.         {
  1066.             $values = array(
  1067.                 'oauth_consumer_key'=>$this->client_id,
  1068.                 'oauth_nonce'=>md5(uniqid(rand(), true)),
  1069.                 'oauth_signature_method'=>$this->signature_method,
  1070.                 'oauth_timestamp'=>time(),
  1071.                 'oauth_version'=>'1.0',
  1072.             );
  1073.             $files = (IsSet($options['Files']) ? $options['Files'] : array());
  1074.             if(count($files))
  1075.             {
  1076.                 foreach($files as $name => $value)
  1077.                 {
  1078.                     if(!IsSet($parameters[$name]))
  1079.                         return($this->SetError('it was specified an file parameters named '.$name));
  1080.                     $file = array();
  1081.                     switch(IsSet($value['Type']) ? $value['Type'] : 'FileName')
  1082.                     {
  1083.                         case 'FileName':
  1084.                             $file['FileName'] = $parameters[$name];
  1085.                             break;
  1086.                         case 'Data':
  1087.                             $file['Data'] = $parameters[$name];
  1088.                             break;
  1089.                         default:
  1090.                             return($this->SetError($value['Type'].' is not a valid type for file '.$name));
  1091.                     }
  1092.                     $file['ContentType'] = (IsSet($value['Content-Type']) ? $value['Content-Type'] : 'automatic/name');
  1093.                     $post_files[$name] = $file;
  1094.                 }
  1095.                 UnSet($parameters[$name]);
  1096.                 if($method !== 'POST')
  1097.                 {
  1098.                     $this->OutputDebug('For uploading files the method should be POST not '.$method);
  1099.                     $method = 'POST';
  1100.                 }
  1101.                 if($type !== 'multipart/form-data')
  1102.                 {
  1103.                     if(IsSet($options['RequestContentType']))
  1104.                         return($this->SetError('the request content type for uploading files should be multipart/form-data'));
  1105.                     $type = 'multipart/form-data';
  1106.                 }
  1107.                 $value_parameters = array();
  1108.             }
  1109.             else
  1110.             {
  1111.                 if($this->url_parameters
  1112.                 && $type === 'application/x-www-form-urlencoded'
  1113.                 && count($parameters))
  1114.                 {
  1115.                     $first = (strpos($url, '?') === false);
  1116.                     foreach($parameters as $parameter => $value)
  1117.                     {
  1118.                         $url .= ($first ? '?' : '&').UrlEncode($parameter).'='.UrlEncode($value);
  1119.                         $first = false;
  1120.                     }
  1121.                     $parameters = array();
  1122.                 }
  1123.                 $value_parameters = ($type !== 'application/x-www-form-urlencoded' ? array() : $parameters);
  1124.             }
  1125.             $values = array_merge($values, $oauth, $value_parameters);
  1126.             $key = $this->Encode($this->client_secret).'&'.$this->Encode($this->access_token_secret);
  1127.             switch($this->signature_method)
  1128.             {
  1129.                 case 'PLAINTEXT':
  1130.                     $values['oauth_signature'] = $key;
  1131.                     break;
  1132.                 case 'HMAC-SHA1':
  1133.                     $uri = strtok($url, '?');
  1134.                     $sign = $method.'&'.$this->Encode($uri).'&';
  1135.                     $first = true;
  1136.                     $sign_values = $values;
  1137.                     $u = parse_url($url);
  1138.                     if(IsSet($u['query']))
  1139.                     {
  1140.                         parse_str($u['query'], $q);
  1141.                         foreach($q as $parameter => $value)
  1142.                             $sign_values[$parameter] = $value;
  1143.                     }
  1144.                     KSort($sign_values);
  1145.                     foreach($sign_values as $parameter => $value)
  1146.                     {
  1147.                         $sign .= $this->Encode(($first ? '' : '&').$parameter.'='.$this->Encode($value));
  1148.                         $first = false;
  1149.                     }
  1150.                     $values['oauth_signature'] = base64_encode($this->HMAC('sha1', $sign, $key));
  1151.                     break;
  1152.                 default:
  1153.                     return $this->SetError($this->signature_method.' signature method is not yet supported');
  1154.             }
  1155.             if($this->authorization_header)
  1156.             {
  1157.                 $authorization = 'OAuth';
  1158.                 $first = true;
  1159.                 foreach($values as $parameter => $value)
  1160.                 {
  1161.                     $authorization .= ($first ? ' ' : ',').$parameter.'="'.$this->Encode($value).'"';
  1162.                     $first = false;
  1163.                 }
  1164.             }
  1165.             else
  1166.             {
  1167.                 if($method === 'GET'
  1168.                 || (IsSet($options['PostValuesInURI'])
  1169.                 && $options['PostValuesInURI']))
  1170.                 {
  1171.                     $first = (strcspn($url, '?') == strlen($url));
  1172.                     foreach($values as $parameter => $value)
  1173.                     {
  1174.                         $url .= ($first ? '?' : '&').$parameter.'='.$this->Encode($value);
  1175.                         $first = false;
  1176.                     }
  1177.                     $post_values = array();
  1178.                 }
  1179.                 else
  1180.                     $post_values = $values;
  1181.             }
  1182.         }
  1183.         if(strlen($authorization) === 0
  1184.         && !strcasecmp($this->access_token_type, 'Bearer'))
  1185.             $authorization = 'Bearer '.$this->access_token;
  1186.         if(strlen($error = $http->GetRequestArguments($url, $arguments)))
  1187.             return($this->SetError('it was not possible to open the '.$options['Resource'].' URL: '.$error));
  1188.         if(strlen($error = $http->Open($arguments)))
  1189.             return($this->SetError('it was not possible to open the '.$options['Resource'].' URL: '.$error));
  1190.         if(count($post_files))
  1191.             $arguments['PostFiles'] = $post_files;
  1192.         $arguments['RequestMethod'] = $method;
  1193.         switch($type)
  1194.         {
  1195.             case 'application/x-www-form-urlencoded':
  1196.             case 'multipart/form-data':
  1197.                 if(IsSet($options['RequestBody']))
  1198.                     return($this->SetError('the request body is defined automatically from the parameters'));
  1199.                 $arguments['PostValues'] = $parameters;
  1200.                 break;
  1201.             case 'application/json':
  1202.                 $arguments['Headers']['Content-Type'] = $options['RequestContentType'];
  1203.                 if(!IsSet($options['RequestBody']))
  1204.                 {
  1205.                     $arguments['Body'] = json_encode($parameters);
  1206.                     break;
  1207.                 }
  1208.             default:
  1209.                 if(!IsSet($options['RequestBody']))
  1210.                     return($this->SetError('it was not specified the body value of the of the API call request'));
  1211.                 $arguments['Headers']['Content-Type'] = $options['RequestContentType'];
  1212.                 $arguments['Body'] = $options['RequestBody'];
  1213.                 break;
  1214.         }
  1215.         $arguments['Headers']['Accept'] = (IsSet($options['Accept']) ? $options['Accept'] : '*/*');
  1216.         if(strlen($authorization))
  1217.             $arguments['Headers']['Authorization'] = $authorization;
  1218.         if(strlen($error = $http->SendRequest($arguments))
  1219.         || strlen($error = $http->ReadReplyHeaders($headers)))
  1220.         {
  1221.             $http->Close();
  1222.             return($this->SetError('it was not possible to retrieve the '.$options['Resource'].': '.$error));
  1223.         }
  1224.         $error = $http->ReadWholeReplyBody($data);
  1225.         $http->Close();
  1226.         if(strlen($error))
  1227.         {
  1228.             return($this->SetError('it was not possible to access the '.$options['Resource'].': '.$error));
  1229.         }
  1230.         $this->response_status = intval($http->response_status);
  1231.         $content_type = (IsSet($options['ResponseContentType']) ? $options['ResponseContentType'] : (IsSet($headers['content-type']) ? strtolower(trim(strtok($headers['content-type'], ';'))) : 'unspecified'));
  1232.         switch($content_type)
  1233.         {
  1234.             case 'text/javascript':
  1235.             case 'application/json':
  1236.                 if(!function_exists('json_decode'))
  1237.                     return($this->SetError('the JSON extension is not available in this PHP setup'));
  1238.                 $object = json_decode($data);
  1239.                 switch(GetType($object))
  1240.                 {
  1241.                     case 'object':
  1242.                         if(!IsSet($options['ConvertObjects'])
  1243.                         || !$options['ConvertObjects'])
  1244.                             $response = $object;
  1245.                         else
  1246.                         {
  1247.                             $response = array();
  1248.                             foreach($object as $property => $value)
  1249.                                 $response[$property] = $value;
  1250.                         }
  1251.                         break;
  1252.                     case 'array':
  1253.                         $response = $object;
  1254.                         break;
  1255.                     default:
  1256.                         if(!IsSet($object))
  1257.                             return($this->SetError('it was not returned a valid JSON definition of the '.$options['Resource'].' values'));
  1258.                         $response = $object;
  1259.                         break;
  1260.                 }
  1261.                 break;
  1262.             case 'application/x-www-form-urlencoded':
  1263.             case 'text/plain':
  1264.             case 'text/html':
  1265.                 parse_str($data, $response);
  1266.                 break;
  1267.             default:
  1268.                 $response = $data;
  1269.                 break;
  1270.         }
  1271.         if($this->response_status >= 200
  1272.         && $this->response_status < 300)
  1273.             $this->access_token_error = '';
  1274.         else
  1275.         {
  1276.             $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;
  1277.             if($this->debug)
  1278.                 $this->OutputDebug('Could not retrieve the OAuth access token. Error: '.$this->access_token_error);
  1279.             if(IsSet($options['FailOnAccessError'])
  1280.             && $options['FailOnAccessError'])
  1281.             {
  1282.                 $this->error = $this->access_token_error;
  1283.                 return false;
  1284.             }
  1285.         }
  1286.         return true;
  1287.     }
  1288.  
  1289.     Function ProcessToken($code, $refresh)
  1290.     {
  1291.         if($refresh)
  1292.         {
  1293.             $values = array(
  1294.                 'client_id'=>$this->client_id,
  1295.                 'client_secret'=>$this->client_secret,
  1296.                 'refresh_token'=>$this->refresh_token,
  1297.                 'grant_type'=>'refresh_token'
  1298.             );
  1299.         }
  1300.         else
  1301.         {
  1302.             if(!$this->GetRedirectURI($redirect_uri))
  1303.                 return false;
  1304.             $values = array(
  1305.                 'code'=>$code,
  1306.                 'client_id'=>$this->client_id,
  1307.                 'client_secret'=>$this->client_secret,
  1308.                 'redirect_uri'=>$redirect_uri,
  1309.                 'grant_type'=>'authorization_code'
  1310.             );
  1311.         }
  1312.         if(!$this->GetAccessTokenURL($url))
  1313.             return false;
  1314.         if(!$this->SendAPIRequest($url, 'POST', $values, null, array('Resource'=>'OAuth '.($refresh ? 'refresh' : 'access').' token', 'ConvertObjects'=>true), $response))
  1315.             return false;
  1316.         if(strlen($this->access_token_error))
  1317.         {
  1318.             $this->authorization_error = $this->access_token_error;
  1319.             return true;
  1320.         }
  1321.         if(!IsSet($response['access_token']))
  1322.         {
  1323.             if(IsSet($response['error']))
  1324.             {
  1325.                 $this->authorization_error = 'it was not possible to retrieve the access token: it was returned the error: '.$response['error'];
  1326.                 return true;
  1327.             }
  1328.             return($this->SetError('OAuth server did not return the access token'));
  1329.         }
  1330.         $access_token = array(
  1331.             'value'=>($this->access_token = $response['access_token']),
  1332.             'authorized'=>true,
  1333.         );
  1334.         if($this->store_access_token_response)
  1335.             $access_token['response'] = $this->access_token_response = $response;
  1336.         if($this->debug)
  1337.             $this->OutputDebug('Access token: '.$this->access_token);
  1338.         if(IsSet($response['expires_in'])
  1339.         && $response['expires_in'] == 0)
  1340.         {
  1341.             if($this->debug)
  1342.                 $this->OutputDebug('Ignoring access token expiry set to 0');
  1343.             $this->access_token_expiry = '';
  1344.         }
  1345.         elseif(IsSet($response['expires'])
  1346.         || IsSet($response['expires_in']))
  1347.         {
  1348.             $expires = (IsSet($response['expires']) ? $response['expires'] : $response['expires_in']);
  1349.             if(strval($expires) !== strval(intval($expires))
  1350.             || $expires <= 0)
  1351.                 return($this->SetError('OAuth server did not return a supported type of access token expiry time'));
  1352.             $this->access_token_expiry = gmstrftime('%Y-%m-%d %H:%M:%S', time() + $expires);
  1353.             if($this->debug)
  1354.                 $this->OutputDebug('Access token expiry: '.$this->access_token_expiry.' UTC');
  1355.             $access_token['expiry'] = $this->access_token_expiry;
  1356.         }
  1357.         else
  1358.             $this->access_token_expiry = '';
  1359.         if(IsSet($response['token_type']))
  1360.         {
  1361.             $this->access_token_type = $response['token_type'];
  1362.             if(strlen($this->access_token_type)
  1363.             && $this->debug)
  1364.                 $this->OutputDebug('Access token type: '.$this->access_token_type);
  1365.             $access_token['type'] = $this->access_token_type;
  1366.         }
  1367.         else
  1368.         {
  1369.             $this->access_token_type = $this->default_access_token_type;
  1370.             if(strlen($this->access_token_type)
  1371.             && $this->debug)
  1372.                 $this->OutputDebug('Assumed the default for OAuth access token type which is '.$this->access_token_type);
  1373.         }
  1374.         if(IsSet($response['refresh_token']))
  1375.         {
  1376.             $this->refresh_token = $response['refresh_token'];
  1377.             if($this->debug)
  1378.                 $this->OutputDebug('New refresh token: '.$this->refresh_token);
  1379.             $access_token['refresh'] = $this->refresh_token;
  1380.         }
  1381.         elseif(strlen($this->refresh_token))
  1382.         {
  1383.             if($this->debug)
  1384.                 $this->OutputDebug('Reusing previous refresh token: '.$this->refresh_token);
  1385.             $access_token['refresh'] = $this->refresh_token;
  1386.         }
  1387.         if(!$this->StoreAccessToken($access_token))
  1388.             return false;
  1389.         return true;
  1390.     }
  1391.  
  1392.     Function RetrieveToken(&$valid)
  1393.     {
  1394.         $valid = false;
  1395.         if(!$this->GetAccessToken($access_token))
  1396.             return false;
  1397.         if(IsSet($access_token['value']))
  1398.         {
  1399.             $this->access_token_expiry = '';
  1400.             if(IsSet($access_token['expiry'])
  1401.             && strcmp($this->access_token_expiry = $access_token['expiry'], gmstrftime('%Y-%m-%d %H:%M:%S')) < 0)
  1402.             {
  1403.                 if($this->debug)
  1404.                     $this->OutputDebug('The OAuth access token expired in '.$this->access_token_expiry);
  1405.             }
  1406.             $this->access_token = $access_token['value'];
  1407.             if($this->debug)
  1408.                 $this->OutputDebug('The OAuth access token '.$this->access_token.' is valid');
  1409.             if(IsSet($access_token['type']))
  1410.             {
  1411.                 $this->access_token_type = $access_token['type'];
  1412.                 if(strlen($this->access_token_type)
  1413.                 && $this->debug)
  1414.                     $this->OutputDebug('The OAuth access token is of type '.$this->access_token_type);
  1415.             }
  1416.             else
  1417.             {
  1418.                 $this->access_token_type = $this->default_access_token_type;
  1419.                 if(strlen($this->access_token_type)
  1420.                 && $this->debug)
  1421.                     $this->OutputDebug('Assumed the default for OAuth access token type which is '.$this->access_token_type);
  1422.             }
  1423.             if(IsSet($access_token['secret']))
  1424.             {
  1425.                 $this->access_token_secret = $access_token['secret'];
  1426.                 if($this->debug)
  1427.                     $this->OutputDebug('The OAuth access token secret is '.$this->access_token_secret);
  1428.             }
  1429.             if(IsSet($access_token['refresh']))
  1430.                 $this->refresh_token = $access_token['refresh'];
  1431.             else
  1432.                 $this->refresh_token = '';
  1433.             $this->access_token_response = (($this->store_access_token_response && IsSet($access_token['response'])) ? $access_token['response'] : null);
  1434.             $valid = true;
  1435.         }
  1436.         return true;
  1437.     }
  1438. /*
  1439. {metadocument}
  1440.     <function>
  1441.         <name>CallAPI</name>
  1442.         <type>BOOLEAN</type>
  1443.         <documentation>
  1444.             <purpose>Send a HTTP request to the Web services API using a
  1445.                 previously obtained authorization token via OAuth.</purpose>
  1446.             <usage>This function can be used to call an API after having
  1447.                 previously obtained an access token through the OAuth protocol
  1448.                 using the <functionlink>Process</functionlink> function, or by
  1449.                 directly setting the variables
  1450.                 <variablelink>access_token</variablelink>, as well as
  1451.                 <variablelink>access_token_secret</variablelink> in case of using
  1452.                 OAuth 1.0 or 1.0a services.</usage>
  1453.             <returnvalue>This function returns <booleanvalue>1</booleanvalue> if
  1454.                 the call was done successfully.</returnvalue>
  1455.         </documentation>
  1456.         <argument>
  1457.             <name>url</name>
  1458.             <type>STRING</type>
  1459.             <documentation>
  1460.                 <purpose>URL of the API where the HTTP request will be sent.</purpose>
  1461.             </documentation>
  1462.         </argument>
  1463.         <argument>
  1464.             <name>method</name>
  1465.             <type>STRING</type>
  1466.             <documentation>
  1467.                 <purpose>HTTP method that will be used to send the request. It can
  1468.                 be <stringvalue>GET</stringvalue>,
  1469.                 <stringvalue>POST</stringvalue>,
  1470.                 <stringvalue>DELETE</stringvalue>, <stringvalue>PUT</stringvalue>,
  1471.                 etc..</purpose>
  1472.             </documentation>
  1473.         </argument>
  1474.         <argument>
  1475.             <name>parameters</name>
  1476.             <type>HASH</type>
  1477.             <documentation>
  1478.                 <purpose>Associative array with the names and values of the API
  1479.                     call request parameters.</purpose>
  1480.             </documentation>
  1481.         </argument>
  1482.         <argument>
  1483.             <name>options</name>
  1484.             <type>HASH</type>
  1485.             <documentation>
  1486.                 <purpose>Associative array with additional options to configure
  1487.                     the request. Currently it supports the following
  1488.                     options:<paragraphbreak />
  1489.                     <stringvalue>2Legged</stringvalue>: boolean option that
  1490.                         determines if the API request should be 2 legged. The default
  1491.                         value is <tt><booleanvalue>0</booleanvalue></tt>.<paragraphbreak />
  1492.                     <stringvalue>Accept</stringvalue>: content type value of the
  1493.                         Accept HTTP header to be sent in the API call HTTP request.
  1494.                         Some APIs require that a certain value be sent to specify
  1495.                         which version of the API is being called. The default value is
  1496.                         <stringvalue>*&#47;*</stringvalue>.<paragraphbreak />
  1497.                     <stringvalue>ConvertObjects</stringvalue>: boolean option that
  1498.                         determines if objects should be converted into arrays when the
  1499.                         response is returned in JSON format. The default value is
  1500.                         <booleanvalue>0</booleanvalue>.<paragraphbreak />
  1501.                     <stringvalue>FailOnAccessError</stringvalue>: boolean option
  1502.                         that determines if this functions should fail when the server
  1503.                         response status is not between 200 and 299. The default value
  1504.                         is <booleanvalue>0</booleanvalue>.<paragraphbreak />
  1505.                     <stringvalue>Files</stringvalue>: associative array with
  1506.                         details of the parameters that must be passed as file uploads.
  1507.                         The array indexes must have the same name of the parameters
  1508.                         to be sent as files. The respective array entry values must
  1509.                         also be associative arrays with the parameters for each file.
  1510.                         Currently it supports the following parameters:<paragraphbreak />
  1511.                         - <tt>Type</tt> - defines how the parameter value should be
  1512.                         treated. It can be <tt>'FileName'</tt> if the parameter value is
  1513.                         is the name of a local file to be uploaded. It may also be
  1514.                         <tt>'Data'</tt> if the parameter value is the actual data of
  1515.                         the file to be uploaded.<paragraphbreak />
  1516.                         - Default: <tt>'FileName'</tt><paragraphbreak />
  1517.                         - <tt>ContentType</tt> - MIME value of the content type of the
  1518.                         file. It can be <tt>'automatic/name'</tt> if the content type
  1519.                         should be determine from the file name extension.<paragraphbreak />
  1520.                         - Default: <tt>'automatic/name'</tt><paragraphbreak />
  1521.                     <stringvalue>PostValuesInURI</stringvalue>: boolean option to
  1522.                         determine that a POST request should pass the request values
  1523.                         in the URI. The default value is
  1524.                         <booleanvalue>0</booleanvalue>.<paragraphbreak />
  1525.                     <stringvalue>FollowRedirection</stringvalue>: limit number of
  1526.                         times that HTTP response redirects will be followed. If it is
  1527.                         set to <integervalue>0</integervalue>, redirection responses
  1528.                         fail in error. The default value is
  1529.                         <integervalue>0</integervalue>.<paragraphbreak />
  1530.                     <stringvalue>RequestBody</stringvalue>: request body data of a
  1531.                         custom type. The <stringvalue>RequestContentType</stringvalue>
  1532.                         option must be specified, so the
  1533.                         <stringvalue>RequestBody</stringvalue> option is considered.<paragraphbreak />
  1534.                     <stringvalue>RequestContentType</stringvalue>: content type that
  1535.                         should be used to send the request values. It can be either
  1536.                         <stringvalue>application/x-www-form-urlencoded</stringvalue>
  1537.                         for sending values like from Web forms, or
  1538.                         <stringvalue>application/json</stringvalue> for sending the
  1539.                         values encoded in JSON format. Other types are accepted if the
  1540.                         <stringvalue>RequestBody</stringvalue> option is specified.
  1541.                         The default value is
  1542.                         <stringvalue>application/x-www-form-urlencoded</stringvalue>.<paragraphbreak />
  1543.                     <stringvalue>RequestBody</stringvalue>: request body data of a
  1544.                         custom type. The <stringvalue>RequestContentType</stringvalue>
  1545.                         option must be specified, so the
  1546.                         <stringvalue>RequestBody</stringvalue> option is considered.<paragraphbreak />
  1547.                     <stringvalue>Resource</stringvalue>: string with a label that
  1548.                         will be used in the error messages and debug log entries to
  1549.                         identify what operation the request is performing. The default
  1550.                         value is <stringvalue>API call</stringvalue>.<paragraphbreak />
  1551.                     <stringvalue>ResponseContentType</stringvalue>: content type
  1552.                         that should be considered when decoding the API request
  1553.                         response. This overrides the <tt>Content-Type</tt> header
  1554.                         returned by the server. If the content type is
  1555.                         <stringvalue>application/x-www-form-urlencoded</stringvalue>
  1556.                         the function will parse the data returning an array of
  1557.                         key-value pairs. If the content type is
  1558.                         <stringvalue>application/json</stringvalue> the response will
  1559.                         be decode as a JSON-encoded data type. Other content type
  1560.                         values will make the function return the original response
  1561.                         value as it was returned from the server. The default value
  1562.                         for this option is to use what the server returned in the
  1563.                         <tt>Content-Type</tt> header.</purpose>
  1564.             </documentation>
  1565.         </argument>
  1566.         <argument>
  1567.             <name>response</name>
  1568.             <type>STRING</type>
  1569.             <out />
  1570.             <documentation>
  1571.                 <purpose>Return the value of the API response. If the value is
  1572.                     JSON encoded, this function will decode it and return the value
  1573.                     converted to respective types. If the value is form encoded,
  1574.                     this function will decode the response and return it as an
  1575.                     array. Otherwise, the class will return the value as a
  1576.                     string.</purpose>
  1577.             </documentation>
  1578.         </argument>
  1579.         <do>
  1580. {/metadocument}
  1581. */
  1582.     Function CallAPI($url, $method, $parameters, $options, &$response)
  1583.     {
  1584.         if(!IsSet($options['Resource']))
  1585.             $options['Resource'] = 'API call';
  1586.         if(!IsSet($options['ConvertObjects']))
  1587.             $options['ConvertObjects'] = false;
  1588.         if(strlen($this->access_token) === 0)
  1589.         {
  1590.             if(!$this->RetrieveToken($valid))
  1591.                 return false;
  1592.             if(!$valid)
  1593.                 return $this->SetError('the access token is not set to a valid value');
  1594.         }
  1595.         switch(intval($this->oauth_version))
  1596.         {
  1597.             case 1:
  1598.                 $oauth = array(
  1599.                     'oauth_token'=>((IsSet($options['2Legged']) && $options['2Legged']) ? '' : $this->access_token)
  1600.                 );
  1601.                 break;
  1602.  
  1603.             case 2:
  1604.                 if(strlen($this->access_token_expiry)
  1605.                 && strcmp($this->access_token_expiry, gmstrftime('%Y-%m-%d %H:%M:%S')) <= 0)
  1606.                 {
  1607.                     if(strlen($this->refresh_token) === 0)
  1608.                         return($this->SetError('the access token expired and no refresh token is available'));
  1609.                     if($this->debug)
  1610.                     {
  1611.                         $this->OutputDebug('The access token expired on '.$this->access_token_expiry);
  1612.                         $this->OutputDebug('Refreshing the access token');
  1613.                     }
  1614.                     if(!$this->ProcessToken(null, true))
  1615.                         return false;
  1616.                 }
  1617.                 $oauth = null;
  1618.                 if(strcasecmp($this->access_token_type, 'Bearer'))
  1619.                     $url .= (strcspn($url, '?') < strlen($url) ? '&' : '?').'access_token='.UrlEncode($this->access_token);
  1620.                 break;
  1621.  
  1622.             default:
  1623.                 return($this->SetError($this->oauth_version.' is not a supported version of the OAuth protocol'));
  1624.         }
  1625.         return($this->SendAPIRequest($url, $method, $parameters, $oauth, $options, $response));
  1626.     }
  1627. /*
  1628. {metadocument}
  1629.         </do>
  1630.     </function>
  1631. {/metadocument}
  1632. */
  1633.  
  1634. /*
  1635. {metadocument}
  1636.     <function>
  1637.         <name>Initialize</name>
  1638.         <type>BOOLEAN</type>
  1639.         <documentation>
  1640.             <purpose>Initialize the class variables and internal state. It must
  1641.                 be called before calling other class functions.</purpose>
  1642.             <usage>Set the <variablelink>server</variablelink> variable before
  1643.                 calling this function to let it initialize the class variables to
  1644.                 work with the specified server type. Alternatively, you can set
  1645.                 other class variables manually to make it work with servers that
  1646.                 are not yet built-in supported.</usage>
  1647.             <returnvalue>This function returns <booleanvalue>1</booleanvalue> if
  1648.                 it was able to successfully initialize the class for the specified
  1649.                 server type.</returnvalue>
  1650.         </documentation>
  1651.         <do>
  1652. {/metadocument}
  1653. */
  1654.     Function Initialize()
  1655.     {
  1656.         if(strlen($this->server) === 0)
  1657.             return true;
  1658.         $this->request_token_url = '';
  1659.         $this->append_state_to_redirect_uri = '';
  1660.         $this->authorization_header = true;
  1661.         $this->url_parameters = false;
  1662.         $this->token_request_method = 'GET';
  1663.         $this->signature_method = 'HMAC-SHA1';
  1664.         switch($this->server)
  1665.         {
  1666.             case 'Bitbucket':
  1667.                 $this->oauth_version = '1.0a';
  1668.                 $this->request_token_url = 'https://bitbucket.org/!api/1.0/oauth/request_token';
  1669.                 $this->dialog_url = 'https://bitbucket.org/!api/1.0/oauth/authenticate';
  1670.                 $this->access_token_url = 'https://bitbucket.org/!api/1.0/oauth/access_token';
  1671.                 $this->url_parameters = true;
  1672.                 break;
  1673.  
  1674.             case 'Box':
  1675.                 $this->oauth_version = '2.0';
  1676.                 $this->dialog_url = 'https://www.box.com/api/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&state={STATE}';
  1677.                 $this->offline_dialog_url = 'https://www.box.com/api/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&state={STATE}&access_type=offline&approval_prompt=force';
  1678.                 $this->access_token_url = 'https://www.box.com/api/oauth2/token';
  1679.                 break;
  1680.  
  1681.             case 'Dropbox':
  1682.                 $this->oauth_version = '1.0';
  1683.                 $this->request_token_url = 'https://api.dropbox.com/1/oauth/request_token';
  1684.                 $this->dialog_url = 'https://www.dropbox.com/1/oauth/authorize';
  1685.                 $this->access_token_url = 'https://api.dropbox.com/1/oauth/access_token';
  1686.                 $this->authorization_header = false;
  1687.                 break;
  1688.  
  1689.             case 'Eventful':
  1690.                 $this->oauth_version = '1.0a';
  1691.                 $this->request_token_url = 'http://eventful.com/oauth/request_token';
  1692.                 $this->dialog_url = 'http://eventful.com/oauth/authorize';
  1693.                 $this->access_token_url = 'http://eventful.com/oauth/access_token';
  1694.                 $this->authorization_header = false;
  1695.                 $this->url_parameters = true;
  1696.                 $this->token_request_method = 'POST';
  1697.                 break;
  1698.  
  1699.             case 'Evernote':
  1700.                 $this->oauth_version = '1.0a';
  1701.                 $this->request_token_url = 'https://sandbox.evernote.com/oauth';
  1702.                 $this->dialog_url = 'https://sandbox.evernote.com/OAuth.action';
  1703.                 $this->access_token_url = 'https://sandbox.evernote.com/oauth';
  1704.                 $this->url_parameters = true;
  1705.                 $this->authorization_header = false;
  1706.                 break;
  1707.  
  1708.             case 'Facebook':
  1709.                 $this->oauth_version = '2.0';
  1710.                 $this->dialog_url = 'https://www.facebook.com/dialog/oauth?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&state={STATE}';
  1711.                 $this->access_token_url = 'https://graph.facebook.com/oauth/access_token';
  1712.                 break;
  1713.  
  1714.             case 'Fitbit':
  1715.                 $this->oauth_version = '1.0a';
  1716.                 $this->request_token_url = 'http://api.fitbit.com/oauth/request_token';
  1717.                 $this->dialog_url = 'http://api.fitbit.com/oauth/authorize';
  1718.                 $this->access_token_url = 'http://api.fitbit.com/oauth/access_token';
  1719.                 break;
  1720.  
  1721.             case 'Flickr':
  1722.                 $this->oauth_version = '1.0a';
  1723.                 $this->request_token_url = 'http://www.flickr.com/services/oauth/request_token';
  1724.                 $this->dialog_url = 'http://www.flickr.com/services/oauth/authorize?perms={SCOPE}';
  1725.                 $this->access_token_url = 'http://www.flickr.com/services/oauth/access_token';
  1726.                 $this->authorization_header = false;
  1727.                 break;
  1728.  
  1729.             case 'Foursquare':
  1730.                 $this->oauth_version = '2.0';
  1731.                 $this->dialog_url = 'https://foursquare.com/oauth2/authorize?client_id={CLIENT_ID}&scope={SCOPE}&response_type=code&redirect_uri={REDIRECT_URI}&state={STATE}';
  1732.                 $this->access_token_url = 'https://foursquare.com/oauth2/access_token';
  1733.                 break;
  1734.  
  1735.             case 'github':
  1736.                 $this->oauth_version = '2.0';
  1737.                 $this->dialog_url = 'https://github.com/login/oauth/authorize?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&state={STATE}';
  1738.                 $this->access_token_url = 'https://github.com/login/oauth/access_token';
  1739.                 break;
  1740.  
  1741.             case 'Google':
  1742.                 $this->oauth_version = '2.0';
  1743.                 $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}';
  1744.                 $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';
  1745.                 $this->access_token_url = 'https://accounts.google.com/o/oauth2/token';
  1746.                 break;
  1747.  
  1748.             case 'Instagram':
  1749.                 $this->oauth_version = '2.0';
  1750.                 $this->dialog_url ='https://api.instagram.com/oauth/authorize/?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&response_type=code&state={STATE}';
  1751.                 $this->access_token_url = 'https://api.instagram.com/oauth/access_token';
  1752.                 break;
  1753.  
  1754.             case 'LinkedIn':
  1755.                 $this->oauth_version = '1.0a';
  1756.                 $this->request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken?scope={SCOPE}';
  1757.                 $this->dialog_url = 'https://api.linkedin.com/uas/oauth/authenticate';
  1758.                 $this->access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken';
  1759.                 $this->url_parameters = true;
  1760.                 break;
  1761.  
  1762.             case 'Microsoft':
  1763.                 $this->oauth_version = '2.0';
  1764.                 $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}';
  1765.                 $this->access_token_url = 'https://login.live.com/oauth20_token.srf';
  1766.                 break;
  1767.  
  1768.             case 'RightSignature':
  1769.                 $this->oauth_version = '1.0a';
  1770.                 $this->request_token_url = 'https://rightsignature.com/oauth/request_token';
  1771.                 $this->dialog_url = 'https://rightsignature.com/oauth/authorize';
  1772.                 $this->access_token_url = 'https://rightsignature.com/oauth/access_token';
  1773.                 $this->authorization_header = false;
  1774.                 break;
  1775.  
  1776.             case 'Salesforce':
  1777.                 $this->oauth_version = '2.0';
  1778.                 $this->dialog_url = 'https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope={SCOPE}&state={STATE}';
  1779.                 $this->access_token_url = 'https://login.salesforce.com/services/oauth2/token';
  1780.                 $this->default_access_token_type = 'Bearer';
  1781.                 $this->store_access_token_response = true;
  1782.                 break;
  1783.  
  1784.             case 'Scoop.it':
  1785.                 $this->oauth_version = '1.0a';
  1786.                 $this->request_token_url = 'https://www.scoop.it/oauth/request';
  1787.                 $this->dialog_url = 'https://www.scoop.it/oauth/authorize';
  1788.                 $this->access_token_url = 'https://www.scoop.it/oauth/access';
  1789.                 $this->authorization_header = false;
  1790.                 break;
  1791.  
  1792.             case 'StockTwits':
  1793.                 $this->oauth_version = '2.0';
  1794.                 $this->dialog_url = 'https://api.stocktwits.com/api/2/oauth/authorize?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&scope={SCOPE}&state={STATE}';
  1795.                 $this->access_token_url = 'https://api.stocktwits.com/api/2/oauth/token';
  1796.                 break;
  1797.  
  1798.             case 'Tumblr':
  1799.                 $this->oauth_version = '1.0a';
  1800.                 $this->request_token_url = 'http://www.tumblr.com/oauth/request_token';
  1801.                 $this->dialog_url = 'http://www.tumblr.com/oauth/authorize';
  1802.                 $this->access_token_url = 'http://www.tumblr.com/oauth/access_token';
  1803.                 break;
  1804.  
  1805.             case 'Twitter':
  1806.                 $this->oauth_version = '1.0a';
  1807.                 $this->request_token_url = 'https://api.twitter.com/oauth/request_token';
  1808.                 $this->dialog_url = 'https://api.twitter.com/oauth/authenticate';
  1809.                 $this->access_token_url = 'https://api.twitter.com/oauth/access_token';
  1810.                 $this->url_parameters = true;
  1811.                 break;
  1812.  
  1813.             case 'XING':
  1814.                 $this->oauth_version = '1.0a';
  1815.                 $this->request_token_url = 'https://api.xing.com/v1/request_token';
  1816.                 $this->dialog_url = 'https://api.xing.com/v1/authorize';
  1817.                 $this->access_token_url = 'https://api.xing.com/v1/access_token';
  1818.                 $this->authorization_header = false;
  1819.                 break;
  1820.  
  1821.             case 'Yahoo':
  1822.                 $this->oauth_version = '1.0a';
  1823.                 $this->request_token_url = 'https://api.login.yahoo.com/oauth/v2/get_request_token';
  1824.                 $this->dialog_url = 'https://api.login.yahoo.com/oauth/v2/request_auth';
  1825.                 $this->access_token_url = 'https://api.login.yahoo.com/oauth/v2/get_token';
  1826.                 $this->authorization_header = false;
  1827.                 break;
  1828.  
  1829.             default:
  1830.                 return($this->SetError($this->server.' is not yet a supported type of OAuth server. Please contact the author Manuel Lemos <[email protected]> to request adding built-in support to this type of OAuth server.'));
  1831.         }
  1832.         return(true);
  1833.     }
  1834. /*
  1835. {metadocument}
  1836.         </do>
  1837.     </function>
  1838. {/metadocument}
  1839. */
  1840.  
  1841. /*
  1842. {metadocument}
  1843.     <function>
  1844.         <name>Process</name>
  1845.         <type>BOOLEAN</type>
  1846.         <documentation>
  1847.             <purpose>Process the OAuth protocol interaction with the OAuth
  1848.                 server.</purpose>
  1849.             <usage>Call this function when you need to retrieve the OAuth access
  1850.                 token. Check the <variablelink>access_token</variablelink> to
  1851.                 determine if the access token was obtained successfully.</usage>
  1852.             <returnvalue>This function returns <booleanvalue>1</booleanvalue> if
  1853.                 the OAuth protocol was processed without errors.</returnvalue>
  1854.         </documentation>
  1855.         <do>
  1856. {/metadocument}
  1857. */
  1858.     Function Process()
  1859.     {
  1860.         switch(intval($this->oauth_version))
  1861.         {
  1862.             case 1:
  1863.                 $one_a = ($this->oauth_version === '1.0a');
  1864.                 if($this->debug)
  1865.                     $this->OutputDebug('Checking the OAuth token authorization state');
  1866.                 if(!$this->GetAccessToken($access_token))
  1867.                     return false;
  1868.                 if(IsSet($access_token['authorized'])
  1869.                 && IsSet($access_token['value']))
  1870.                 {
  1871.                     $expired = (IsSet($access_token['expiry']) && strcmp($access_token['expiry'], gmstrftime('%Y-%m-%d %H:%M:%S')) <= 0);
  1872.                     if(!$access_token['authorized']
  1873.                     || $expired)
  1874.                     {
  1875.                         if($this->debug)
  1876.                         {
  1877.                             if($expired)
  1878.                                 $this->OutputDebug('The OAuth token expired on '.$access_token['expiry'].'UTC');
  1879.                             else
  1880.                                 $this->OutputDebug('The OAuth token is not yet authorized');
  1881.                             $this->OutputDebug('Checking the OAuth token and verifier');
  1882.                         }
  1883.                         if(!$this->GetRequestToken($token, $verifier))
  1884.                             return false;
  1885.                         if(!IsSet($token)
  1886.                         || ($one_a
  1887.                         && !IsSet($verifier)))
  1888.                         {
  1889.                             if(!$this->GetRequestDenied($denied))
  1890.                                 return false;
  1891.                             if(IsSet($denied)
  1892.                             && $denied === $access_token['value'])
  1893.                             {
  1894.                                 if($this->debug)
  1895.                                     $this->OutputDebug('The authorization request was denied');
  1896.                                 $this->authorization_error = 'the request was denied';
  1897.                                 return true;
  1898.                             }
  1899.                             else
  1900.                             {
  1901.                                 if($this->debug)
  1902.                                     $this->OutputDebug('Reset the OAuth token state because token and verifier are not both set');
  1903.                                 $access_token = array();
  1904.                             }
  1905.                         }
  1906.                         elseif($token !== $access_token['value'])
  1907.                         {
  1908.                             if($this->debug)
  1909.                                 $this->OutputDebug('Reset the OAuth token state because token does not match what as previously retrieved');
  1910.                             $access_token = array();
  1911.                         }
  1912.                         else
  1913.                         {
  1914.                             if(!$this->GetAccessTokenURL($url))
  1915.                                 return false;
  1916.                             $oauth = array(
  1917.                                 'oauth_token'=>$token,
  1918.                             );
  1919.                             if($one_a)
  1920.                                 $oauth['oauth_verifier'] = $verifier;
  1921.                             $this->access_token_secret = $access_token['secret'];
  1922.                             $options = array('Resource'=>'OAuth access token');
  1923.                             $method = strtoupper($this->token_request_method);
  1924.                             switch($method)
  1925.                             {
  1926.                                 case 'GET':
  1927.                                     break;
  1928.                                 case 'POST':
  1929.                                     $options['PostValuesInURI'] = true;
  1930.                                     break;
  1931.                                 default:
  1932.                                     $this->error = $method.' is not a supported method to request tokens';
  1933.                                     break;
  1934.                             }
  1935.                             if(!$this->SendAPIRequest($url, $method, array(), $oauth, $options, $response))
  1936.                                 return false;
  1937.                             if(strlen($this->access_token_error))
  1938.                             {
  1939.                                 $this->authorization_error = $this->access_token_error;
  1940.                                 return true;
  1941.                             }
  1942.                             if(!IsSet($response['oauth_token'])
  1943.                             || !IsSet($response['oauth_token_secret']))
  1944.                             {
  1945.                                 $this->authorization_error= 'it was not returned the access token and secret';
  1946.                                 return true;
  1947.                             }
  1948.                             $access_token = array(
  1949.                                 'value'=>$response['oauth_token'],
  1950.                                 'secret'=>$response['oauth_token_secret'],
  1951.                                 'authorized'=>true
  1952.                             );
  1953.                             if(IsSet($response['oauth_expires_in'])
  1954.                             && $response['oauth_expires_in'] == 0)
  1955.                             {
  1956.                                 if($this->debug)
  1957.                                     $this->OutputDebug('Ignoring access token expiry set to 0');
  1958.                                 $this->access_token_expiry = '';
  1959.                             }
  1960.                             elseif(IsSet($response['oauth_expires_in']))
  1961.                             {
  1962.                                 $expires = $response['oauth_expires_in'];
  1963.                                 if(strval($expires) !== strval(intval($expires))
  1964.                                 || $expires <= 0)
  1965.                                     return($this->SetError('OAuth server did not return a supported type of access token expiry time'));
  1966.                                 $this->access_token_expiry = gmstrftime('%Y-%m-%d %H:%M:%S', time() + $expires);
  1967.                                 if($this->debug)
  1968.                                     $this->OutputDebug('Access token expiry: '.$this->access_token_expiry.' UTC');
  1969.                                 $access_token['expiry'] = $this->access_token_expiry;
  1970.                             }
  1971.                             else
  1972.                                 $this->access_token_expiry = '';
  1973.  
  1974.                             if(!$this->StoreAccessToken($access_token))
  1975.                                 return false;
  1976.                             if($this->debug)
  1977.                                 $this->OutputDebug('The OAuth token was authorized');
  1978.                         }
  1979.                     }
  1980.                     elseif($this->debug)
  1981.                         $this->OutputDebug('The OAuth token was already authorized');
  1982.                     if(IsSet($access_token['authorized'])
  1983.                     && $access_token['authorized'])
  1984.                     {
  1985.                         $this->access_token = $access_token['value'];
  1986.                         $this->access_token_secret = $access_token['secret'];
  1987.                         return true;
  1988.                     }
  1989.                 }
  1990.                 else
  1991.                 {
  1992.                     if($this->debug)
  1993.                         $this->OutputDebug('The OAuth access token is not set');
  1994.                     $access_token = array();
  1995.                 }
  1996.                 if(!IsSet($access_token['authorized']))
  1997.                 {
  1998.                     if($this->debug)
  1999.                         $this->OutputDebug('Requesting the unauthorized OAuth token');
  2000.                     if(!$this->GetRequestTokenURL($url))
  2001.                         return false;
  2002.                     $url = str_replace('{SCOPE}', UrlEncode($this->scope), $url);
  2003.                     if(!$this->GetRedirectURI($redirect_uri))
  2004.                         return false;
  2005.                     $oauth = array(
  2006.                         'oauth_callback'=>$redirect_uri,
  2007.                     );
  2008.                     $options = array(
  2009.                         'Resource'=>'OAuth request token',
  2010.                         'FailOnAccessError'=>true
  2011.                     );
  2012.                     $method = strtoupper($this->token_request_method);
  2013.                     switch($method)
  2014.                     {
  2015.                         case 'GET':
  2016.                             break;
  2017.                         case 'POST':
  2018.                             $options['PostValuesInURI'] = true;
  2019.                             break;
  2020.                         default:
  2021.                             $this->error = $method.' is not a supported method to request tokens';
  2022.                             break;
  2023.                     }
  2024.                     if(!$this->SendAPIRequest($url, $method, array(), $oauth, $options, $response))
  2025.                         return false;
  2026.                     if(strlen($this->access_token_error))
  2027.                     {
  2028.                         $this->authorization_error = $this->access_token_error;
  2029.                         return true;
  2030.                     }
  2031.                     if(!IsSet($response['oauth_token'])
  2032.                     || !IsSet($response['oauth_token_secret']))
  2033.                     {
  2034.                         $this->authorization_error = 'it was not returned the requested token';
  2035.                         return true;
  2036.                     }
  2037.                     $access_token = array(
  2038.                         'value'=>$response['oauth_token'],
  2039.                         'secret'=>$response['oauth_token_secret'],
  2040.                         'authorized'=>false
  2041.                     );
  2042.                     if(!$this->StoreAccessToken($access_token))
  2043.                         return false;
  2044.                 }
  2045.                 if(!$this->GetDialogURL($url))
  2046.                     return false;
  2047.                 $url .= (strpos($url, '?') === false ? '?' : '&').'oauth_token='.$access_token['value'];
  2048.                 if(!$one_a)
  2049.                 {
  2050.                     if(!$this->GetRedirectURI($redirect_uri))
  2051.                         return false;
  2052.                     $url .= '&oauth_callback='.UrlEncode($redirect_uri);
  2053.                 }
  2054.                 if($this->debug)
  2055.                     $this->OutputDebug('Redirecting to OAuth authorize page '.$url);
  2056.                 Header('HTTP/1.0 302 OAuth Redirection');
  2057.                 Header('Location: '.$url);
  2058.                 $this->exit = true;
  2059.                 return true;
  2060.  
  2061.             case 2:
  2062.                 if($this->debug)
  2063.                     $this->OutputDebug('Checking if OAuth access token was already retrieved from '.$this->access_token_url);
  2064.                 if(!$this->RetrieveToken($valid))
  2065.                     return false;
  2066.                 if($valid)
  2067.                     return true;
  2068.                 if($this->debug)
  2069.                     $this->OutputDebug('Checking the authentication state in URI '.$_SERVER['REQUEST_URI']);
  2070.                 if(!$this->GetStoredState($stored_state))
  2071.                     return false;
  2072.                 if(strlen($stored_state) == 0)
  2073.                     return($this->SetError('it was not set the OAuth state'));
  2074.                 if(!$this->GetRequestState($state))
  2075.                     return false;
  2076.                 if($state === $stored_state)
  2077.                 {
  2078.                     if($this->debug)
  2079.                         $this->OutputDebug('Checking the authentication code');
  2080.                     if(!$this->GetRequestCode($code))
  2081.                         return false;
  2082.                     if(strlen($code) == 0)
  2083.                     {
  2084.                         if(!$this->GetRequestError($this->authorization_error))
  2085.                             return false;
  2086.                         if(IsSet($this->authorization_error))
  2087.                         {
  2088.                             if($this->debug)
  2089.                                 $this->OutputDebug('Authorization failed with error code '.$this->authorization_error);
  2090.                             switch($this->authorization_error)
  2091.                             {
  2092.                                 case 'invalid_request':
  2093.                                 case 'unauthorized_client':
  2094.                                 case 'access_denied':
  2095.                                 case 'unsupported_response_type':
  2096.                                 case 'invalid_scope':
  2097.                                 case 'server_error':
  2098.                                 case 'temporarily_unavailable':
  2099.                                 case 'user_denied':
  2100.                                     return true;
  2101.                                 default:
  2102.                                     return($this->SetError('it was returned an unknown OAuth error code'));
  2103.                             }
  2104.                         }
  2105.                         return($this->SetError('it was not returned the OAuth dialog code'));
  2106.                     }
  2107.                     if(!$this->ProcessToken($code, false))
  2108.                         return false;
  2109.                 }
  2110.                 else
  2111.                 {
  2112.                     if(!$this->GetRedirectURI($redirect_uri))
  2113.                         return false;
  2114.                     if(strlen($this->append_state_to_redirect_uri))
  2115.                         $redirect_uri .= (strpos($redirect_uri, '?') === false ? '?' : '&').$this->append_state_to_redirect_uri.'='.$stored_state;
  2116.                     if(!$this->GetDialogURL($url, $redirect_uri, $stored_state))
  2117.                         return false;
  2118.                     if(strlen($url) == 0)
  2119.                         return($this->SetError('it was not set the OAuth dialog URL'));
  2120.                     if($this->debug)
  2121.                         $this->OutputDebug('Redirecting to OAuth Dialog '.$url);
  2122.                     Header('HTTP/1.0 302 OAuth Redirection');
  2123.                     Header('Location: '.$url);
  2124.                     $this->exit = true;
  2125.                 }
  2126.                 break;
  2127.  
  2128.             default:
  2129.                 return($this->SetError($this->oauth_version.' is not a supported version of the OAuth protocol'));
  2130.         }
  2131.         return(true);
  2132.     }
  2133. /*
  2134. {metadocument}
  2135.         </do>
  2136.     </function>
  2137. {/metadocument}
  2138. */
  2139.  
  2140. /*
  2141. {metadocument}
  2142.     <function>
  2143.         <name>Finalize</name>
  2144.         <type>BOOLEAN</type>
  2145.         <documentation>
  2146.             <purpose>Cleanup any resources that may have been used during the
  2147.                 OAuth protocol processing or execution of API calls.</purpose>
  2148.             <usage>Always call this function as the last step after calling the
  2149.                 functions <functionlink>Process</functionlink> or
  2150.                 <functionlink>CallAPI</functionlink>.</usage>
  2151.             <returnvalue>This function returns <booleanvalue>1</booleanvalue> if
  2152.                 the function cleaned up any resources successfully.</returnvalue>
  2153.         </documentation>
  2154.         <argument>
  2155.             <name>success</name>
  2156.             <type>BOOLEAN</type>
  2157.             <documentation>
  2158.                 <purpose>Pass the last success state returned by the class or any
  2159.                     external code processing the class function results.</purpose>
  2160.             </documentation>
  2161.         </argument>
  2162.         <do>
  2163. {/metadocument}
  2164. */
  2165.     Function Finalize($success)
  2166.     {
  2167.         return($success);
  2168.     }
  2169. /*
  2170. {metadocument}
  2171.         </do>
  2172.     </function>
  2173. {/metadocument}
  2174. */
  2175.  
  2176. /*
  2177. {metadocument}
  2178.     <function>
  2179.         <name>Output</name>
  2180.         <type>VOID</type>
  2181.         <documentation>
  2182.             <purpose>Display the results of the OAuth protocol processing.</purpose>
  2183.             <usage>Only call this function if you are debugging the OAuth
  2184.                 authorization process and you need to view what was its
  2185.                 results.</usage>
  2186.         </documentation>
  2187.         <do>
  2188. {/metadocument}
  2189. */
  2190.     Function Output()
  2191.     {
  2192.         if(strlen($this->authorization_error)
  2193.         || strlen($this->access_token_error)
  2194.         || strlen($this->access_token))
  2195.         {
  2196. ?>
  2197. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2198. <html>
  2199. <head>
  2200. <title>OAuth client result</title>
  2201. </head>
  2202. <body>
  2203. <h1>OAuth client result</h1>
  2204. <?php
  2205.             if(strlen($this->authorization_error))
  2206.             {
  2207. ?>
  2208. <p>It was not possible to authorize the application.<?php
  2209.                 if($this->debug)
  2210.                 {
  2211. ?>
  2212. <br>Authorization error: <?php echo HtmlSpecialChars($this->authorization_error);
  2213.                 }
  2214. ?></p>
  2215. <?php
  2216.             }
  2217.             elseif(strlen($this->access_token_error))
  2218.             {
  2219. ?>
  2220. <p>It was not possible to use the application access token.
  2221. <?php
  2222.                 if($this->debug)
  2223.                 {
  2224. ?>
  2225. <br>Error: <?php echo HtmlSpecialChars($this->access_token_error);
  2226.                 }
  2227. ?></p>
  2228. <?php
  2229.             }
  2230.             elseif(strlen($this->access_token))
  2231.             {
  2232. ?>
  2233. <p>The application authorization was obtained successfully.
  2234. <?php
  2235.                 if($this->debug)
  2236.                 {
  2237. ?>
  2238. <br>Access token: <?php echo HtmlSpecialChars($this->access_token);
  2239.                     if(IsSet($this->access_token_secret))
  2240.                     {
  2241. ?>
  2242. <br>Access token secret: <?php echo HtmlSpecialChars($this->access_token_secret);
  2243.                     }
  2244.                 }
  2245. ?></p>
  2246. <?php
  2247.                 if(strlen($this->access_token_expiry))
  2248.                 {
  2249. ?>
  2250. <p>Access token expiry: <?php echo $this->access_token_expiry; ?> UTC</p>
  2251. <?php
  2252.                 }
  2253.             }
  2254. ?>
  2255. </body>
  2256. </html>
  2257. <?php
  2258.         }
  2259.     }
  2260. /*
  2261. {metadocument}
  2262.         </do>
  2263.     </function>
  2264. {/metadocument}
  2265. */
  2266.  
  2267. };
  2268.  
  2269. /*
  2270.  
  2271. {metadocument}
  2272. </class>
  2273. {/metadocument}
  2274.  
  2275. */
  2276.  
  2277. ?>
Add Comment
Please, Sign In to add comment