3 * Name: StatusNet Connector
4 * Description: Relay public postings to a connected StatusNet account
6 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions are met:
14 * * Redistributions of source code must retain the above copyright notice,
15 * this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above
17 * * copyright notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the distribution.
19 * * Neither the name of the <organization> nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
27 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
31 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
32 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
39 * installation abroad. Basically it's only make the API path variable and be happy.
41 * Thank you guys for the Twitter compatible API!
44 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
46 require_once('library/twitteroauth.php');
48 class StatusNetOAuth extends TwitterOAuth {
49 function get_maxlength() {
50 $config = $this->get($this->host . 'statusnet/config.json');
51 return $config->site->textlimit;
53 function accessTokenURL() { return $this->host.'oauth/access_token'; }
54 function authenticateURL() { return $this->host.'oauth/authenticate'; }
55 function authorizeURL() { return $this->host.'oauth/authorize'; }
56 function requestTokenURL() { return $this->host.'oauth/request_token'; }
57 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
58 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
59 $this->host = $apipath;
62 * Make an HTTP request
66 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
68 function http($url, $method, $postfields = NULL) {
69 $this->http_info = array();
72 $prx = get_config('system','proxy');
74 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
75 curl_setopt($ci, CURLOPT_PROXY, $prx);
76 $prxusr = get_config('system','proxyuser');
78 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
80 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
81 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
82 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
83 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
84 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
85 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
86 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
87 curl_setopt($ci, CURLOPT_HEADER, FALSE);
91 curl_setopt($ci, CURLOPT_POST, TRUE);
92 if (!empty($postfields)) {
93 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
97 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
98 if (!empty($postfields)) {
99 $url = "{$url}?{$postfields}";
103 curl_setopt($ci, CURLOPT_URL, $url);
104 $response = curl_exec($ci);
105 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
106 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
113 function statusnet_install() {
114 // we need some hooks, for the configuration and for sending tweets
115 register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
116 register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
117 register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
118 register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
119 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
120 register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
121 register_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
122 logger("installed statusnet");
126 function statusnet_uninstall() {
127 unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
128 unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
129 unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
130 unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
131 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
132 unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
133 unregister_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
135 // old setting - remove only
136 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
137 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
138 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
142 function statusnet_jot_nets(&$a,&$b) {
146 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
147 if(intval($statusnet_post) == 1) {
148 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
149 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
150 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
151 . t('Post to StatusNet') . '</div>';
155 function statusnet_settings_post ($a,$post) {
158 // don't check statusnet settings if statusnet submit button is not clicked
159 if (!x($_POST,'statusnet-submit'))
162 if (isset($_POST['statusnet-disconnect'])) {
164 * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
166 del_pconfig(local_user(), 'statusnet', 'consumerkey');
167 del_pconfig(local_user(), 'statusnet', 'consumersecret');
168 del_pconfig(local_user(), 'statusnet', 'post');
169 del_pconfig(local_user(), 'statusnet', 'post_by_default');
170 del_pconfig(local_user(), 'statusnet', 'oauthtoken');
171 del_pconfig(local_user(), 'statusnet', 'oauthsecret');
172 del_pconfig(local_user(), 'statusnet', 'baseapi');
173 del_pconfig(local_user(), 'statusnet', 'lastid');
174 del_pconfig(local_user(), 'statusnet', 'mirror_posts');
175 del_pconfig(local_user(), 'statusnet', 'import');
176 del_pconfig(local_user(), 'statusnet', 'create_user');
177 del_pconfig(local_user(), 'statusnet', 'own_id');
179 if (isset($_POST['statusnet-preconf-apiurl'])) {
181 * If the user used one of the preconfigured StatusNet server credentials
182 * use them. All the data are available in the global config.
183 * Check the API Url never the less and blame the admin if it's not working ^^
185 $globalsn = get_config('statusnet', 'sites');
186 foreach ( $globalsn as $asn) {
187 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
188 $apibase = $asn['apiurl'];
189 $c = fetch_url( $apibase . 'statusnet/version.xml' );
190 if (strlen($c) > 0) {
191 set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
192 set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
193 set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
194 //set_pconfig(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
196 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
200 goaway($a->get_baseurl().'/settings/connectors');
202 if (isset($_POST['statusnet-consumersecret'])) {
203 // check if we can reach the API of the StatusNet server
204 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
205 // resign quickly after this one try to fix the path ;-)
206 $apibase = $_POST['statusnet-baseapi'];
207 $c = fetch_url( $apibase . 'statusnet/version.xml' );
208 if (strlen($c) > 0) {
209 // ok the API path is correct, let's save the settings
210 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
211 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
212 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
213 //set_pconfig(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
215 // the API path is not correct, maybe missing trailing / ?
216 $apibase = $apibase . '/';
217 $c = fetch_url( $apibase . 'statusnet/version.xml' );
218 if (strlen($c) > 0) {
219 // ok the API path is now correct, let's save the settings
220 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
221 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
222 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
224 // still not the correct API base, let's do noting
225 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
228 goaway($a->get_baseurl().'/settings/connectors');
230 if (isset($_POST['statusnet-pin'])) {
231 // if the user supplied us with a PIN from StatusNet, let the magic of OAuth happen
232 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
233 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
234 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
235 // the token and secret for which the PIN was generated were hidden in the settings
236 // form as token and token2, we need a new connection to StatusNet using these token
237 // and secret to request a Access Token with the PIN
238 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
239 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
240 // ok, now that we have the Access Token, save them in the user config
241 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
242 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
243 set_pconfig(local_user(),'statusnet', 'post', 1);
244 set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
245 // reload the Addon Settings page, if we don't do it see Bug #42
246 goaway($a->get_baseurl().'/settings/connectors');
248 // if no PIN is supplied in the POST variables, the user has changed the setting
249 // to post a dent for every new __public__ posting to the wall
250 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
251 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
252 set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
253 set_pconfig(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
254 set_pconfig(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
256 if (!intval($_POST['statusnet-mirror']))
257 del_pconfig(local_user(),'statusnet','lastid');
259 info( t('StatusNet settings updated.') . EOL);
262 function statusnet_settings(&$a,&$s) {
265 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
267 * 1) Check that we have a base api url and a consumer key & secret
268 * 2) If no OAuthtoken & stuff is present, generate button to get some
269 * allow the user to cancel the connection process at this step
270 * 3) Checkbox for "Send public notices (respect size limitation)
272 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
273 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey');
274 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret');
275 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken');
276 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret');
277 $enabled = get_pconfig(local_user(), 'statusnet', 'post');
278 $checked = (($enabled) ? ' checked="checked" ' : '');
279 $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
280 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
281 $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
282 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
283 $importenabled = get_pconfig(local_user(),'statusnet','import');
284 $importchecked = (($importenabled) ? ' checked="checked" ' : '');
285 $create_userenabled = get_pconfig(local_user(),'statusnet','create_user');
286 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
288 $css = (($enabled) ? '' : '-disabled');
290 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
291 $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('StatusNet Import/Export/Mirror').'</h3>';
293 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
294 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
295 $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('StatusNet Import/Export/Mirror').'</h3>';
298 if ( (!$ckey) && (!$csecret) ) {
302 $globalsn = get_config('statusnet', 'sites');
304 * lets check if we have one or more globally configured StatusNet
305 * server OAuth credentials in the configuration. If so offer them
306 * with a little explanation to the user as choice - otherwise
307 * ignore this option entirely.
309 if (! $globalsn == null) {
310 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
311 $s .= '<p>'. t("There are preconfigured OAuth key pairs for some StatusNet servers available. If you are using one of them, please use these credentials. If not feel free to connect to any other StatusNet instance \x28see below\x29.") .'</p>';
312 $s .= '<div id="statusnet-preconf-wrapper">';
313 foreach ($globalsn as $asn) {
314 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
316 $s .= '<p></p><div class="clear"></div></div>';
317 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
319 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
320 $s .= '<p>'. t('No consumer key pair for StatusNet found. Register your Friendica Account as an desktop client on your StatusNet account, copy the consumer key pair here and enter the API base root.<br />Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendica installation at your favorited StatusNet installation.') .'</p>';
321 $s .= '<div id="statusnet-consumer-wrapper">';
322 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
323 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
324 $s .= '<div class="clear"></div>';
325 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
326 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
327 $s .= '<div class="clear"></div>';
328 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
329 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
330 $s .= '<div class="clear"></div>';
331 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('StatusNet application name').'</label>';
332 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
333 $s .= '<p></p><div class="clear"></div>';
334 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
338 * ok we have a consumer key pair now look into the OAuth stuff
340 if ( (!$otoken) && (!$osecret) ) {
342 * the user has not yet connected the account to statusnet
343 * get a temporary OAuth key/secret pair and display a button with
344 * which the user can request a PIN to connect the account to a
345 * account at statusnet
347 $connection = new StatusNetOAuth($api, $ckey, $csecret);
348 $request_token = $connection->getRequestToken('oob');
349 $token = $request_token['oauth_token'];
351 * make some nice form
353 $s .= '<p>'. t('To connect to your StatusNet account click the button below to get a security code from StatusNet which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to StatusNet.') .'</p>';
354 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
355 $s .= '<div id="statusnet-pin-wrapper">';
356 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
357 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
358 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
359 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
360 $s .= '</div><div class="clear"></div>';
361 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
362 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
363 $s .= '<div id="statusnet-cancel-wrapper">';
364 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
365 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
366 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
367 $s .= '</div><div class="clear"></div>';
368 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
371 * we have an OAuth key / secret pair for the user
372 * so let's give a chance to disable the postings to statusnet
374 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
375 $details = $connection->get('account/verify_credentials');
376 $s .= '<div id="statusnet-info" ><img id="statusnet-avatar" src="'.$details->profile_image_url.'" /><p id="statusnet-info-block">'. t('Currently connected to: ') .'<a href="'.$details->statusnet_profile_url.'" target="_statusnet">'.$details->screen_name.'</a><br /><em>'.$details->description.'</em></p></div>';
377 $s .= '<p>'. t('If enabled all your <strong>public</strong> postings can be posted to the associated StatusNet account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.') .'</p>';
378 if ($a->user['hidewall']) {
379 $s .= '<p>'. t('<strong>Note</strong>: Due your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to StatusNet will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') .'</p>';
381 $s .= '<div id="statusnet-enable-wrapper">';
382 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
383 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
384 $s .= '<div class="clear"></div>';
385 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
386 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
387 $s .= '<div class="clear"></div>';
389 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
390 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
391 $s .= '<div class="clear"></div>';
394 $s .= '<label id="statusnet-import-label" for="statusnet-import">'.t('Import the remote timeline').'</label>';
395 $s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
396 $s .= '<div class="clear"></div>';
398 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.t('Automatically create contacts').'</label>';
399 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
400 $s .= '<div class="clear"></div>';
402 $s .= '<div id="statusnet-disconnect-wrapper">';
403 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
404 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
405 $s .= '</div><div class="clear"></div>';
406 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
409 $s .= '</div><div class="clear"></div>';
413 function statusnet_post_local(&$a,&$b) {
417 if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
419 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
420 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
422 // if API is used, default to the chosen settings
423 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
424 $statusnet_enable = 1;
426 if(! $statusnet_enable)
429 if(strlen($b['postopts']))
430 $b['postopts'] .= ',';
431 $b['postopts'] .= 'statusnet';
435 function statusnet_action($a, $uid, $pid, $action) {
436 $api = get_pconfig($uid, 'statusnet', 'baseapi');
437 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
438 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
439 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
440 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
442 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
444 logger("statusnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
448 $result = $connection->post("statuses/destroy/".$pid);
451 $result = $connection->post("favorites/create/".$pid);
454 $result = $connection->post("favorites/destroy/".$pid);
457 logger("statusnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
460 function statusnet_post_hook(&$a,&$b) {
466 if (!get_pconfig($b["uid"],'statusnet','import')) {
467 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
471 $api = get_pconfig($b["uid"], 'statusnet', 'baseapi');
472 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
474 if($b['parent'] != $b['id']) {
475 logger("statusnet_post_hook: parameter ".print_r($b, true), LOGGER_DATA);
477 // Looking if its a reply to a statusnet post
478 $hostlength = strlen($hostname) + 2;
479 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname."::") AND (substr($b["extid"], 0, $hostlength) != $hostname."::")
480 AND (substr($b["thr-parent"], 0, $hostlength) != $hostname."::")) {
481 logger("statusnet_post_hook: no statusnet post ".$b["parent"]);
485 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
486 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
487 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
488 dbesc($b["thr-parent"]),
492 logger("statusnet_post_hook: no parent found ".$b["thr-parent"]);
499 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
500 //$nicknameplain = "@".$orig_post["contact_nick"];
502 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
504 $nickname = "@[url=".$orig_post["author-link"]."]".$nick."[/url]";
505 $nicknameplain = "@".$nick;
507 logger("statusnet_post_hook: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
508 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
509 $b["body"] = $nickname." ".$b["body"];
511 logger("statusnet_post_hook: parent found ".print_r($orig_post, true), LOGGER_DEBUG);
515 if($b['private'] OR !strstr($b['postopts'],'statusnet'))
519 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
520 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
522 if($b['verb'] == ACTIVITY_LIKE) {
523 logger("statusnet_post_hook: parameter 2 ".substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
525 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
527 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
531 if($b['deleted'] || ($b['created'] !== $b['edited']))
534 // if posts comes from statusnet don't send it back
535 if($b['extid'] == NETWORK_STATUSNET)
538 if($b['app'] == "StatusNet")
541 logger('statusnet post invoked');
543 load_pconfig($b['uid'], 'statusnet');
545 $api = get_pconfig($b['uid'], 'statusnet', 'baseapi');
546 $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
547 $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
548 $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
549 $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
551 if($ckey && $csecret && $otoken && $osecret) {
553 // If it's a repeated message from statusnet then do a native retweet and exit
554 if (statusnet_is_retweet($a, $b['uid'], $b['body']))
557 require_once('include/bbcode.php');
558 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
559 $max_char = $dent->get_maxlength(); // max. length for a dent
561 set_pconfig($b['uid'], 'statusnet', 'max_char', $max_char);
564 require_once("include/plaintext.php");
565 require_once("include/network.php");
566 $msgarr = plaintext($a, $b, $max_char, true, 7);
567 $msg = $msgarr["text"];
569 if (($msg == "") AND isset($msgarr["title"]))
570 $msg = shortenmsg($msgarr["title"], $max_char - 50);
574 if (isset($msgarr["url"])) {
575 if ((strlen($msgarr["url"]) > 20) AND
576 ((strlen($msg." \n".$msgarr["url"]) > $max_char)))
577 $msg .= " \n".short_link($msgarr["url"]);
579 $msg .= " \n".$msgarr["url"];
580 } elseif (isset($msgarr["image"]) AND ($msgarr["type"] != "video"))
581 $image = $msgarr["image"];
584 $img_str = fetch_url($image);
585 $tempfile = tempnam(get_temppath(), "cache");
586 file_put_contents($tempfile, $img_str);
587 $postdata = array("status" => $msg, "media[]" => $tempfile);
589 $postdata = array("status"=>$msg);
591 // and now dent it :-)
595 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
596 logger('statusnet_post send reply '.print_r($postdata, true), LOGGER_DEBUG);
599 // New code that is able to post pictures
600 require_once("addon/statusnet/codebird.php");
601 $cb = \CodebirdSN\CodebirdSN::getInstance();
602 $cb->setAPIEndpoint($api);
603 $cb->setConsumerKey($ckey, $csecret);
604 $cb->setToken($otoken, $osecret);
605 $result = $cb->statuses_update($postdata);
606 //$result = $dent->post('statuses/update', $postdata);
607 logger('statusnet_post send, result: ' . print_r($result, true).
608 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
611 set_pconfig($b["uid"], "statusnet", "application_name", strip_tags($result->source));
613 if ($result->error) {
614 logger('Send to StatusNet failed: "'.$result->error.'"');
615 } elseif ($iscomment) {
616 logger('statusnet_post: Update extid '.$result->id." for post id ".$b['id']);
617 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
618 dbesc($hostname."::".$result->id),
619 dbesc($result->text),
629 function statusnet_plugin_admin_post(&$a){
633 foreach($_POST['sitename'] as $id=>$sitename){
634 $sitename=trim($sitename);
635 $apiurl=trim($_POST['apiurl'][$id]);
636 if (! (substr($apiurl, -1)=='/'))
638 $secret=trim($_POST['secret'][$id]);
639 $key=trim($_POST['key'][$id]);
640 //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
645 !x($_POST['delete'][$id])){
648 'sitename' => $sitename,
650 'consumersecret' => $secret,
651 'consumerkey' => $key,
652 //'applicationname' => $applicationname
657 $sites = set_config('statusnet','sites', $sites);
661 function statusnet_plugin_admin(&$a, &$o){
663 $sites = get_config('statusnet','sites');
665 if (is_array($sites)){
666 foreach($sites as $id=>$s){
667 $sitesform[] = Array(
668 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
669 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29") ),
670 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
671 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
672 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
673 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
677 /* empty form to add new site */
679 $sitesform[] = Array(
680 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
681 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29") ),
682 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
683 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
684 //'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
687 $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
688 $o = replace_macros($t, array(
689 '$submit' => t('Save Settings'),
690 '$sites' => $sitesform,
694 function statusnet_prepare_body(&$a,&$b) {
695 if ($b["item"]["network"] != NETWORK_STATUSNET)
699 $max_char = get_pconfig(local_user(),'statusnet','max_char');
700 if (intval($max_char) == 0)
703 require_once("include/plaintext.php");
705 $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"];
707 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
708 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
709 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
710 dbesc($item["thr-parent"]),
711 intval(local_user()));
715 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
716 //$nicknameplain = "@".$orig_post["contact_nick"];
718 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
720 $nickname = "@[url=".$orig_post["author-link"]."]".$nick."[/url]";
721 $nicknameplain = "@".$nick;
723 if ((strpos($item["body"], $nickname) === false) AND (strpos($item["body"], $nicknameplain) === false))
724 $item["body"] = $nickname." ".$item["body"];
728 $msgarr = plaintext($a, $item, $max_char, true, 7);
729 $msg = $msgarr["text"];
731 if (isset($msgarr["url"]))
732 $msg .= " ".$msgarr["url"];
734 if (isset($msgarr["image"]))
735 $msg .= " ".$msgarr["image"];
737 $b['html'] = nl2br(htmlspecialchars($msg));
741 function statusnet_cron($a,$b) {
742 $last = get_config('statusnet','last_poll');
744 $poll_interval = intval(get_config('statusnet','poll_interval'));
746 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
749 $next = $last + ($poll_interval * 60);
751 logger('statusnet: poll intervall not reached');
755 logger('statusnet: cron_start');
757 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
760 logger('statusnet: fetching for user '.$rr['uid']);
761 statusnet_fetchtimeline($a, $rr['uid']);
765 $abandon_days = intval(get_config('system','account_abandon_days'));
766 if ($abandon_days < 1)
769 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
771 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
774 if ($abandon_days != 0) {
775 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
777 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
782 logger('statusnet: importing timeline from user '.$rr['uid']);
783 statusnet_fetchhometimeline($a, $rr["uid"]);
787 logger('statusnet: cron_end');
789 set_config('statusnet','last_poll', time());
792 function statusnet_fetchtimeline($a, $uid) {
793 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
794 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
795 $api = get_pconfig($uid, 'statusnet', 'baseapi');
796 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
797 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
798 $lastid = get_pconfig($uid, 'statusnet', 'lastid');
800 require_once('mod/item.php');
801 require_once('include/items.php');
803 // get the application name for the SN app
804 // 1st try personal config, then system config and fallback to the
805 // hostname of the node if neither one is set.
806 $application_name = get_pconfig( $uid, 'statusnet', 'application_name');
807 if ($application_name == "")
808 $application_name = get_config('statusnet', 'application_name');
809 if ($application_name == "")
810 $application_name = $a->get_hostname();
812 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
814 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
816 $first_time = ($lastid == "");
819 $parameters["since_id"] = $lastid;
821 $items = $connection->get('statuses/user_timeline', $parameters);
823 if (!is_array($items))
826 $posts = array_reverse($items);
829 foreach ($posts as $post) {
830 if ($post->id > $lastid)
836 if ($post->source == "activity")
839 if (is_object($post->retweeted_status))
842 if ($post->in_reply_to_status_id != "")
845 if (!stristr($post->source, $application_name)) {
846 $_SESSION["authenticated"] = true;
847 $_SESSION["uid"] = $uid;
850 $_REQUEST["type"] = "wall";
851 $_REQUEST["api_source"] = true;
852 $_REQUEST["profile_uid"] = $uid;
853 //$_REQUEST["source"] = "StatusNet";
854 $_REQUEST["source"] = $post->source;
855 $_REQUEST["extid"] = NETWORK_STATUSNET;
857 //$_REQUEST["date"] = $post->created_at;
859 $_REQUEST["title"] = "";
861 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
862 if (is_string($post->place->name))
863 $_REQUEST["location"] = $post->place->name;
865 if (is_string($post->place->full_name))
866 $_REQUEST["location"] = $post->place->full_name;
868 if (is_array($post->geo->coordinates))
869 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
871 if (is_array($post->coordinates->coordinates))
872 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
874 //print_r($_REQUEST);
875 if ($_REQUEST["body"] != "") {
876 logger('statusnet: posting for user '.$uid);
883 set_pconfig($uid, 'statusnet', 'lastid', $lastid);
886 function statusnet_address($contact) {
887 $hostname = normalise_link($contact->statusnet_profile_url);
888 $nickname = $contact->screen_name;
890 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
892 $address = $contact->screen_name."@".$hostname;
897 function statusnet_fetch_contact($uid, $contact, $create_user) {
898 if ($contact->statusnet_profile_url == "")
901 // Check if the unique contact is existing
902 // To-Do: only update once a while
903 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
904 dbesc(normalise_link($contact->statusnet_profile_url)));
907 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
908 dbesc(normalise_link($contact->statusnet_profile_url)),
909 dbesc($contact->name),
910 dbesc($contact->screen_name),
911 dbesc($contact->profile_image_url));
913 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
914 dbesc($contact->name),
915 dbesc($contact->screen_name),
916 dbesc($contact->profile_image_url),
917 dbesc(normalise_link($contact->statusnet_profile_url)));
919 if (DB_UPDATE_VERSION >= "1177")
920 q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'",
921 dbesc($contact->location),
922 dbesc($contact->description),
923 dbesc(normalise_link($contact->statusnet_profile_url)));
925 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
926 intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)));
928 if(!count($r) AND !$create_user)
931 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
932 logger("statusnet_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
937 // create contact record
938 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
939 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
940 `writable`, `blocked`, `readonly`, `pending` )
941 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
943 dbesc(datetime_convert()),
944 dbesc($contact->statusnet_profile_url),
945 dbesc(normalise_link($contact->statusnet_profile_url)),
946 dbesc(statusnet_address($contact)),
947 dbesc(normalise_link($contact->statusnet_profile_url)),
950 dbesc($contact->name),
951 dbesc($contact->screen_name),
952 dbesc($contact->profile_image_url),
953 dbesc(NETWORK_STATUSNET),
954 intval(CONTACT_IS_FRIEND),
959 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
960 dbesc($contact->statusnet_profile_url),
967 $contact_id = $r[0]['id'];
969 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
973 if($g && intval($g[0]['def_gid'])) {
974 require_once('include/group.php');
975 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
978 require_once("Photo.php");
980 $photos = import_profile_photo($contact->profile_image_url,$uid,$contact_id);
982 q("UPDATE `contact` SET `photo` = '%s',
990 dbesc(datetime_convert()),
994 if (DB_UPDATE_VERSION >= "1177")
995 q("UPDATE `contact` SET `location` = '%s',
998 dbesc($contact->location),
999 dbesc($contact->description),
1004 // update profile photos once every two weeks as we have no notification of when they change.
1006 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1007 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1009 // check that we have all the photos, this has been known to fail on occasion
1011 if((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1013 logger("statusnet_fetch_contact: Updating contact ".$contact->screen_name, LOGGER_DEBUG);
1015 require_once("Photo.php");
1017 $photos = import_profile_photo($contact->profile_image_url, $uid, $r[0]['id']);
1019 q("UPDATE `contact` SET `photo` = '%s',
1024 `avatar-date` = '%s',
1034 dbesc(datetime_convert()),
1035 dbesc(datetime_convert()),
1036 dbesc(datetime_convert()),
1037 dbesc($contact->statusnet_profile_url),
1038 dbesc(normalise_link($contact->statusnet_profile_url)),
1039 dbesc(statusnet_address($contact)),
1040 dbesc($contact->name),
1041 dbesc($contact->screen_name),
1045 if (DB_UPDATE_VERSION >= "1177")
1046 q("UPDATE `contact` SET `location` = '%s',
1049 dbesc($contact->location),
1050 dbesc($contact->description),
1056 return($r[0]["id"]);
1059 function statusnet_fetchuser($a, $uid, $screen_name = "", $user_id = "") {
1060 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1061 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1062 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1063 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1064 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1066 require_once("addon/statusnet/codebird.php");
1068 $cb = \Codebird\Codebird::getInstance();
1069 $cb->setConsumerKey($ckey, $csecret);
1070 $cb->setToken($otoken, $osecret);
1072 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1080 $parameters = array();
1082 if ($screen_name != "")
1083 $parameters["screen_name"] = $screen_name;
1086 $parameters["user_id"] = $user_id;
1088 // Fetching user data
1089 $user = $cb->users_show($parameters);
1091 if (!is_object($user))
1094 $contact_id = statusnet_fetch_contact($uid, $user, true);
1099 function statusnet_createpost($a, $uid, $post, $self, $create_user, $only_existing_contact) {
1101 require_once("include/html2bbcode.php");
1103 logger("statusnet_createpost: start", LOGGER_DEBUG);
1105 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1106 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1108 $postarray = array();
1109 $postarray['network'] = NETWORK_STATUSNET;
1110 $postarray['gravity'] = 0;
1111 $postarray['uid'] = $uid;
1112 $postarray['wall'] = 0;
1114 if (is_object($post->retweeted_status)) {
1115 $content = $post->retweeted_status;
1116 statusnet_fetch_contact($uid, $content->user, false);
1120 $postarray['uri'] = $hostname."::".$content->id;
1122 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1123 dbesc($postarray['uri']),
1132 if ($content->in_reply_to_status_id != "") {
1134 $parent = $hostname."::".$content->in_reply_to_status_id;
1136 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1141 $postarray['thr-parent'] = $r[0]["uri"];
1142 $postarray['parent-uri'] = $r[0]["parent-uri"];
1143 $postarray['parent'] = $r[0]["parent"];
1144 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1146 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1151 $postarray['thr-parent'] = $r[0]['uri'];
1152 $postarray['parent-uri'] = $r[0]['parent-uri'];
1153 $postarray['parent'] = $r[0]['parent'];
1154 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1156 $postarray['thr-parent'] = $postarray['uri'];
1157 $postarray['parent-uri'] = $postarray['uri'];
1158 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1163 $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1165 if ($content->user->id == $own_url) {
1166 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1170 $contactid = $r[0]["id"];
1172 $postarray['owner-name'] = $r[0]["name"];
1173 $postarray['owner-link'] = $r[0]["url"];
1174 $postarray['owner-avatar'] = $r[0]["photo"];
1178 // Don't create accounts of people who just comment something
1179 $create_user = false;
1181 $postarray['parent-uri'] = $postarray['uri'];
1182 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1185 if ($contactid == 0) {
1186 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1187 $postarray['owner-name'] = $post->user->name;
1188 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1189 $postarray['owner-avatar'] = $post->user->profile_image_url;
1191 if(($contactid == 0) AND !$only_existing_contact)
1192 $contactid = $self['id'];
1193 elseif ($contactid <= 0)
1196 $postarray['contact-id'] = $contactid;
1198 $postarray['verb'] = ACTIVITY_POST;
1200 $postarray['author-name'] = $content->user->name;
1201 $postarray['author-link'] = $content->user->statusnet_profile_url;
1202 $postarray['author-avatar'] = $content->user->profile_image_url;
1204 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1205 $hostname = str_replace("/api/", "/notice/", get_pconfig($uid, 'statusnet', 'baseapi'));
1207 $postarray['plink'] = $hostname.$content->id;
1208 $postarray['app'] = strip_tags($content->source);
1210 if ($content->user->protected) {
1211 $postarray['private'] = 1;
1212 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1215 $postarray['body'] = html2bbcode($content->statusnet_html);
1217 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1218 $postarray['body'] = $converted["body"];
1219 $postarray['tag'] = $converted["tags"];
1221 $postarray['created'] = datetime_convert('UTC','UTC',$content->created_at);
1222 $postarray['edited'] = datetime_convert('UTC','UTC',$content->created_at);
1224 if (is_string($content->place->name))
1225 $postarray["location"] = $content->place->name;
1227 if (is_string($content->place->full_name))
1228 $postarray["location"] = $content->place->full_name;
1230 if (is_array($content->geo->coordinates))
1231 $postarray["coord"] = $content->geo->coordinates[0]." ".$content->geo->coordinates[1];
1233 if (is_array($content->coordinates->coordinates))
1234 $postarray["coord"] = $content->coordinates->coordinates[1]." ".$content->coordinates->coordinates[0];
1236 /*if (is_object($post->retweeted_status)) {
1237 $postarray['body'] = html2bbcode($post->retweeted_status->statusnet_html);
1239 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1240 $postarray['body'] = $converted["body"];
1241 $postarray['tag'] = $converted["tags"];
1243 statusnet_fetch_contact($uid, $post->retweeted_status->user, false);
1245 // Let retweets look like wall-to-wall posts
1246 $postarray['author-name'] = $post->retweeted_status->user->name;
1247 $postarray['author-link'] = $post->retweeted_status->user->statusnet_profile_url;
1248 $postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url;
1250 logger("statusnet_createpost: end", LOGGER_DEBUG);
1254 function statusnet_checknotification($a, $uid, $own_url, $top_item, $postarray) {
1256 // This function necer worked and need cleanup
1258 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1266 if (link_compare($user[0]["url"], $postarray['author-link']))
1269 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1274 if(!count($own_user))
1277 // Is it me from statusnet?
1278 if (link_compare($own_user[0]["url"], $postarray['author-link']))
1281 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1282 dbesc($postarray['parent-uri']),
1286 if(count($myconv)) {
1288 foreach($myconv as $conv) {
1289 // now if we find a match, it means we're in this conversation
1291 if(!link_compare($conv['author-link'],$user[0]["url"]) AND !link_compare($conv['author-link'],$own_user[0]["url"]))
1294 require_once('include/enotify.php');
1296 $conv_parent = $conv['parent'];
1299 'type' => NOTIFY_COMMENT,
1300 'notify_flags' => $user[0]['notify-flags'],
1301 'language' => $user[0]['language'],
1302 'to_name' => $user[0]['username'],
1303 'to_email' => $user[0]['email'],
1304 'uid' => $user[0]['uid'],
1305 'item' => $postarray,
1306 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1307 'source_name' => $postarray['author-name'],
1308 'source_link' => $postarray['author-link'],
1309 'source_photo' => $postarray['author-avatar'],
1310 'verb' => ACTIVITY_POST,
1312 'parent' => $conv_parent,
1315 // only send one notification
1321 function statusnet_fetchhometimeline($a, $uid) {
1322 $conversations = array();
1324 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1325 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1326 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1327 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1328 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1329 $create_user = get_pconfig($uid, 'statusnet', 'create_user');
1331 // "create_user" is deactivated, since currently you cannot add users manually by now
1332 $create_user = true;
1334 logger("statusnet_fetchhometimeline: Fetching for user ".$uid, LOGGER_DEBUG);
1336 require_once('library/twitteroauth.php');
1337 require_once('include/items.php');
1339 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1341 $own_contact = statusnet_fetch_own_contact($a, $uid);
1343 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1344 intval($own_contact),
1348 $nick = $r[0]["nick"];
1350 logger("statusnet_fetchhometimeline: Own statusnet contact not found for user ".$uid, LOGGER_DEBUG);
1354 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1360 logger("statusnet_fetchhometimeline: Own contact not found for user ".$uid, LOGGER_DEBUG);
1364 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1367 logger("statusnet_fetchhometimeline: Own user not found for user ".$uid, LOGGER_DEBUG);
1371 $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1372 //$parameters["count"] = 200;
1375 // Fetching timeline
1376 $lastid = get_pconfig($uid, 'statusnet', 'lasthometimelineid');
1379 $first_time = ($lastid == "");
1382 $parameters["since_id"] = $lastid;
1384 $items = $connection->get('statuses/home_timeline', $parameters);
1386 if (!is_array($items)) {
1387 if (is_object($items) AND isset($items->error))
1388 $errormsg = $items->error;
1389 elseif (is_object($items))
1390 $errormsg = print_r($items, true);
1391 elseif (is_string($items) OR is_float($items) OR is_int($items))
1394 $errormsg = "Unknown error";
1396 logger("statusnet_fetchhometimeline: Error fetching home timeline: ".$errormsg, LOGGER_DEBUG);
1400 $posts = array_reverse($items);
1402 logger("statusnet_fetchhometimeline: Fetching timeline for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1404 if (count($posts)) {
1405 foreach ($posts as $post) {
1407 if ($post->id > $lastid)
1408 $lastid = $post->id;
1413 if (isset($post->statusnet_conversation_id)) {
1414 if (!isset($conversations[$post->statusnet_conversation_id])) {
1415 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1416 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1419 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1421 if (trim($postarray['body']) == "")
1424 $item = item_store($postarray);
1425 $postarray["id"] = $item;
1427 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted home timeline item '.$item);
1430 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1435 set_pconfig($uid, 'statusnet', 'lasthometimelineid', $lastid);
1437 // Fetching mentions
1438 $lastid = get_pconfig($uid, 'statusnet', 'lastmentionid');
1439 $first_time = ($lastid == "");
1442 $parameters["since_id"] = $lastid;
1444 $items = $connection->get('statuses/mentions_timeline', $parameters);
1446 if (!is_array($items)) {
1447 logger("statusnet_fetchhometimeline: Error fetching mentions: ".print_r($items, true), LOGGER_DEBUG);
1451 $posts = array_reverse($items);
1453 logger("statusnet_fetchhometimeline: Fetching mentions for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1455 if (count($posts)) {
1456 foreach ($posts as $post) {
1457 if ($post->id > $lastid)
1458 $lastid = $post->id;
1463 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1465 if (isset($post->statusnet_conversation_id)) {
1466 if (!isset($conversations[$post->statusnet_conversation_id])) {
1467 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1468 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1471 if (trim($postarray['body']) != "") {
1474 $item = item_store($postarray);
1475 $postarray["id"] = $item;
1477 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted mention timeline item '.$item);
1481 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1482 dbesc($postarray['uri']),
1486 $item = $r[0]['id'];
1487 $parent_id = $r[0]['parent'];
1491 require_once('include/enotify.php');
1493 'type' => NOTIFY_TAGSELF,
1494 'notify_flags' => $u[0]['notify-flags'],
1495 'language' => $u[0]['language'],
1496 'to_name' => $u[0]['username'],
1497 'to_email' => $u[0]['email'],
1498 'uid' => $u[0]['uid'],
1499 'item' => $postarray,
1500 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
1501 'source_name' => $postarray['author-name'],
1502 'source_link' => $postarray['author-link'],
1503 'source_photo' => $postarray['author-avatar'],
1504 'verb' => ACTIVITY_TAG,
1506 'parent' => $parent_id,
1512 set_pconfig($uid, 'statusnet', 'lastmentionid', $lastid);
1515 function statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $conversation) {
1516 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1517 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1518 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1519 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1520 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1522 require_once('library/twitteroauth.php');
1524 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1526 $parameters["count"] = 200;
1528 $items = $connection->get('statusnet/conversation/'.$conversation, $parameters);
1529 if (is_array($items)) {
1530 $posts = array_reverse($items);
1532 foreach($posts AS $post) {
1533 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1535 if (trim($postarray['body']) == "")
1538 //print_r($postarray);
1539 $item = item_store($postarray);
1540 $postarray["id"] = $item;
1542 logger('statusnet_complete_conversation: User '.$self["nick"].' posted home timeline item '.$item);
1545 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1550 function statusnet_convertmsg($a, $body, $no_tags = false) {
1552 require_once("include/oembed.php");
1553 require_once("include/items.php");
1554 require_once("include/network.php");
1556 $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism","$1.$2.$3.$4/$5",$body);
1558 $URLSearchString = "^\[\]";
1559 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body,$matches,PREG_SET_ORDER);
1567 foreach ($matches AS $match) {
1568 $search = "[url=".$match[1]."]".$match[2]."[/url]";
1570 logger("statusnet_convertmsg: expanding url ".$match[1], LOGGER_DEBUG);
1572 $expanded_url = original_url($match[1]);
1574 logger("statusnet_convertmsg: fetching data for ".$expanded_url, LOGGER_DEBUG);
1576 $oembed_data = oembed_fetch_url($expanded_url, true);
1578 logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG);
1581 $type = $oembed_data->type;
1582 if ($oembed_data->type == "video") {
1583 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1584 $type = $oembed_data->type;
1585 $footerurl = $expanded_url;
1586 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1588 $body = str_replace($search, $footerlink, $body);
1589 } elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia)
1590 $body = str_replace($search, "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]", $body);
1591 elseif ($oembed_data->type != "link")
1592 $body = str_replace($search, "[url=".$expanded_url."]".$expanded_url."[/url]", $body);
1594 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1596 $tempfile = tempnam(get_temppath(), "cache");
1597 file_put_contents($tempfile, $img_str);
1598 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1601 if (substr($mime, 0, 6) == "image/") {
1603 $body = str_replace($search, "[img]".$expanded_url."[/img]", $body);
1605 $type = $oembed_data->type;
1606 $footerurl = $expanded_url;
1607 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1609 $body = str_replace($search, $footerlink, $body);
1614 if ($footerurl != "")
1615 $footer = add_page_info($footerurl);
1617 if (($footerlink != "") AND (trim($footer) != "")) {
1618 $removedlink = trim(str_replace($footerlink, "", $body));
1620 if (($removedlink == "") OR strstr($body, $removedlink))
1621 $body = $removedlink;
1628 return(array("body" => $body, "tags" => ""));
1632 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$body,$matches,PREG_SET_ORDER);
1634 foreach($matches as $mtch) {
1635 if(strlen($str_tags))
1638 if ($mtch[1] == "#") {
1639 // Replacing the hash tags that are directed to the statusnet server with internal links
1640 $snhash = "#[url=".$mtch[2]."]".$mtch[3]."[/url]";
1641 $frdchash = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($mtch[3]).']'.$mtch[3].'[/url]';
1642 $body = str_replace($snhash, $frdchash, $body);
1644 $str_tags .= $frdchash;
1646 $str_tags .= "@[url=".$mtch[2]."]".$mtch[3]."[/url]";
1648 // There is a problem with links with to statusnet groups, so these links are stored with "@" like friendica groups
1649 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1653 return(array("body"=>$body, "tags"=>$str_tags));
1657 function statusnet_fetch_own_contact($a, $uid) {
1658 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1659 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1660 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1661 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1662 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1663 $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1667 if ($own_url == "") {
1668 require_once('library/twitteroauth.php');
1670 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1672 // Fetching user data
1673 $user = $connection->get('account/verify_credentials');
1675 set_pconfig($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1677 $contact_id = statusnet_fetch_contact($uid, $user, true);
1680 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1681 intval($uid), dbesc($own_url));
1683 $contact_id = $r[0]["id"];
1685 del_pconfig($uid, 'statusnet', 'own_url');
1688 return($contact_id);
1691 function statusnet_is_retweet($a, $uid, $body) {
1692 $body = trim($body);
1694 // Skip if it isn't a pure repeated messages
1695 // Does it start with a share?
1696 if (strpos($body, "[share") > 0)
1699 // Does it end with a share?
1700 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1703 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1704 // Skip if there is no shared message in there
1705 if ($body == $attributes)
1709 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1710 if ($matches[1] != "")
1711 $link = $matches[1];
1713 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1714 if ($matches[1] != "")
1715 $link = $matches[1];
1717 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1718 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1719 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1720 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1721 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1722 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1724 $id = preg_replace("=https?://".$hostname."/notice/(.*)=ism", "$1", $link);
1729 logger('statusnet_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG);
1731 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1733 $result = $connection->post('statuses/retweet/'.$id);
1735 logger('statusnet_is_retweet: result '.print_r($result, true), LOGGER_DEBUG);
1736 return(isset($result->id));