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';
40 use CodebirdSN\CodebirdSN;
42 use Friendica\Content\OEmbed;
43 use Friendica\Content\Text\HTML;
44 use Friendica\Content\Text\Plaintext;
45 use Friendica\Core\Config;
46 use Friendica\Core\Hook;
47 use Friendica\Core\Logger;
48 use Friendica\Core\Protocol;
49 use Friendica\Core\Renderer;
50 use Friendica\Database\DBA;
52 use Friendica\Model\Contact;
53 use Friendica\Model\Group;
54 use Friendica\Model\Item;
55 use Friendica\Model\ItemContent;
56 use Friendica\Model\Photo;
57 use Friendica\Model\User;
58 use Friendica\Protocol\Activity;
59 use Friendica\Util\DateTimeFormat;
60 use Friendica\Util\Network;
61 use Friendica\Util\Strings;
63 function statusnet_install()
65 // we need some hooks, for the configuration and for sending tweets
66 Hook::register('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
67 Hook::register('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
68 Hook::register('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
69 Hook::register('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
70 Hook::register('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
71 Hook::register('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
72 Hook::register('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
73 Hook::register('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
74 Hook::register('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
75 Logger::log("installed GNU Social");
78 function statusnet_uninstall()
80 Hook::unregister('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
81 Hook::unregister('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
82 Hook::unregister('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
83 Hook::unregister('hook_fork', 'addon/statusnet/statusnet.php', 'statusnet_hook_fork');
84 Hook::unregister('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
85 Hook::unregister('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
86 Hook::unregister('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
87 Hook::unregister('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
88 Hook::unregister('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
90 // old setting - remove only
91 Hook::unregister('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
92 Hook::unregister('addon_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
93 Hook::unregister('addon_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
96 function statusnet_check_item_notification(App $a, &$notification_data)
98 if (DI::pConfig()->get($notification_data["uid"], 'statusnet', 'post')) {
99 $notification_data["profiles"][] = DI::pConfig()->get($notification_data["uid"], 'statusnet', 'own_url');
103 function statusnet_jot_nets(App $a, array &$jotnets_fields)
109 if (DI::pConfig()->get(local_user(), 'statusnet', 'post')) {
110 $jotnets_fields[] = [
111 'type' => 'checkbox',
114 DI::l10n()->t('Post to GNU Social'),
115 DI::pConfig()->get(local_user(), 'statusnet', 'post_by_default')
121 function statusnet_settings_post(App $a, $post)
126 // don't check GNU Social settings if GNU Social submit button is not clicked
127 if (empty($_POST['statusnet-submit'])) {
131 if (isset($_POST['statusnet-disconnect'])) {
133 * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration
135 DI::pConfig()->delete(local_user(), 'statusnet', 'consumerkey');
136 DI::pConfig()->delete(local_user(), 'statusnet', 'consumersecret');
137 DI::pConfig()->delete(local_user(), 'statusnet', 'post');
138 DI::pConfig()->delete(local_user(), 'statusnet', 'post_by_default');
139 DI::pConfig()->delete(local_user(), 'statusnet', 'oauthtoken');
140 DI::pConfig()->delete(local_user(), 'statusnet', 'oauthsecret');
141 DI::pConfig()->delete(local_user(), 'statusnet', 'baseapi');
142 DI::pConfig()->delete(local_user(), 'statusnet', 'lastid');
143 DI::pConfig()->delete(local_user(), 'statusnet', 'mirror_posts');
144 DI::pConfig()->delete(local_user(), 'statusnet', 'import');
145 DI::pConfig()->delete(local_user(), 'statusnet', 'create_user');
146 DI::pConfig()->delete(local_user(), 'statusnet', 'own_url');
148 if (isset($_POST['statusnet-preconf-apiurl'])) {
150 * If the user used one of the preconfigured GNU Social server credentials
151 * use them. All the data are available in the global config.
152 * Check the API Url never the less and blame the admin if it's not working ^^
154 $globalsn = Config::get('statusnet', 'sites');
155 foreach ($globalsn as $asn) {
156 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
157 $apibase = $asn['apiurl'];
158 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
159 if (strlen($c) > 0) {
160 DI::pConfig()->set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey']);
161 DI::pConfig()->set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret']);
162 DI::pConfig()->set(local_user(), 'statusnet', 'baseapi', $asn['apiurl']);
163 //DI::pConfig()->set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
165 notice(DI::l10n()->t('Please contact your site administrator.<br />The provided API URL is not valid.') . EOL . $asn['apiurl'] . EOL);
169 DI::baseUrl()->redirect('settings/connectors');
171 if (isset($_POST['statusnet-consumersecret'])) {
172 // check if we can reach the API of the GNU Social server
173 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
174 // resign quickly after this one try to fix the path ;-)
175 $apibase = $_POST['statusnet-baseapi'];
176 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
177 if (strlen($c) > 0) {
178 // ok the API path is correct, let's save the settings
179 DI::pConfig()->set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
180 DI::pConfig()->set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
181 DI::pConfig()->set(local_user(), 'statusnet', 'baseapi', $apibase);
182 //DI::pConfig()->set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
184 // the API path is not correct, maybe missing trailing / ?
185 $apibase = $apibase . '/';
186 $c = Network::fetchUrl($apibase . 'statusnet/version.xml');
187 if (strlen($c) > 0) {
188 // ok the API path is now correct, let's save the settings
189 DI::pConfig()->set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
190 DI::pConfig()->set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
191 DI::pConfig()->set(local_user(), 'statusnet', 'baseapi', $apibase);
193 // still not the correct API base, let's do noting
194 notice(DI::l10n()->t('We could not contact the GNU Social API with the Path you entered.') . EOL);
197 DI::baseUrl()->redirect('settings/connectors');
199 if (isset($_POST['statusnet-pin'])) {
200 // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
201 $api = DI::pConfig()->get(local_user(), 'statusnet', 'baseapi');
202 $ckey = DI::pConfig()->get(local_user(), 'statusnet', 'consumerkey');
203 $csecret = DI::pConfig()->get(local_user(), 'statusnet', 'consumersecret');
204 // the token and secret for which the PIN was generated were hidden in the settings
205 // form as token and token2, we need a new connection to GNU Social using these token
206 // and secret to request a Access Token with the PIN
207 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
208 $token = $connection->getAccessToken($_POST['statusnet-pin']);
209 // ok, now that we have the Access Token, save them in the user config
210 DI::pConfig()->set(local_user(), 'statusnet', 'oauthtoken', $token['oauth_token']);
211 DI::pConfig()->set(local_user(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
212 DI::pConfig()->set(local_user(), 'statusnet', 'post', 1);
213 DI::pConfig()->set(local_user(), 'statusnet', 'post_taglinks', 1);
214 // reload the Addon Settings page, if we don't do it see Bug #42
215 DI::baseUrl()->redirect('settings/connectors');
217 // if no PIN is supplied in the POST variables, the user has changed the setting
218 // to post a dent for every new __public__ posting to the wall
219 DI::pConfig()->set(local_user(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
220 DI::pConfig()->set(local_user(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
221 DI::pConfig()->set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
222 DI::pConfig()->set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
223 DI::pConfig()->set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
225 if (!intval($_POST['statusnet-mirror']))
226 DI::pConfig()->delete(local_user(), 'statusnet', 'lastid');
228 info(DI::l10n()->t('GNU Social settings updated.') . EOL);
235 function statusnet_settings(App $a, &$s)
240 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
242 * 1) Check that we have a base api url and a consumer key & secret
243 * 2) If no OAuthtoken & stuff is present, generate button to get some
244 * allow the user to cancel the connection process at this step
245 * 3) Checkbox for "Send public notices (respect size limitation)
247 $api = DI::pConfig()->get(local_user(), 'statusnet', 'baseapi');
248 $ckey = DI::pConfig()->get(local_user(), 'statusnet', 'consumerkey');
249 $csecret = DI::pConfig()->get(local_user(), 'statusnet', 'consumersecret');
250 $otoken = DI::pConfig()->get(local_user(), 'statusnet', 'oauthtoken');
251 $osecret = DI::pConfig()->get(local_user(), 'statusnet', 'oauthsecret');
252 $enabled = DI::pConfig()->get(local_user(), 'statusnet', 'post');
253 $checked = (($enabled) ? ' checked="checked" ' : '');
254 $defenabled = DI::pConfig()->get(local_user(), 'statusnet', 'post_by_default');
255 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
256 $mirrorenabled = DI::pConfig()->get(local_user(), 'statusnet', 'mirror_posts');
257 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
258 $import = DI::pConfig()->get(local_user(), 'statusnet', 'import');
259 $importselected = ["", "", ""];
260 $importselected[$import] = ' selected="selected"';
261 //$importenabled = DI::pConfig()->get(local_user(),'statusnet','import');
262 //$importchecked = (($importenabled) ? ' checked="checked" ' : '');
263 $create_userenabled = DI::pConfig()->get(local_user(), 'statusnet', 'create_user');
264 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
266 $css = (($enabled) ? '' : '-disabled');
268 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
269 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . DI::l10n()->t('GNU Social Import/Export/Mirror') . '</h3>';
271 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
272 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
273 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . DI::l10n()->t('GNU Social Import/Export/Mirror') . '</h3>';
276 if ((!$ckey) && (!$csecret)) {
280 $globalsn = Config::get('statusnet', 'sites');
282 * lets check if we have one or more globally configured GNU Social
283 * server OAuth credentials in the configuration. If so offer them
284 * with a little explanation to the user as choice - otherwise
285 * ignore this option entirely.
287 if (!$globalsn == null) {
288 $s .= '<h4>' . DI::l10n()->t('Globally Available GNU Social OAuthKeys') . '</h4>';
289 $s .= '<p>' . DI::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>';
290 $s .= '<div id="statusnet-preconf-wrapper">';
291 foreach ($globalsn as $asn) {
292 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="' . $asn['apiurl'] . '">' . $asn['sitename'] . '<br />';
294 $s .= '<p></p><div class="clear"></div></div>';
295 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div>';
297 $s .= '<h4>' . DI::l10n()->t('Provide your own OAuth Credentials') . '</h4>';
298 $s .= '<p>' . DI::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>';
299 $s .= '<div id="statusnet-consumer-wrapper">';
300 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">' . DI::l10n()->t('OAuth Consumer Key') . '</label>';
301 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
302 $s .= '<div class="clear"></div>';
303 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">' . DI::l10n()->t('OAuth Consumer Secret') . '</label>';
304 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
305 $s .= '<div class="clear"></div>';
306 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">' . DI::l10n()->t("Base API Path \x28remember the trailing /\x29") . '</label>';
307 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
308 $s .= '<div class="clear"></div>';
309 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.DI::l10n()->t('GNU Socialapplication name').'</label>';
310 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
311 $s .= '<p></p><div class="clear"></div>';
312 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div>';
316 * ok we have a consumer key pair now look into the OAuth stuff
318 if ((!$otoken) && (!$osecret)) {
320 * the user has not yet connected the account to GNU Social
321 * get a temporary OAuth key/secret pair and display a button with
322 * which the user can request a PIN to connect the account to a
323 * account at GNU Social
325 $connection = new StatusNetOAuth($api, $ckey, $csecret);
326 $request_token = $connection->getRequestToken('oob');
327 $token = $request_token['oauth_token'];
329 * make some nice form
331 $s .= '<p>' . DI::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>';
332 $s .= '<a href="' . $connection->getAuthorizeURL($token, False) . '" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="' . DI::l10n()->t('Log in with GNU Social') . '"></a>';
333 $s .= '<div id="statusnet-pin-wrapper">';
334 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">' . DI::l10n()->t('Copy the security code from GNU Social here') . '</label>';
335 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
336 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="' . $token . '" />';
337 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="' . $request_token['oauth_token_secret'] . '" />';
338 $s .= '</div><div class="clear"></div>';
339 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div>';
340 $s .= '<h4>' . DI::l10n()->t('Cancel Connection Process') . '</h4>';
341 $s .= '<div id="statusnet-cancel-wrapper">';
342 $s .= '<p>' . DI::l10n()->t('Current GNU Social API is') . ': ' . $api . '</p>';
343 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">' . DI::l10n()->t('Cancel GNU Social Connection') . '</label>';
344 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
345 $s .= '</div><div class="clear"></div>';
346 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div>';
349 * we have an OAuth key / secret pair for the user
350 * so let's give a chance to disable the postings to GNU Social
352 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
353 $details = $connection->get('account/verify_credentials');
354 if (!empty($details)) {
355 $s .= '<div id="statusnet-info" ><img id="statusnet-avatar" src="' . $details->profile_image_url . '" /><p id="statusnet-info-block">' . DI::l10n()->t('Currently connected to: ') . '<a href="' . $details->statusnet_profile_url . '" target="_statusnet">' . $details->screen_name . '</a><br /><em>' . $details->description . '</em></p></div>';
357 $s .= '<p>' . DI::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>';
358 if ($a->user['hidewall']) {
359 $s .= '<p>' . DI::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>';
361 $s .= '<div id="statusnet-enable-wrapper">';
362 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">' . DI::l10n()->t('Allow posting to GNU Social') . '</label>';
363 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
364 $s .= '<div class="clear"></div>';
365 $s .= '<label id="statusnet-default-label" for="statusnet-default">' . DI::l10n()->t('Send public postings to GNU Social by default') . '</label>';
366 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
367 $s .= '<div class="clear"></div>';
369 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">' . DI::l10n()->t('Mirror all posts from GNU Social that are no replies or repeated messages') . '</label>';
370 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" ' . $mirrorchecked . '/>';
372 $s .= '<div class="clear"></div>';
375 $s .= '<label id="statusnet-import-label" for="statusnet-import">' . DI::l10n()->t('Import the remote timeline') . '</label>';
376 //$s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
378 $s .= '<select name="statusnet-import" id="statusnet-import" />';
379 $s .= '<option value="0" ' . $importselected[0] . '>' . DI::l10n()->t("Disabled") . '</option>';
380 $s .= '<option value="1" ' . $importselected[1] . '>' . DI::l10n()->t("Full Timeline") . '</option>';
381 $s .= '<option value="2" ' . $importselected[2] . '>' . DI::l10n()->t("Only Mentions") . '</option>';
383 $s .= '<div class="clear"></div>';
385 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.DI::l10n()->t('Automatically create contacts').'</label>';
386 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
387 $s .= '<div class="clear"></div>';
389 $s .= '<div id="statusnet-disconnect-wrapper">';
390 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">' . DI::l10n()->t('Clear OAuth configuration') . '</label>';
391 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
392 $s .= '</div><div class="clear"></div>';
393 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div>';
396 $s .= '</div><div class="clear"></div>';
399 function statusnet_hook_fork(App $a, array &$b)
401 if ($b['name'] != 'notifier_normal') {
407 // Deleting and editing is not supported by the addon
408 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
409 $b['execute'] = false;
413 // if post comes from GNU Social don't send it back
414 if ($post['extid'] == Protocol::STATUSNET) {
415 $b['execute'] = false;
419 if ($post['app'] == 'StatusNet') {
420 $b['execute'] = false;
424 if (DI::pConfig()->get($post['uid'], 'statusnet', 'import')) {
425 // Don't fork if it isn't a reply to a GNU Social post
426 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::STATUSNET])) {
427 Logger::log('No GNU Social parent found for item ' . $post['id']);
428 $b['execute'] = false;
432 // Comments are never exported when we don't import the GNU Social timeline
433 if (!strstr($post['postopts'], 'statusnet') || ($post['parent'] != $post['id']) || $post['private']) {
434 $b['execute'] = false;
440 function statusnet_post_local(App $a, &$b)
446 if (!local_user() || (local_user() != $b['uid'])) {
450 $statusnet_post = DI::pConfig()->get(local_user(), 'statusnet', 'post');
451 $statusnet_enable = (($statusnet_post && !empty($_REQUEST['statusnet_enable'])) ? intval($_REQUEST['statusnet_enable']) : 0);
453 // if API is used, default to the chosen settings
454 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'statusnet', 'post_by_default'))) {
455 $statusnet_enable = 1;
458 if (!$statusnet_enable) {
462 if (strlen($b['postopts'])) {
463 $b['postopts'] .= ',';
466 $b['postopts'] .= 'statusnet';
469 function statusnet_action(App $a, $uid, $pid, $action)
471 $api = DI::pConfig()->get($uid, 'statusnet', 'baseapi');
472 $ckey = DI::pConfig()->get($uid, 'statusnet', 'consumerkey');
473 $csecret = DI::pConfig()->get($uid, 'statusnet', 'consumersecret');
474 $otoken = DI::pConfig()->get($uid, 'statusnet', 'oauthtoken');
475 $osecret = DI::pConfig()->get($uid, 'statusnet', 'oauthsecret');
477 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
479 Logger::log("statusnet_action '" . $action . "' ID: " . $pid, Logger::DATA);
483 $result = $connection->post("statuses/destroy/" . $pid);
486 $result = $connection->post("favorites/create/" . $pid);
489 $result = $connection->post("favorites/destroy/" . $pid);
492 Logger::log("statusnet_action '" . $action . "' send, result: " . print_r($result, true), Logger::DEBUG);
495 function statusnet_post_hook(App $a, &$b)
500 if (!DI::pConfig()->get($b["uid"], 'statusnet', 'import')) {
501 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
505 $api = DI::pConfig()->get($b["uid"], 'statusnet', 'baseapi');
506 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
508 if ($b['parent'] != $b['id']) {
509 Logger::log("statusnet_post_hook: parameter " . print_r($b, true), Logger::DATA);
511 // Looking if its a reply to a GNU Social post
512 $hostlength = strlen($hostname) + 2;
513 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) {
514 Logger::log("statusnet_post_hook: no GNU Social post " . $b["parent"]);
518 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
519 $orig_post = Item::selectFirst(['author-link', 'uri'], $condition);
520 if (!DBA::isResult($orig_post)) {
521 Logger::log("statusnet_post_hook: no parent found " . $b["thr-parent"]);
527 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
529 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
530 $nicknameplain = "@" . $nick;
532 Logger::log("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], Logger::DEBUG);
533 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
534 $b["body"] = $nickname . " " . $b["body"];
537 Logger::log("statusnet_post_hook: parent found " . print_r($orig_post, true), Logger::DEBUG);
541 if ($b['private'] || !strstr($b['postopts'], 'statusnet')) {
545 // Dont't post if the post doesn't belong to us.
546 // This is a check for forum postings
547 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
548 if ($b['contact-id'] != $self['id']) {
553 if (($b['verb'] == Activity::POST) && $b['deleted']) {
554 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
557 if ($b['verb'] == Activity::LIKE) {
558 Logger::log("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), Logger::DEBUG);
560 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
562 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
566 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
570 // if posts comes from GNU Social don't send it back
571 if ($b['extid'] == Protocol::STATUSNET) {
575 if ($b['app'] == "StatusNet") {
579 Logger::log('GNU Socialpost invoked');
581 DI::pConfig()->load($b['uid'], 'statusnet');
583 $api = DI::pConfig()->get($b['uid'], 'statusnet', 'baseapi');
584 $ckey = DI::pConfig()->get($b['uid'], 'statusnet', 'consumerkey');
585 $csecret = DI::pConfig()->get($b['uid'], 'statusnet', 'consumersecret');
586 $otoken = DI::pConfig()->get($b['uid'], 'statusnet', 'oauthtoken');
587 $osecret = DI::pConfig()->get($b['uid'], 'statusnet', 'oauthsecret');
589 if ($ckey && $csecret && $otoken && $osecret) {
590 // If it's a repeated message from GNU Social then do a native retweet and exit
591 if (statusnet_is_retweet($a, $b['uid'], $b['body'])) {
595 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
596 $max_char = $dent->get_maxlength(); // max. length for a dent
598 DI::pConfig()->set($b['uid'], 'statusnet', 'max_char', $max_char);
601 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 7);
602 $msg = $msgarr["text"];
604 if (($msg == "") && isset($msgarr["title"]))
605 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
609 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
610 $msg .= " \n" . $msgarr["url"];
611 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
612 $image = $msgarr["image"];
616 $img_str = Network::fetchUrl($image);
617 $tempfile = tempnam(get_temppath(), "cache");
618 file_put_contents($tempfile, $img_str);
619 $postdata = ["status" => $msg, "media[]" => $tempfile];
621 $postdata = ["status" => $msg];
624 // and now send it :-)
627 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
628 Logger::log('statusnet_post send reply ' . print_r($postdata, true), Logger::DEBUG);
631 // New code that is able to post pictures
632 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
633 $cb = CodebirdSN::getInstance();
634 $cb->setAPIEndpoint($api);
635 $cb->setConsumerKey($ckey, $csecret);
636 $cb->setToken($otoken, $osecret);
637 $result = $cb->statuses_update($postdata);
638 //$result = $dent->post('statuses/update', $postdata);
639 Logger::log('statusnet_post send, result: ' . print_r($result, true) .
640 "\nmessage: " . $msg . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true), Logger::DEBUG);
642 if (!empty($result->source)) {
643 DI::pConfig()->set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
646 if (!empty($result->error)) {
647 Logger::log('Send to GNU Social failed: "' . $result->error . '"');
648 } elseif ($iscomment) {
649 Logger::log('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
650 Item::update(['extid' => $hostname . "::" . $result->id, 'body' => $result->text], ['id' => $b['id']]);
653 if ($tempfile != "") {
659 function statusnet_addon_admin_post(App $a)
663 foreach ($_POST['sitename'] as $id => $sitename) {
664 $sitename = trim($sitename);
665 $apiurl = trim($_POST['apiurl'][$id]);
666 if (!(substr($apiurl, -1) == '/')) {
667 $apiurl = $apiurl . '/';
669 $secret = trim($_POST['secret'][$id]);
670 $key = trim($_POST['key'][$id]);
671 //$applicationname = (!empty($_POST['applicationname']) ? Strings::escapeTags(trim($_POST['applicationname'][$id])):'');
672 if ($sitename != "" &&
676 empty($_POST['delete'][$id])) {
679 'sitename' => $sitename,
681 'consumersecret' => $secret,
682 'consumerkey' => $key,
683 //'applicationname' => $applicationname
688 $sites = Config::set('statusnet', 'sites', $sites);
691 function statusnet_addon_admin(App $a, &$o)
693 $sites = Config::get('statusnet', 'sites');
695 if (is_array($sites)) {
696 foreach ($sites as $id => $s) {
698 'sitename' => ["sitename[$id]", "Site name", $s['sitename'], ""],
699 'apiurl' => ["apiurl[$id]", "Api url", $s['apiurl'], DI::l10n()->t("Base API Path \x28remember the trailing /\x29")],
700 'secret' => ["secret[$id]", "Secret", $s['consumersecret'], ""],
701 'key' => ["key[$id]", "Key", $s['consumerkey'], ""],
702 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
703 'delete' => ["delete[$id]", "Delete", False, "Check to delete this preset"],
707 /* empty form to add new site */
708 $id = count($sitesform);
710 'sitename' => ["sitename[$id]", DI::l10n()->t("Site name"), "", ""],
711 'apiurl' => ["apiurl[$id]", "Api url", "", DI::l10n()->t("Base API Path \x28remember the trailing /\x29")],
712 'secret' => ["secret[$id]", DI::l10n()->t("Consumer Secret"), "", ""],
713 'key' => ["key[$id]", DI::l10n()->t("Consumer Key"), "", ""],
714 //'applicationname' => Array("applicationname[$id]", DI::l10n()->t("Application name"), "", ""),
717 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/statusnet/");
718 $o = Renderer::replaceMacros($t, [
719 '$submit' => DI::l10n()->t('Save Settings'),
720 '$sites' => $sitesform,
724 function statusnet_prepare_body(App $a, &$b)
726 if ($b["item"]["network"] != Protocol::STATUSNET) {
731 $max_char = DI::pConfig()->get(local_user(), 'statusnet', 'max_char');
732 if (intval($max_char) == 0) {
737 $item["plink"] = DI::baseUrl()->get() . "/display/" . $item["guid"];
739 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
740 $orig_post = Item::selectFirst(['author-link', 'uri'], $condition);
741 if (DBA::isResult($orig_post)) {
742 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
744 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
745 $nicknameplain = "@" . $nick;
747 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
748 $item["body"] = $nickname . " " . $item["body"];
752 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 7);
753 $msg = $msgarr["text"];
755 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
756 $msg .= " " . $msgarr["url"];
759 if (isset($msgarr["image"])) {
760 $msg .= " " . $msgarr["image"];
763 $b['html'] = nl2br(htmlspecialchars($msg));
767 function statusnet_cron(App $a, $b)
769 $last = Config::get('statusnet', 'last_poll');
771 $poll_interval = intval(Config::get('statusnet', 'poll_interval'));
772 if (!$poll_interval) {
773 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
777 $next = $last + ($poll_interval * 60);
778 if ($next > time()) {
779 Logger::log('statusnet: poll intervall not reached');
783 Logger::log('statusnet: cron_start');
785 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
786 if (DBA::isResult($r)) {
787 foreach ($r as $rr) {
788 Logger::log('statusnet: fetching for user ' . $rr['uid']);
789 statusnet_fetchtimeline($a, $rr['uid']);
793 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
794 if ($abandon_days < 1) {
798 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
800 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
801 if (DBA::isResult($r)) {
802 foreach ($r as $rr) {
803 if ($abandon_days != 0) {
804 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
805 if (!DBA::isResult($user)) {
806 Logger::log('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
811 Logger::log('statusnet: importing timeline from user ' . $rr['uid']);
812 statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
816 Logger::log('statusnet: cron_end');
818 Config::set('statusnet', 'last_poll', time());
821 function statusnet_fetchtimeline(App $a, $uid)
823 $ckey = DI::pConfig()->get($uid, 'statusnet', 'consumerkey');
824 $csecret = DI::pConfig()->get($uid, 'statusnet', 'consumersecret');
825 $api = DI::pConfig()->get($uid, 'statusnet', 'baseapi');
826 $otoken = DI::pConfig()->get($uid, 'statusnet', 'oauthtoken');
827 $osecret = DI::pConfig()->get($uid, 'statusnet', 'oauthsecret');
828 $lastid = DI::pConfig()->get($uid, 'statusnet', 'lastid');
830 require_once 'mod/item.php';
831 // get the application name for the SN app
832 // 1st try personal config, then system config and fallback to the
833 // hostname of the node if neither one is set.
834 $application_name = DI::pConfig()->get($uid, 'statusnet', 'application_name');
835 if ($application_name == "") {
836 $application_name = Config::get('statusnet', 'application_name');
838 if ($application_name == "") {
839 $application_name = DI::baseUrl()->getHostname();
842 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
844 $parameters = ["exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false];
846 $first_time = ($lastid == "");
849 $parameters["since_id"] = $lastid;
852 $items = $connection->get('statuses/user_timeline', $parameters);
854 if (!is_array($items)) {
858 $posts = array_reverse($items);
861 foreach ($posts as $post) {
862 if ($post->id > $lastid)
869 if ($post->source == "activity") {
873 if (!empty($post->retweeted_status)) {
877 if ($post->in_reply_to_status_id != "") {
881 if (!stristr($post->source, $application_name)) {
882 $_SESSION["authenticated"] = true;
883 $_SESSION["uid"] = $uid;
886 $_REQUEST["api_source"] = true;
887 $_REQUEST["profile_uid"] = $uid;
888 //$_REQUEST["source"] = "StatusNet";
889 $_REQUEST["source"] = $post->source;
890 $_REQUEST["extid"] = Protocol::STATUSNET;
892 if (isset($post->id)) {
893 $_REQUEST['message_id'] = Item::newURI($uid, Protocol::STATUSNET . ":" . $post->id);
896 //$_REQUEST["date"] = $post->created_at;
898 $_REQUEST["title"] = "";
900 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
901 if (is_string($post->place->name)) {
902 $_REQUEST["location"] = $post->place->name;
905 if (is_string($post->place->full_name)) {
906 $_REQUEST["location"] = $post->place->full_name;
909 if (is_array($post->geo->coordinates)) {
910 $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
913 if (is_array($post->coordinates->coordinates)) {
914 $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
917 //print_r($_REQUEST);
918 if ($_REQUEST["body"] != "") {
919 Logger::log('statusnet: posting for user ' . $uid);
926 DI::pConfig()->set($uid, 'statusnet', 'lastid', $lastid);
929 function statusnet_address($contact)
931 $hostname = Strings::normaliseLink($contact->statusnet_profile_url);
932 $nickname = $contact->screen_name;
934 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
936 $address = $contact->screen_name . "@" . $hostname;
941 function statusnet_fetch_contact($uid, $contact, $create_user)
943 if (empty($contact->statusnet_profile_url)) {
947 $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));
949 if (!DBA::isResult($r) && !$create_user) {
953 if (DBA::isResult($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
954 Logger::log("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", Logger::DEBUG);
958 if (!DBA::isResult($r)) {
959 // create contact record
960 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
961 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
962 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
963 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
965 DBA::escape(DateTimeFormat::utcNow()),
966 DBA::escape($contact->statusnet_profile_url),
967 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
968 DBA::escape(statusnet_address($contact)),
969 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
972 DBA::escape($contact->name),
973 DBA::escape($contact->screen_name),
974 DBA::escape($contact->profile_image_url),
975 DBA::escape(Protocol::STATUSNET),
976 intval(Contact::FRIEND),
978 DBA::escape($contact->location),
979 DBA::escape($contact->description),
983 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
984 DBA::escape($contact->statusnet_profile_url),
986 DBA::escape(Protocol::STATUSNET));
988 if (!DBA::isResult($r)) {
992 $contact_id = $r[0]['id'];
994 Group::addMember(User::getDefaultGroup($uid), $contact_id);
996 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
998 q("UPDATE `contact` SET `photo` = '%s',
1001 `avatar-date` = '%s'
1003 DBA::escape($photos[0]),
1004 DBA::escape($photos[1]),
1005 DBA::escape($photos[2]),
1006 DBA::escape(DateTimeFormat::utcNow()),
1010 // update profile photos once every two weeks as we have no notification of when they change.
1011 //$update_photo = (($r[0]['avatar-date'] < DateTimeFormat::convert('now -2 days', '', '', )) ? true : false);
1012 $update_photo = ($r[0]['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1014 // check that we have all the photos, this has been known to fail on occasion
1015 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1016 Logger::log("statusnet_fetch_contact: Updating contact " . $contact->screen_name, Logger::DEBUG);
1018 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1020 q("UPDATE `contact` SET `photo` = '%s',
1025 `avatar-date` = '%s',
1034 DBA::escape($photos[0]),
1035 DBA::escape($photos[1]),
1036 DBA::escape($photos[2]),
1037 DBA::escape(DateTimeFormat::utcNow()),
1038 DBA::escape(DateTimeFormat::utcNow()),
1039 DBA::escape(DateTimeFormat::utcNow()),
1040 DBA::escape($contact->statusnet_profile_url),
1041 DBA::escape(Strings::normaliseLink($contact->statusnet_profile_url)),
1042 DBA::escape(statusnet_address($contact)),
1043 DBA::escape($contact->name),
1044 DBA::escape($contact->screen_name),
1045 DBA::escape($contact->location),
1046 DBA::escape($contact->description),
1055 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1057 $ckey = DI::pConfig()->get($uid, 'statusnet', 'consumerkey');
1058 $csecret = DI::pConfig()->get($uid, 'statusnet', 'consumersecret');
1059 $api = DI::pConfig()->get($uid, 'statusnet', 'baseapi');
1060 $otoken = DI::pConfig()->get($uid, 'statusnet', 'oauthtoken');
1061 $osecret = DI::pConfig()->get($uid, 'statusnet', 'oauthsecret');
1063 require_once __DIR__ . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'codebirdsn.php';
1065 $cb = CodebirdSN::getInstance();
1066 $cb->setConsumerKey($ckey, $csecret);
1067 $cb->setToken($otoken, $osecret);
1069 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1072 if (DBA::isResult($r)) {
1080 if ($screen_name != "") {
1081 $parameters["screen_name"] = $screen_name;
1084 if ($user_id != "") {
1085 $parameters["user_id"] = $user_id;
1088 // Fetching user data
1089 $user = $cb->users_show($parameters);
1091 if (!is_object($user)) {
1095 $contact_id = statusnet_fetch_contact($uid, $user, true);
1100 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1102 Logger::log("statusnet_createpost: start", Logger::DEBUG);
1104 $api = DI::pConfig()->get($uid, 'statusnet', 'baseapi');
1105 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1108 $postarray['network'] = Protocol::STATUSNET;
1109 $postarray['uid'] = $uid;
1110 $postarray['wall'] = 0;
1112 if (!empty($post->retweeted_status)) {
1113 $content = $post->retweeted_status;
1114 statusnet_fetch_contact($uid, $content->user, false);
1119 $postarray['uri'] = $hostname . "::" . $content->id;
1121 if (Item::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
1127 if (!empty($content->in_reply_to_status_id)) {
1129 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1131 $fields = ['uri', 'parent-uri', 'parent'];
1132 $item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
1134 if (!DBA::isResult($item)) {
1135 $item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
1138 if (DBA::isResult($item)) {
1139 $postarray['thr-parent'] = $item['uri'];
1140 $postarray['parent-uri'] = $item['parent-uri'];
1141 $postarray['parent'] = $item['parent'];
1142 $postarray['object-type'] = Activity\ObjectType::COMMENT;
1144 $postarray['thr-parent'] = $postarray['uri'];
1145 $postarray['parent-uri'] = $postarray['uri'];
1146 $postarray['object-type'] = Activity\ObjectType::NOTE;
1150 $own_url = DI::pConfig()->get($uid, 'statusnet', 'own_url');
1152 if ($content->user->id == $own_url) {
1153 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1156 if (DBA::isResult($r)) {
1157 $contactid = $r[0]["id"];
1159 $postarray['owner-name'] = $r[0]["name"];
1160 $postarray['owner-link'] = $r[0]["url"];
1161 $postarray['owner-avatar'] = $r[0]["photo"];
1166 // Don't create accounts of people who just comment something
1167 $create_user = false;
1169 $postarray['parent-uri'] = $postarray['uri'];
1170 $postarray['object-type'] = Activity\ObjectType::NOTE;
1173 if ($contactid == 0) {
1174 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1175 $postarray['owner-name'] = $post->user->name;
1176 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1177 $postarray['owner-avatar'] = $post->user->profile_image_url;
1179 if (($contactid == 0) && !$only_existing_contact) {
1180 $contactid = $self['id'];
1181 } elseif ($contactid <= 0) {
1185 $postarray['contact-id'] = $contactid;
1187 $postarray['verb'] = Activity::POST;
1189 $postarray['author-name'] = $content->user->name;
1190 $postarray['author-link'] = $content->user->statusnet_profile_url;
1191 $postarray['author-avatar'] = $content->user->profile_image_url;
1193 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1194 $hostname = str_replace("/api/", "/notice/", DI::pConfig()->get($uid, 'statusnet', 'baseapi'));
1196 $postarray['plink'] = $hostname . $content->id;
1197 $postarray['app'] = strip_tags($content->source);
1199 if ($content->user->protected) {
1200 $postarray['private'] = 1;
1201 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1204 $postarray['body'] = HTML::toBBCode($content->statusnet_html);
1206 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1207 $postarray['body'] = $converted["body"];
1208 $postarray['tag'] = $converted["tags"];
1210 $postarray['created'] = DateTimeFormat::utc($content->created_at);
1211 $postarray['edited'] = DateTimeFormat::utc($content->created_at);
1213 if (!empty($content->place->name)) {
1214 $postarray["location"] = $content->place->name;
1217 if (!empty($content->place->full_name)) {
1218 $postarray["location"] = $content->place->full_name;
1221 if (!empty($content->geo->coordinates)) {
1222 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1225 if (!empty($content->coordinates->coordinates)) {
1226 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1229 Logger::log("statusnet_createpost: end", Logger::DEBUG);
1234 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1236 $conversations = [];
1238 $ckey = DI::pConfig()->get($uid, 'statusnet', 'consumerkey');
1239 $csecret = DI::pConfig()->get($uid, 'statusnet', 'consumersecret');
1240 $api = DI::pConfig()->get($uid, 'statusnet', 'baseapi');
1241 $otoken = DI::pConfig()->get($uid, 'statusnet', 'oauthtoken');
1242 $osecret = DI::pConfig()->get($uid, 'statusnet', 'oauthsecret');
1243 $create_user = DI::pConfig()->get($uid, 'statusnet', 'create_user');
1245 // "create_user" is deactivated, since currently you cannot add users manually by now
1246 $create_user = true;
1248 Logger::log("statusnet_fetchhometimeline: Fetching for user " . $uid, Logger::DEBUG);
1250 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1252 $own_contact = statusnet_fetch_own_contact($a, $uid);
1254 if (empty($own_contact)) {
1258 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1259 intval($own_contact),
1262 if (DBA::isResult($r)) {
1263 $nick = $r[0]["nick"];
1265 Logger::log("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, Logger::DEBUG);
1269 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1272 if (DBA::isResult($r)) {
1275 Logger::log("statusnet_fetchhometimeline: Own contact not found for user " . $uid, Logger::DEBUG);
1279 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1281 if (!DBA::isResult($u)) {
1282 Logger::log("statusnet_fetchhometimeline: Own user not found for user " . $uid, Logger::DEBUG);
1286 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true];
1287 //$parameters["count"] = 200;
1290 // Fetching timeline
1291 $lastid = DI::pConfig()->get($uid, 'statusnet', 'lasthometimelineid');
1294 $first_time = ($lastid == "");
1296 if ($lastid != "") {
1297 $parameters["since_id"] = $lastid;
1300 $items = $connection->get('statuses/home_timeline', $parameters);
1302 if (!is_array($items)) {
1303 if (is_object($items) && isset($items->error)) {
1304 $errormsg = $items->error;
1305 } elseif (is_object($items)) {
1306 $errormsg = print_r($items, true);
1307 } elseif (is_string($items) || is_float($items) || is_int($items)) {
1310 $errormsg = "Unknown error";
1313 Logger::log("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, Logger::DEBUG);
1317 $posts = array_reverse($items);
1319 Logger::log("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
1321 if (count($posts)) {
1322 foreach ($posts as $post) {
1324 if ($post->id > $lastid) {
1325 $lastid = $post->id;
1332 if (isset($post->statusnet_conversation_id)) {
1333 if (!isset($conversations[$post->statusnet_conversation_id])) {
1334 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1335 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1338 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1340 if (trim($postarray['body']) == "") {
1344 $item = Item::insert($postarray);
1345 $postarray["id"] = $item;
1347 Logger::log('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1351 DI::pConfig()->set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1354 // Fetching mentions
1355 $lastid = DI::pConfig()->get($uid, 'statusnet', 'lastmentionid');
1356 $first_time = ($lastid == "");
1358 if ($lastid != "") {
1359 $parameters["since_id"] = $lastid;
1362 $items = $connection->get('statuses/mentions_timeline', $parameters);
1364 if (!is_array($items)) {
1365 Logger::log("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), Logger::DEBUG);
1369 $posts = array_reverse($items);
1371 Logger::log("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
1373 if (count($posts)) {
1374 foreach ($posts as $post) {
1375 if ($post->id > $lastid) {
1376 $lastid = $post->id;
1383 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1385 if (isset($post->statusnet_conversation_id)) {
1386 if (!isset($conversations[$post->statusnet_conversation_id])) {
1387 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1388 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1391 if (trim($postarray['body']) == "") {
1395 $item = Item::insert($postarray);
1397 Logger::log('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1402 DI::pConfig()->set($uid, 'statusnet', 'lastmentionid', $lastid);
1405 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1407 $ckey = DI::pConfig()->get($uid, 'statusnet', 'consumerkey');
1408 $csecret = DI::pConfig()->get($uid, 'statusnet', 'consumersecret');
1409 $api = DI::pConfig()->get($uid, 'statusnet', 'baseapi');
1410 $otoken = DI::pConfig()->get($uid, 'statusnet', 'oauthtoken');
1411 $osecret = DI::pConfig()->get($uid, 'statusnet', 'oauthsecret');
1412 $own_url = DI::pConfig()->get($uid, 'statusnet', 'own_url');
1414 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1416 $parameters["count"] = 200;
1418 $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1419 if (is_array($items)) {
1420 $posts = array_reverse($items);
1422 foreach ($posts as $post) {
1423 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1425 if (empty($postarray['body'])) {
1429 $item = Item::insert($postarray);
1430 $postarray["id"] = $item;
1432 Logger::log('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1437 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1439 $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
1441 $URLSearchString = "^\[\]";
1442 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1450 foreach ($matches AS $match) {
1451 $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
1453 Logger::log("statusnet_convertmsg: expanding url " . $match[1], Logger::DEBUG);
1455 $expanded_url = Network::finalUrl($match[1]);
1457 Logger::log("statusnet_convertmsg: fetching data for " . $expanded_url, Logger::DEBUG);
1459 $oembed_data = OEmbed::fetchURL($expanded_url, true);
1461 Logger::log("statusnet_convertmsg: fetching data: done", Logger::DEBUG);
1464 $type = $oembed_data->type;
1467 if ($oembed_data->type == "video") {
1468 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1469 $type = $oembed_data->type;
1470 $footerurl = $expanded_url;
1471 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1473 $body = str_replace($search, $footerlink, $body);
1474 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) {
1475 $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1476 } elseif ($oembed_data->type != "link") {
1477 $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1479 $img_str = Network::fetchUrl($expanded_url, true, 4);
1481 $tempfile = tempnam(get_temppath(), "cache");
1482 file_put_contents($tempfile, $img_str);
1483 $mime = mime_content_type($tempfile);
1486 if (substr($mime, 0, 6) == "image/") {
1488 $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body);
1490 $type = $oembed_data->type;
1491 $footerurl = $expanded_url;
1492 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1494 $body = str_replace($search, $footerlink, $body);
1499 if ($footerurl != "") {
1500 $footer = add_page_info($footerurl);
1503 if (($footerlink != "") && (trim($footer) != "")) {
1504 $removedlink = trim(str_replace($footerlink, "", $body));
1506 if (($removedlink == "") || strstr($body, $removedlink)) {
1507 $body = $removedlink;
1515 return ["body" => $body, "tags" => ""];
1520 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1522 foreach ($matches as $mtch) {
1523 if (strlen($str_tags)) {
1527 if ($mtch[1] == "#") {
1528 // Replacing the hash tags that are directed to the GNU Social server with internal links
1529 $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1530 $frdchash = '#[url=' . DI::baseUrl()->get() . '/search?tag=' . $mtch[3] . ']' . $mtch[3] . '[/url]';
1531 $body = str_replace($snhash, $frdchash, $body);
1533 $str_tags .= $frdchash;
1535 $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1538 // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1539 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1543 return ["body" => $body, "tags" => $str_tags];
1546 function statusnet_fetch_own_contact(App $a, $uid)
1548 $ckey = DI::pConfig()->get($uid, 'statusnet', 'consumerkey');
1549 $csecret = DI::pConfig()->get($uid, 'statusnet', 'consumersecret');
1550 $api = DI::pConfig()->get($uid, 'statusnet', 'baseapi');
1551 $otoken = DI::pConfig()->get($uid, 'statusnet', 'oauthtoken');
1552 $osecret = DI::pConfig()->get($uid, 'statusnet', 'oauthsecret');
1553 $own_url = DI::pConfig()->get($uid, 'statusnet', 'own_url');
1557 if ($own_url == "") {
1558 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1560 // Fetching user data
1561 $user = $connection->get('account/verify_credentials');
1567 DI::pConfig()->set($uid, 'statusnet', 'own_url', Strings::normaliseLink($user->statusnet_profile_url));
1569 $contact_id = statusnet_fetch_contact($uid, $user, true);
1571 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1572 intval($uid), DBA::escape($own_url));
1573 if (DBA::isResult($r)) {
1574 $contact_id = $r[0]["id"];
1576 DI::pConfig()->delete($uid, 'statusnet', 'own_url');
1582 function statusnet_is_retweet(App $a, $uid, $body)
1584 $body = trim($body);
1586 // Skip if it isn't a pure repeated messages
1587 // Does it start with a share?
1588 if (strpos($body, "[share") > 0) {
1592 // Does it end with a share?
1593 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1597 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1598 // Skip if there is no shared message in there
1599 if ($body == $attributes) {
1604 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1605 if (!empty($matches[1])) {
1606 $link = $matches[1];
1609 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1610 if (!empty($matches[1])) {
1611 $link = $matches[1];
1614 $ckey = DI::pConfig()->get($uid, 'statusnet', 'consumerkey');
1615 $csecret = DI::pConfig()->get($uid, 'statusnet', 'consumersecret');
1616 $api = DI::pConfig()->get($uid, 'statusnet', 'baseapi');
1617 $otoken = DI::pConfig()->get($uid, 'statusnet', 'oauthtoken');
1618 $osecret = DI::pConfig()->get($uid, 'statusnet', 'oauthsecret');
1619 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1621 $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link);
1627 Logger::log('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, Logger::DEBUG);
1629 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1631 $result = $connection->post('statuses/retweet/' . $id);
1633 Logger::log('statusnet_is_retweet: result ' . print_r($result, true), Logger::DEBUG);
1635 return isset($result->id);