]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/BitlyUrl/BitlyUrlPlugin.php
Merge branch 'master' into nightly
[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://api.bit.ly/v3/shorten?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             // TRANS: Exception thrown when bit.ly URL shortening plugin was configured incorrectly.
47             throw new Exception(_m('You must specify a serviceUrl for bit.ly URL shortening.'));
48         }
49     }
50
51     /**
52      * Add bit.ly to the list of available URL shorteners if it's configured,
53      * otherwise leave it out.
54      *
55      * @param array $shorteners
56      * @return boolean hook return value
57      */
58     function onGetUrlShorteners(&$shorteners)
59     {
60         if ($this->getLogin() && $this->getApiKey()) {
61             return parent::onGetUrlShorteners($shorteners);
62         }
63         return true;
64     }
65
66     /**
67      * Short a URL
68      * @param url
69      * @return string shortened version of the url, or null if URL shortening failed
70      */
71     protected function shorten($url) {
72         common_log(LOG_INFO, "bit.ly call for $url");
73         $response = $this->query($url);
74         common_log(LOG_INFO, "bit.ly answer for $url is ".$response->getBody());
75         return $this->decode($url, $response);
76     }
77
78     /**
79      * Get the user's or site-wide default bit.ly login name.
80      *
81      * @return string
82      */
83     protected function getLogin()
84     {
85         $login = common_config('bitly', 'default_login');
86         if (!$login) {
87             $login = $this->login;
88         }
89         return $login;
90     }
91
92     /**
93      * Get the user's or site-wide default bit.ly API key.
94      *
95      * @return string
96      */
97     protected function getApiKey()
98     {
99         $key = common_config('bitly', 'default_apikey');
100         if (!$key) {
101             $key = $this->apiKey;
102         }
103         return $key;
104     }
105
106     /**
107      * Inject API key into query before sending out...
108      *
109      * @param string $url
110      * @return HTTPResponse
111      */
112     protected function query($url)
113     {
114         $params = http_build_query(array(
115             'login' => $this->getLogin(),
116             'apiKey' => $this->getApiKey()), '', '&');
117         $serviceUrl = sprintf($this->serviceUrl, urlencode($url)) . '&' . $params;
118
119         $request = HTTPClient::start();
120         return $request->get($serviceUrl);
121     }
122
123     /**
124      * JSON decode for API result
125      */
126     protected function decode($url, $response)
127     {
128         $msg = "bit.ly returned unknown response with unknown message for $url";
129         if ($response->isOk()) {
130             $body = $response->getBody();
131             common_log(LOG_INFO, $body);
132             $json = json_decode($body, true);
133             if ($json['status_code'] == 200) {
134                 if (isset($json['data']['url'])) {
135                                         common_log(LOG_INFO, "bit.ly returned ".$json['data']['url']." as short URL for $url");
136                     return $json['data']['url'];
137                 }
138                                 $msg = "bit.ly returned ".$json['status_code']." response, but didn't find expected URL $url in $body";
139                         }else{
140                                 $msg = "bit.ly returned ".$json['status_code']." response with ".$json['status_txt']." for $url";
141                         }
142                 }
143                 common_log(LOG_ERR, $msg);
144                 return null;
145     }
146
147     function onPluginVersion(array &$versions)
148     {
149         $versions[] = array('name' => sprintf('BitlyUrl (%s)', $this->shortenerName),
150                             'version' => GNUSOCIAL_VERSION,
151                             'author' => 'Craig Andrews, Brion Vibber',
152                             'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/BitlyUrl',
153                             'rawdescription' =>
154                             // TRANS: Plugin description. %1$s is the URL shortening service base URL (for example "bit.ly").
155                             sprintf(_m('Uses <a href="http://%1$s/">%1$s</a> URL-shortener service.'),
156                                     $this->shortenerName));
157
158         return true;
159     }
160
161     /**
162      * Hook for RouterInitialized event.
163      *
164      * @param URLMapper $m path-to-action mapper
165      * @return boolean hook return
166      */
167     public function onRouterInitialized(URLMapper $m)
168     {
169         $m->connect('panel/bitly',
170                     array('action' => 'bitlyadminpanel'));
171         return true;
172     }
173
174     /**
175      * If the plugin's installed, this should be accessible to admins.
176      */
177     function onAdminPanelCheck($name, &$isOK)
178     {
179         if ($name == 'bitly') {
180             $isOK = true;
181             return false;
182         }
183
184         return true;
185     }
186
187     /**
188      * Add the bit.ly admin panel to the list...
189      */
190     function onEndAdminPanelNav($nav)
191     {
192         if (AdminPanelAction::canAdmin('bitly')) {
193             $action_name = $nav->action->trimmed('action');
194
195             $nav->out->menuItem(common_local_url('bitlyadminpanel'),
196                                 // TRANS: Menu item in administration menus for bit.ly URL shortening settings.
197                                 _m('bit.ly'),
198                                 // TRANS: Title for menu item in administration menus for bit.ly URL shortening settings.
199                                 _m('bit.ly URL shortening.'),
200                                 $action_name == 'bitlyadminpanel',
201                                 'nav_bitly_admin_panel');
202         }
203
204         return true;
205     }
206
207     /**
208      * Internal hook point to check the default global credentials so
209      * the admin form knows if we have a fallback or not.
210      *
211      * @param string $login
212      * @param string $apiKey
213      * @return boolean hook return value
214      */
215     function onBitlyDefaultCredentials(&$login, &$apiKey)
216     {
217         $login = $this->login;
218         $apiKey = $this->apiKey;
219         return false;
220     }
221
222 }