PageRenderTime 28ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/sample/oauth/functions.php

http://github.com/evernote/evernote-sdk-php
PHP | 274 lines | 174 code | 27 blank | 73 comment | 32 complexity | 91f3b8fab476e9ca18aa04a8d2398776 MD5 | raw file
Possible License(s): BSD-3-Clause-No-Nuclear-License-2014
  1. <?php
  2. /*
  3. * Copyright 2011-2012 Evernote Corporation.
  4. *
  5. * This file contains functions used by Evernote's PHP OAuth samples.
  6. */
  7. // Include the Evernote API from the lib subdirectory.
  8. // lib simply contains the contents of /php/lib from the Evernote API SDK
  9. define("EVERNOTE_LIBS", dirname(__FILE__) . DIRECTORY_SEPARATOR . "lib");
  10. ini_set("include_path", ini_get("include_path") . PATH_SEPARATOR . EVERNOTE_LIBS);
  11. require_once 'Evernote/Client.php';
  12. require_once 'packages/Types/Types_types.php';
  13. // Import the classes that we're going to be using
  14. use EDAM\Error\EDAMSystemException,
  15. EDAM\Error\EDAMUserException,
  16. EDAM\Error\EDAMErrorCode,
  17. EDAM\Error\EDAMNotFoundException;
  18. use Evernote\Client;
  19. // Verify that you successfully installed the PHP OAuth Extension
  20. if (!class_exists('OAuth')) {
  21. die("<span style=\"color:red\">The PHP OAuth Extension is not installed</span>");
  22. }
  23. // Verify that you have configured your API key
  24. if (strlen(OAUTH_CONSUMER_KEY) == 0 || strlen(OAUTH_CONSUMER_SECRET) == 0) {
  25. $configFile = dirname(__FILE__) . '/config.php';
  26. die("<span style=\"color:red\">Before using this sample code you must edit the file $configFile " .
  27. "and fill in OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET with the values that you received from Evernote. " .
  28. "If you do not have an API key, you can request one from " .
  29. "<a href=\"http://dev.evernote.com/documentation/cloud/\">http://dev.evernote.com/documentation/cloud/</a></span>");
  30. }
  31. /*
  32. * The first step of OAuth authentication: the client (this application)
  33. * obtains temporary credentials from the server (Evernote).
  34. *
  35. * After successfully completing this step, the client has obtained the
  36. * temporary credentials identifier, an opaque string that is only meaningful
  37. * to the server, and the temporary credentials secret, which is used in
  38. * signing the token credentials request in step 3.
  39. *
  40. * This step is defined in RFC 5849 section 2.1:
  41. * http://tools.ietf.org/html/rfc5849#section-2.1
  42. *
  43. * @return boolean TRUE on success, FALSE on failure
  44. */
  45. function getTemporaryCredentials()
  46. {
  47. global $lastError, $currentStatus;
  48. try {
  49. $client = new Client(array(
  50. 'consumerKey' => OAUTH_CONSUMER_KEY,
  51. 'consumerSecret' => OAUTH_CONSUMER_SECRET,
  52. 'sandbox' => SANDBOX
  53. ));
  54. $requestTokenInfo = $client->getRequestToken(getCallbackUrl());
  55. if ($requestTokenInfo) {
  56. $_SESSION['requestToken'] = $requestTokenInfo['oauth_token'];
  57. $_SESSION['requestTokenSecret'] = $requestTokenInfo['oauth_token_secret'];
  58. $currentStatus = 'Obtained temporary credentials';
  59. return TRUE;
  60. } else {
  61. $lastError = 'Failed to obtain temporary credentials.';
  62. }
  63. } catch (OAuthException $e) {
  64. $lastError = 'Error obtaining temporary credentials: ' . $e->getMessage();
  65. }
  66. return FALSE;
  67. }
  68. /*
  69. * The completion of the second step in OAuth authentication: the resource owner
  70. * authorizes access to their account and the server (Evernote) redirects them
  71. * back to the client (this application).
  72. *
  73. * After successfully completing this step, the client has obtained the
  74. * verification code that is passed to the server in step 3.
  75. *
  76. * This step is defined in RFC 5849 section 2.2:
  77. * http://tools.ietf.org/html/rfc5849#section-2.2
  78. *
  79. * @return boolean TRUE if the user authorized access, FALSE if they declined access.
  80. */
  81. function handleCallback()
  82. {
  83. global $lastError, $currentStatus;
  84. if (isset($_GET['oauth_verifier'])) {
  85. $_SESSION['oauthVerifier'] = $_GET['oauth_verifier'];
  86. $currentStatus = 'Content owner authorized the temporary credentials';
  87. return TRUE;
  88. } else {
  89. // If the User clicks "decline" instead of "authorize", no verification code is sent
  90. $lastError = 'Content owner did not authorize the temporary credentials';
  91. return FALSE;
  92. }
  93. }
  94. /*
  95. * The third and final step in OAuth authentication: the client (this application)
  96. * exchanges the authorized temporary credentials for token credentials.
  97. *
  98. * After successfully completing this step, the client has obtained the
  99. * token credentials that are used to authenticate to the Evernote API.
  100. * In this sample application, we simply store these credentials in the user's
  101. * session. A real application would typically persist them.
  102. *
  103. * This step is defined in RFC 5849 section 2.3:
  104. * http://tools.ietf.org/html/rfc5849#section-2.3
  105. *
  106. * @return boolean TRUE on success, FALSE on failure
  107. */
  108. function getTokenCredentials()
  109. {
  110. global $lastError, $currentStatus;
  111. if (isset($_SESSION['accessToken'])) {
  112. $lastError = 'Temporary credentials may only be exchanged for token credentials once';
  113. return FALSE;
  114. }
  115. try {
  116. $client = new Client(array(
  117. 'consumerKey' => OAUTH_CONSUMER_KEY,
  118. 'consumerSecret' => OAUTH_CONSUMER_SECRET,
  119. 'sandbox' => SANDBOX
  120. ));
  121. $accessTokenInfo = $client->getAccessToken($_SESSION['requestToken'], $_SESSION['requestTokenSecret'], $_SESSION['oauthVerifier']);
  122. if ($accessTokenInfo) {
  123. $_SESSION['accessToken'] = $accessTokenInfo['oauth_token'];
  124. $currentStatus = 'Exchanged the authorized temporary credentials for token credentials';
  125. return TRUE;
  126. } else {
  127. $lastError = 'Failed to obtain token credentials.';
  128. }
  129. } catch (OAuthException $e) {
  130. $lastError = 'Error obtaining token credentials: ' . $e->getMessage();
  131. }
  132. return FALSE;
  133. }
  134. /*
  135. * Demonstrate the use of token credentials obtained via OAuth by listing the notebooks
  136. * in the resource owner's Evernote account using the Evernote API. Returns an array
  137. * of String notebook names.
  138. *
  139. * Once you have obtained the token credentials identifier via OAuth, you can use it
  140. * as the auth token in any call to an Evernote API function.
  141. *
  142. * @return boolean TRUE on success, FALSE on failure
  143. */
  144. function listNotebooks()
  145. {
  146. global $lastError, $currentStatus;
  147. try {
  148. $accessToken = $_SESSION['accessToken'];
  149. $client = new Client(array(
  150. 'token' => $accessToken,
  151. 'sandbox' => SANDBOX
  152. ));
  153. $notebooks = $client->getNoteStore()->listNotebooks();
  154. $result = array();
  155. if (!empty($notebooks)) {
  156. foreach ($notebooks as $notebook) {
  157. $result[] = $notebook->name;
  158. }
  159. }
  160. $_SESSION['notebooks'] = $result;
  161. $currentStatus = 'Successfully listed content owner\'s notebooks';
  162. return TRUE;
  163. } catch (EDAMSystemException $e) {
  164. if (isset(EDAMErrorCode::$__names[$e->errorCode])) {
  165. $lastError = 'Error listing notebooks: ' . EDAMErrorCode::$__names[$e->errorCode] . ": " . $e->parameter;
  166. } else {
  167. $lastError = 'Error listing notebooks: ' . $e->getCode() . ": " . $e->getMessage();
  168. }
  169. } catch (EDAMUserException $e) {
  170. if (isset(EDAMErrorCode::$__names[$e->errorCode])) {
  171. $lastError = 'Error listing notebooks: ' . EDAMErrorCode::$__names[$e->errorCode] . ": " . $e->parameter;
  172. } else {
  173. $lastError = 'Error listing notebooks: ' . $e->getCode() . ": " . $e->getMessage();
  174. }
  175. } catch (EDAMNotFoundException $e) {
  176. if (isset(EDAMErrorCode::$__names[$e->errorCode])) {
  177. $lastError = 'Error listing notebooks: ' . EDAMErrorCode::$__names[$e->errorCode] . ": " . $e->parameter;
  178. } else {
  179. $lastError = 'Error listing notebooks: ' . $e->getCode() . ": " . $e->getMessage();
  180. }
  181. } catch (Exception $e) {
  182. $lastError = 'Error listing notebooks: ' . $e->getMessage();
  183. }
  184. return FALSE;
  185. }
  186. /*
  187. * Reset the current session.
  188. */
  189. function resetSession()
  190. {
  191. if (isset($_SESSION['requestToken'])) {
  192. unset($_SESSION['requestToken']);
  193. }
  194. if (isset($_SESSION['requestTokenSecret'])) {
  195. unset($_SESSION['requestTokenSecret']);
  196. }
  197. if (isset($_SESSION['oauthVerifier'])) {
  198. unset($_SESSION['oauthVerifier']);
  199. }
  200. if (isset($_SESSION['accessToken'])) {
  201. unset($_SESSION['accessToken']);
  202. }
  203. if (isset($_SESSION['accessTokenSecret'])) {
  204. unset($_SESSION['accessTokenSecret']);
  205. }
  206. if (isset($_SESSION['noteStoreUrl'])) {
  207. unset($_SESSION['noteStoreUrl']);
  208. }
  209. if (isset($_SESSION['webApiUrlPrefix'])) {
  210. unset($_SESSION['webApiUrlPrefix']);
  211. }
  212. if (isset($_SESSION['tokenExpires'])) {
  213. unset($_SESSION['tokenExpires']);
  214. }
  215. if (isset($_SESSION['userId'])) {
  216. unset($_SESSION['userId']);
  217. }
  218. if (isset($_SESSION['notebooks'])) {
  219. unset($_SESSION['notebooks']);
  220. }
  221. }
  222. /*
  223. * Get the URL of this application. This URL is passed to the server (Evernote)
  224. * while obtaining unauthorized temporary credentials (step 1). The resource owner
  225. * is redirected to this URL after authorizing the temporary credentials (step 2).
  226. */
  227. function getCallbackUrl()
  228. {
  229. $thisUrl = (empty($_SERVER['HTTPS'])) ? "http://" : "https://";
  230. $thisUrl .= $_SERVER['SERVER_NAME'];
  231. $thisUrl .= ($_SERVER['SERVER_PORT'] == 80 || $_SERVER['SERVER_PORT'] == 443) ? "" : (":".$_SERVER['SERVER_PORT']);
  232. $thisUrl .= $_SERVER['SCRIPT_NAME'];
  233. $thisUrl .= '?action=callback';
  234. return $thisUrl;
  235. }
  236. /*
  237. * Get the Evernote server URL used to authorize unauthorized temporary credentials.
  238. */
  239. function getAuthorizationUrl()
  240. {
  241. $client = new Client(array(
  242. 'consumerKey' => OAUTH_CONSUMER_KEY,
  243. 'consumerSecret' => OAUTH_CONSUMER_SECRET,
  244. 'sandbox' => SANDBOX
  245. ));
  246. return $client->getAuthorizeUrl($_SESSION['requestToken']);
  247. }