PageRenderTime 35ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/source/ws/TextMarksV2APIClient.php

http://sharebooks.googlecode.com/
PHP | 284 lines | 116 code | 41 blank | 127 comment | 14 complexity | 27db8d1a6fa6d1ce2d734aacd557eb93 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * TextMarks V2 API Client Library (PHP). v2.60d.
  4. * ---------------------------------------------------------------------------
  5. *
  6. * TextMarks provides a text-messaging platform you can integrate into
  7. * your own applications to send and receive text messages to individual
  8. * users or groups of users.
  9. *
  10. * For full online documentation, visit:
  11. * http://www.textmarks.com/dev/docs/api2/
  12. * http://www.textmarks.com/dev/
  13. * http://www.textmarks.com/
  14. *
  15. * The HTTP API that this library integrates with is NOT REQUIRED.
  16. * You can do all kinds of wonderful things without this API and without
  17. * writing any code at all. However if you wish to automate and integrate
  18. * TextMarks more deeply into your applications, this API may be useful.
  19. *
  20. * This optional PHP client library provides one way to integrate with
  21. * the platform's HTTP API from your PHP applications.
  22. *
  23. * This library requires:
  24. * - PHP 5.1 or greater.
  25. * - libCURL (normally included with PHP).
  26. *
  27. * ---------------------------------------------------------------------------
  28. * @author Dan Kamins [d k a m i n s A.T t e x t m a r k s D.O.T c o m]
  29. * @package tmAPIClient
  30. * ---------------------------------------------------------------------------
  31. * Copyright (c) 2009, TextMarks Inc. All rights reserved.
  32. * ---------------------------------------------------------------------------
  33. *
  34. * THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
  35. * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
  36. * LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
  37. * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  38. *
  39. * RECIPIENT IS SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS
  40. * OF USING AND DISTRIBUTING THE PROGRAM AND ASSUMES ALL RISKS ASSOCIATED
  41. * WITH ITS EXERCISE OF RIGHTS UNDER THIS AGREEMENT, INCLUDING BUT NOT
  42. * LIMITED TO THE RISKS AND COSTS OF PROGRAM ERRORS, COMPLIANCE WITH
  43. * APPLICABLE LAWS, DAMAGE TO OR LOSS OF DATA, PROGRAMS OR EQUIPMENT,
  44. * AND UNAVAILABILITY OR INTERRUPTION OF OPERATIONS.
  45. *
  46. * NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR
  47. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  48. * DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND
  49. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  50. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
  51. * DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
  52. * HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  53. */
  54. /** */
  55. // ---------------------------------------------------------------------------
  56. /*
  57. * For PHP prior to 5.2 (which introduced native JSON support),
  58. * we include a free JSON library and bind it to json_decode.
  59. */
  60. if (!function_exists('json_decode')) {
  61. require_once('JSON.php');
  62. function json_decode($json) {
  63. $svc = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
  64. return $svc->decode($json);
  65. }
  66. }
  67. // ---------------------------------------------------------------------------
  68. /**
  69. * Exception subclass used by TextMarksAPIClient.
  70. */
  71. class TextMarksV2APIClientException extends Exception
  72. {
  73. }
  74. /**
  75. * Exception subclass used by TextMarksV2APIClient for transport-level errors.
  76. */
  77. class TextMarksV2APIClientTransportException extends TextMarksV2APIClientException
  78. {
  79. }
  80. // ---------------------------------------------------------------------------
  81. /**
  82. * TextMarksV2APIClient - construct and call().
  83. */
  84. class TextMarksV2APIClient
  85. {
  86. public $db_sms = null;
  87. public $error_code = '';
  88. public $error_code_info = '';
  89. // Public constants:
  90. const HTTP_GET = 'GET';
  91. const HTTP_POST = 'POST';
  92. // -----------------------------------------------------------------------
  93. // Configuration:
  94. const API_URL_BASE = 'http://php1.api2.textmarks.com';
  95. // -----------------------------------------------------------------------
  96. /**
  97. * Create TextMarksV2APIClient around indicated authentication info (optional).
  98. *
  99. * @param string $sApiKey API Key ( register at http://www.textmarks.com/dev/api/reg/ ). (NULL for none).
  100. * @param string $sAuthUser Phone# or TextMarks username to authenticate to API with. (NULL for none).
  101. * @param string $sAuthPass TextMarks Password associated with sAuthUser. (NULL for none).
  102. */
  103. public function TextMarksV2APIClient( $sApiKey = NULL, $sAuthUser = NULL, $sAuthPass = NULL )
  104. {
  105. $this->m_sApiKey = $sApiKey;
  106. $this->m_sAuthUser = $sAuthUser;
  107. $this->m_sAuthPass = $sAuthPass;
  108. }
  109. // Initialize database connections
  110. function connectDB()
  111. {
  112. // x. Create a connection to the front database
  113. if (!$this->db_sms = @mysql_connect(SMS_SERVER, SMS_USER, SMS_PASSWORD, true))
  114. {
  115. // Logging
  116. writeLog(ERROR_CODE_INFO. ": Couldn't connect to database");
  117. return false;
  118. }
  119. if (!@mysql_select_db(SMS_DATABASE, $this->db_sms)) {
  120. // Logging
  121. writeLog(ERROR_CODE_INFO. ": Couldn't connect to database");
  122. return false;
  123. }
  124. mysql_query("SET NAMES 'utf8'", $this->db_sms);
  125. return true;
  126. }
  127. function closeConnections(){
  128. mysql_close($this->db_sms);
  129. }
  130. function outputXML ($code,$description,$result=''){
  131. $description = htmlspecialchars($description,ENT_NOQUOTES,"UTF-8");
  132. $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
  133. $xml .= "<result>\n";
  134. $xml .= "<status>\n";
  135. $xml .= "<code>$code</code>\n";
  136. $xml .= "<description>".htmlspecialchars($description,ENT_NOQUOTES,"UTF-8")."</description>\n";
  137. $xml .= "</status>\n";
  138. $xml .= $result;
  139. $xml .= "</result>";
  140. return $xml;
  141. }
  142. /**
  143. * Public method to call API.
  144. *
  145. * The API Key and auth params are automatically added if present.
  146. *
  147. * @param string $sPackageName Package name.
  148. * @param string $sMethodName Method name.
  149. * @param map(string,string) $mssParams Params for method.
  150. * @param string $sHttpMethod 'GET' or 'POST'.
  151. * @return Decoded (from JSON) response.
  152. * @throws Exception on error.
  153. */
  154. public function call( $sPackageName, $sMethodName, $mssParams, $sHttpMethod = self::HTTP_POST )
  155. {
  156. return $this->_callJsonApiMethod($sPackageName, $sMethodName, $mssParams, $sHttpMethod);
  157. }
  158. // -----------------------------------------------------------------------
  159. /**
  160. * Execute HTTP request (post params to API endpoint) and return string response.
  161. *
  162. * @param string $sUrl URL to request (method endpoint).
  163. * @param map(string,string) $mssParams Request params.
  164. * @param string $sHttpMethod 'GET' or 'POST'.
  165. * @return string Response (usually JSON string).
  166. * @throws TextMarksV2APIClientTransportException on error.
  167. */
  168. protected function _rawHttpCall( $sUrl, $mssParams, $sHttpMethod = self::HTTP_POST )
  169. {
  170. // Convert param map to encoded form (to post):
  171. $sPostData = "";
  172. foreach ($mssParams as $sK => $sV) {
  173. $sPostData .= "&" . urlencode($sK) . "=" . urlencode($sV);
  174. }
  175. // Prep curl:
  176. $ch = curl_init();
  177. $arsHeaders = array();
  178. if ($sHttpMethod == 'POST') {
  179. curl_setopt($ch, CURLOPT_POST, 1);
  180. curl_setopt($ch, CURLOPT_URL, $sUrl);
  181. $arsHeaders[] = "Content-Type: application/x-www-form-urlencoded";
  182. curl_setopt($ch, CURLOPT_POSTFIELDS, $sPostData);
  183. } else {
  184. curl_setopt($ch, CURLOPT_HTTPGET, 1);
  185. curl_setopt($ch, CURLOPT_URL, $sUrl . "?" . $sPostData);
  186. }
  187. curl_setopt($ch, CURLOPT_HTTPHEADER, $arsHeaders);
  188. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // (response as string, not output)
  189. // Make request (synchronous):
  190. $sResponse = curl_exec($ch);
  191. // Check for transport-level errors:
  192. $iCurlErrNo = curl_errno($ch);
  193. $iHttpRespCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  194. if ($iCurlErrNo != 0) {
  195. curl_close($ch);
  196. throw new TextMarksV2APIClientTransportException("TextMarksV2APIClient ($sUrl) saw CURL error #$iCurlErrNo: " . curl_error($ch), curl_error($ch));
  197. }
  198. if ($iHttpRespCode != 200) {
  199. curl_close($ch);
  200. throw new TextMarksV2APIClientTransportException("TextMarksV2APIClient ($sUrl) saw non-200 HTTP response #$iHttpRespCode.", -1);
  201. }
  202. // No obvious transport-level errors. Return response:
  203. return $sResponse;
  204. }
  205. /**
  206. * Execute API call and return decoded JSON response.
  207. *
  208. * The API Key and auth params are automatically added.
  209. *
  210. * @param string $sPackageName Package name.
  211. * @param string $sMethodName Method name.
  212. * @param map(string,string) $mssParams Params for method.
  213. * @param string $sHttpMethod 'GET' or 'POST'.
  214. * @return Decoded (from JSON) response.
  215. * @throws Exception on error.
  216. */
  217. protected function _callJsonApiMethod( $sPackageName, $sMethodName, $mssParams, $sHttpMethod = self::HTTP_POST )
  218. {
  219. // Prep:
  220. $mssParamsFull = $mssParams; // (copy array to keep original clean)
  221. if ($this->m_sApiKey !== NULL) { $mssParamsFull['api_key'] = $this->m_sApiKey; }
  222. if ($this->m_sAuthUser !== NULL) { $mssParamsFull['auth_user'] = $this->m_sAuthUser; }
  223. if ($this->m_sAuthPass !== NULL) { $mssParamsFull['auth_pass'] = $this->m_sAuthPass; }
  224. $sUrl = self::API_URL_BASE . '/' . $sPackageName . '/' . $sMethodName . '/';
  225. // Make actual HTTP call:
  226. $sResp = $this->_rawHttpCall( $sUrl, $mssParamsFull, $sHttpMethod );
  227. // Parse JSON response:
  228. $oDecoded = json_decode($sResp, TRUE);
  229. // Check API response code:
  230. $iResCode = (int) $oDecoded['head']['rescode'];
  231. $sResMsg = $oDecoded['head']['resmsg'];
  232. if ($iResCode != 0) {
  233. throw new TextMarksV2APIClientException("TextMarksV2APIClient.call($sPackageName.$sMethodName) got API error #$iResCode: $sResMsg", $iResCode);
  234. }
  235. return $oDecoded;
  236. }
  237. // -----------------------------------------------------------------------
  238. protected $m_sApiKey;
  239. protected $m_sAuthUser;
  240. protected $m_sAuthPass;
  241. }
  242. ?>