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.
36 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
38 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'statusnetoauth.php';
39 use CodebirdSN\CodebirdSN;
41 use Friendica\Content\OEmbed;
42 use Friendica\Content\Text\HTML;
43 use Friendica\Content\Text\Plaintext;
44 use Friendica\Core\Config;
45 use Friendica\Core\Hook;
46 use Friendica\Core\L10n;
47 use Friendica\Core\Logger;
48 use Friendica\Core\PConfig;
49 use Friendica\Core\Protocol;
50 use Friendica\Core\Renderer;
51 use Friendica\Core\System;
52 use Friendica\Database\DBA;
53 use Friendica\Model\Contact;
54 use Friendica\Model\GContact;
55 use Friendica\Model\Group;
56 use Friendica\Model\Item;
57 use Friendica\Model\ItemContent;
58 use Friendica\Model\Photo;
59 use Friendica\Model\User;
60 use Friendica\Util\DateTimeFormat;
61 use Friendica\Util\Network;
62 use Friendica\Util\Strings;
64 function statusnet_install()
66 // we need some hooks, for the configuration and for sending tweets
67 Hook::register('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
68 Hook::register('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
69 Hook::register('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
70 Hook::register('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
71 Hook::register('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
72 Hook::register('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
73 Hook::register('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
74 Hook::register('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
75 Hook::register('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
76 Logger::log("installed GNU Social");
79 function statusnet_uninstall()
81 Hook::unregister('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
82 Hook::unregister('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
83 Hook::unregister('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
84 Hook::unregister('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
85 Hook::unregister('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
86 Hook::unregister('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
87 Hook::unregister('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
88 Hook::unregister('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
89 Hook::unregister('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
91 // old setting - remove only
92 Hook::unregister('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
93 Hook::unregister('addon_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
94 Hook::unregister('addon_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
97 function statusnet_check_item_notification(App $a, &$notification_data)
99 if (PConfig::get($notification_data["uid"], 'statusnet', 'post')) {
100 $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
104 function statusnet_jot_nets(App $a, &$b)
110 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
111 if (intval($statusnet_post) == 1) {
112 $statusnet_defpost = PConfig::get(local_user(), 'statusnet', 'post_by_default');
113 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
114 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
115 . L10n::t('Post to GNU Social') . '</div>';
119 function statusnet_settings_post(App $a, $post)
124 // don't check GNU Social settings if GNU Social submit button is not clicked
125 if (empty($_POST['statusnet-submit'])) {
129 if (isset($_POST['statusnet-disconnect'])) {
131 * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration
133 PConfig::delete(local_user(), 'statusnet', 'consumerkey');
134 PConfig::delete(local_user(), 'statusnet', 'consumersecret');
135 PConfig::delete(local_user(), 'statusnet', 'post');
136 PConfig::delete(local_user(), 'statusnet', 'post_by_default');
137 PConfig::delete(local_user(), 'statusnet', 'oauthtoken');
138 PConfig::delete(local_user(), 'statusnet', 'oauthsecret');
139 PConfig::delete(local_user(), 'statusnet', 'baseapi');
140 PConfig::delete(local_user(), 'statusnet', 'lastid');
141 PConfig::delete(local_user(), 'statusnet', 'mirror_posts');
142 PConfig::delete(local_user(), 'statusnet', 'import');
143 PConfig::delete(local_user(), 'statusnet', 'create_user');
144 PConfig::delete(local_user(), 'statusnet', 'own_url');
146 if (isset($_POST['statusnet-preconf-apiurl'])) {
148 * If the user used one of the preconfigured GNU Social server credentials
149 * use them. All the data are available in the global config.
150 * Check the API Url never the less and blame the admin if it's not working ^^
152 $globalsn = Config::get('statusnet', 'sites');
153 foreach ($globalsn as $asn) {
154 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
155 $apibase = $asn['apiurl'];
156 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
157 if (strlen($c) > 0) {
158 PConfig::set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey']);
159 PConfig::set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret']);
160 PConfig::set(local_user(), 'statusnet', 'baseapi', $asn['apiurl']);
161 //PConfig::set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
163 notice(L10n::t('Please contact your site administrator.<br />The provided API URL is not valid.') . EOL . $asn['apiurl'] . EOL);
167 $a->internalRedirect('settings/connectors');
169 if (isset($_POST['statusnet-consumersecret'])) {
170 // check if we can reach the API of the GNU Social server
171 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
172 // resign quickly after this one try to fix the path ;-)
173 $apibase = $_POST['statusnet-baseapi'];
174 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
175 if (strlen($c) > 0) {
176 // ok the API path is correct, let's save the settings
177 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
178 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
179 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
180 //PConfig::set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
182 // the API path is not correct, maybe missing trailing / ?
183 $apibase = $apibase . '/';
184 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
185 if (strlen($c) > 0) {
186 // ok the API path is now correct, let's save the settings
187 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
188 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
189 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
191 // still not the correct API base, let's do noting
192 notice(L10n::t('We could not contact the GNU Social API with the Path you entered.') . EOL);
195 $a->internalRedirect('settings/connectors');
197 if (isset($_POST['statusnet-pin'])) {
198 // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
199 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
200 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
201 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
202 // the token and secret for which the PIN was generated were hidden in the settings
203 // form as token and token2, we need a new connection to GNU Social using these token
204 // and secret to request a Access Token with the PIN
205 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
206 $token = $connection->getAccessToken($_POST['statusnet-pin']);
207 // ok, now that we have the Access Token, save them in the user config
208 PConfig::set(local_user(), 'statusnet', 'oauthtoken', $token['oauth_token']);
209 PConfig::set(local_user(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
210 PConfig::set(local_user(), 'statusnet', 'post', 1);
211 PConfig::set(local_user(), 'statusnet', 'post_taglinks', 1);
212 // reload the Addon Settings page, if we don't do it see Bug #42
213 $a->internalRedirect('settings/connectors');
215 // if no PIN is supplied in the POST variables, the user has changed the setting
216 // to post a dent for every new __public__ posting to the wall
217 PConfig::set(local_user(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
218 PConfig::set(local_user(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
219 PConfig::set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
220 PConfig::set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
221 PConfig::set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
223 if (!intval($_POST['statusnet-mirror']))
224 PConfig::delete(local_user(), 'statusnet', 'lastid');
226 info(L10n::t('GNU Social settings updated.') . EOL);
233 function statusnet_settings(App $a, &$s)
238 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
240 * 1) Check that we have a base api url and a consumer key & secret
241 * 2) If no OAuthtoken & stuff is present, generate button to get some
242 * allow the user to cancel the connection process at this step
243 * 3) Checkbox for "Send public notices (respect size limitation)
245 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
246 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
247 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
248 $otoken = PConfig::get(local_user(), 'statusnet', 'oauthtoken');
249 $osecret = PConfig::get(local_user(), 'statusnet', 'oauthsecret');
250 $enabled = PConfig::get(local_user(), 'statusnet', 'post');
251 $checked = (($enabled) ? ' checked="checked" ' : '');
252 $defenabled = PConfig::get(local_user(), 'statusnet', 'post_by_default');
253 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
254 $mirrorenabled = PConfig::get(local_user(), 'statusnet', 'mirror_posts');
255 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
256 $import = PConfig::get(local_user(), 'statusnet', 'import');
257 $importselected = ["", "", ""];
258 $importselected[$import] = ' selected="selected"';
259 //$importenabled = PConfig::get(local_user(),'statusnet','import');
260 //$importchecked = (($importenabled) ? ' checked="checked" ' : '');
261 $create_userenabled = PConfig::get(local_user(), 'statusnet', 'create_user');
262 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
264 $css = (($enabled) ? '' : '-disabled');
266 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
267 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . L10n::t('GNU Social Import/Export/Mirror') . '</h3>';
269 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
270 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
271 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . L10n::t('GNU Social Import/Export/Mirror') . '</h3>';
274 if ((!$ckey) && (!$csecret)) {
278 $globalsn = Config::get('statusnet', 'sites');
280 * lets check if we have one or more globally configured GNU Social
281 * server OAuth credentials in the configuration. If so offer them
282 * with a little explanation to the user as choice - otherwise
283 * ignore this option entirely.
285 if (!$globalsn == null) {
286 $s .= '<h4>' . L10n::t('Globally Available GNU Social OAuthKeys') . '</h4>';
287 $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>';
288 $s .= '<div id="statusnet-preconf-wrapper">';
289 foreach ($globalsn as $asn) {
290 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="' . $asn['apiurl'] . '">' . $asn['sitename'] . '<br />';
292 $s .= '<p></p><div class="clear"></div></div>';
293 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
295 $s .= '<h4>' . L10n::t('Provide your own OAuth Credentials') . '</h4>';
296 $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>';
297 $s .= '<div id="statusnet-consumer-wrapper">';
298 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">' . L10n::t('OAuth Consumer Key') . '</label>';
299 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
300 $s .= '<div class="clear"></div>';
301 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">' . L10n::t('OAuth Consumer Secret') . '</label>';
302 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
303 $s .= '<div class="clear"></div>';
304 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">' . L10n::t("Base API Path \x28remember the trailing /\x29") . '</label>';
305 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
306 $s .= '<div class="clear"></div>';
307 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.L10n::t('GNU Socialapplication name').'</label>';
308 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
309 $s .= '<p></p><div class="clear"></div>';
310 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
314 * ok we have a consumer key pair now look into the OAuth stuff
316 if ((!$otoken) && (!$osecret)) {
318 * the user has not yet connected the account to GNU Social
319 * get a temporary OAuth key/secret pair and display a button with
320 * which the user can request a PIN to connect the account to a
321 * account at GNU Social
323 $connection = new StatusNetOAuth($api, $ckey, $csecret);
324 $request_token = $connection->getRequestToken('oob');
325 $token = $request_token['oauth_token'];
327 * make some nice form
329 $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>';
330 $s .= '<a href="' . $connection->getAuthorizeURL($token, False) . '" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="' . L10n::t('Log in with GNU Social') . '"></a>';
331 $s .= '<div id="statusnet-pin-wrapper">';
332 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">' . L10n::t('Copy the security code from GNU Social here') . '</label>';
333 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
334 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="' . $token . '" />';
335 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="' . $request_token['oauth_token_secret'] . '" />';
336 $s .= '</div><div class="clear"></div>';
337 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
338 $s .= '<h4>' . L10n::t('Cancel Connection Process') . '</h4>';
339 $s .= '<div id="statusnet-cancel-wrapper">';
340 $s .= '<p>' . L10n::t('Current GNU Social API is') . ': ' . $api . '</p>';
341 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">' . L10n::t('Cancel GNU Social Connection') . '</label>';
342 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
343 $s .= '</div><div class="clear"></div>';
344 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
347 * we have an OAuth key / secret pair for the user
348 * so let's give a chance to disable the postings to GNU Social
350 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
351 $details = $connection->get('account/verify_credentials');
352 if (!empty($details)) {
353 $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>';
355 $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>';
356 if ($a->user['hidewall']) {
357 $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>';
359 $s .= '<div id="statusnet-enable-wrapper">';
360 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">' . L10n::t('Allow posting to GNU Social') . '</label>';
361 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
362 $s .= '<div class="clear"></div>';
363 $s .= '<label id="statusnet-default-label" for="statusnet-default">' . L10n::t('Send public postings to GNU Social by default') . '</label>';
364 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
365 $s .= '<div class="clear"></div>';
367 $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>';
368 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" ' . $mirrorchecked . '/>';
370 $s .= '<div class="clear"></div>';
373 $s .= '<label id="statusnet-import-label" for="statusnet-import">' . L10n::t('Import the remote timeline') . '</label>';
374 //$s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
376 $s .= '<select name="statusnet-import" id="statusnet-import" />';
377 $s .= '<option value="0" ' . $importselected[0] . '>' . L10n::t("Disabled") . '</option>';
378 $s .= '<option value="1" ' . $importselected[1] . '>' . L10n::t("Full Timeline") . '</option>';
379 $s .= '<option value="2" ' . $importselected[2] . '>' . L10n::t("Only Mentions") . '</option>';
381 $s .= '<div class="clear"></div>';
383 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.L10n::t('Automatically create contacts').'</label>';
384 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
385 $s .= '<div class="clear"></div>';
387 $s .= '<div id="statusnet-disconnect-wrapper">';
388 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">' . L10n::t('Clear OAuth configuration') . '</label>';
389 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
390 $s .= '</div><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>';
394 $s .= '</div><div class="clear"></div>';
397 function statusnet_hook_fork(App $a, array &$b)
399 if ($b['name'] != 'notifier_normal') {
405 // Deleting and editing is not supported by the addon
406 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
407 $b['execute'] = false;
411 // if post comes from GNU Social don't send it back
412 if ($post['extid'] == Protocol::STATUSNET) {
413 $b['execute'] = false;
417 if ($post['app'] == 'StatusNet') {
418 $b['execute'] = false;
422 if (PConfig::get($post['uid'], 'statusnet', 'import')) {
423 // Don't fork if it isn't a reply to a GNU Social post
424 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::STATUSNET])) {
425 Logger::log('No GNU Social parent found for item ' . $post['id']);
426 $b['execute'] = false;
430 // Comments are never exported when we don't import the GNU Social timeline
431 if (!strstr($post['postopts'], 'statusnet') || ($post['parent'] != $post['id']) || $post['private']) {
432 $b['execute'] = false;
438 function statusnet_post_local(App $a, &$b)
444 if (!local_user() || (local_user() != $b['uid'])) {
448 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
449 $statusnet_enable = (($statusnet_post && !empty($_REQUEST['statusnet_enable'])) ? intval($_REQUEST['statusnet_enable']) : 0);
451 // if API is used, default to the chosen settings
452 if ($b['api_source'] && intval(PConfig::get(local_user(), 'statusnet', 'post_by_default'))) {
453 $statusnet_enable = 1;
456 if (!$statusnet_enable) {
460 if (strlen($b['postopts'])) {
461 $b['postopts'] .= ',';
464 $b['postopts'] .= 'statusnet';
467 function statusnet_action(App $a, $uid, $pid, $action)
469 $api = PConfig::get($uid, 'statusnet', 'baseapi');
470 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
471 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
472 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
473 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
475 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
477 Logger::log("statusnet_action '" . $action . "' ID: " . $pid, Logger::DATA);
481 $result = $connection->post("statuses/destroy/" . $pid);
484 $result = $connection->post("favorites/create/" . $pid);
487 $result = $connection->post("favorites/destroy/" . $pid);
490 Logger::log("statusnet_action '" . $action . "' send, result: " . print_r($result, true), Logger::DEBUG);
493 function statusnet_post_hook(App $a, &$b)
498 if (!PConfig::get($b["uid"], 'statusnet', 'import')) {
499 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
503 $api = PConfig::get($b["uid"], 'statusnet', 'baseapi');
504 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
506 if ($b['parent'] != $b['id']) {
507 Logger::log("statusnet_post_hook: parameter " . print_r($b, true), Logger::DATA);
509 // Looking if its a reply to a GNU Social post
510 $hostlength = strlen($hostname) + 2;
511 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) {
512 Logger::log("statusnet_post_hook: no GNU Social post " . $b["parent"]);
516 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
517 $orig_post = Item::selectFirst(['author-link', 'uri'], $condition);
518 if (!DBA::isResult($orig_post)) {
519 Logger::log("statusnet_post_hook: no parent found " . $b["thr-parent"]);
525 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
527 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
528 $nicknameplain = "@" . $nick;
530 Logger::log("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], Logger::DEBUG);
531 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
532 $b["body"] = $nickname . " " . $b["body"];
535 Logger::log("statusnet_post_hook: parent found " . print_r($orig_post, true), Logger::DEBUG);
539 if ($b['private'] || !strstr($b['postopts'], 'statusnet')) {
543 // Dont't post if the post doesn't belong to us.
544 // This is a check for forum postings
545 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
546 if ($b['contact-id'] != $self['id']) {
551 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
552 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
555 if ($b['verb'] == ACTIVITY_LIKE) {
556 Logger::log("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), Logger::DEBUG);
558 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
560 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
564 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
568 // if posts comes from GNU Social don't send it back
569 if ($b['extid'] == Protocol::STATUSNET) {
573 if ($b['app'] == "StatusNet") {
577 Logger::log('GNU Socialpost invoked');
579 PConfig::load($b['uid'], 'statusnet');
581 $api = PConfig::get($b['uid'], 'statusnet', 'baseapi');
582 $ckey = PConfig::get($b['uid'], 'statusnet', 'consumerkey');
583 $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret');
584 $otoken = PConfig::get($b['uid'], 'statusnet', 'oauthtoken');
585 $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret');
587 if ($ckey && $csecret && $otoken && $osecret) {
588 // If it's a repeated message from GNU Social then do a native retweet and exit
589 if (statusnet_is_retweet($a, $b['uid'], $b['body'])) {
593 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
594 $max_char = $dent->get_maxlength(); // max. length for a dent
596 PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char);
599 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 7);
600 $msg = $msgarr["text"];
602 if (($msg == "") && isset($msgarr["title"]))
603 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
607 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
608 $msg .= " \n" . $msgarr["url"];
609 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
610 $image = $msgarr["image"];
614 $img_str = Network::fetchUrl($image);
615 $tempfile = tempnam(get_temppath(), "cache");
616 file_put_contents($tempfile, $img_str);
617 $postdata = ["status" => $msg, "media[]" => $tempfile];
619 $postdata = ["status" => $msg];
622 // and now send it :-)
625 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
626 Logger::log('statusnet_post send reply ' . print_r($postdata, true), Logger::DEBUG);
629 // New code that is able to post pictures
630 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
631 $cb = CodebirdSN::getInstance();
632 $cb->setAPIEndpoint($api);
633 $cb->setConsumerKey($ckey, $csecret);
634 $cb->setToken($otoken, $osecret);
635 $result = $cb->statuses_update($postdata);
636 //$result = $dent->post('statuses/update', $postdata);
637 Logger::log('statusnet_post send, result: ' . print_r($result, true) .
638 "\nmessage: " . $msg . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true), Logger::DEBUG);
640 if (!empty($result->source)) {
641 PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
644 if (!empty($result->error)) {
645 Logger::log('Send to GNU Social failed: "' . $result->error . '"');
646 } elseif ($iscomment) {
647 Logger::log('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
648 Item::update(['extid' => $hostname . "::" . $result->id, 'body' => $result->text], ['id' => $b['id']]);
651 if ($tempfile != "") {
657 function statusnet_addon_admin_post(App $a)
661 foreach ($_POST['sitename'] as $id => $sitename) {
662 $sitename = trim($sitename);
663 $apiurl = trim($_POST['apiurl'][$id]);
664 if (!(substr($apiurl, -1) == '/')) {
665 $apiurl = $apiurl . '/';
667 $secret = trim($_POST['secret'][$id]);
668 $key = trim($_POST['key'][$id]);
669 //$applicationname = (!empty($_POST['applicationname']) ? Strings::escapeTags(trim($_POST['applicationname'][$id])):'');
670 if ($sitename != "" &&
674 empty($_POST['delete'][$id])) {
677 'sitename' => $sitename,
679 'consumersecret' => $secret,
680 'consumerkey' => $key,
681 //'applicationname' => $applicationname
686 $sites = Config::set('statusnet', 'sites', $sites);
689 function statusnet_addon_admin(App $a, &$o)
691 $sites = Config::get('statusnet', 'sites');
693 if (is_array($sites)) {
694 foreach ($sites as $id => $s) {
696 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""],
697 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], L10n::t("Base API Path \x28remember the trailing /\x29")],
698 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""],
699 'key' => ["key[$id]", "Key", $s['consumerkey'], ""],
700 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
701 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"],
705 /* empty form to add new site */
706 $id = count($sitesform);
708 'sitename' => ["sitename[$id]", L10n::t("Site name"), "", ""],
709 'apiurl' => ["apiurl[$id]", "Api url", "", L10n::t("Base API Path \x28remember the trailing /\x29")],
710 'secret' => ["secret[$id]", L10n::t("Consumer Secret"), "", ""],
711 'key' => ["key[$id]", L10n::t("Consumer Key"), "", ""],
712 //'applicationname' => Array("applicationname[$id]", L10n::t("Application name"), "", ""),
715 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/statusnet/");
716 $o = Renderer::replaceMacros($t, [
717 '$submit' => L10n::t('Save Settings'),
718 '$sites' => $sitesform,
722 function statusnet_prepare_body(App $a, &$b)
724 if ($b["item"]["network"] != Protocol::STATUSNET) {
729 $max_char = PConfig::get(local_user(), 'statusnet', 'max_char');
730 if (intval($max_char) == 0) {
735 $item["plink"] = $a->getBaseURL() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
737 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
738 $orig_post = Item::selectFirst(['author-link', 'uri'], $condition);
739 if (DBA::isResult($orig_post)) {
740 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
742 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
743 $nicknameplain = "@" . $nick;
745 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
746 $item["body"] = $nickname . " " . $item["body"];
750 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 7);
751 $msg = $msgarr["text"];
753 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
754 $msg .= " " . $msgarr["url"];
757 if (isset($msgarr["image"])) {
758 $msg .= " " . $msgarr["image"];
761 $b['html'] = nl2br(htmlspecialchars($msg));
765 function statusnet_cron(App $a, $b)
767 $last = Config::get('statusnet', 'last_poll');
769 $poll_interval = intval(Config::get('statusnet', 'poll_interval'));
770 if (!$poll_interval) {
771 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
775 $next = $last + ($poll_interval * 60);
776 if ($next > time()) {
777 Logger::log('statusnet: poll intervall not reached');
781 Logger::log('statusnet: cron_start');
783 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
784 if (DBA::isResult($r)) {
785 foreach ($r as $rr) {
786 Logger::log('statusnet: fetching for user ' . $rr['uid']);
787 statusnet_fetchtimeline($a, $rr['uid']);
791 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
792 if ($abandon_days < 1) {
796 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
798 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
799 if (DBA::isResult($r)) {
800 foreach ($r as $rr) {
801 if ($abandon_days != 0) {
802 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
803 if (!DBA::isResult($user)) {
804 Logger::log('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
809 Logger::log('statusnet: importing timeline from user ' . $rr['uid']);
810 statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
814 Logger::log('statusnet: cron_end');
816 Config::set('statusnet', 'last_poll', time());
819 function statusnet_fetchtimeline(App $a, $uid)
821 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
822 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
823 $api = PConfig::get($uid, 'statusnet', 'baseapi');
824 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
825 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
826 $lastid = PConfig::get($uid, 'statusnet', 'lastid');
828 require_once 'mod/item.php';
829 // get the application name for the SN app
830 // 1st try personal config, then system config and fallback to the
831 // hostname of the node if neither one is set.
832 $application_name = PConfig::get($uid, 'statusnet', 'application_name');
833 if ($application_name == "") {
834 $application_name = Config::get('statusnet', 'application_name');
836 if ($application_name == "") {
837 $application_name = $a->getHostName();
840 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
842 $parameters = ["exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false];
844 $first_time = ($lastid == "");
847 $parameters["since_id"] = $lastid;
850 $items = $connection->get('statuses/user_timeline', $parameters);
852 if (!is_array($items)) {
856 $posts = array_reverse($items);
859 foreach ($posts as $post) {
860 if ($post->id > $lastid)
867 if ($post->source == "activity") {
871 if (!empty($post->retweeted_status)) {
875 if ($post->in_reply_to_status_id != "") {
879 if (!stristr($post->source, $application_name)) {
880 $_SESSION["authenticated"] = true;
881 $_SESSION["uid"] = $uid;
884 $_REQUEST["api_source"] = true;
885 $_REQUEST["profile_uid"] = $uid;
886 //$_REQUEST["source"] = "StatusNet";
887 $_REQUEST["source"] = $post->source;
888 $_REQUEST["extid"] = Protocol::STATUSNET;
890 if (isset($post->id)) {
891 $_REQUEST['message_id'] = Item::newURI($uid, Protocol::STATUSNET . ":" . $post->id);
894 //$_REQUEST["date"] = $post->created_at;
896 $_REQUEST["title"] = "";
898 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
899 if (is_string($post->place->name)) {
900 $_REQUEST["location"] = $post->place->name;
903 if (is_string($post->place->full_name)) {
904 $_REQUEST["location"] = $post->place->full_name;
907 if (is_array($post->geo->coordinates)) {
908 $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
911 if (is_array($post->coordinates->coordinates)) {
912 $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
915 //print_r($_REQUEST);
916 if ($_REQUEST["body"] != "") {
917 Logger::log('statusnet: posting for user ' . $uid);
924 PConfig::set($uid, 'statusnet', 'lastid', $lastid);
927 function statusnet_address($contact)
929 $hostname = Strings::normaliseLink($contact->statusnet_profile_url);
930 $nickname = $contact->screen_name;
932 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
934 $address = $contact->screen_name . "@" . $hostname;
939 function statusnet_fetch_contact($uid, $contact, $create_user)
941 if (empty($contact->statusnet_profile_url)) {
945 GContact::update(["url" => $contact->statusnet_profile_url,
946 "network" => Protocol::STATUSNET, "photo" => $contact->profile_image_url,
947 "name" => $contact->name, "nick" => $contact->screen_name,
948 "location" => $contact->location, "about" => $contact->description,
949 "addr" => statusnet_address($contact), "generation" => 3]);
951 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", intval($uid), DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)), DBA::escape(Protocol::STATUSNET));
953 if (!DBA::isResult($r) && !$create_user) {
957 if (DBA::isResult($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
958 Logger::log("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", Logger::DEBUG);
962 if (!DBA::isResult($r)) {
963 // create contact record
964 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
965 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
966 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
967 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
969 DBA::escape(DateTimeFormat::utcNow()),
970 DBA::escape($contact->statusnet_profile_url),
971 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
972 DBA::escape(statusnet_address($contact)),
973 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
976 DBA::escape($contact->name),
977 DBA::escape($contact->screen_name),
978 DBA::escape($contact->profile_image_url),
979 DBA::escape(Protocol::STATUSNET),
980 intval(Contact::FRIEND),
982 DBA::escape($contact->location),
983 DBA::escape($contact->description),
987 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
988 DBA::escape($contact->statusnet_profile_url),
990 DBA::escape(Protocol::STATUSNET));
992 if (!DBA::isResult($r)) {
996 $contact_id = $r[0]['id'];
998 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1000 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
1002 q("UPDATE `contact` SET `photo` = '%s',
1005 `avatar-date` = '%s'
1007 DBA::escape($photos[0]),
1008 DBA::escape($photos[1]),
1009 DBA::escape($photos[2]),
1010 DBA::escape(DateTimeFormat::utcNow()),
1014 // update profile photos once every two weeks as we have no notification of when they change.
1015 //$update_photo = (($r[0]['avatar-date'] < DateTimeFormat::convert('now -2 days', '', '', )) ? true : false);
1016 $update_photo = ($r[0]['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1018 // check that we have all the photos, this has been known to fail on occasion
1019 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1020 Logger::log("statusnet_fetch_contact: Updating contact " . $contact->screen_name, Logger::DEBUG);
1022 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1024 q("UPDATE `contact` SET `photo` = '%s',
1029 `avatar-date` = '%s',
1038 DBA::escape($photos[0]),
1039 DBA::escape($photos[1]),
1040 DBA::escape($photos[2]),
1041 DBA::escape(DateTimeFormat::utcNow()),
1042 DBA::escape(DateTimeFormat::utcNow()),
1043 DBA::escape(DateTimeFormat::utcNow()),
1044 DBA::escape($contact->statusnet_profile_url),
1045 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
1046 DBA::escape(statusnet_address($contact)),
1047 DBA::escape($contact->name),
1048 DBA::escape($contact->screen_name),
1049 DBA::escape($contact->location),
1050 DBA::escape($contact->description),
1059 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1061 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1062 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1063 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1064 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1065 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1067 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
1069 $cb = CodebirdSN::getInstance();
1070 $cb->setConsumerKey($ckey, $csecret);
1071 $cb->setToken($otoken, $osecret);
1073 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1076 if (DBA::isResult($r)) {
1084 if ($screen_name != "") {
1085 $parameters["screen_name"] = $screen_name;
1088 if ($user_id != "") {
1089 $parameters["user_id"] = $user_id;
1092 // Fetching user data
1093 $user = $cb->users_show($parameters);
1095 if (!is_object($user)) {
1099 $contact_id = statusnet_fetch_contact($uid, $user, true);
1104 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1106 Logger::log("statusnet_createpost: start", Logger::DEBUG);
1108 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1109 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1112 $postarray['network'] = Protocol::STATUSNET;
1113 $postarray['uid'] = $uid;
1114 $postarray['wall'] = 0;
1116 if (!empty($post->retweeted_status)) {
1117 $content = $post->retweeted_status;
1118 statusnet_fetch_contact($uid, $content->user, false);
1123 $postarray['uri'] = $hostname . "::" . $content->id;
1125 if (Item::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
1131 if (!empty($content->in_reply_to_status_id)) {
1133 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1135 $fields = ['uri', 'parent-uri', 'parent'];
1136 $item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
1138 if (!DBA::isResult($item)) {
1139 $item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
1142 if (DBA::isResult($item)) {
1143 $postarray['thr-parent'] = $item['uri'];
1144 $postarray['parent-uri'] = $item['parent-uri'];
1145 $postarray['parent'] = $item['parent'];
1146 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1148 $postarray['thr-parent'] = $postarray['uri'];
1149 $postarray['parent-uri'] = $postarray['uri'];
1150 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1154 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1156 if ($content->user->id == $own_url) {
1157 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1160 if (DBA::isResult($r)) {
1161 $contactid = $r[0]["id"];
1163 $postarray['owner-name'] = $r[0]["name"];
1164 $postarray['owner-link'] = $r[0]["url"];
1165 $postarray['owner-avatar'] = $r[0]["photo"];
1170 // Don't create accounts of people who just comment something
1171 $create_user = false;
1173 $postarray['parent-uri'] = $postarray['uri'];
1174 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1177 if ($contactid == 0) {
1178 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1179 $postarray['owner-name'] = $post->user->name;
1180 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1181 $postarray['owner-avatar'] = $post->user->profile_image_url;
1183 if (($contactid == 0) && !$only_existing_contact) {
1184 $contactid = $self['id'];
1185 } elseif ($contactid <= 0) {
1189 $postarray['contact-id'] = $contactid;
1191 $postarray['verb'] = ACTIVITY_POST;
1193 $postarray['author-name'] = $content->user->name;
1194 $postarray['author-link'] = $content->user->statusnet_profile_url;
1195 $postarray['author-avatar'] = $content->user->profile_image_url;
1197 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1198 $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1200 $postarray['plink'] = $hostname . $content->id;
1201 $postarray['app'] = strip_tags($content->source);
1203 if ($content->user->protected) {
1204 $postarray['private'] = 1;
1205 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1208 $postarray['body'] = HTML::toBBCode($content->statusnet_html);
1210 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1211 $postarray['body'] = $converted["body"];
1212 $postarray['tag'] = $converted["tags"];
1214 $postarray['created'] = DateTimeFormat::utc($content->created_at);
1215 $postarray['edited'] = DateTimeFormat::utc($content->created_at);
1217 if (!empty($content->place->name)) {
1218 $postarray["location"] = $content->place->name;
1221 if (!empty($content->place->full_name)) {
1222 $postarray["location"] = $content->place->full_name;
1225 if (!empty($content->geo->coordinates)) {
1226 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1229 if (!empty($content->coordinates->coordinates)) {
1230 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1233 Logger::log("statusnet_createpost: end", Logger::DEBUG);
1238 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1240 $conversations = [];
1242 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1243 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1244 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1245 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1246 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1247 $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1249 // "create_user" is deactivated, since currently you cannot add users manually by now
1250 $create_user = true;
1252 Logger::log("statusnet_fetchhometimeline: Fetching for user " . $uid, Logger::DEBUG);
1254 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1256 $own_contact = statusnet_fetch_own_contact($a, $uid);
1258 if (empty($own_contact)) {
1262 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1263 intval($own_contact),
1266 if (DBA::isResult($r)) {
1267 $nick = $r[0]["nick"];
1269 Logger::log("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, Logger::DEBUG);
1273 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1276 if (DBA::isResult($r)) {
1279 Logger::log("statusnet_fetchhometimeline: Own contact not found for user " . $uid, Logger::DEBUG);
1283 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1285 if (!DBA::isResult($u)) {
1286 Logger::log("statusnet_fetchhometimeline: Own user not found for user " . $uid, Logger::DEBUG);
1290 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true];
1291 //$parameters["count"] = 200;
1294 // Fetching timeline
1295 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1298 $first_time = ($lastid == "");
1300 if ($lastid != "") {
1301 $parameters["since_id"] = $lastid;
1304 $items = $connection->get('statuses/home_timeline', $parameters);
1306 if (!is_array($items)) {
1307 if (is_object($items) && isset($items->error)) {
1308 $errormsg = $items->error;
1309 } elseif (is_object($items)) {
1310 $errormsg = print_r($items, true);
1311 } elseif (is_string($items) || is_float($items) || is_int($items)) {
1314 $errormsg = "Unknown error";
1317 Logger::log("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, Logger::DEBUG);
1321 $posts = array_reverse($items);
1323 Logger::log("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
1325 if (count($posts)) {
1326 foreach ($posts as $post) {
1328 if ($post->id > $lastid) {
1329 $lastid = $post->id;
1336 if (isset($post->statusnet_conversation_id)) {
1337 if (!isset($conversations[$post->statusnet_conversation_id])) {
1338 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1339 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1342 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1344 if (trim($postarray['body']) == "") {
1348 $item = Item::insert($postarray);
1349 $postarray["id"] = $item;
1351 Logger::log('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1355 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1358 // Fetching mentions
1359 $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1360 $first_time = ($lastid == "");
1362 if ($lastid != "") {
1363 $parameters["since_id"] = $lastid;
1366 $items = $connection->get('statuses/mentions_timeline', $parameters);
1368 if (!is_array($items)) {
1369 Logger::log("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), Logger::DEBUG);
1373 $posts = array_reverse($items);
1375 Logger::log("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
1377 if (count($posts)) {
1378 foreach ($posts as $post) {
1379 if ($post->id > $lastid) {
1380 $lastid = $post->id;
1387 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1389 if (isset($post->statusnet_conversation_id)) {
1390 if (!isset($conversations[$post->statusnet_conversation_id])) {
1391 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1392 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1395 if (trim($postarray['body']) == "") {
1399 $item = Item::insert($postarray);
1401 Logger::log('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1406 PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1409 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1411 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1412 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1413 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1414 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1415 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1416 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1418 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1420 $parameters["count"] = 200;
1422 $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1423 if (is_array($items)) {
1424 $posts = array_reverse($items);
1426 foreach ($posts as $post) {
1427 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1429 if (empty($postarray['body'])) {
1433 $item = Item::insert($postarray);
1434 $postarray["id"] = $item;
1436 Logger::log('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1441 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1443 $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
1445 $URLSearchString = "^\[\]";
1446 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1454 foreach ($matches AS $match) {
1455 $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
1457 Logger::log("statusnet_convertmsg: expanding url " . $match[1], Logger::DEBUG);
1459 $expanded_url = Network::finalUrl($match[1]);
1461 Logger::log("statusnet_convertmsg: fetching data for " . $expanded_url, Logger::DEBUG);
1463 $oembed_data = OEmbed::fetchURL($expanded_url, true);
1465 Logger::log("statusnet_convertmsg: fetching data: done", Logger::DEBUG);
1468 $type = $oembed_data->type;
1471 if ($oembed_data->type == "video") {
1472 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1473 $type = $oembed_data->type;
1474 $footerurl = $expanded_url;
1475 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1477 $body = str_replace($search, $footerlink, $body);
1478 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) {
1479 $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1480 } elseif ($oembed_data->type != "link") {
1481 $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1483 $img_str = Network::fetchUrl($expanded_url, true, $redirects, 4);
1485 $tempfile = tempnam(get_temppath(), "cache");
1486 file_put_contents($tempfile, $img_str);
1487 $mime = mime_content_type($tempfile);
1490 if (substr($mime, 0, 6) == "image/") {
1492 $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body);
1494 $type = $oembed_data->type;
1495 $footerurl = $expanded_url;
1496 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1498 $body = str_replace($search, $footerlink, $body);
1503 if ($footerurl != "") {
1504 $footer = add_page_info($footerurl);
1507 if (($footerlink != "") && (trim($footer) != "")) {
1508 $removedlink = trim(str_replace($footerlink, "", $body));
1510 if (($removedlink == "") || strstr($body, $removedlink)) {
1511 $body = $removedlink;
1519 return ["body" => $body, "tags" => ""];
1524 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1526 foreach ($matches as $mtch) {
1527 if (strlen($str_tags)) {
1531 if ($mtch[1] == "#") {
1532 // Replacing the hash tags that are directed to the GNU Social server with internal links
1533 $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1534 $frdchash = '#[url=' . $a->getBaseURL() . '/search?tag=' . $mtch[3] . ']' . $mtch[3] . '[/url]';
1535 $body = str_replace($snhash, $frdchash, $body);
1537 $str_tags .= $frdchash;
1539 $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1542 // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1543 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1547 return ["body" => $body, "tags" => $str_tags];
1550 function statusnet_fetch_own_contact(App $a, $uid)
1552 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1553 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1554 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1555 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1556 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1557 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1561 if ($own_url == "") {
1562 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1564 // Fetching user data
1565 $user = $connection->get('account/verify_credentials');
1571 PConfig::set($uid, 'statusnet', 'own_url', Strings::normaliseLink($user->statusnet_profile_url));
1573 $contact_id = statusnet_fetch_contact($uid, $user, true);
1575 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1576 intval($uid), DBA::escape($own_url));
1577 if (DBA::isResult($r)) {
1578 $contact_id = $r[0]["id"];
1580 PConfig::delete($uid, 'statusnet', 'own_url');
1586 function statusnet_is_retweet(App $a, $uid, $body)
1588 $body = trim($body);
1590 // Skip if it isn't a pure repeated messages
1591 // Does it start with a share?
1592 if (strpos($body, "[share") > 0) {
1596 // Does it end with a share?
1597 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1601 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1602 // Skip if there is no shared message in there
1603 if ($body == $attributes) {
1608 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1609 if (!empty($matches[1])) {
1610 $link = $matches[1];
1613 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1614 if (!empty($matches[1])) {
1615 $link = $matches[1];
1618 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1619 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1620 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1621 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1622 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1623 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1625 $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link);
1631 Logger::log('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, Logger::DEBUG);
1633 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1635 $result = $connection->post('statuses/retweet/' . $id);
1637 Logger::log('statusnet_is_retweet: result ' . print_r($result, true), Logger::DEBUG);
1639 return isset($result->id);