PageRenderTime 32ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/3.1/modules/bitly/helpers/bitly.php

https://github.com/wrlee/gallery3-contrib
PHP | 217 lines | 149 code | 16 blank | 52 comment | 23 complexity | b13292cf81f723209ef6a21287ea3c71 MD5 | raw file
  1. <?php defined("SYSPATH") or die("No direct script access.");
  2. /**
  3. * Gallery - a web based photo album viewer and editor
  4. * Copyright (C) 2000-2011 Bharat Mediratta
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or (at
  9. * your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful, but
  12. * WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. class bitly_Core {
  21. public static $test_mode = TEST_MODE;
  22. public static $api_host = "api.bit.ly";
  23. public static $api_version = "v3";
  24. public static $api_methods = array(
  25. 'expand' => 'expand',
  26. 'shorten' => 'shorten',
  27. 'validate' => 'validate',
  28. 'clicks' => 'clicks',
  29. 'referrers' => 'referrers',
  30. 'countries' => 'countries',
  31. 'clicks_by_minute' => 'clicks_by_minute',
  32. 'clicks_by_day' => 'clicks_by_day',
  33. 'lookup' => 'lookup',
  34. 'info' => 'info',
  35. );
  36. static function get_configure_form() {
  37. $form = new Forge("admin/bitly", "", "post", array("id" => "g-configure-bitly-form"));
  38. $group = $form->group("configure_bitly")->label(t("Configure bit.ly"));
  39. $group->input("login")
  40. ->label(t("Login"))
  41. ->value(module::get_var("bitly", "login"))
  42. ->rules("required")
  43. ->error_messages("required", t("You must enter a login"));
  44. $group->input("api_key")
  45. ->label(t("API Key"))
  46. ->value(module::get_var("bitly", "api_key"))
  47. ->rules("required")
  48. ->error_messages("required", t("You must enter an API key"));
  49. $group->dropdown("domain")
  50. ->label(t("Preferred Domain"))
  51. ->options(array("bit.ly" => "bit.ly", "j.mp" => "j.mp"))
  52. ->selected(module::get_var("bitly", "domain"));
  53. $group->submit("")->value(t("Save"));
  54. return $form;
  55. }
  56. /**
  57. * Check a login and an API Key against bit.ly to make sure they're valid
  58. * @param string $login bit.ly login
  59. * @param string $api_key bit.ly API key
  60. * @return boolean
  61. */
  62. static function validate_config($login, $api_key) {
  63. if (!empty($login) && !empty($api_key)) {
  64. $parameters = array(
  65. 'login' => $login,
  66. 'apiKey' => $api_key,
  67. 'x_login' => $login,
  68. 'x_apiKey' => $api_key
  69. );
  70. $request = self::_build_http_request('validate', $parameters);
  71. $response = self::_http_post($request, "api.bit.ly");
  72. $json_decoded = json_decode($response->body[0]);
  73. if (!$json_decoded->data->valid) {
  74. if ("INVALID_LOGIN" == $json_decoded->status_txt) {
  75. message::error(t("Your bit.ly login is incorrect"));
  76. } else if ("INVALID_APIKEY" == $json_decoded->status_txt) {
  77. message::error(t("Your bit.ly API Key is incorrect."));
  78. }
  79. return false;
  80. } else {
  81. return true;
  82. }
  83. }
  84. }
  85. /**
  86. * Check whether the module's configured correctly
  87. * @return boolean
  88. */
  89. static function check_config() {
  90. $login = module::get_var("bitly", "login");
  91. $api_key = module::get_var("bitly", "api_key");
  92. if (empty($login) || empty($api_key)) {
  93. site_status::warning(
  94. t("bit.ly is not quite ready! Please provide a <a href=\"%url\">login and API Key</a>",
  95. array("url" => html::mark_clean(url::site("admin/bitly")))),
  96. "bitly_config");
  97. } else if (!self::validate_config($login, $api_key)) {
  98. site_status::warning(
  99. t("bit.ly is not properly configured! URLs will not be shortened until its <a href=\"%url\">configuration</a> is updated.",
  100. array("url" => html::mark_clean(url::site("admin/bitly")))),
  101. "bitly_config");
  102. } else {
  103. site_status::clear("bitly_config");
  104. return true;
  105. }
  106. return false;
  107. }
  108. /**
  109. * Assemble a bitly API request
  110. * @param string $type Type of API request, ex. shorten
  111. * @param array $params Query string key/value pairs
  112. * @return string
  113. */
  114. private static function _build_http_request($type, $params) {
  115. $http_request = '';
  116. if (!empty($type) && count($params)) {
  117. foreach($params as $k => $v) {
  118. $query_string[] = "$k=" . urlencode($v);
  119. }
  120. $path = "/" . self::$api_version . "/$type?" . implode('&', $query_string);
  121. $module_version = module::get_version("bitly");
  122. $http_request = "GET $path HTTP/1.0\r\n";
  123. $http_request .= "Host: " . self::$api_host . "\r\n";
  124. $http_request .= "User-Agent: Gallery/3 | bitly/" . module::get_version("bitly") . "\r\n";
  125. $http_request .= "\r\n";
  126. $http_request .= $path;
  127. }
  128. return $http_request;
  129. }
  130. /**
  131. * Send an http POST request
  132. * @param string $http_request
  133. * @param string $host
  134. * @return object
  135. */
  136. private static function _http_post($http_request) {
  137. $response = '';
  138. if (false !== ($fs = @fsockopen(self::$api_host, 80, $errno, $errstr, 5))) {
  139. fwrite($fs, $http_request);
  140. while ( !feof($fs) ) {
  141. $response .= fgets($fs, 1160); // One TCP-IP packet
  142. }
  143. fclose($fs);
  144. list($headers, $body) = explode("\r\n\r\n", $response);
  145. $headers = explode("\r\n", $headers);
  146. $body = explode("\r\n", $body);
  147. $response = new ArrayObject(
  148. array("headers" => $headers, "body" => $body), ArrayObject::ARRAY_AS_PROPS);
  149. } else {
  150. throw new Exception("@todo CONNECTION TO URL SHORTENING SERVICE FAILED");
  151. }
  152. Kohana_Log::add("debug", "Received response\n" . print_r($response, 1));
  153. return $response;
  154. }
  155. /**
  156. * Shorten a Gallery URL
  157. * @param int $item_id
  158. * @param string $format
  159. * @return mixed string|false
  160. */
  161. static function shorten_url($item_id, $format='json') {
  162. $item = ORM::factory("item", $item_id);
  163. $short_url = '';
  164. $long_url = url::abs_site($item->relative_url_cache);
  165. $parameters = array(
  166. "login" => module::get_var("bitly", "login"),
  167. 'apiKey' => module::get_var("bitly", "api_key"),
  168. 'longUrl' => $long_url,
  169. 'domain' => module::get_var("bitly", "domain"),
  170. 'format' => $format,
  171. );
  172. $request = self::_build_http_request('shorten', $parameters);
  173. $response = self::_http_post($request, self::$api_host);
  174. $json_response = json_decode($response->body[0]);
  175. $status_txt = $json_response->status_txt;
  176. if ('OK' == $status_txt) {
  177. $short_url = $json_response->data->url;
  178. // Save the link hash to the database
  179. $link = ORM::factory("bitly_link");
  180. $link->item_id = $item_id;
  181. $link->hash = $json_response->data->hash;
  182. $link->global_hash = $json_response->data->global_hash;
  183. $link->save();
  184. return $json_response->data->url;
  185. } else {
  186. $status_code = $json_response->status_code;
  187. log::error("content", "Shortened URL", "Error: $status_code $status_txt <a href=\"{$long_url}\">item</a>");
  188. return false;
  189. }
  190. }
  191. /**
  192. * Build a bit.ly link for a specified hash
  193. * @param string $hash
  194. * @return string
  195. */
  196. static function url($hash) {
  197. if (!empty($hash)) {
  198. return "http://" . module::get_var("bitly", "domain") . "/$hash";
  199. }
  200. }
  201. }