]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/BitlyUrl/BitlyUrlPlugin.php
Merge remote branch 'gitorious/0.9.x' into 0.9.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 require_once INSTALLDIR.'/plugins/UrlShortener/UrlShortenerPlugin.php';
37
38 class BitlyUrlPlugin extends UrlShortenerPlugin
39 {
40     public $shortenerName = 'bit.ly';
41     public $serviceUrl = 'http://bit.ly/api?method=shorten&version=2.0.1&longUrl=%s';
42     public $login; // To set a site-default when admins or users don't override it.
43     public $apiKey;
44
45     function onInitializePlugin(){
46         parent::onInitializePlugin();
47         if(!isset($this->serviceUrl)){
48             throw new Exception(_m("You must specify a serviceUrl for bit.ly shortening."));
49         }
50     }
51
52     /**
53      * Add bit.ly to the list of available URL shorteners if it's configured,
54      * otherwise leave it out.
55      *
56      * @param array $shorteners
57      * @return boolean hook return value
58      */
59     function onGetUrlShorteners(&$shorteners)
60     {
61         if ($this->getLogin() && $this->getApiKey()) {
62             return parent::onGetUrlShorteners($shorteners);
63         }
64         return true;
65     }
66
67     /**
68      * Short a URL
69      * @param url
70      * @return string shortened version of the url, or null if URL shortening failed
71      */
72     protected function shorten($url) {
73         $response = $this->query($url);
74         if ($this->isOk($url, $response)) {
75             return $this->decode($url, $response->getBody());
76         } else {
77             return null;
78         }
79     }
80
81     /**
82      * Get the user's or site-wide default bit.ly login name.
83      *
84      * @return string
85      */
86     protected function getLogin()
87     {
88         $login = common_config('bitly', 'default_login');
89         if (!$login) {
90             $login = $this->login;
91         }
92         return $login;
93     }
94
95     /**
96      * Get the user's or site-wide default bit.ly API key.
97      *
98      * @return string
99      */
100     protected function getApiKey()
101     {
102         $key = common_config('bitly', 'default_apikey');
103         if (!$key) {
104             $key = $this->apiKey;
105         }
106         return $key;
107     }
108
109     /**
110      * Inject API key into query before sending out...
111      *
112      * @param string $url
113      * @return HTTPResponse
114      */
115     protected function query($url)
116     {
117         // http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/shorten
118         $params = http_build_query(array(
119             'login' => $this->getLogin(),
120             'apiKey' => $this->getApiKey()), '', '&');
121         $serviceUrl = sprintf($this->serviceUrl, $url) . '&' . $params;
122
123         $request = HTTPClient::start();
124         return $request->get($serviceUrl);
125     }
126
127     /**
128      * JSON decode for API result
129      */
130     protected function decode($url, $body)
131     {
132         $json = json_decode($body, true);
133         return $json['results'][$url]['shortUrl'];
134     }
135
136     /**
137      * JSON decode for API result
138      */
139     protected function isOk($url, $response)
140     {
141         $code = 'unknown';
142         $msg = '';
143         if ($response->isOk()) {
144             $body = $response->getBody();
145             common_log(LOG_INFO, $body);
146             $json = json_decode($body, true);
147             if ($json['statusCode'] == 'OK') {
148                 $data = $json['results'][$url];
149                 if (isset($data['shortUrl'])) {
150                     return true;
151                 } else if (isset($data['statusCode']) && $data['statusCode'] == 'ERROR') {
152                     $code = $data['errorCode'];
153                     $msg = $data['errorMessage'];
154                 }
155             } else if ($json['statusCode'] == 'ERROR') {
156                 $code = $json['errorCode'];
157                 $msg = $json['errorMessage'];
158             }
159             common_log(LOG_ERR, "bit.ly returned error $code $msg for $url");
160         }
161         return false;
162     }
163
164     function onPluginVersion(&$versions)
165     {
166         $versions[] = array('name' => sprintf('BitlyUrl (%s)', $this->shortenerName),
167                             'version' => STATUSNET_VERSION,
168                             'author' => 'Craig Andrews, Brion Vibber',
169                             'homepage' => 'http://status.net/wiki/Plugin:BitlyUrl',
170                             'rawdescription' =>
171                             sprintf(_m('Uses <a href="http://%1$s/">%1$s</a> URL-shortener service.'),
172                                     $this->shortenerName));
173
174         return true;
175     }
176
177     /**
178      * Hook for RouterInitialized event.
179      *
180      * @param Net_URL_Mapper $m path-to-action mapper
181      * @return boolean hook return
182      */
183     function onRouterInitialized($m)
184     {
185         $m->connect('admin/bitly',
186                     array('action' => 'bitlyadminpanel'));
187         return true;
188     }
189
190     /**
191      * If the plugin's installed, this should be accessible to admins.
192      */
193     function onAdminPanelCheck($name, &$isOK)
194     {
195         if ($name == 'bitly') {
196             $isOK = true;
197             return false;
198         }
199
200         return true;
201     }
202
203     /**
204      * Add the bit.ly admin panel to the list...
205      */
206     function onEndAdminPanelNav($nav)
207     {
208         if (AdminPanelAction::canAdmin('bitly')) {
209             $action_name = $nav->action->trimmed('action');
210
211             $nav->out->menuItem(common_local_url('bitlyadminpanel'),
212                                 _m('bit.ly'),
213                                 _m('bit.ly URL shortening'),
214                                 $action_name == 'bitlyadminpanel',
215                                 'nav_bitly_admin_panel');
216         }
217
218         return true;
219     }
220
221     /**
222      * Automatically load the actions and libraries used by the plugin
223      *
224      * @param Class $cls the class
225      *
226      * @return boolean hook return
227      *
228      */
229     function onAutoload($cls)
230     {
231         $base = dirname(__FILE__);
232         $lower = strtolower($cls);
233         switch ($lower) {
234         case 'bitlyadminpanelaction':
235             require_once "$base/$lower.php";
236             return false;
237         default:
238             return true;
239         }
240     }
241
242     /**
243      * Internal hook point to check the default global credentials so
244      * the admin form knows if we have a fallback or not.
245      *
246      * @param string $login
247      * @param string $apiKey
248      * @return boolean hook return value
249      */
250     function onBitlyDefaultCredentials(&$login, &$apiKey)
251     {
252         $login = $this->login;
253         $apiKey = $this->apiKey;
254         return false;
255     }
256
257 }