]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/BitlyUrl/BitlyUrlPlugin.php
bit.ly admin panel to set the API keys to use.
[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
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      * Short a URL
52      * @param url
53      * @return string shortened version of the url, or null if URL shortening failed
54      */
55     protected function shorten($url) {
56         $response = $this->query($url);
57         if ($this->isOk($url, $response)) {
58             return $this->decode($url, $response->getBody());
59         } else {
60             return null;
61         }
62     }
63
64     /**
65      * Get the user's or site-wide default bit.ly login name.
66      *
67      * @return string
68      */
69     protected function getLogin()
70     {
71         return common_config('bitly', 'default_login');
72     }
73
74     /**
75      * Get the user's or site-wide default bit.ly API key.
76      *
77      * @return string
78      */
79     protected function getApiKey()
80     {
81         return common_config('bitly', 'default_apikey');
82     }
83
84     /**
85      * Inject API key into query before sending out...
86      *
87      * @param string $url
88      * @return HTTPResponse
89      */
90     protected function query($url)
91     {
92         // http://code.google.com/p/bitly-api/wiki/ApiDocumentation#/shorten
93         $params = http_build_query(array(
94             'login' => $this->getLogin(),
95             'apiKey' => $this->getApiKey()), '', '&');
96         $serviceUrl = sprintf($this->serviceUrl, $url) . '&' . $params;
97
98         $request = HTTPClient::start();
99         return $request->get($serviceUrl);
100     }
101
102     /**
103      * JSON decode for API result
104      */
105     protected function decode($url, $body)
106     {
107         $json = json_decode($body, true);
108         return $json['results'][$url]['shortUrl'];
109     }
110
111     /**
112      * JSON decode for API result
113      */
114     protected function isOk($url, $response)
115     {
116         $code = 'unknown';
117         $msg = '';
118         if ($response->isOk()) {
119             $body = $response->getBody();
120             common_log(LOG_INFO, $body);
121             $json = json_decode($body, true);
122             if ($json['statusCode'] == 'OK') {
123                 $data = $json['results'][$url];
124                 if (isset($data['shortUrl'])) {
125                     return true;
126                 } else if (isset($data['statusCode']) && $data['statusCode'] == 'ERROR') {
127                     $code = $data['errorCode'];
128                     $msg = $data['errorMessage'];
129                 }
130             } else if ($json['statusCode'] == 'ERROR') {
131                 $code = $json['errorCode'];
132                 $msg = $json['errorMessage'];
133             }
134             common_log(LOG_ERR, "bit.ly returned error $code $msg for $url");
135         }
136         return false;
137     }
138
139     function onPluginVersion(&$versions)
140     {
141         $versions[] = array('name' => sprintf('BitlyUrl (%s)', $this->shortenerName),
142                             'version' => STATUSNET_VERSION,
143                             'author' => 'Craig Andrews, Brion Vibber',
144                             'homepage' => 'http://status.net/wiki/Plugin:BitlyUrl',
145                             'rawdescription' =>
146                             sprintf(_m('Uses <a href="http://%1$s/">%1$s</a> URL-shortener service.'),
147                                     $this->shortenerName));
148
149         return true;
150     }
151
152     /**
153      * Hook for RouterInitialized event.
154      *
155      * @param Net_URL_Mapper $m path-to-action mapper
156      * @return boolean hook return
157      */
158     function onRouterInitialized($m)
159     {
160         $m->connect('admin/bitly',
161                     array('action' => 'bitlyadminpanel'));
162         return true;
163     }
164
165     /**
166      * If the plugin's installed, this should be accessible to admins.
167      */
168     function onAdminPanelCheck($name, &$isOK)
169     {
170         if ($name == 'bitly') {
171             $isOK = true;
172             return false;
173         }
174
175         return true;
176     }
177
178     /**
179      * Add the bit.ly admin panel to the list...
180      */
181     function onEndAdminPanelNav($nav)
182     {
183         if (AdminPanelAction::canAdmin('bitly')) {
184             $action_name = $nav->action->trimmed('action');
185
186             $nav->out->menuItem(common_local_url('bitlyadminpanel'),
187                                 _m('bit.ly'),
188                                 _m('bit.ly URL shortening'),
189                                 $action_name == 'bitlyadminpanel',
190                                 'nav_bitly_admin_panel');
191         }
192
193         return true;
194     }
195
196     /**
197      * Automatically load the actions and libraries used by the plugin
198      *
199      * @param Class $cls the class
200      *
201      * @return boolean hook return
202      *
203      */
204     function onAutoload($cls)
205     {
206         $base = dirname(__FILE__);
207         $lower = strtolower($cls);
208         switch ($lower) {
209         case 'bitlyadminpanelaction':
210             require_once "$base/$lower.php";
211             return false;
212         default:
213             return true;
214         }
215     }
216 }