]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/BitlyUrl/BitlyUrlPlugin.php
Merge branch '0.9.x' into 1.0.x
[quix0rs-gnu-social.git] / plugins / BitlyUrl / BitlyUrlPlugin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Plugin to use bit.ly URL shortening services.
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Plugin
23  * @package   StatusNet
24  * @author    Craig Andrews <candrews@integralblue.com>
25  * @author    Brion Vibber <brion@status.net>
26  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
27  * @copyright 2010 StatusNet, Inc http://status.net/
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29  * @link      http://status.net/
30  */
31
32 if (!defined('STATUSNET')) {
33     exit(1);
34 }
35
36 class BitlyUrlPlugin extends UrlShortenerPlugin
37 {
38     public $shortenerName = 'bit.ly';
39     public $serviceUrl = 'http://bit.ly/api?method=shorten&version=2.0.1&longUrl=%s';
40     public $login; // To set a site-default when admins or users don't override it.
41     public $apiKey;
42
43     function onInitializePlugin(){
44         parent::onInitializePlugin();
45         if(!isset($this->serviceUrl)){
46             throw new Exception(_m("You must specify a serviceUrl for bit.ly shortening."));
47         }
48     }
49
50     /**
51      * Add bit.ly to the list of available URL shorteners if it's configured,
52      * otherwise leave it out.
53      *
54      * @param array $shorteners
55      * @return boolean hook return value
56      */
57     function onGetUrlShorteners(&$shorteners)
58     {
59         if ($this->getLogin() && $this->getApiKey()) {
60             return parent::onGetUrlShorteners($shorteners);
61         }
62         return true;
63     }
64
65     /**
66      * Short a URL
67      * @param url
68      * @return string shortened version of the url, or null if URL shortening failed
69      */
70     protected function shorten($url) {
71         $response = $this->query($url);
72         if ($this->isOk($url, $response)) {
73             return $this->decode($url, $response->getBody());
74         } else {
75             return null;
76         }
77     }
78
79     /**
80      * Get the user's or site-wide default bit.ly login name.
81      *
82      * @return string
83      */
84     protected function getLogin()
85     {
86         $login = common_config('bitly', 'default_login');
87         if (!$login) {
88             $login = $this->login;
89         }
90         return $login;
91     }
92
93     /**
94      * Get the user's or site-wide default bit.ly API key.
95      *
96      * @return string
97      */
98     protected function getApiKey()
99     {
100         $key = common_config('bitly', 'default_apikey');
101         if (!$key) {
102             $key = $this->apiKey;
103         }
104         return $key;
105     }
106
107     /**
108      * Inject API key into query before sending out...
109      *
110      * @param string $url
111      * @return HTTPResponse
112      */
113     protected function query($url)
114     {
115         // http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/shorten
116         $params = http_build_query(array(
117             'login' => $this->getLogin(),
118             'apiKey' => $this->getApiKey()), '', '&');
119         $serviceUrl = sprintf($this->serviceUrl, urlencode($url)) . '&' . $params;
120
121         $request = HTTPClient::start();
122         return $request->get($serviceUrl);
123     }
124
125     /**
126      * JSON decode for API result
127      */
128     protected function decode($url, $body)
129     {
130         $json = json_decode($body, true);
131         return $json['results'][$url]['shortUrl'];
132     }
133
134     /**
135      * JSON decode for API result
136      */
137     protected function isOk($url, $response)
138     {
139         $code = 'unknown';
140         $msg = '';
141         if ($response->isOk()) {
142             $body = $response->getBody();
143             common_log(LOG_INFO, $body);
144             $json = json_decode($body, true);
145             if ($json['statusCode'] == 'OK') {
146                 if (!isset($json['results'][$url])) {
147                     common_log(LOG_ERR, "bit.ly returned OK response, but didn't find expected URL $url in $body");
148                     return false;
149                 }
150                 $data = $json['results'][$url];
151                 if (isset($data['shortUrl'])) {
152                     return true;
153                 } else if (isset($data['statusCode']) && $data['statusCode'] == 'ERROR') {
154                     $code = $data['errorCode'];
155                     $msg = $data['errorMessage'];
156                 }
157             } else if ($json['statusCode'] == 'ERROR') {
158                 $code = $json['errorCode'];
159                 $msg = $json['errorMessage'];
160             }
161             common_log(LOG_ERR, "bit.ly returned error $code $msg for $url");
162         }
163         return false;
164     }
165
166     function onPluginVersion(&$versions)
167     {
168         $versions[] = array('name' => sprintf('BitlyUrl (%s)', $this->shortenerName),
169                             'version' => STATUSNET_VERSION,
170                             'author' => 'Craig Andrews, Brion Vibber',
171                             'homepage' => 'http://status.net/wiki/Plugin:BitlyUrl',
172                             'rawdescription' =>
173                             sprintf(_m('Uses <a href="http://%1$s/">%1$s</a> URL-shortener service.'),
174                                     $this->shortenerName));
175
176         return true;
177     }
178
179     /**
180      * Hook for RouterInitialized event.
181      *
182      * @param Net_URL_Mapper $m path-to-action mapper
183      * @return boolean hook return
184      */
185     function onRouterInitialized($m)
186     {
187         $m->connect('admin/bitly',
188                     array('action' => 'bitlyadminpanel'));
189         return true;
190     }
191
192     /**
193      * If the plugin's installed, this should be accessible to admins.
194      */
195     function onAdminPanelCheck($name, &$isOK)
196     {
197         if ($name == 'bitly') {
198             $isOK = true;
199             return false;
200         }
201
202         return true;
203     }
204
205     /**
206      * Add the bit.ly admin panel to the list...
207      */
208     function onEndAdminPanelNav($nav)
209     {
210         if (AdminPanelAction::canAdmin('bitly')) {
211             $action_name = $nav->action->trimmed('action');
212
213             $nav->out->menuItem(common_local_url('bitlyadminpanel'),
214                                 _m('bit.ly'),
215                                 _m('bit.ly URL shortening'),
216                                 $action_name == 'bitlyadminpanel',
217                                 'nav_bitly_admin_panel');
218         }
219
220         return true;
221     }
222
223     /**
224      * Automatically load the actions and libraries used by the plugin
225      *
226      * @param Class $cls the class
227      *
228      * @return boolean hook return
229      *
230      */
231     function onAutoload($cls)
232     {
233         $base = dirname(__FILE__);
234         $lower = strtolower($cls);
235         switch ($lower) {
236         case 'bitlyadminpanelaction':
237             require_once "$base/$lower.php";
238             return false;
239         default:
240             return true;
241         }
242     }
243
244     /**
245      * Internal hook point to check the default global credentials so
246      * the admin form knows if we have a fallback or not.
247      *
248      * @param string $login
249      * @param string $apiKey
250      * @return boolean hook return value
251      */
252     function onBitlyDefaultCredentials(&$login, &$apiKey)
253     {
254         $login = $this->login;
255         $apiKey = $this->apiKey;
256         return false;
257     }
258
259 }