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 require_once 'include/enotify.php';
41 use CodebirdSN\CodebirdSN;
43 use Friendica\Content\OEmbed;
44 use Friendica\Content\Text\HTML;
45 use Friendica\Content\Text\Plaintext;
46 use Friendica\Core\Config;
47 use Friendica\Core\Hook;
48 use Friendica\Core\L10n;
49 use Friendica\Core\Logger;
50 use Friendica\Core\PConfig;
51 use Friendica\Core\Protocol;
52 use Friendica\Core\Renderer;
53 use Friendica\Database\DBA;
54 use Friendica\Model\Contact;
55 use Friendica\Model\GContact;
56 use Friendica\Model\Group;
57 use Friendica\Model\Item;
58 use Friendica\Model\ItemContent;
59 use Friendica\Model\Photo;
60 use Friendica\Model\User;
61 use Friendica\Util\DateTimeFormat;
62 use Friendica\Util\Network;
63 use Friendica\Util\Strings;
65 function statusnet_install()
67 // we need some hooks, for the configuration and for sending tweets
68 Hook::register('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
69 Hook::register('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
70 Hook::register('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
71 Hook::register('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
72 Hook::register('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
73 Hook::register('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
74 Hook::register('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
75 Hook::register('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
76 Hook::register('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
77 Logger::log("installed GNU Social");
80 function statusnet_uninstall()
82 Hook::unregister('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
83 Hook::unregister('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
84 Hook::unregister('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
85 Hook::unregister('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
86 Hook::unregister('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
87 Hook::unregister('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
88 Hook::unregister('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
89 Hook::unregister('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
90 Hook::unregister('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
92 // old setting - remove only
93 Hook::unregister('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
94 Hook::unregister('addon_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
95 Hook::unregister('addon_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
98 function statusnet_check_item_notification(App $a, &$notification_data)
100 if (PConfig::get($notification_data["uid"], 'statusnet', 'post')) {
101 $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
105 function statusnet_jot_nets(App $a, &$b)
111 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
112 if (intval($statusnet_post) == 1) {
113 $statusnet_defpost = PConfig::get(local_user(), 'statusnet', 'post_by_default');
114 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
115 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
116 . L10n::t('Post to GNU Social') . '</div>';
120 function statusnet_settings_post(App $a, $post)
125 // don't check GNU Social settings if GNU Social submit button is not clicked
126 if (empty($_POST['statusnet-submit'])) {
130 if (isset($_POST['statusnet-disconnect'])) {
132 * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration
134 PConfig::delete(local_user(), 'statusnet', 'consumerkey');
135 PConfig::delete(local_user(), 'statusnet', 'consumersecret');
136 PConfig::delete(local_user(), 'statusnet', 'post');
137 PConfig::delete(local_user(), 'statusnet', 'post_by_default');
138 PConfig::delete(local_user(), 'statusnet', 'oauthtoken');
139 PConfig::delete(local_user(), 'statusnet', 'oauthsecret');
140 PConfig::delete(local_user(), 'statusnet', 'baseapi');
141 PConfig::delete(local_user(), 'statusnet', 'lastid');
142 PConfig::delete(local_user(), 'statusnet', 'mirror_posts');
143 PConfig::delete(local_user(), 'statusnet', 'import');
144 PConfig::delete(local_user(), 'statusnet', 'create_user');
145 PConfig::delete(local_user(), 'statusnet', 'own_url');
147 if (isset($_POST['statusnet-preconf-apiurl'])) {
149 * If the user used one of the preconfigured GNU Social server credentials
150 * use them. All the data are available in the global config.
151 * Check the API Url never the less and blame the admin if it's not working ^^
153 $globalsn = Config::get('statusnet', 'sites');
154 foreach ($globalsn as $asn) {
155 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
156 $apibase = $asn['apiurl'];
157 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
158 if (strlen($c) > 0) {
159 PConfig::set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey']);
160 PConfig::set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret']);
161 PConfig::set(local_user(), 'statusnet', 'baseapi', $asn['apiurl']);
162 //PConfig::set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
164 notice(L10n::t('Please contact your site administrator.<br />The provided API URL is not valid.') . EOL . $asn['apiurl'] . EOL);
168 $a->internalRedirect('settings/connectors');
170 if (isset($_POST['statusnet-consumersecret'])) {
171 // check if we can reach the API of the GNU Social server
172 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
173 // resign quickly after this one try to fix the path ;-)
174 $apibase = $_POST['statusnet-baseapi'];
175 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
176 if (strlen($c) > 0) {
177 // ok the API path is correct, let's save the settings
178 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
179 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
180 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
181 //PConfig::set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
183 // the API path is not correct, maybe missing trailing / ?
184 $apibase = $apibase . '/';
185 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
186 if (strlen($c) > 0) {
187 // ok the API path is now correct, let's save the settings
188 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
189 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
190 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
192 // still not the correct API base, let's do noting
193 notice(L10n::t('We could not contact the GNU Social API with the Path you entered.') . EOL);
196 $a->internalRedirect('settings/connectors');
198 if (isset($_POST['statusnet-pin'])) {
199 // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
200 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
201 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
202 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
203 // the token and secret for which the PIN was generated were hidden in the settings
204 // form as token and token2, we need a new connection to GNU Social using these token
205 // and secret to request a Access Token with the PIN
206 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
207 $token = $connection->getAccessToken($_POST['statusnet-pin']);
208 // ok, now that we have the Access Token, save them in the user config
209 PConfig::set(local_user(), 'statusnet', 'oauthtoken', $token['oauth_token']);
210 PConfig::set(local_user(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
211 PConfig::set(local_user(), 'statusnet', 'post', 1);
212 PConfig::set(local_user(), 'statusnet', 'post_taglinks', 1);
213 // reload the Addon Settings page, if we don't do it see Bug #42
214 $a->internalRedirect('settings/connectors');
216 // if no PIN is supplied in the POST variables, the user has changed the setting
217 // to post a dent for every new __public__ posting to the wall
218 PConfig::set(local_user(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
219 PConfig::set(local_user(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
220 PConfig::set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
221 PConfig::set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
222 PConfig::set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
224 if (!intval($_POST['statusnet-mirror']))
225 PConfig::delete(local_user(), 'statusnet', 'lastid');
227 info(L10n::t('GNU Social settings updated.') . EOL);
234 function statusnet_settings(App $a, &$s)
239 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
241 * 1) Check that we have a base api url and a consumer key & secret
242 * 2) If no OAuthtoken & stuff is present, generate button to get some
243 * allow the user to cancel the connection process at this step
244 * 3) Checkbox for "Send public notices (respect size limitation)
246 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
247 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
248 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
249 $otoken = PConfig::get(local_user(), 'statusnet', 'oauthtoken');
250 $osecret = PConfig::get(local_user(), 'statusnet', 'oauthsecret');
251 $enabled = PConfig::get(local_user(), 'statusnet', 'post');
252 $checked = (($enabled) ? ' checked="checked" ' : '');
253 $defenabled = PConfig::get(local_user(), 'statusnet', 'post_by_default');
254 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
255 $mirrorenabled = PConfig::get(local_user(), 'statusnet', 'mirror_posts');
256 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
257 $import = PConfig::get(local_user(), 'statusnet', 'import');
258 $importselected = ["", "", ""];
259 $importselected[$import] = ' selected="selected"';
260 //$importenabled = PConfig::get(local_user(),'statusnet','import');
261 //$importchecked = (($importenabled) ? ' checked="checked" ' : '');
262 $create_userenabled = PConfig::get(local_user(), 'statusnet', 'create_user');
263 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
265 $css = (($enabled) ? '' : '-disabled');
267 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
268 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . L10n::t('GNU Social Import/Export/Mirror') . '</h3>';
270 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
271 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
272 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . L10n::t('GNU Social Import/Export/Mirror') . '</h3>';
275 if ((!$ckey) && (!$csecret)) {
279 $globalsn = Config::get('statusnet', 'sites');
281 * lets check if we have one or more globally configured GNU Social
282 * server OAuth credentials in the configuration. If so offer them
283 * with a little explanation to the user as choice - otherwise
284 * ignore this option entirely.
286 if (!$globalsn == null) {
287 $s .= '<h4>' . L10n::t('Globally Available GNU Social OAuthKeys') . '</h4>';
288 $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>';
289 $s .= '<div id="statusnet-preconf-wrapper">';
290 foreach ($globalsn as $asn) {
291 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="' . $asn['apiurl'] . '">' . $asn['sitename'] . '<br />';
293 $s .= '<p></p><div class="clear"></div></div>';
294 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
296 $s .= '<h4>' . L10n::t('Provide your own OAuth Credentials') . '</h4>';
297 $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>';
298 $s .= '<div id="statusnet-consumer-wrapper">';
299 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">' . L10n::t('OAuth Consumer Key') . '</label>';
300 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
301 $s .= '<div class="clear"></div>';
302 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">' . L10n::t('OAuth Consumer Secret') . '</label>';
303 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
304 $s .= '<div class="clear"></div>';
305 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">' . L10n::t("Base API Path \x28remember the trailing /\x29") . '</label>';
306 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
307 $s .= '<div class="clear"></div>';
308 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.L10n::t('GNU Socialapplication name').'</label>';
309 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
310 $s .= '<p></p><div class="clear"></div>';
311 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
315 * ok we have a consumer key pair now look into the OAuth stuff
317 if ((!$otoken) && (!$osecret)) {
319 * the user has not yet connected the account to GNU Social
320 * get a temporary OAuth key/secret pair and display a button with
321 * which the user can request a PIN to connect the account to a
322 * account at GNU Social
324 $connection = new StatusNetOAuth($api, $ckey, $csecret);
325 $request_token = $connection->getRequestToken('oob');
326 $token = $request_token['oauth_token'];
328 * make some nice form
330 $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>';
331 $s .= '<a href="' . $connection->getAuthorizeURL($token, False) . '" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="' . L10n::t('Log in with GNU Social') . '"></a>';
332 $s .= '<div id="statusnet-pin-wrapper">';
333 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">' . L10n::t('Copy the security code from GNU Social here') . '</label>';
334 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
335 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="' . $token . '" />';
336 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="' . $request_token['oauth_token_secret'] . '" />';
337 $s .= '</div><div class="clear"></div>';
338 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
339 $s .= '<h4>' . L10n::t('Cancel Connection Process') . '</h4>';
340 $s .= '<div id="statusnet-cancel-wrapper">';
341 $s .= '<p>' . L10n::t('Current GNU Social API is') . ': ' . $api . '</p>';
342 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">' . L10n::t('Cancel GNU Social Connection') . '</label>';
343 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
344 $s .= '</div><div class="clear"></div>';
345 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
348 * we have an OAuth key / secret pair for the user
349 * so let's give a chance to disable the postings to GNU Social
351 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
352 $details = $connection->get('account/verify_credentials');
353 if (!empty($details)) {
354 $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>';
356 $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>';
357 if ($a->user['hidewall']) {
358 $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>';
360 $s .= '<div id="statusnet-enable-wrapper">';
361 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">' . L10n::t('Allow posting to GNU Social') . '</label>';
362 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
363 $s .= '<div class="clear"></div>';
364 $s .= '<label id="statusnet-default-label" for="statusnet-default">' . L10n::t('Send public postings to GNU Social by default') . '</label>';
365 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
366 $s .= '<div class="clear"></div>';
368 $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>';
369 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" ' . $mirrorchecked . '/>';
371 $s .= '<div class="clear"></div>';
374 $s .= '<label id="statusnet-import-label" for="statusnet-import">' . L10n::t('Import the remote timeline') . '</label>';
375 //$s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
377 $s .= '<select name="statusnet-import" id="statusnet-import" />';
378 $s .= '<option value="0" ' . $importselected[0] . '>' . L10n::t("Disabled") . '</option>';
379 $s .= '<option value="1" ' . $importselected[1] . '>' . L10n::t("Full Timeline") . '</option>';
380 $s .= '<option value="2" ' . $importselected[2] . '>' . L10n::t("Only Mentions") . '</option>';
382 $s .= '<div class="clear"></div>';
384 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.L10n::t('Automatically create contacts').'</label>';
385 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
386 $s .= '<div class="clear"></div>';
388 $s .= '<div id="statusnet-disconnect-wrapper">';
389 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">' . L10n::t('Clear OAuth configuration') . '</label>';
390 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
391 $s .= '</div><div class="clear"></div>';
392 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
395 $s .= '</div><div class="clear"></div>';
398 function statusnet_hook_fork(App $a, array &$b)
400 if ($b['name'] != 'notifier_normal') {
406 // Deleting and editing is not supported by the addon
407 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
408 $b['execute'] = false;
412 // if post comes from GNU Social don't send it back
413 if ($post['extid'] == Protocol::STATUSNET) {
414 $b['execute'] = false;
418 if ($post['app'] == 'StatusNet') {
419 $b['execute'] = false;
423 if (PConfig::get($post['uid'], 'statusnet', 'import')) {
424 // Don't fork if it isn't a reply to a GNU Social post
425 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::STATUSNET])) {
426 Logger::log('No GNU Social parent found for item ' . $post['id']);
427 $b['execute'] = false;
431 // Comments are never exported when we don't import the GNU Social timeline
432 if (!strstr($post['postopts'], 'statusnet') || ($post['parent'] != $post['id']) || $post['private']) {
433 $b['execute'] = false;
439 function statusnet_post_local(App $a, &$b)
445 if (!local_user() || (local_user() != $b['uid'])) {
449 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
450 $statusnet_enable = (($statusnet_post && !empty($_REQUEST['statusnet_enable'])) ? intval($_REQUEST['statusnet_enable']) : 0);
452 // if API is used, default to the chosen settings
453 if ($b['api_source'] && intval(PConfig::get(local_user(), 'statusnet', 'post_by_default'))) {
454 $statusnet_enable = 1;
457 if (!$statusnet_enable) {
461 if (strlen($b['postopts'])) {
462 $b['postopts'] .= ',';
465 $b['postopts'] .= 'statusnet';
468 function statusnet_action(App $a, $uid, $pid, $action)
470 $api = PConfig::get($uid, 'statusnet', 'baseapi');
471 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
472 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
473 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
474 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
476 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
478 Logger::log("statusnet_action '" . $action . "' ID: " . $pid, Logger::DATA);
482 $result = $connection->post("statuses/destroy/" . $pid);
485 $result = $connection->post("favorites/create/" . $pid);
488 $result = $connection->post("favorites/destroy/" . $pid);
491 Logger::log("statusnet_action '" . $action . "' send, result: " . print_r($result, true), Logger::DEBUG);
494 function statusnet_post_hook(App $a, &$b)
499 if (!PConfig::get($b["uid"], 'statusnet', 'import')) {
500 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
504 $api = PConfig::get($b["uid"], 'statusnet', 'baseapi');
505 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
507 if ($b['parent'] != $b['id']) {
508 Logger::log("statusnet_post_hook: parameter " . print_r($b, true), Logger::DATA);
510 // Looking if its a reply to a GNU Social post
511 $hostlength = strlen($hostname) + 2;
512 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) {
513 Logger::log("statusnet_post_hook: no GNU Social post " . $b["parent"]);
517 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
518 $orig_post = Item::selectFirst(['author-link', 'uri'], $condition);
519 if (!DBA::isResult($orig_post)) {
520 Logger::log("statusnet_post_hook: no parent found " . $b["thr-parent"]);
526 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
528 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
529 $nicknameplain = "@" . $nick;
531 Logger::log("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], Logger::DEBUG);
532 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
533 $b["body"] = $nickname . " " . $b["body"];
536 Logger::log("statusnet_post_hook: parent found " . print_r($orig_post, true), Logger::DEBUG);
540 if ($b['private'] || !strstr($b['postopts'], 'statusnet')) {
544 // Dont't post if the post doesn't belong to us.
545 // This is a check for forum postings
546 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
547 if ($b['contact-id'] != $self['id']) {
552 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
553 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
556 if ($b['verb'] == ACTIVITY_LIKE) {
557 Logger::log("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), Logger::DEBUG);
559 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
561 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
565 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
569 // if posts comes from GNU Social don't send it back
570 if ($b['extid'] == Protocol::STATUSNET) {
574 if ($b['app'] == "StatusNet") {
578 Logger::log('GNU Socialpost invoked');
580 PConfig::load($b['uid'], 'statusnet');
582 $api = PConfig::get($b['uid'], 'statusnet', 'baseapi');
583 $ckey = PConfig::get($b['uid'], 'statusnet', 'consumerkey');
584 $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret');
585 $otoken = PConfig::get($b['uid'], 'statusnet', 'oauthtoken');
586 $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret');
588 if ($ckey && $csecret && $otoken && $osecret) {
589 // If it's a repeated message from GNU Social then do a native retweet and exit
590 if (statusnet_is_retweet($a, $b['uid'], $b['body'])) {
594 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
595 $max_char = $dent->get_maxlength(); // max. length for a dent
597 PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char);
600 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 7);
601 $msg = $msgarr["text"];
603 if (($msg == "") && isset($msgarr["title"]))
604 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
608 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
609 $msg .= " \n" . $msgarr["url"];
610 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
611 $image = $msgarr["image"];
615 $img_str = Network::fetchUrl($image);
616 $tempfile = tempnam(get_temppath(), "cache");
617 file_put_contents($tempfile, $img_str);
618 $postdata = ["status" => $msg, "media[]" => $tempfile];
620 $postdata = ["status" => $msg];
623 // and now send it :-)
626 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
627 Logger::log('statusnet_post send reply ' . print_r($postdata, true), Logger::DEBUG);
630 // New code that is able to post pictures
631 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
632 $cb = CodebirdSN::getInstance();
633 $cb->setAPIEndpoint($api);
634 $cb->setConsumerKey($ckey, $csecret);
635 $cb->setToken($otoken, $osecret);
636 $result = $cb->statuses_update($postdata);
637 //$result = $dent->post('statuses/update', $postdata);
638 Logger::log('statusnet_post send, result: ' . print_r($result, true) .
639 "\nmessage: " . $msg . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true), Logger::DEBUG);
641 if (!empty($result->source)) {
642 PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
645 if (!empty($result->error)) {
646 Logger::log('Send to GNU Social failed: "' . $result->error . '"');
647 } elseif ($iscomment) {
648 Logger::log('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
649 Item::update(['extid' => $hostname . "::" . $result->id, 'body' => $result->text], ['id' => $b['id']]);
652 if ($tempfile != "") {
658 function statusnet_addon_admin_post(App $a)
662 foreach ($_POST['sitename'] as $id => $sitename) {
663 $sitename = trim($sitename);
664 $apiurl = trim($_POST['apiurl'][$id]);
665 if (!(substr($apiurl, -1) == '/')) {
666 $apiurl = $apiurl . '/';
668 $secret = trim($_POST['secret'][$id]);
669 $key = trim($_POST['key'][$id]);
670 //$applicationname = (!empty($_POST['applicationname']) ? Strings::escapeTags(trim($_POST['applicationname'][$id])):'');
671 if ($sitename != "" &&
675 empty($_POST['delete'][$id])) {
678 'sitename' => $sitename,
680 'consumersecret' => $secret,
681 'consumerkey' => $key,
682 //'applicationname' => $applicationname
687 $sites = Config::set('statusnet', 'sites', $sites);
690 function statusnet_addon_admin(App $a, &$o)
692 $sites = Config::get('statusnet', 'sites');
694 if (is_array($sites)) {
695 foreach ($sites as $id => $s) {
697 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""],
698 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], L10n::t("Base API Path \x28remember the trailing /\x29")],
699 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""],
700 'key' => ["key[$id]", "Key", $s['consumerkey'], ""],
701 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
702 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"],
706 /* empty form to add new site */
707 $id = count($sitesform);
709 'sitename' => ["sitename[$id]", L10n::t("Site name"), "", ""],
710 'apiurl' => ["apiurl[$id]", "Api url", "", L10n::t("Base API Path \x28remember the trailing /\x29")],
711 'secret' => ["secret[$id]", L10n::t("Consumer Secret"), "", ""],
712 'key' => ["key[$id]", L10n::t("Consumer Key"), "", ""],
713 //'applicationname' => Array("applicationname[$id]", L10n::t("Application name"), "", ""),
716 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/statusnet/");
717 $o = Renderer::replaceMacros($t, [
718 '$submit' => L10n::t('Save Settings'),
719 '$sites' => $sitesform,
723 function statusnet_prepare_body(App $a, &$b)
725 if ($b["item"]["network"] != Protocol::STATUSNET) {
730 $max_char = PConfig::get(local_user(), 'statusnet', 'max_char');
731 if (intval($max_char) == 0) {
736 $item["plink"] = $a->getBaseURL() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
738 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
739 $orig_post = Item::selectFirst(['author-link', 'uri'], $condition);
740 if (DBA::isResult($orig_post)) {
741 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
743 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
744 $nicknameplain = "@" . $nick;
746 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
747 $item["body"] = $nickname . " " . $item["body"];
751 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 7);
752 $msg = $msgarr["text"];
754 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
755 $msg .= " " . $msgarr["url"];
758 if (isset($msgarr["image"])) {
759 $msg .= " " . $msgarr["image"];
762 $b['html'] = nl2br(htmlspecialchars($msg));
766 function statusnet_cron(App $a, $b)
768 $last = Config::get('statusnet', 'last_poll');
770 $poll_interval = intval(Config::get('statusnet', 'poll_interval'));
771 if (!$poll_interval) {
772 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
776 $next = $last + ($poll_interval * 60);
777 if ($next > time()) {
778 Logger::log('statusnet: poll intervall not reached');
782 Logger::log('statusnet: cron_start');
784 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
785 if (DBA::isResult($r)) {
786 foreach ($r as $rr) {
787 Logger::log('statusnet: fetching for user ' . $rr['uid']);
788 statusnet_fetchtimeline($a, $rr['uid']);
792 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
793 if ($abandon_days < 1) {
797 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
799 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
800 if (DBA::isResult($r)) {
801 foreach ($r as $rr) {
802 if ($abandon_days != 0) {
803 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
804 if (!DBA::isResult($user)) {
805 Logger::log('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
810 Logger::log('statusnet: importing timeline from user ' . $rr['uid']);
811 statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
815 Logger::log('statusnet: cron_end');
817 Config::set('statusnet', 'last_poll', time());
820 function statusnet_fetchtimeline(App $a, $uid)
822 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
823 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
824 $api = PConfig::get($uid, 'statusnet', 'baseapi');
825 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
826 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
827 $lastid = PConfig::get($uid, 'statusnet', 'lastid');
829 require_once 'mod/item.php';
830 require_once 'include/items.php';
832 // get the application name for the SN app
833 // 1st try personal config, then system config and fallback to the
834 // hostname of the node if neither one is set.
835 $application_name = PConfig::get($uid, 'statusnet', 'application_name');
836 if ($application_name == "") {
837 $application_name = Config::get('statusnet', 'application_name');
839 if ($application_name == "") {
840 $application_name = $a->getHostName();
843 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
845 $parameters = ["exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false];
847 $first_time = ($lastid == "");
850 $parameters["since_id"] = $lastid;
853 $items = $connection->get('statuses/user_timeline', $parameters);
855 if (!is_array($items)) {
859 $posts = array_reverse($items);
862 foreach ($posts as $post) {
863 if ($post->id > $lastid)
870 if ($post->source == "activity") {
874 if (!empty($post->retweeted_status)) {
878 if ($post->in_reply_to_status_id != "") {
882 if (!stristr($post->source, $application_name)) {
883 $_SESSION["authenticated"] = true;
884 $_SESSION["uid"] = $uid;
887 $_REQUEST["api_source"] = true;
888 $_REQUEST["profile_uid"] = $uid;
889 //$_REQUEST["source"] = "StatusNet";
890 $_REQUEST["source"] = $post->source;
891 $_REQUEST["extid"] = Protocol::STATUSNET;
893 if (isset($post->id)) {
894 $_REQUEST['message_id'] = Item::newURI($uid, Protocol::STATUSNET . ":" . $post->id);
897 //$_REQUEST["date"] = $post->created_at;
899 $_REQUEST["title"] = "";
901 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
902 if (is_string($post->place->name)) {
903 $_REQUEST["location"] = $post->place->name;
906 if (is_string($post->place->full_name)) {
907 $_REQUEST["location"] = $post->place->full_name;
910 if (is_array($post->geo->coordinates)) {
911 $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
914 if (is_array($post->coordinates->coordinates)) {
915 $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
918 //print_r($_REQUEST);
919 if ($_REQUEST["body"] != "") {
920 Logger::log('statusnet: posting for user ' . $uid);
927 PConfig::set($uid, 'statusnet', 'lastid', $lastid);
930 function statusnet_address($contact)
932 $hostname = Strings::normaliseLink($contact->statusnet_profile_url);
933 $nickname = $contact->screen_name;
935 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
937 $address = $contact->screen_name . "@" . $hostname;
942 function statusnet_fetch_contact($uid, $contact, $create_user)
944 if ($contact->statusnet_profile_url == "") {
948 GContact::update(["url" => $contact->statusnet_profile_url,
949 "network" => Protocol::STATUSNET, "photo" => $contact->profile_image_url,
950 "name" => $contact->name, "nick" => $contact->screen_name,
951 "location" => $contact->location, "about" => $contact->description,
952 "addr" => statusnet_address($contact), "generation" => 3]);
954 $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));
956 if (!DBA::isResult($r) && !$create_user) {
960 if (DBA::isResult($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
961 Logger::log("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", Logger::DEBUG);
965 if (!DBA::isResult($r)) {
966 // create contact record
967 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
968 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
969 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
970 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
972 DBA::escape(DateTimeFormat::utcNow()),
973 DBA::escape($contact->statusnet_profile_url),
974 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
975 DBA::escape(statusnet_address($contact)),
976 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
979 DBA::escape($contact->name),
980 DBA::escape($contact->screen_name),
981 DBA::escape($contact->profile_image_url),
982 DBA::escape(Protocol::STATUSNET),
983 intval(Contact::FRIEND),
985 DBA::escape($contact->location),
986 DBA::escape($contact->description),
990 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
991 DBA::escape($contact->statusnet_profile_url),
993 DBA::escape(Protocol::STATUSNET));
995 if (!DBA::isResult($r)) {
999 $contact_id = $r[0]['id'];
1001 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1003 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
1005 q("UPDATE `contact` SET `photo` = '%s',
1008 `avatar-date` = '%s'
1010 DBA::escape($photos[0]),
1011 DBA::escape($photos[1]),
1012 DBA::escape($photos[2]),
1013 DBA::escape(DateTimeFormat::utcNow()),
1017 // update profile photos once every two weeks as we have no notification of when they change.
1018 //$update_photo = (($r[0]['avatar-date'] < DateTimeFormat::convert('now -2 days', '', '', )) ? true : false);
1019 $update_photo = ($r[0]['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1021 // check that we have all the photos, this has been known to fail on occasion
1022 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1023 Logger::log("statusnet_fetch_contact: Updating contact " . $contact->screen_name, Logger::DEBUG);
1025 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1027 q("UPDATE `contact` SET `photo` = '%s',
1032 `avatar-date` = '%s',
1041 DBA::escape($photos[0]),
1042 DBA::escape($photos[1]),
1043 DBA::escape($photos[2]),
1044 DBA::escape(DateTimeFormat::utcNow()),
1045 DBA::escape(DateTimeFormat::utcNow()),
1046 DBA::escape(DateTimeFormat::utcNow()),
1047 DBA::escape($contact->statusnet_profile_url),
1048 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
1049 DBA::escape(statusnet_address($contact)),
1050 DBA::escape($contact->name),
1051 DBA::escape($contact->screen_name),
1052 DBA::escape($contact->location),
1053 DBA::escape($contact->description),
1062 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1064 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1065 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1066 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1067 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1068 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1070 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
1072 $cb = CodebirdSN::getInstance();
1073 $cb->setConsumerKey($ckey, $csecret);
1074 $cb->setToken($otoken, $osecret);
1076 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1079 if (DBA::isResult($r)) {
1087 if ($screen_name != "") {
1088 $parameters["screen_name"] = $screen_name;
1091 if ($user_id != "") {
1092 $parameters["user_id"] = $user_id;
1095 // Fetching user data
1096 $user = $cb->users_show($parameters);
1098 if (!is_object($user)) {
1102 $contact_id = statusnet_fetch_contact($uid, $user, true);
1107 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1109 Logger::log("statusnet_createpost: start", Logger::DEBUG);
1111 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1112 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1115 $postarray['network'] = Protocol::STATUSNET;
1116 $postarray['uid'] = $uid;
1117 $postarray['wall'] = 0;
1119 if (!empty($post->retweeted_status)) {
1120 $content = $post->retweeted_status;
1121 statusnet_fetch_contact($uid, $content->user, false);
1126 $postarray['uri'] = $hostname . "::" . $content->id;
1128 if (Item::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
1134 if (!empty($content->in_reply_to_status_id)) {
1136 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1138 $fields = ['uri', 'parent-uri', 'parent'];
1139 $item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
1141 if (!DBA::isResult($item)) {
1142 $item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
1145 if (DBA::isResult($item)) {
1146 $postarray['thr-parent'] = $item['uri'];
1147 $postarray['parent-uri'] = $item['parent-uri'];
1148 $postarray['parent'] = $item['parent'];
1149 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1151 $postarray['thr-parent'] = $postarray['uri'];
1152 $postarray['parent-uri'] = $postarray['uri'];
1153 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1157 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1159 if ($content->user->id == $own_url) {
1160 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1163 if (DBA::isResult($r)) {
1164 $contactid = $r[0]["id"];
1166 $postarray['owner-name'] = $r[0]["name"];
1167 $postarray['owner-link'] = $r[0]["url"];
1168 $postarray['owner-avatar'] = $r[0]["photo"];
1173 // Don't create accounts of people who just comment something
1174 $create_user = false;
1176 $postarray['parent-uri'] = $postarray['uri'];
1177 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1180 if ($contactid == 0) {
1181 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1182 $postarray['owner-name'] = $post->user->name;
1183 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1184 $postarray['owner-avatar'] = $post->user->profile_image_url;
1186 if (($contactid == 0) && !$only_existing_contact) {
1187 $contactid = $self['id'];
1188 } elseif ($contactid <= 0) {
1192 $postarray['contact-id'] = $contactid;
1194 $postarray['verb'] = ACTIVITY_POST;
1196 $postarray['author-name'] = $content->user->name;
1197 $postarray['author-link'] = $content->user->statusnet_profile_url;
1198 $postarray['author-avatar'] = $content->user->profile_image_url;
1200 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1201 $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1203 $postarray['plink'] = $hostname . $content->id;
1204 $postarray['app'] = strip_tags($content->source);
1206 if ($content->user->protected) {
1207 $postarray['private'] = 1;
1208 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1211 $postarray['body'] = HTML::toBBCode($content->statusnet_html);
1213 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1214 $postarray['body'] = $converted["body"];
1215 $postarray['tag'] = $converted["tags"];
1217 $postarray['created'] = DateTimeFormat::utc($content->created_at);
1218 $postarray['edited'] = DateTimeFormat::utc($content->created_at);
1220 if (!empty($content->place->name)) {
1221 $postarray["location"] = $content->place->name;
1224 if (!empty($content->place->full_name)) {
1225 $postarray["location"] = $content->place->full_name;
1228 if (!empty($content->geo->coordinates)) {
1229 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1232 if (!empty($content->coordinates->coordinates)) {
1233 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1236 Logger::log("statusnet_createpost: end", Logger::DEBUG);
1241 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1243 $conversations = [];
1245 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1246 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1247 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1248 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1249 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1250 $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1252 // "create_user" is deactivated, since currently you cannot add users manually by now
1253 $create_user = true;
1255 Logger::log("statusnet_fetchhometimeline: Fetching for user " . $uid, Logger::DEBUG);
1257 require_once 'include/items.php';
1259 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1261 $own_contact = statusnet_fetch_own_contact($a, $uid);
1263 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1264 intval($own_contact),
1267 if (DBA::isResult($r)) {
1268 $nick = $r[0]["nick"];
1270 Logger::log("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, Logger::DEBUG);
1274 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1277 if (DBA::isResult($r)) {
1280 Logger::log("statusnet_fetchhometimeline: Own contact not found for user " . $uid, Logger::DEBUG);
1284 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1286 if (!DBA::isResult($u)) {
1287 Logger::log("statusnet_fetchhometimeline: Own user not found for user " . $uid, Logger::DEBUG);
1291 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true];
1292 //$parameters["count"] = 200;
1295 // Fetching timeline
1296 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1299 $first_time = ($lastid == "");
1301 if ($lastid != "") {
1302 $parameters["since_id"] = $lastid;
1305 $items = $connection->get('statuses/home_timeline', $parameters);
1307 if (!is_array($items)) {
1308 if (is_object($items) && isset($items->error)) {
1309 $errormsg = $items->error;
1310 } elseif (is_object($items)) {
1311 $errormsg = print_r($items, true);
1312 } elseif (is_string($items) || is_float($items) || is_int($items)) {
1315 $errormsg = "Unknown error";
1318 Logger::log("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, Logger::DEBUG);
1322 $posts = array_reverse($items);
1324 Logger::log("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
1326 if (count($posts)) {
1327 foreach ($posts as $post) {
1329 if ($post->id > $lastid) {
1330 $lastid = $post->id;
1337 if (isset($post->statusnet_conversation_id)) {
1338 if (!isset($conversations[$post->statusnet_conversation_id])) {
1339 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1340 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1343 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1345 if (trim($postarray['body']) == "") {
1349 $item = Item::insert($postarray);
1350 $postarray["id"] = $item;
1352 Logger::log('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1356 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1359 // Fetching mentions
1360 $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1361 $first_time = ($lastid == "");
1363 if ($lastid != "") {
1364 $parameters["since_id"] = $lastid;
1367 $items = $connection->get('statuses/mentions_timeline', $parameters);
1369 if (!is_array($items)) {
1370 Logger::log("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), Logger::DEBUG);
1374 $posts = array_reverse($items);
1376 Logger::log("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
1378 if (count($posts)) {
1379 foreach ($posts as $post) {
1380 if ($post->id > $lastid) {
1381 $lastid = $post->id;
1388 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1390 if (isset($post->statusnet_conversation_id)) {
1391 if (!isset($conversations[$post->statusnet_conversation_id])) {
1392 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1393 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1396 if (trim($postarray['body']) == "") {
1400 $item = Item::insert($postarray);
1402 Logger::log('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1407 PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1410 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1412 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1413 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1414 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1415 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1416 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1417 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1419 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1421 $parameters["count"] = 200;
1423 $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1424 if (is_array($items)) {
1425 $posts = array_reverse($items);
1427 foreach ($posts as $post) {
1428 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1430 if (empty($postarray['body'])) {
1434 $item = Item::insert($postarray);
1435 $postarray["id"] = $item;
1437 Logger::log('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1442 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1444 require_once "include/items.php";
1446 $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
1448 $URLSearchString = "^\[\]";
1449 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1457 foreach ($matches AS $match) {
1458 $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
1460 Logger::log("statusnet_convertmsg: expanding url " . $match[1], Logger::DEBUG);
1462 $expanded_url = Network::finalUrl($match[1]);
1464 Logger::log("statusnet_convertmsg: fetching data for " . $expanded_url, Logger::DEBUG);
1466 $oembed_data = OEmbed::fetchURL($expanded_url, true);
1468 Logger::log("statusnet_convertmsg: fetching data: done", Logger::DEBUG);
1471 $type = $oembed_data->type;
1474 if ($oembed_data->type == "video") {
1475 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1476 $type = $oembed_data->type;
1477 $footerurl = $expanded_url;
1478 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1480 $body = str_replace($search, $footerlink, $body);
1481 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) {
1482 $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1483 } elseif ($oembed_data->type != "link") {
1484 $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1486 $img_str = Network::fetchUrl($expanded_url, true, $redirects, 4);
1488 $tempfile = tempnam(get_temppath(), "cache");
1489 file_put_contents($tempfile, $img_str);
1490 $mime = mime_content_type($tempfile);
1493 if (substr($mime, 0, 6) == "image/") {
1495 $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body);
1497 $type = $oembed_data->type;
1498 $footerurl = $expanded_url;
1499 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1501 $body = str_replace($search, $footerlink, $body);
1506 if ($footerurl != "") {
1507 $footer = add_page_info($footerurl);
1510 if (($footerlink != "") && (trim($footer) != "")) {
1511 $removedlink = trim(str_replace($footerlink, "", $body));
1513 if (($removedlink == "") || strstr($body, $removedlink)) {
1514 $body = $removedlink;
1522 return ["body" => $body, "tags" => ""];
1527 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1529 foreach ($matches as $mtch) {
1530 if (strlen($str_tags)) {
1534 if ($mtch[1] == "#") {
1535 // Replacing the hash tags that are directed to the GNU Social server with internal links
1536 $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1537 $frdchash = '#[url=' . $a->getBaseURL() . '/search?tag=' . $mtch[3] . ']' . $mtch[3] . '[/url]';
1538 $body = str_replace($snhash, $frdchash, $body);
1540 $str_tags .= $frdchash;
1542 $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1545 // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1546 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1550 return ["body" => $body, "tags" => $str_tags];
1553 function statusnet_fetch_own_contact(App $a, $uid)
1555 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1556 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1557 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1558 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1559 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1560 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1564 if ($own_url == "") {
1565 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1567 // Fetching user data
1568 $user = $connection->get('account/verify_credentials');
1570 PConfig::set($uid, 'statusnet', 'own_url', Strings::normaliseLink($user->statusnet_profile_url));
1572 $contact_id = statusnet_fetch_contact($uid, $user, true);
1574 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1575 intval($uid), DBA::escape($own_url));
1576 if (DBA::isResult($r)) {
1577 $contact_id = $r[0]["id"];
1579 PConfig::delete($uid, 'statusnet', 'own_url');
1585 function statusnet_is_retweet(App $a, $uid, $body)
1587 $body = trim($body);
1589 // Skip if it isn't a pure repeated messages
1590 // Does it start with a share?
1591 if (strpos($body, "[share") > 0) {
1595 // Does it end with a share?
1596 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1600 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1601 // Skip if there is no shared message in there
1602 if ($body == $attributes) {
1607 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1608 if (!empty($matches[1])) {
1609 $link = $matches[1];
1612 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1613 if (!empty($matches[1])) {
1614 $link = $matches[1];
1617 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1618 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1619 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1620 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1621 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1622 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1624 $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link);
1630 Logger::log('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, Logger::DEBUG);
1632 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1634 $result = $connection->post('statuses/retweet/' . $id);
1636 Logger::log('statusnet_is_retweet: result ' . print_r($result, true), Logger::DEBUG);
1638 return isset($result->id);