]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/BitlyUrl/BitlyUrlPlugin.php
Fix BitlyUrl plugin.
[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://api.bit.ly/v3/shorten?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         common_log(LOG_INFO, "bit.ly call for $url");
74         $response = $this->query($url);
75         common_log(LOG_INFO, "bit.ly answer for $url is ".$response->getBody());
76         return $this->decode($url, $response);
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, $response)
129     {
130         $msg = "bit.ly returned unknown response with unknown message for $url";
131         if ($response->isOk()) {
132             $body = $response->getBody();
133             common_log(LOG_INFO, $body);
134             $json = json_decode($body, true);
135             if ($json['status_code'] == 200) {
136                 if (isset($json['data']['url'])) {
137                                         common_log(LOG_INFO, "bit.ly returned ".$json['data']['url']." as short URL for $url");
138                     return $json['data']['url'];
139                 }
140                                 $msg = "bit.ly returned ".$json['status_code']." response, but didn't find expected URL $url in $body";
141                         }else{
142                                 $msg = "bit.ly returned ".$json['status_code']." response with ".$json['status_txt']." for $url";
143                         }
144                 }
145                 common_log(LOG_ERR, $msg);
146                 return null;
147     }
148
149     function onPluginVersion(&$versions)
150     {
151         $versions[] = array('name' => sprintf('BitlyUrl (%s)', $this->shortenerName),
152                             'version' => STATUSNET_VERSION,
153                             'author' => 'Craig Andrews, Brion Vibber',
154                             'homepage' => 'http://status.net/wiki/Plugin:BitlyUrl',
155                             'rawdescription' =>
156                             sprintf(_m('Uses <a href="http://%1$s/">%1$s</a> URL-shortener service.'),
157                                     $this->shortenerName));
158
159         return true;
160     }
161
162     /**
163      * Hook for RouterInitialized event.
164      *
165      * @param Net_URL_Mapper $m path-to-action mapper
166      * @return boolean hook return
167      */
168     function onRouterInitialized($m)
169     {
170         $m->connect('admin/bitly',
171                     array('action' => 'bitlyadminpanel'));
172         return true;
173     }
174
175     /**
176      * If the plugin's installed, this should be accessible to admins.
177      */
178     function onAdminPanelCheck($name, &$isOK)
179     {
180         if ($name == 'bitly') {
181             $isOK = true;
182             return false;
183         }
184
185         return true;
186     }
187
188     /**
189      * Add the bit.ly admin panel to the list...
190      */
191     function onEndAdminPanelNav($nav)
192     {
193         if (AdminPanelAction::canAdmin('bitly')) {
194             $action_name = $nav->action->trimmed('action');
195
196             $nav->out->menuItem(common_local_url('bitlyadminpanel'),
197                                 _m('bit.ly'),
198                                 _m('bit.ly URL shortening'),
199                                 $action_name == 'bitlyadminpanel',
200                                 'nav_bitly_admin_panel');
201         }
202
203         return true;
204     }
205
206     /**
207      * Automatically load the actions and libraries used by the plugin
208      *
209      * @param Class $cls the class
210      *
211      * @return boolean hook return
212      *
213      */
214     function onAutoload($cls)
215     {
216         $base = dirname(__FILE__);
217         $lower = strtolower($cls);
218         switch ($lower) {
219         case 'bitlyadminpanelaction':
220             require_once "$base/$lower.php";
221             return false;
222         default:
223             return true;
224         }
225     }
226
227     /**
228      * Internal hook point to check the default global credentials so
229      * the admin form knows if we have a fallback or not.
230      *
231      * @param string $login
232      * @param string $apiKey
233      * @return boolean hook return value
234      */
235     function onBitlyDefaultCredentials(&$login, &$apiKey)
236     {
237         $login = $this->login;
238         $apiKey = $this->apiKey;
239         return false;
240     }
241
242 }