4 * Name: GNU Social Connector
5 * Description: Bidirectional (posting, relaying and reading) connector for GNU Social.
7 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
8 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
10 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
11 * All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions are met:
15 * * Redistributions of source code must retain the above copyright notice,
16 * this list of conditions and the following disclaimer.
17 * * Redistributions in binary form must reproduce the above
18 * * copyright notice, this list of conditions and the following disclaimer in
19 * the documentation and/or other materials provided with the distribution.
20 * * Neither the name of the <organization> nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
28 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 * We have to alter the TwitterOAuth class a little bit to work with any GNU Social
38 * installation abroad. Basically it's only make the API path variable and be happy.
40 * Thank you guys for the Twitter compatible API!
43 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
45 require_once 'library/twitteroauth.php';
46 require_once 'include/enotify.php';
49 use Friendica\Content\OEmbed;
50 use Friendica\Content\Text\BBCode;
51 use Friendica\Content\Text\Plaintext;
52 use Friendica\Core\Addon;
53 use Friendica\Core\Config;
54 use Friendica\Core\L10n;
55 use Friendica\Core\PConfig;
56 use Friendica\Model\GContact;
57 use Friendica\Model\Group;
58 use Friendica\Model\Photo;
59 use Friendica\Model\User;
61 class StatusNetOAuth extends TwitterOAuth
63 function get_maxlength()
65 $config = $this->get($this->host . 'statusnet/config.json');
66 return $config->site->textlimit;
69 function accessTokenURL()
71 return $this->host . 'oauth/access_token';
74 function authenticateURL()
76 return $this->host . 'oauth/authenticate';
79 function authorizeURL()
81 return $this->host . 'oauth/authorize';
84 function requestTokenURL()
86 return $this->host . 'oauth/request_token';
89 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL)
91 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
92 $this->host = $apipath;
96 * Make an HTTP request
100 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
102 function http($url, $method, $postfields = NULL)
104 $this->http_info = [];
107 $prx = Config::get('system', 'proxy');
109 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
110 curl_setopt($ci, CURLOPT_PROXY, $prx);
111 $prxusr = Config::get('system', 'proxyuser');
112 if (strlen($prxusr)) {
113 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
116 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
117 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
118 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
119 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
120 curl_setopt($ci, CURLOPT_HTTPHEADER, ['Expect:']);
121 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
122 curl_setopt($ci, CURLOPT_HEADERFUNCTION, [$this, 'getHeader']);
123 curl_setopt($ci, CURLOPT_HEADER, FALSE);
127 curl_setopt($ci, CURLOPT_POST, TRUE);
128 if (!empty($postfields)) {
129 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
133 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
134 if (!empty($postfields)) {
135 $url = "{$url}?{$postfields}";
139 curl_setopt($ci, CURLOPT_URL, $url);
140 $response = curl_exec($ci);
141 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
142 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
149 function statusnet_install()
151 // we need some hooks, for the configuration and for sending tweets
152 Addon::registerHook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
153 Addon::registerHook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
154 Addon::registerHook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
155 Addon::registerHook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
156 Addon::registerHook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
157 Addon::registerHook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
158 Addon::registerHook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
159 Addon::registerHook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
160 logger("installed GNU Social");
163 function statusnet_uninstall()
165 Addon::unregisterHook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
166 Addon::unregisterHook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
167 Addon::unregisterHook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
168 Addon::unregisterHook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
169 Addon::unregisterHook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
170 Addon::unregisterHook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
171 Addon::unregisterHook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
172 Addon::unregisterHook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
174 // old setting - remove only
175 Addon::unregisterHook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
176 Addon::unregisterHook('addon_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
177 Addon::unregisterHook('addon_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
180 function statusnet_check_item_notification(App $a, &$notification_data)
182 $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
185 function statusnet_jot_nets(App $a, &$b)
191 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
192 if (intval($statusnet_post) == 1) {
193 $statusnet_defpost = PConfig::get(local_user(), 'statusnet', 'post_by_default');
194 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
195 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
196 . L10n::t('Post to GNU Social') . '</div>';
200 function statusnet_settings_post(App $a, $post)
205 // don't check GNU Social settings if GNU Social submit button is not clicked
206 if (!x($_POST, 'statusnet-submit')) {
210 if (isset($_POST['statusnet-disconnect'])) {
212 * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration
214 PConfig::delete(local_user(), 'statusnet', 'consumerkey');
215 PConfig::delete(local_user(), 'statusnet', 'consumersecret');
216 PConfig::delete(local_user(), 'statusnet', 'post');
217 PConfig::delete(local_user(), 'statusnet', 'post_by_default');
218 PConfig::delete(local_user(), 'statusnet', 'oauthtoken');
219 PConfig::delete(local_user(), 'statusnet', 'oauthsecret');
220 PConfig::delete(local_user(), 'statusnet', 'baseapi');
221 PConfig::delete(local_user(), 'statusnet', 'lastid');
222 PConfig::delete(local_user(), 'statusnet', 'mirror_posts');
223 PConfig::delete(local_user(), 'statusnet', 'import');
224 PConfig::delete(local_user(), 'statusnet', 'create_user');
225 PConfig::delete(local_user(), 'statusnet', 'own_id');
227 if (isset($_POST['statusnet-preconf-apiurl'])) {
229 * If the user used one of the preconfigured GNU Social server credentials
230 * use them. All the data are available in the global config.
231 * Check the API Url never the less and blame the admin if it's not working ^^
233 $globalsn = Config::get('statusnet', 'sites');
234 foreach ($globalsn as $asn) {
235 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
236 $apibase = $asn['apiurl'];
237 $c = fetch_url($apibase . 'statusnet/version.xml');
238 if (strlen($c) > 0) {
239 PConfig::set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey']);
240 PConfig::set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret']);
241 PConfig::set(local_user(), 'statusnet', 'baseapi', $asn['apiurl']);
242 //PConfig::set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
244 notice(L10n::t('Please contact your site administrator.<br />The provided API URL is not valid.') . EOL . $asn['apiurl'] . EOL);
248 goaway('settings/connectors');
250 if (isset($_POST['statusnet-consumersecret'])) {
251 // check if we can reach the API of the GNU Social server
252 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
253 // resign quickly after this one try to fix the path ;-)
254 $apibase = $_POST['statusnet-baseapi'];
255 $c = fetch_url($apibase . 'statusnet/version.xml');
256 if (strlen($c) > 0) {
257 // ok the API path is correct, let's save the settings
258 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
259 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
260 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
261 //PConfig::set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
263 // the API path is not correct, maybe missing trailing / ?
264 $apibase = $apibase . '/';
265 $c = fetch_url($apibase . 'statusnet/version.xml');
266 if (strlen($c) > 0) {
267 // ok the API path is now correct, let's save the settings
268 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
269 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
270 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
272 // still not the correct API base, let's do noting
273 notice(L10n::t('We could not contact the GNU Social API with the Path you entered.') . EOL);
276 goaway('settings/connectors');
278 if (isset($_POST['statusnet-pin'])) {
279 // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
280 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
281 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
282 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
283 // the token and secret for which the PIN was generated were hidden in the settings
284 // form as token and token2, we need a new connection to GNU Social using these token
285 // and secret to request a Access Token with the PIN
286 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
287 $token = $connection->getAccessToken($_POST['statusnet-pin']);
288 // ok, now that we have the Access Token, save them in the user config
289 PConfig::set(local_user(), 'statusnet', 'oauthtoken', $token['oauth_token']);
290 PConfig::set(local_user(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
291 PConfig::set(local_user(), 'statusnet', 'post', 1);
292 PConfig::set(local_user(), 'statusnet', 'post_taglinks', 1);
293 // reload the Addon Settings page, if we don't do it see Bug #42
294 goaway('settings/connectors');
296 // if no PIN is supplied in the POST variables, the user has changed the setting
297 // to post a dent for every new __public__ posting to the wall
298 PConfig::set(local_user(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
299 PConfig::set(local_user(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
300 PConfig::set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
301 PConfig::set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
302 PConfig::set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
304 if (!intval($_POST['statusnet-mirror']))
305 PConfig::delete(local_user(), 'statusnet', 'lastid');
307 info(L10n::t('GNU Social settings updated.') . EOL);
314 function statusnet_settings(App $a, &$s)
319 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
321 * 1) Check that we have a base api url and a consumer key & secret
322 * 2) If no OAuthtoken & stuff is present, generate button to get some
323 * allow the user to cancel the connection process at this step
324 * 3) Checkbox for "Send public notices (respect size limitation)
326 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
327 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
328 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
329 $otoken = PConfig::get(local_user(), 'statusnet', 'oauthtoken');
330 $osecret = PConfig::get(local_user(), 'statusnet', 'oauthsecret');
331 $enabled = PConfig::get(local_user(), 'statusnet', 'post');
332 $checked = (($enabled) ? ' checked="checked" ' : '');
333 $defenabled = PConfig::get(local_user(), 'statusnet', 'post_by_default');
334 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
335 $mirrorenabled = PConfig::get(local_user(), 'statusnet', 'mirror_posts');
336 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
337 $import = PConfig::get(local_user(), 'statusnet', 'import');
338 $importselected = ["", "", ""];
339 $importselected[$import] = ' selected="selected"';
340 //$importenabled = PConfig::get(local_user(),'statusnet','import');
341 //$importchecked = (($importenabled) ? ' checked="checked" ' : '');
342 $create_userenabled = PConfig::get(local_user(), 'statusnet', 'create_user');
343 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
345 $css = (($enabled) ? '' : '-disabled');
347 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
348 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . L10n::t('GNU Social Import/Export/Mirror') . '</h3>';
350 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
351 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
352 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . L10n::t('GNU Social Import/Export/Mirror') . '</h3>';
355 if ((!$ckey) && (!$csecret)) {
359 $globalsn = Config::get('statusnet', 'sites');
361 * lets check if we have one or more globally configured GNU Social
362 * server OAuth credentials in the configuration. If so offer them
363 * with a little explanation to the user as choice - otherwise
364 * ignore this option entirely.
366 if (!$globalsn == null) {
367 $s .= '<h4>' . L10n::t('Globally Available GNU Social OAuthKeys') . '</h4>';
368 $s .= '<p>' . L10n::t("There are preconfigured OAuth key pairs for some GNU Social servers available. If you are using one of them, please use these credentials. If not feel free to connect to any other GNU Social instance \x28see below\x29.") . '</p>';
369 $s .= '<div id="statusnet-preconf-wrapper">';
370 foreach ($globalsn as $asn) {
371 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="' . $asn['apiurl'] . '">' . $asn['sitename'] . '<br />';
373 $s .= '<p></p><div class="clear"></div></div>';
374 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
376 $s .= '<h4>' . L10n::t('Provide your own OAuth Credentials') . '</h4>';
377 $s .= '<p>' . L10n::t('No consumer key pair for GNU Social found. Register your Friendica Account as an desktop client on your GNU Social 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 GNU Social installation.') . '</p>';
378 $s .= '<div id="statusnet-consumer-wrapper">';
379 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">' . L10n::t('OAuth Consumer Key') . '</label>';
380 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
381 $s .= '<div class="clear"></div>';
382 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">' . L10n::t('OAuth Consumer Secret') . '</label>';
383 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
384 $s .= '<div class="clear"></div>';
385 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">' . L10n::t("Base API Path \x28remember the trailing /\x29") . '</label>';
386 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
387 $s .= '<div class="clear"></div>';
388 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.L10n::t('GNU Socialapplication name').'</label>';
389 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
390 $s .= '<p></p><div class="clear"></div>';
391 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
395 * ok we have a consumer key pair now look into the OAuth stuff
397 if ((!$otoken) && (!$osecret)) {
399 * the user has not yet connected the account to GNU Social
400 * get a temporary OAuth key/secret pair and display a button with
401 * which the user can request a PIN to connect the account to a
402 * account at GNU Social
404 $connection = new StatusNetOAuth($api, $ckey, $csecret);
405 $request_token = $connection->getRequestToken('oob');
406 $token = $request_token['oauth_token'];
408 * make some nice form
410 $s .= '<p>' . L10n::t('To connect to your GNU Social account click the button below to get a security code from GNU Social which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to GNU Social.') . '</p>';
411 $s .= '<a href="' . $connection->getAuthorizeURL($token, False) . '" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="' . L10n::t('Log in with GNU Social') . '"></a>';
412 $s .= '<div id="statusnet-pin-wrapper">';
413 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">' . L10n::t('Copy the security code from GNU Social here') . '</label>';
414 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
415 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="' . $token . '" />';
416 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="' . $request_token['oauth_token_secret'] . '" />';
417 $s .= '</div><div class="clear"></div>';
418 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
419 $s .= '<h4>' . L10n::t('Cancel Connection Process') . '</h4>';
420 $s .= '<div id="statusnet-cancel-wrapper">';
421 $s .= '<p>' . L10n::t('Current GNU Social API is') . ': ' . $api . '</p>';
422 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">' . L10n::t('Cancel GNU Social Connection') . '</label>';
423 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
424 $s .= '</div><div class="clear"></div>';
425 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
428 * we have an OAuth key / secret pair for the user
429 * so let's give a chance to disable the postings to GNU Social
431 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
432 $details = $connection->get('account/verify_credentials');
433 $s .= '<div id="statusnet-info" ><img id="statusnet-avatar" src="' . $details->profile_image_url . '" /><p id="statusnet-info-block">' . L10n::t('Currently connected to: ') . '<a href="' . $details->statusnet_profile_url . '" target="_statusnet">' . $details->screen_name . '</a><br /><em>' . $details->description . '</em></p></div>';
434 $s .= '<p>' . L10n::t('If enabled all your <strong>public</strong> postings can be posted to the associated GNU Social account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.') . '</p>';
435 if ($a->user['hidewall']) {
436 $s .= '<p>' . L10n::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 GNU Social will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
438 $s .= '<div id="statusnet-enable-wrapper">';
439 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">' . L10n::t('Allow posting to GNU Social') . '</label>';
440 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
441 $s .= '<div class="clear"></div>';
442 $s .= '<label id="statusnet-default-label" for="statusnet-default">' . L10n::t('Send public postings to GNU Social by default') . '</label>';
443 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
444 $s .= '<div class="clear"></div>';
446 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">' . L10n::t('Mirror all posts from GNU Social that are no replies or repeated messages') . '</label>';
447 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" ' . $mirrorchecked . '/>';
449 $s .= '<div class="clear"></div>';
452 $s .= '<label id="statusnet-import-label" for="statusnet-import">' . L10n::t('Import the remote timeline') . '</label>';
453 //$s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
455 $s .= '<select name="statusnet-import" id="statusnet-import" />';
456 $s .= '<option value="0" ' . $importselected[0] . '>' . L10n::t("Disabled") . '</option>';
457 $s .= '<option value="1" ' . $importselected[1] . '>' . L10n::t("Full Timeline") . '</option>';
458 $s .= '<option value="2" ' . $importselected[2] . '>' . L10n::t("Only Mentions") . '</option>';
460 $s .= '<div class="clear"></div>';
462 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.L10n::t('Automatically create contacts').'</label>';
463 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
464 $s .= '<div class="clear"></div>';
466 $s .= '<div id="statusnet-disconnect-wrapper">';
467 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">' . L10n::t('Clear OAuth configuration') . '</label>';
468 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
469 $s .= '</div><div class="clear"></div>';
470 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
473 $s .= '</div><div class="clear"></div>';
476 function statusnet_post_local(App $a, &$b)
482 if (!local_user() || (local_user() != $b['uid'])) {
486 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
487 $statusnet_enable = (($statusnet_post && x($_REQUEST, 'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
489 // if API is used, default to the chosen settings
490 if ($b['api_source'] && intval(PConfig::get(local_user(), 'statusnet', 'post_by_default'))) {
491 $statusnet_enable = 1;
494 if (!$statusnet_enable) {
498 if (strlen($b['postopts'])) {
499 $b['postopts'] .= ',';
502 $b['postopts'] .= 'statusnet';
505 function statusnet_action(App $a, $uid, $pid, $action)
507 $api = PConfig::get($uid, 'statusnet', 'baseapi');
508 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
509 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
510 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
511 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
513 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
515 logger("statusnet_action '" . $action . "' ID: " . $pid, LOGGER_DATA);
519 $result = $connection->post("statuses/destroy/" . $pid);
522 $result = $connection->post("favorites/create/" . $pid);
525 $result = $connection->post("favorites/destroy/" . $pid);
528 logger("statusnet_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
531 function statusnet_post_hook(App $a, &$b)
536 if (!PConfig::get($b["uid"], 'statusnet', 'import')) {
537 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
541 $api = PConfig::get($b["uid"], 'statusnet', 'baseapi');
542 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
544 if ($b['parent'] != $b['id']) {
545 logger("statusnet_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
547 // Looking if its a reply to a GNU Social post
548 $hostlength = strlen($hostname) + 2;
549 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) {
550 logger("statusnet_post_hook: no GNU Social post " . $b["parent"]);
554 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
555 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
556 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1", dbesc($b["thr-parent"]), intval($b["uid"]));
559 logger("statusnet_post_hook: no parent found " . $b["thr-parent"]);
566 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
567 //$nicknameplain = "@".$orig_post["contact_nick"];
569 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
571 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
572 $nicknameplain = "@" . $nick;
574 logger("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
575 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
576 $b["body"] = $nickname . " " . $b["body"];
579 logger("statusnet_post_hook: parent found " . print_r($orig_post, true), LOGGER_DEBUG);
583 if ($b['private'] || !strstr($b['postopts'], 'statusnet')) {
587 // Dont't post if the post doesn't belong to us.
588 // This is a check for forum postings
589 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
590 if ($b['contact-id'] != $self['id']) {
595 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
596 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
599 if ($b['verb'] == ACTIVITY_LIKE) {
600 logger("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
602 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
604 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
608 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
612 // if posts comes from GNU Social don't send it back
613 if ($b['extid'] == NETWORK_STATUSNET) {
617 if ($b['app'] == "StatusNet") {
621 logger('GNU Socialpost invoked');
623 PConfig::load($b['uid'], 'statusnet');
625 $api = PConfig::get($b['uid'], 'statusnet', 'baseapi');
626 $ckey = PConfig::get($b['uid'], 'statusnet', 'consumerkey');
627 $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret');
628 $otoken = PConfig::get($b['uid'], 'statusnet', 'oauthtoken');
629 $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret');
631 if ($ckey && $csecret && $otoken && $osecret) {
632 // If it's a repeated message from GNU Social then do a native retweet and exit
633 if (statusnet_is_retweet($a, $b['uid'], $b['body'])) {
637 require_once 'include/bbcode.php';
638 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
639 $max_char = $dent->get_maxlength(); // max. length for a dent
641 PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char);
644 require_once "include/network.php";
645 $msgarr = BBCode::toPlaintext($b, $max_char, true, 7);
646 $msg = $msgarr["text"];
648 if (($msg == "") && isset($msgarr["title"]))
649 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
653 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
654 if ((strlen($msgarr["url"]) > 20) &&
655 ((strlen($msg . " \n" . $msgarr["url"]) > $max_char))) {
656 $msg .= " \n" . short_link($msgarr["url"]);
658 $msg .= " \n" . $msgarr["url"];
660 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
661 $image = $msgarr["image"];
665 $img_str = fetch_url($image);
666 $tempfile = tempnam(get_temppath(), "cache");
667 file_put_contents($tempfile, $img_str);
668 $postdata = ["status" => $msg, "media[]" => $tempfile];
670 $postdata = ["status" => $msg];
673 // and now dent it :-)
676 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
677 logger('statusnet_post send reply ' . print_r($postdata, true), LOGGER_DEBUG);
680 // New code that is able to post pictures
681 require_once "addon/statusnet/codebird.php";
682 $cb = \CodebirdSN\CodebirdSN::getInstance();
683 $cb->setAPIEndpoint($api);
684 $cb->setConsumerKey($ckey, $csecret);
685 $cb->setToken($otoken, $osecret);
686 $result = $cb->statuses_update($postdata);
687 //$result = $dent->post('statuses/update', $postdata);
688 logger('statusnet_post send, result: ' . print_r($result, true) .
689 "\nmessage: " . $msg, LOGGER_DEBUG . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
691 if ($result->source) {
692 PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
695 if ($result->error) {
696 logger('Send to GNU Social failed: "' . $result->error . '"');
697 } elseif ($iscomment) {
698 logger('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
699 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
700 dbesc($hostname . "::" . $result->id),
701 dbesc($result->text),
706 if ($tempfile != "") {
712 function statusnet_addon_admin_post(App $a)
716 foreach ($_POST['sitename'] as $id => $sitename) {
717 $sitename = trim($sitename);
718 $apiurl = trim($_POST['apiurl'][$id]);
719 if (!(substr($apiurl, -1) == '/')) {
720 $apiurl = $apiurl . '/';
722 $secret = trim($_POST['secret'][$id]);
723 $key = trim($_POST['key'][$id]);
724 //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
725 if ($sitename != "" &&
729 !x($_POST['delete'][$id])) {
732 'sitename' => $sitename,
734 'consumersecret' => $secret,
735 'consumerkey' => $key,
736 //'applicationname' => $applicationname
741 $sites = Config::set('statusnet', 'sites', $sites);
744 function statusnet_addon_admin(App $a, &$o)
746 $sites = Config::get('statusnet', 'sites');
748 if (is_array($sites)) {
749 foreach ($sites as $id => $s) {
751 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""],
752 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], L10n::t("Base API Path \x28remember the trailing /\x29")],
753 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""],
754 'key' => ["key[$id]", "Key", $s['consumerkey'], ""],
755 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
756 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"],
760 /* empty form to add new site */
763 'sitename' => ["sitename[$id]", L10n::t("Site name"), "", ""],
764 'apiurl' => ["apiurl[$id]", "Api url", "", L10n::t("Base API Path \x28remember the trailing /\x29")],
765 'secret' => ["secret[$id]", L10n::t("Consumer Secret"), "", ""],
766 'key' => ["key[$id]", L10n::t("Consumer Key"), "", ""],
767 //'applicationname' => Array("applicationname[$id]", L10n::t("Application name"), "", ""),
770 $t = get_markup_template("admin.tpl", "addon/statusnet/");
771 $o = replace_macros($t, [
772 '$submit' => L10n::t('Save Settings'),
773 '$sites' => $sitesform,
777 function statusnet_prepare_body(App $a, &$b)
779 if ($b["item"]["network"] != NETWORK_STATUSNET) {
784 $max_char = PConfig::get(local_user(), 'statusnet', 'max_char');
785 if (intval($max_char) == 0) {
790 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
792 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
793 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
794 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
795 dbesc($item["thr-parent"]),
796 intval(local_user()));
800 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
801 //$nicknameplain = "@".$orig_post["contact_nick"];
803 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
805 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
806 $nicknameplain = "@" . $nick;
808 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
809 $item["body"] = $nickname . " " . $item["body"];
813 $msgarr = BBCode::toPlaintext($item, $max_char, true, 7);
814 $msg = $msgarr["text"];
816 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
817 $msg .= " " . $msgarr["url"];
820 if (isset($msgarr["image"])) {
821 $msg .= " " . $msgarr["image"];
824 $b['html'] = nl2br(htmlspecialchars($msg));
828 function statusnet_cron(App $a, $b)
830 $last = Config::get('statusnet', 'last_poll');
832 $poll_interval = intval(Config::get('statusnet', 'poll_interval'));
833 if (!$poll_interval) {
834 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
838 $next = $last + ($poll_interval * 60);
839 if ($next > time()) {
840 logger('statusnet: poll intervall not reached');
844 logger('statusnet: cron_start');
846 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
848 foreach ($r as $rr) {
849 logger('statusnet: fetching for user ' . $rr['uid']);
850 statusnet_fetchtimeline($a, $rr['uid']);
854 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
855 if ($abandon_days < 1) {
859 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
861 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
863 foreach ($r as $rr) {
864 if ($abandon_days != 0) {
865 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
867 logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
872 logger('statusnet: importing timeline from user ' . $rr['uid']);
873 statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
877 logger('statusnet: cron_end');
879 Config::set('statusnet', 'last_poll', time());
882 function statusnet_fetchtimeline(App $a, $uid)
884 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
885 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
886 $api = PConfig::get($uid, 'statusnet', 'baseapi');
887 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
888 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
889 $lastid = PConfig::get($uid, 'statusnet', 'lastid');
891 require_once 'mod/item.php';
892 require_once 'include/items.php';
894 // get the application name for the SN app
895 // 1st try personal config, then system config and fallback to the
896 // hostname of the node if neither one is set.
897 $application_name = PConfig::get($uid, 'statusnet', 'application_name');
898 if ($application_name == "") {
899 $application_name = Config::get('statusnet', 'application_name');
901 if ($application_name == "") {
902 $application_name = $a->get_hostname();
905 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
907 $parameters = ["exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false];
909 $first_time = ($lastid == "");
912 $parameters["since_id"] = $lastid;
915 $items = $connection->get('statuses/user_timeline', $parameters);
917 if (!is_array($items)) {
921 $posts = array_reverse($items);
924 foreach ($posts as $post) {
925 if ($post->id > $lastid)
932 if ($post->source == "activity") {
936 if (is_object($post->retweeted_status)) {
940 if ($post->in_reply_to_status_id != "") {
944 if (!stristr($post->source, $application_name)) {
945 $_SESSION["authenticated"] = true;
946 $_SESSION["uid"] = $uid;
949 $_REQUEST["type"] = "wall";
950 $_REQUEST["api_source"] = true;
951 $_REQUEST["profile_uid"] = $uid;
952 //$_REQUEST["source"] = "StatusNet";
953 $_REQUEST["source"] = $post->source;
954 $_REQUEST["extid"] = NETWORK_STATUSNET;
956 if (isset($post->id)) {
957 $_REQUEST['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_STATUSNET . ":" . $post->id);
960 //$_REQUEST["date"] = $post->created_at;
962 $_REQUEST["title"] = "";
964 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
965 if (is_string($post->place->name)) {
966 $_REQUEST["location"] = $post->place->name;
969 if (is_string($post->place->full_name)) {
970 $_REQUEST["location"] = $post->place->full_name;
973 if (is_array($post->geo->coordinates)) {
974 $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
977 if (is_array($post->coordinates->coordinates)) {
978 $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
981 //print_r($_REQUEST);
982 if ($_REQUEST["body"] != "") {
983 logger('statusnet: posting for user ' . $uid);
990 PConfig::set($uid, 'statusnet', 'lastid', $lastid);
993 function statusnet_address($contact)
995 $hostname = normalise_link($contact->statusnet_profile_url);
996 $nickname = $contact->screen_name;
998 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
1000 $address = $contact->screen_name . "@" . $hostname;
1005 function statusnet_fetch_contact($uid, $contact, $create_user)
1007 if ($contact->statusnet_profile_url == "") {
1011 GContact::update(["url" => $contact->statusnet_profile_url,
1012 "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url,
1013 "name" => $contact->name, "nick" => $contact->screen_name,
1014 "location" => $contact->location, "about" => $contact->description,
1015 "addr" => statusnet_address($contact), "generation" => 3]);
1017 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)), dbesc(NETWORK_STATUSNET));
1019 if (!count($r) && !$create_user) {
1023 if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
1024 logger("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
1029 // create contact record
1030 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1031 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1032 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1033 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
1035 dbesc(datetime_convert()),
1036 dbesc($contact->statusnet_profile_url),
1037 dbesc(normalise_link($contact->statusnet_profile_url)),
1038 dbesc(statusnet_address($contact)),
1039 dbesc(normalise_link($contact->statusnet_profile_url)),
1042 dbesc($contact->name),
1043 dbesc($contact->screen_name),
1044 dbesc($contact->profile_image_url),
1045 dbesc(NETWORK_STATUSNET),
1046 intval(CONTACT_IS_FRIEND),
1048 dbesc($contact->location),
1049 dbesc($contact->description),
1053 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
1054 dbesc($contact->statusnet_profile_url),
1056 dbesc(NETWORK_STATUSNET));
1062 $contact_id = $r[0]['id'];
1064 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1066 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
1068 q("UPDATE `contact` SET `photo` = '%s',
1071 `avatar-date` = '%s'
1076 dbesc(datetime_convert()),
1080 // update profile photos once every two weeks as we have no notification of when they change.
1081 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1082 $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours'));
1084 // check that we have all the photos, this has been known to fail on occasion
1085 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1086 logger("statusnet_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
1088 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1090 q("UPDATE `contact` SET `photo` = '%s',
1095 `avatar-date` = '%s',
1107 dbesc(datetime_convert()),
1108 dbesc(datetime_convert()),
1109 dbesc(datetime_convert()),
1110 dbesc($contact->statusnet_profile_url),
1111 dbesc(normalise_link($contact->statusnet_profile_url)),
1112 dbesc(statusnet_address($contact)),
1113 dbesc($contact->name),
1114 dbesc($contact->screen_name),
1115 dbesc($contact->location),
1116 dbesc($contact->description),
1125 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1127 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1128 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1129 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1130 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1131 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1133 require_once "addon/statusnet/codebird.php";
1135 $cb = \Codebird\Codebird::getInstance();
1136 $cb->setConsumerKey($ckey, $csecret);
1137 $cb->setToken($otoken, $osecret);
1139 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1150 if ($screen_name != "") {
1151 $parameters["screen_name"] = $screen_name;
1154 if ($user_id != "") {
1155 $parameters["user_id"] = $user_id;
1158 // Fetching user data
1159 $user = $cb->users_show($parameters);
1161 if (!is_object($user)) {
1165 $contact_id = statusnet_fetch_contact($uid, $user, true);
1170 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1172 require_once "include/html2bbcode.php";
1174 logger("statusnet_createpost: start", LOGGER_DEBUG);
1176 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1177 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1180 $postarray['network'] = NETWORK_STATUSNET;
1181 $postarray['gravity'] = 0;
1182 $postarray['uid'] = $uid;
1183 $postarray['wall'] = 0;
1185 if (is_object($post->retweeted_status)) {
1186 $content = $post->retweeted_status;
1187 statusnet_fetch_contact($uid, $content->user, false);
1192 $postarray['uri'] = $hostname . "::" . $content->id;
1194 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1195 dbesc($postarray['uri']),
1205 if ($content->in_reply_to_status_id != "") {
1207 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1209 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1214 $postarray['thr-parent'] = $r[0]["uri"];
1215 $postarray['parent-uri'] = $r[0]["parent-uri"];
1216 $postarray['parent'] = $r[0]["parent"];
1217 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1219 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1224 $postarray['thr-parent'] = $r[0]['uri'];
1225 $postarray['parent-uri'] = $r[0]['parent-uri'];
1226 $postarray['parent'] = $r[0]['parent'];
1227 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1229 $postarray['thr-parent'] = $postarray['uri'];
1230 $postarray['parent-uri'] = $postarray['uri'];
1231 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1236 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1238 if ($content->user->id == $own_url) {
1239 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1243 $contactid = $r[0]["id"];
1245 $postarray['owner-name'] = $r[0]["name"];
1246 $postarray['owner-link'] = $r[0]["url"];
1247 $postarray['owner-avatar'] = $r[0]["photo"];
1252 // Don't create accounts of people who just comment something
1253 $create_user = false;
1255 $postarray['parent-uri'] = $postarray['uri'];
1256 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1259 if ($contactid == 0) {
1260 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1261 $postarray['owner-name'] = $post->user->name;
1262 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1263 $postarray['owner-avatar'] = $post->user->profile_image_url;
1265 if (($contactid == 0) && !$only_existing_contact) {
1266 $contactid = $self['id'];
1267 } elseif ($contactid <= 0) {
1271 $postarray['contact-id'] = $contactid;
1273 $postarray['verb'] = ACTIVITY_POST;
1275 $postarray['author-name'] = $content->user->name;
1276 $postarray['author-link'] = $content->user->statusnet_profile_url;
1277 $postarray['author-avatar'] = $content->user->profile_image_url;
1279 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1280 $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1282 $postarray['plink'] = $hostname . $content->id;
1283 $postarray['app'] = strip_tags($content->source);
1285 if ($content->user->protected) {
1286 $postarray['private'] = 1;
1287 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1290 $postarray['body'] = html2bbcode($content->statusnet_html);
1292 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1293 $postarray['body'] = $converted["body"];
1294 $postarray['tag'] = $converted["tags"];
1296 $postarray['created'] = datetime_convert('UTC', 'UTC', $content->created_at);
1297 $postarray['edited'] = datetime_convert('UTC', 'UTC', $content->created_at);
1299 if (is_string($content->place->name)) {
1300 $postarray["location"] = $content->place->name;
1303 if (is_string($content->place->full_name)) {
1304 $postarray["location"] = $content->place->full_name;
1307 if (is_array($content->geo->coordinates)) {
1308 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1311 if (is_array($content->coordinates->coordinates)) {
1312 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1315 logger("statusnet_createpost: end", LOGGER_DEBUG);
1320 function statusnet_checknotification(App $a, $uid, $own_url, $top_item, $postarray)
1322 // This function necer worked and need cleanup
1323 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1327 if (!count($user)) {
1332 if (link_compare($user[0]["url"], $postarray['author-link'])) {
1336 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1341 if (!count($own_user)) {
1345 // Is it me from GNU Social?
1346 if (link_compare($own_user[0]["url"], $postarray['author-link'])) {
1350 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1351 dbesc($postarray['parent-uri']),
1355 if (count($myconv)) {
1356 foreach ($myconv as $conv) {
1357 // now if we find a match, it means we're in this conversation
1358 if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) {
1362 require_once 'include/enotify.php';
1364 $conv_parent = $conv['parent'];
1367 'type' => NOTIFY_COMMENT,
1368 'notify_flags' => $user[0]['notify-flags'],
1369 'language' => $user[0]['language'],
1370 'to_name' => $user[0]['username'],
1371 'to_email' => $user[0]['email'],
1372 'uid' => $user[0]['uid'],
1373 'item' => $postarray,
1374 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)),
1375 'source_name' => $postarray['author-name'],
1376 'source_link' => $postarray['author-link'],
1377 'source_photo' => $postarray['author-avatar'],
1378 'verb' => ACTIVITY_POST,
1380 'parent' => $conv_parent,
1383 // only send one notification
1389 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1391 $conversations = [];
1393 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1394 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1395 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1396 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1397 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1398 $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1400 // "create_user" is deactivated, since currently you cannot add users manually by now
1401 $create_user = true;
1403 logger("statusnet_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1405 require_once 'library/twitteroauth.php';
1406 require_once 'include/items.php';
1408 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1410 $own_contact = statusnet_fetch_own_contact($a, $uid);
1412 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1413 intval($own_contact),
1417 $nick = $r[0]["nick"];
1419 logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, LOGGER_DEBUG);
1423 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1429 logger("statusnet_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1433 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1436 logger("statusnet_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1440 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true];
1441 //$parameters["count"] = 200;
1444 // Fetching timeline
1445 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1448 $first_time = ($lastid == "");
1450 if ($lastid != "") {
1451 $parameters["since_id"] = $lastid;
1454 $items = $connection->get('statuses/home_timeline', $parameters);
1456 if (!is_array($items)) {
1457 if (is_object($items) && isset($items->error)) {
1458 $errormsg = $items->error;
1459 } elseif (is_object($items)) {
1460 $errormsg = print_r($items, true);
1461 } elseif (is_string($items) || is_float($items) || is_int($items)) {
1464 $errormsg = "Unknown error";
1467 logger("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, LOGGER_DEBUG);
1471 $posts = array_reverse($items);
1473 logger("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1475 if (count($posts)) {
1476 foreach ($posts as $post) {
1478 if ($post->id > $lastid) {
1479 $lastid = $post->id;
1486 if (isset($post->statusnet_conversation_id)) {
1487 if (!isset($conversations[$post->statusnet_conversation_id])) {
1488 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1489 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1492 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1494 if (trim($postarray['body']) == "") {
1498 $item = item_store($postarray);
1499 $postarray["id"] = $item;
1501 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1503 if ($item && !function_exists("check_item_notification")) {
1504 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1509 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1512 // Fetching mentions
1513 $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1514 $first_time = ($lastid == "");
1516 if ($lastid != "") {
1517 $parameters["since_id"] = $lastid;
1520 $items = $connection->get('statuses/mentions_timeline', $parameters);
1522 if (!is_array($items)) {
1523 logger("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1527 $posts = array_reverse($items);
1529 logger("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1531 if (count($posts)) {
1532 foreach ($posts as $post) {
1533 if ($post->id > $lastid) {
1534 $lastid = $post->id;
1541 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1543 if (isset($post->statusnet_conversation_id)) {
1544 if (!isset($conversations[$post->statusnet_conversation_id])) {
1545 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1546 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1549 if (trim($postarray['body']) == "") {
1553 $item = item_store($postarray);
1554 $postarray["id"] = $item;
1556 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1558 if ($item && function_exists("check_item_notification")) {
1559 check_item_notification($item, $uid, NOTIFY_TAGSELF);
1563 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1564 dbesc($postarray['uri']),
1568 $item = $r[0]['id'];
1569 $parent_id = $r[0]['parent'];
1572 if (($item != 0) && !function_exists("check_item_notification")) {
1573 require_once 'include/enotify.php';
1575 'type' => NOTIFY_TAGSELF,
1576 'notify_flags' => $u[0]['notify-flags'],
1577 'language' => $u[0]['language'],
1578 'to_name' => $u[0]['username'],
1579 'to_email' => $u[0]['email'],
1580 'uid' => $u[0]['uid'],
1581 'item' => $postarray,
1582 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)),
1583 'source_name' => $postarray['author-name'],
1584 'source_link' => $postarray['author-link'],
1585 'source_photo' => $postarray['author-avatar'],
1586 'verb' => ACTIVITY_TAG,
1588 'parent' => $parent_id,
1594 PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1597 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1599 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1600 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1601 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1602 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1603 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1604 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1606 require_once 'library/twitteroauth.php';
1608 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1610 $parameters["count"] = 200;
1612 $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1613 if (is_array($items)) {
1614 $posts = array_reverse($items);
1616 foreach ($posts AS $post) {
1617 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1619 if (trim($postarray['body']) == "") {
1623 $item = item_store($postarray);
1624 $postarray["id"] = $item;
1626 logger('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1628 if ($item && !function_exists("check_item_notification")) {
1629 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1635 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1637 require_once "include/items.php";
1638 require_once "include/network.php";
1640 $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
1642 $URLSearchString = "^\[\]";
1643 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1651 foreach ($matches AS $match) {
1652 $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
1654 logger("statusnet_convertmsg: expanding url " . $match[1], LOGGER_DEBUG);
1656 $expanded_url = original_url($match[1]);
1658 logger("statusnet_convertmsg: fetching data for " . $expanded_url, LOGGER_DEBUG);
1660 $oembed_data = OEmbed::fetchURL($expanded_url, true);
1662 logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG);
1665 $type = $oembed_data->type;
1668 if ($oembed_data->type == "video") {
1669 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1670 $type = $oembed_data->type;
1671 $footerurl = $expanded_url;
1672 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1674 $body = str_replace($search, $footerlink, $body);
1675 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia) {
1676 $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1677 } elseif ($oembed_data->type != "link") {
1678 $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1680 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1682 $tempfile = tempnam(get_temppath(), "cache");
1683 file_put_contents($tempfile, $img_str);
1684 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1687 if (substr($mime, 0, 6) == "image/") {
1689 $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body);
1691 $type = $oembed_data->type;
1692 $footerurl = $expanded_url;
1693 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1695 $body = str_replace($search, $footerlink, $body);
1700 if ($footerurl != "") {
1701 $footer = add_page_info($footerurl);
1704 if (($footerlink != "") && (trim($footer) != "")) {
1705 $removedlink = trim(str_replace($footerlink, "", $body));
1707 if (($removedlink == "") || strstr($body, $removedlink)) {
1708 $body = $removedlink;
1716 return ["body" => $body, "tags" => ""];
1721 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1723 foreach ($matches as $mtch) {
1724 if (strlen($str_tags)) {
1728 if ($mtch[1] == "#") {
1729 // Replacing the hash tags that are directed to the GNU Social server with internal links
1730 $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1731 $frdchash = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($mtch[3]) . ']' . $mtch[3] . '[/url]';
1732 $body = str_replace($snhash, $frdchash, $body);
1734 $str_tags .= $frdchash;
1736 $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1739 // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1740 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1744 return ["body" => $body, "tags" => $str_tags];
1747 function statusnet_fetch_own_contact(App $a, $uid)
1749 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1750 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1751 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1752 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1753 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1754 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1758 if ($own_url == "") {
1759 require_once 'library/twitteroauth.php';
1761 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1763 // Fetching user data
1764 $user = $connection->get('account/verify_credentials');
1766 PConfig::set($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1768 $contact_id = statusnet_fetch_contact($uid, $user, true);
1770 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1771 intval($uid), dbesc($own_url));
1773 $contact_id = $r[0]["id"];
1775 PConfig::delete($uid, 'statusnet', 'own_url');
1781 function statusnet_is_retweet(App $a, $uid, $body)
1783 $body = trim($body);
1785 // Skip if it isn't a pure repeated messages
1786 // Does it start with a share?
1787 if (strpos($body, "[share") > 0) {
1791 // Does it end with a share?
1792 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1796 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1797 // Skip if there is no shared message in there
1798 if ($body == $attributes) {
1803 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1804 if ($matches[1] != "") {
1805 $link = $matches[1];
1808 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1809 if ($matches[1] != "") {
1810 $link = $matches[1];
1813 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1814 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1815 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1816 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1817 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1818 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1820 $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link);
1826 logger('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1828 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1830 $result = $connection->post('statuses/retweet/' . $id);
1832 logger('statusnet_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1834 return isset($result->id);