+ $response = $this->query($url);
+ if ($this->isOk($url, $response)) {
+ return $this->decode($url, $response->getBody());
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Get the user's or site-wide default bit.ly login name.
+ *
+ * @return string
+ */
+ protected function getLogin()
+ {
+ $login = common_config('bitly', 'default_login');
+ if (!$login) {
+ $login = $this->login;
+ }
+ return $login;
+ }
+
+ /**
+ * Get the user's or site-wide default bit.ly API key.
+ *
+ * @return string
+ */
+ protected function getApiKey()
+ {
+ $key = common_config('bitly', 'default_apikey');
+ if (!$key) {
+ $key = $this->apiKey;
+ }
+ return $key;
+ }
+
+ /**
+ * Inject API key into query before sending out...
+ *
+ * @param string $url
+ * @return HTTPResponse
+ */
+ protected function query($url)
+ {
+ // http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/shorten
+ $params = http_build_query(array(
+ 'login' => $this->getLogin(),
+ 'apiKey' => $this->getApiKey()), '', '&');
+ $serviceUrl = sprintf($this->serviceUrl, $url) . '&' . $params;
+
+ $request = HTTPClient::start();
+ return $request->get($serviceUrl);
+ }
+
+ /**
+ * JSON decode for API result
+ */
+ protected function decode($url, $body)
+ {
+ $json = json_decode($body, true);
+ return $json['results'][$url]['shortUrl'];
+ }
+
+ /**
+ * JSON decode for API result
+ */
+ protected function isOk($url, $response)
+ {
+ $code = 'unknown';
+ $msg = '';
+ if ($response->isOk()) {
+ $body = $response->getBody();
+ common_log(LOG_INFO, $body);
+ $json = json_decode($body, true);
+ if ($json['statusCode'] == 'OK') {
+ $data = $json['results'][$url];
+ if (isset($data['shortUrl'])) {
+ return true;
+ } else if (isset($data['statusCode']) && $data['statusCode'] == 'ERROR') {
+ $code = $data['errorCode'];
+ $msg = $data['errorMessage'];
+ }
+ } else if ($json['statusCode'] == 'ERROR') {
+ $code = $json['errorCode'];
+ $msg = $json['errorMessage'];
+ }
+ common_log(LOG_ERR, "bit.ly returned error $code $msg for $url");
+ }
+ return false;