4 * Name: GNU Social Connector
5 * Description: Bidirectional (posting, relaying and reading) connector for GNU Social.
7 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
8 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
10 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
11 * All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions are met:
15 * * Redistributions of source code must retain the above copyright notice,
16 * this list of conditions and the following disclaimer.
17 * * Redistributions in binary form must reproduce the above
18 * * copyright notice, this list of conditions and the following disclaimer in
19 * the documentation and/or other materials provided with the distribution.
20 * * Neither the name of the <organization> nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
28 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 * We have to alter the TwitterOAuth class a little bit to work with any GNU Social
38 * installation abroad. Basically it's only make the API path variable and be happy.
40 * Thank you guys for the Twitter compatible API!
43 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
45 require_once 'library/twitteroauth.php';
46 require_once 'include/enotify.php';
49 use Friendica\Content\OEmbed;
50 use Friendica\Core\Config;
51 use Friendica\Core\PConfig;
52 use Friendica\Model\GContact;
53 use Friendica\Model\Group;
54 use Friendica\Model\Photo;
55 use Friendica\Model\User;
57 class StatusNetOAuth extends TwitterOAuth
59 function get_maxlength()
61 $config = $this->get($this->host . 'statusnet/config.json');
62 return $config->site->textlimit;
65 function accessTokenURL()
67 return $this->host . 'oauth/access_token';
70 function authenticateURL()
72 return $this->host . 'oauth/authenticate';
75 function authorizeURL()
77 return $this->host . 'oauth/authorize';
80 function requestTokenURL()
82 return $this->host . 'oauth/request_token';
85 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL)
87 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
88 $this->host = $apipath;
92 * Make an HTTP request
96 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
98 function http($url, $method, $postfields = NULL)
100 $this->http_info = array();
103 $prx = Config::get('system', 'proxy');
105 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
106 curl_setopt($ci, CURLOPT_PROXY, $prx);
107 $prxusr = Config::get('system', 'proxyuser');
108 if (strlen($prxusr)) {
109 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
112 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
113 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
114 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
115 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
116 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
117 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
118 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
119 curl_setopt($ci, CURLOPT_HEADER, FALSE);
123 curl_setopt($ci, CURLOPT_POST, TRUE);
124 if (!empty($postfields)) {
125 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
129 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
130 if (!empty($postfields)) {
131 $url = "{$url}?{$postfields}";
135 curl_setopt($ci, CURLOPT_URL, $url);
136 $response = curl_exec($ci);
137 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
138 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
145 function statusnet_install()
147 // we need some hooks, for the configuration and for sending tweets
148 register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
149 register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
150 register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
151 register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
152 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
153 register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
154 register_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
155 register_hook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
156 logger("installed GNU Social");
159 function statusnet_uninstall()
161 unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
162 unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
163 unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
164 unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
165 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
166 unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
167 unregister_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
168 unregister_hook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
170 // old setting - remove only
171 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
172 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
173 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
176 function statusnet_check_item_notification(App $a, &$notification_data)
178 $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
181 function statusnet_jot_nets(App $a, &$b)
187 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
188 if (intval($statusnet_post) == 1) {
189 $statusnet_defpost = PConfig::get(local_user(), 'statusnet', 'post_by_default');
190 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
191 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
192 . t('Post to GNU Social') . '</div>';
196 function statusnet_settings_post(App $a, $post)
201 // don't check GNU Social settings if GNU Social submit button is not clicked
202 if (!x($_POST, 'statusnet-submit')) {
206 if (isset($_POST['statusnet-disconnect'])) {
208 * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration
210 PConfig::delete(local_user(), 'statusnet', 'consumerkey');
211 PConfig::delete(local_user(), 'statusnet', 'consumersecret');
212 PConfig::delete(local_user(), 'statusnet', 'post');
213 PConfig::delete(local_user(), 'statusnet', 'post_by_default');
214 PConfig::delete(local_user(), 'statusnet', 'oauthtoken');
215 PConfig::delete(local_user(), 'statusnet', 'oauthsecret');
216 PConfig::delete(local_user(), 'statusnet', 'baseapi');
217 PConfig::delete(local_user(), 'statusnet', 'lastid');
218 PConfig::delete(local_user(), 'statusnet', 'mirror_posts');
219 PConfig::delete(local_user(), 'statusnet', 'import');
220 PConfig::delete(local_user(), 'statusnet', 'create_user');
221 PConfig::delete(local_user(), 'statusnet', 'own_id');
223 if (isset($_POST['statusnet-preconf-apiurl'])) {
225 * If the user used one of the preconfigured GNU Social server credentials
226 * use them. All the data are available in the global config.
227 * Check the API Url never the less and blame the admin if it's not working ^^
229 $globalsn = Config::get('statusnet', 'sites');
230 foreach ($globalsn as $asn) {
231 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
232 $apibase = $asn['apiurl'];
233 $c = fetch_url($apibase . 'statusnet/version.xml');
234 if (strlen($c) > 0) {
235 PConfig::set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey']);
236 PConfig::set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret']);
237 PConfig::set(local_user(), 'statusnet', 'baseapi', $asn['apiurl']);
238 //PConfig::set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
240 notice(t('Please contact your site administrator.<br />The provided API URL is not valid.') . EOL . $asn['apiurl'] . EOL);
244 goaway('settings/connectors');
246 if (isset($_POST['statusnet-consumersecret'])) {
247 // check if we can reach the API of the GNU Social server
248 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
249 // resign quickly after this one try to fix the path ;-)
250 $apibase = $_POST['statusnet-baseapi'];
251 $c = fetch_url($apibase . 'statusnet/version.xml');
252 if (strlen($c) > 0) {
253 // ok the API path is correct, let's save the settings
254 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
255 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
256 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
257 //PConfig::set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
259 // the API path is not correct, maybe missing trailing / ?
260 $apibase = $apibase . '/';
261 $c = fetch_url($apibase . 'statusnet/version.xml');
262 if (strlen($c) > 0) {
263 // ok the API path is now correct, let's save the settings
264 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
265 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
266 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
268 // still not the correct API base, let's do noting
269 notice(t('We could not contact the GNU Social API with the Path you entered.') . EOL);
272 goaway('settings/connectors');
274 if (isset($_POST['statusnet-pin'])) {
275 // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
276 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
277 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
278 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
279 // the token and secret for which the PIN was generated were hidden in the settings
280 // form as token and token2, we need a new connection to GNU Social using these token
281 // and secret to request a Access Token with the PIN
282 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
283 $token = $connection->getAccessToken($_POST['statusnet-pin']);
284 // ok, now that we have the Access Token, save them in the user config
285 PConfig::set(local_user(), 'statusnet', 'oauthtoken', $token['oauth_token']);
286 PConfig::set(local_user(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
287 PConfig::set(local_user(), 'statusnet', 'post', 1);
288 PConfig::set(local_user(), 'statusnet', 'post_taglinks', 1);
289 // reload the Addon Settings page, if we don't do it see Bug #42
290 goaway('settings/connectors');
292 // if no PIN is supplied in the POST variables, the user has changed the setting
293 // to post a dent for every new __public__ posting to the wall
294 PConfig::set(local_user(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
295 PConfig::set(local_user(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
296 PConfig::set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
297 PConfig::set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
298 PConfig::set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
300 if (!intval($_POST['statusnet-mirror']))
301 PConfig::delete(local_user(), 'statusnet', 'lastid');
303 info(t('GNU Social settings updated.') . EOL);
310 function statusnet_settings(App $a, &$s)
315 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
317 * 1) Check that we have a base api url and a consumer key & secret
318 * 2) If no OAuthtoken & stuff is present, generate button to get some
319 * allow the user to cancel the connection process at this step
320 * 3) Checkbox for "Send public notices (respect size limitation)
322 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
323 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
324 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
325 $otoken = PConfig::get(local_user(), 'statusnet', 'oauthtoken');
326 $osecret = PConfig::get(local_user(), 'statusnet', 'oauthsecret');
327 $enabled = PConfig::get(local_user(), 'statusnet', 'post');
328 $checked = (($enabled) ? ' checked="checked" ' : '');
329 $defenabled = PConfig::get(local_user(), 'statusnet', 'post_by_default');
330 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
331 $mirrorenabled = PConfig::get(local_user(), 'statusnet', 'mirror_posts');
332 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
333 $import = PConfig::get(local_user(), 'statusnet', 'import');
334 $importselected = array("", "", "");
335 $importselected[$import] = ' selected="selected"';
336 //$importenabled = PConfig::get(local_user(),'statusnet','import');
337 //$importchecked = (($importenabled) ? ' checked="checked" ' : '');
338 $create_userenabled = PConfig::get(local_user(), 'statusnet', 'create_user');
339 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
341 $css = (($enabled) ? '' : '-disabled');
343 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
344 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . t('GNU Social Import/Export/Mirror') . '</h3>';
346 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
347 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
348 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . t('GNU Social Import/Export/Mirror') . '</h3>';
351 if ((!$ckey) && (!$csecret)) {
355 $globalsn = Config::get('statusnet', 'sites');
357 * lets check if we have one or more globally configured GNU Social
358 * server OAuth credentials in the configuration. If so offer them
359 * with a little explanation to the user as choice - otherwise
360 * ignore this option entirely.
362 if (!$globalsn == null) {
363 $s .= '<h4>' . t('Globally Available GNU Social OAuthKeys') . '</h4>';
364 $s .= '<p>' . 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>';
365 $s .= '<div id="statusnet-preconf-wrapper">';
366 foreach ($globalsn as $asn) {
367 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="' . $asn['apiurl'] . '">' . $asn['sitename'] . '<br />';
369 $s .= '<p></p><div class="clear"></div></div>';
370 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
372 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
373 $s .= '<p>' . 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>';
374 $s .= '<div id="statusnet-consumer-wrapper">';
375 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">' . t('OAuth Consumer Key') . '</label>';
376 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
377 $s .= '<div class="clear"></div>';
378 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">' . t('OAuth Consumer Secret') . '</label>';
379 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
380 $s .= '<div class="clear"></div>';
381 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">' . t("Base API Path \x28remember the trailing /\x29") . '</label>';
382 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
383 $s .= '<div class="clear"></div>';
384 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('GNU Socialapplication name').'</label>';
385 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
386 $s .= '<p></p><div class="clear"></div>';
387 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
391 * ok we have a consumer key pair now look into the OAuth stuff
393 if ((!$otoken) && (!$osecret)) {
395 * the user has not yet connected the account to GNU Social
396 * get a temporary OAuth key/secret pair and display a button with
397 * which the user can request a PIN to connect the account to a
398 * account at GNU Social
400 $connection = new StatusNetOAuth($api, $ckey, $csecret);
401 $request_token = $connection->getRequestToken('oob');
402 $token = $request_token['oauth_token'];
404 * make some nice form
406 $s .= '<p>' . 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>';
407 $s .= '<a href="' . $connection->getAuthorizeURL($token, False) . '" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="' . t('Log in with GNU Social') . '"></a>';
408 $s .= '<div id="statusnet-pin-wrapper">';
409 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">' . t('Copy the security code from GNU Social here') . '</label>';
410 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
411 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="' . $token . '" />';
412 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="' . $request_token['oauth_token_secret'] . '" />';
413 $s .= '</div><div class="clear"></div>';
414 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
415 $s .= '<h4>' . t('Cancel Connection Process') . '</h4>';
416 $s .= '<div id="statusnet-cancel-wrapper">';
417 $s .= '<p>' . t('Current GNU Social API is') . ': ' . $api . '</p>';
418 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">' . t('Cancel GNU Social Connection') . '</label>';
419 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
420 $s .= '</div><div class="clear"></div>';
421 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
424 * we have an OAuth key / secret pair for the user
425 * so let's give a chance to disable the postings to GNU Social
427 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
428 $details = $connection->get('account/verify_credentials');
429 $s .= '<div id="statusnet-info" ><img id="statusnet-avatar" src="' . $details->profile_image_url . '" /><p id="statusnet-info-block">' . t('Currently connected to: ') . '<a href="' . $details->statusnet_profile_url . '" target="_statusnet">' . $details->screen_name . '</a><br /><em>' . $details->description . '</em></p></div>';
430 $s .= '<p>' . 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>';
431 if ($a->user['hidewall']) {
432 $s .= '<p>' . t('<strong>Note</strong>: Due your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to GNU Social will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
434 $s .= '<div id="statusnet-enable-wrapper">';
435 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">' . t('Allow posting to GNU Social') . '</label>';
436 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
437 $s .= '<div class="clear"></div>';
438 $s .= '<label id="statusnet-default-label" for="statusnet-default">' . t('Send public postings to GNU Social by default') . '</label>';
439 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
440 $s .= '<div class="clear"></div>';
442 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">' . t('Mirror all posts from GNU Social that are no replies or repeated messages') . '</label>';
443 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" ' . $mirrorchecked . '/>';
445 $s .= '<div class="clear"></div>';
448 $s .= '<label id="statusnet-import-label" for="statusnet-import">' . t('Import the remote timeline') . '</label>';
449 //$s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
451 $s .= '<select name="statusnet-import" id="statusnet-import" />';
452 $s .= '<option value="0" ' . $importselected[0] . '>' . t("Disabled") . '</option>';
453 $s .= '<option value="1" ' . $importselected[1] . '>' . t("Full Timeline") . '</option>';
454 $s .= '<option value="2" ' . $importselected[2] . '>' . t("Only Mentions") . '</option>';
456 $s .= '<div class="clear"></div>';
458 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.t('Automatically create contacts').'</label>';
459 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
460 $s .= '<div class="clear"></div>';
462 $s .= '<div id="statusnet-disconnect-wrapper">';
463 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">' . t('Clear OAuth configuration') . '</label>';
464 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
465 $s .= '</div><div class="clear"></div>';
466 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
469 $s .= '</div><div class="clear"></div>';
472 function statusnet_post_local(App $a, &$b)
478 if (!local_user() || (local_user() != $b['uid'])) {
482 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
483 $statusnet_enable = (($statusnet_post && x($_REQUEST, 'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
485 // if API is used, default to the chosen settings
486 if ($b['api_source'] && intval(PConfig::get(local_user(), 'statusnet', 'post_by_default'))) {
487 $statusnet_enable = 1;
490 if (!$statusnet_enable) {
494 if (strlen($b['postopts'])) {
495 $b['postopts'] .= ',';
498 $b['postopts'] .= 'statusnet';
501 function statusnet_action(App $a, $uid, $pid, $action)
503 $api = PConfig::get($uid, 'statusnet', 'baseapi');
504 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
505 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
506 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
507 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
509 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
511 logger("statusnet_action '" . $action . "' ID: " . $pid, LOGGER_DATA);
515 $result = $connection->post("statuses/destroy/" . $pid);
518 $result = $connection->post("favorites/create/" . $pid);
521 $result = $connection->post("favorites/destroy/" . $pid);
524 logger("statusnet_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
527 function statusnet_post_hook(App $a, &$b)
532 if (!PConfig::get($b["uid"], 'statusnet', 'import')) {
533 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
537 $api = PConfig::get($b["uid"], 'statusnet', 'baseapi');
538 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
540 if ($b['parent'] != $b['id']) {
541 logger("statusnet_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
543 // Looking if its a reply to a GNU Social post
544 $hostlength = strlen($hostname) + 2;
545 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) {
546 logger("statusnet_post_hook: no GNU Social post " . $b["parent"]);
550 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
551 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
552 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1", dbesc($b["thr-parent"]), intval($b["uid"]));
555 logger("statusnet_post_hook: no parent found " . $b["thr-parent"]);
562 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
563 //$nicknameplain = "@".$orig_post["contact_nick"];
565 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
567 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
568 $nicknameplain = "@" . $nick;
570 logger("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
571 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
572 $b["body"] = $nickname . " " . $b["body"];
575 logger("statusnet_post_hook: parent found " . print_r($orig_post, true), LOGGER_DEBUG);
579 if ($b['private'] || !strstr($b['postopts'], 'statusnet')) {
583 // Dont't post if the post doesn't belong to us.
584 // This is a check for forum postings
585 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
586 if ($b['contact-id'] != $self['id']) {
591 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
592 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
595 if ($b['verb'] == ACTIVITY_LIKE) {
596 logger("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
598 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
600 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
604 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
608 // if posts comes from GNU Social don't send it back
609 if ($b['extid'] == NETWORK_STATUSNET) {
613 if ($b['app'] == "StatusNet") {
617 logger('GNU Socialpost invoked');
619 PConfig::load($b['uid'], 'statusnet');
621 $api = PConfig::get($b['uid'], 'statusnet', 'baseapi');
622 $ckey = PConfig::get($b['uid'], 'statusnet', 'consumerkey');
623 $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret');
624 $otoken = PConfig::get($b['uid'], 'statusnet', 'oauthtoken');
625 $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret');
627 if ($ckey && $csecret && $otoken && $osecret) {
628 // If it's a repeated message from GNU Social then do a native retweet and exit
629 if (statusnet_is_retweet($a, $b['uid'], $b['body'])) {
633 require_once 'include/bbcode.php';
634 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
635 $max_char = $dent->get_maxlength(); // max. length for a dent
637 PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char);
640 require_once "include/plaintext.php";
641 require_once "include/network.php";
642 $msgarr = plaintext($b, $max_char, true, 7);
643 $msg = $msgarr["text"];
645 if (($msg == "") && isset($msgarr["title"]))
646 $msg = shortenmsg($msgarr["title"], $max_char - 50);
650 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
651 if ((strlen($msgarr["url"]) > 20) &&
652 ((strlen($msg . " \n" . $msgarr["url"]) > $max_char))) {
653 $msg .= " \n" . short_link($msgarr["url"]);
655 $msg .= " \n" . $msgarr["url"];
657 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
658 $image = $msgarr["image"];
662 $img_str = fetch_url($image);
663 $tempfile = tempnam(get_temppath(), "cache");
664 file_put_contents($tempfile, $img_str);
665 $postdata = array("status" => $msg, "media[]" => $tempfile);
667 $postdata = array("status" => $msg);
670 // and now dent it :-)
673 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
674 logger('statusnet_post send reply ' . print_r($postdata, true), LOGGER_DEBUG);
677 // New code that is able to post pictures
678 require_once "addon/statusnet/codebird.php";
679 $cb = \CodebirdSN\CodebirdSN::getInstance();
680 $cb->setAPIEndpoint($api);
681 $cb->setConsumerKey($ckey, $csecret);
682 $cb->setToken($otoken, $osecret);
683 $result = $cb->statuses_update($postdata);
684 //$result = $dent->post('statuses/update', $postdata);
685 logger('statusnet_post send, result: ' . print_r($result, true) .
686 "\nmessage: " . $msg, LOGGER_DEBUG . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
688 if ($result->source) {
689 PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
692 if ($result->error) {
693 logger('Send to GNU Social failed: "' . $result->error . '"');
694 } elseif ($iscomment) {
695 logger('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
696 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
697 dbesc($hostname . "::" . $result->id),
698 dbesc($result->text),
703 if ($tempfile != "") {
709 function statusnet_plugin_admin_post(App $a)
713 foreach ($_POST['sitename'] as $id => $sitename) {
714 $sitename = trim($sitename);
715 $apiurl = trim($_POST['apiurl'][$id]);
716 if (!(substr($apiurl, -1) == '/')) {
717 $apiurl = $apiurl . '/';
719 $secret = trim($_POST['secret'][$id]);
720 $key = trim($_POST['key'][$id]);
721 //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
722 if ($sitename != "" &&
726 !x($_POST['delete'][$id])) {
729 'sitename' => $sitename,
731 'consumersecret' => $secret,
732 'consumerkey' => $key,
733 //'applicationname' => $applicationname
738 $sites = Config::set('statusnet', 'sites', $sites);
741 function statusnet_plugin_admin(App $a, &$o)
743 $sites = Config::get('statusnet', 'sites');
744 $sitesform = array();
745 if (is_array($sites)) {
746 foreach ($sites as $id => $s) {
747 $sitesform[] = Array(
748 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
749 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29")),
750 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
751 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
752 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
753 'delete' => Array("delete[$id]", "Delete", False, "Check to delete this preset"),
757 /* empty form to add new site */
759 $sitesform[] = Array(
760 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
761 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29")),
762 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
763 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
764 //'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
767 $t = get_markup_template("admin.tpl", "addon/statusnet/");
768 $o = replace_macros($t, array(
769 '$submit' => t('Save Settings'),
770 '$sites' => $sitesform,
774 function statusnet_prepare_body(App $a, &$b)
776 if ($b["item"]["network"] != NETWORK_STATUSNET) {
781 $max_char = PConfig::get(local_user(), 'statusnet', 'max_char');
782 if (intval($max_char) == 0) {
786 require_once "include/plaintext.php";
788 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
790 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
791 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
792 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
793 dbesc($item["thr-parent"]),
794 intval(local_user()));
798 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
799 //$nicknameplain = "@".$orig_post["contact_nick"];
801 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
803 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
804 $nicknameplain = "@" . $nick;
806 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
807 $item["body"] = $nickname . " " . $item["body"];
811 $msgarr = plaintext($item, $max_char, true, 7);
812 $msg = $msgarr["text"];
814 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
815 $msg .= " " . $msgarr["url"];
818 if (isset($msgarr["image"])) {
819 $msg .= " " . $msgarr["image"];
822 $b['html'] = nl2br(htmlspecialchars($msg));
826 function statusnet_cron(App $a, $b)
828 $last = Config::get('statusnet', 'last_poll');
830 $poll_interval = intval(Config::get('statusnet', 'poll_interval'));
831 if (!$poll_interval) {
832 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
836 $next = $last + ($poll_interval * 60);
837 if ($next > time()) {
838 logger('statusnet: poll intervall not reached');
842 logger('statusnet: cron_start');
844 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
846 foreach ($r as $rr) {
847 logger('statusnet: fetching for user ' . $rr['uid']);
848 statusnet_fetchtimeline($a, $rr['uid']);
852 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
853 if ($abandon_days < 1) {
857 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
859 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
861 foreach ($r as $rr) {
862 if ($abandon_days != 0) {
863 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
865 logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
870 logger('statusnet: importing timeline from user ' . $rr['uid']);
871 statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
875 logger('statusnet: cron_end');
877 Config::set('statusnet', 'last_poll', time());
880 function statusnet_fetchtimeline(App $a, $uid)
882 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
883 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
884 $api = PConfig::get($uid, 'statusnet', 'baseapi');
885 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
886 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
887 $lastid = PConfig::get($uid, 'statusnet', 'lastid');
889 require_once 'mod/item.php';
890 require_once 'include/items.php';
892 // get the application name for the SN app
893 // 1st try personal config, then system config and fallback to the
894 // hostname of the node if neither one is set.
895 $application_name = PConfig::get($uid, 'statusnet', 'application_name');
896 if ($application_name == "") {
897 $application_name = Config::get('statusnet', 'application_name');
899 if ($application_name == "") {
900 $application_name = $a->get_hostname();
903 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
905 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
907 $first_time = ($lastid == "");
910 $parameters["since_id"] = $lastid;
913 $items = $connection->get('statuses/user_timeline', $parameters);
915 if (!is_array($items)) {
919 $posts = array_reverse($items);
922 foreach ($posts as $post) {
923 if ($post->id > $lastid)
930 if ($post->source == "activity") {
934 if (is_object($post->retweeted_status)) {
938 if ($post->in_reply_to_status_id != "") {
942 if (!stristr($post->source, $application_name)) {
943 $_SESSION["authenticated"] = true;
944 $_SESSION["uid"] = $uid;
947 $_REQUEST["type"] = "wall";
948 $_REQUEST["api_source"] = true;
949 $_REQUEST["profile_uid"] = $uid;
950 //$_REQUEST["source"] = "StatusNet";
951 $_REQUEST["source"] = $post->source;
952 $_REQUEST["extid"] = NETWORK_STATUSNET;
954 if (isset($post->id)) {
955 $_REQUEST['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_STATUSNET . ":" . $post->id);
958 //$_REQUEST["date"] = $post->created_at;
960 $_REQUEST["title"] = "";
962 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
963 if (is_string($post->place->name)) {
964 $_REQUEST["location"] = $post->place->name;
967 if (is_string($post->place->full_name)) {
968 $_REQUEST["location"] = $post->place->full_name;
971 if (is_array($post->geo->coordinates)) {
972 $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
975 if (is_array($post->coordinates->coordinates)) {
976 $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
979 //print_r($_REQUEST);
980 if ($_REQUEST["body"] != "") {
981 logger('statusnet: posting for user ' . $uid);
988 PConfig::set($uid, 'statusnet', 'lastid', $lastid);
991 function statusnet_address($contact)
993 $hostname = normalise_link($contact->statusnet_profile_url);
994 $nickname = $contact->screen_name;
996 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
998 $address = $contact->screen_name . "@" . $hostname;
1003 function statusnet_fetch_contact($uid, $contact, $create_user)
1005 if ($contact->statusnet_profile_url == "") {
1009 GContact::update(array("url" => $contact->statusnet_profile_url,
1010 "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url,
1011 "name" => $contact->name, "nick" => $contact->screen_name,
1012 "location" => $contact->location, "about" => $contact->description,
1013 "addr" => statusnet_address($contact), "generation" => 3));
1015 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)), dbesc(NETWORK_STATUSNET));
1017 if (!count($r) && !$create_user) {
1021 if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
1022 logger("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
1027 // create contact record
1028 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1029 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1030 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1031 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
1033 dbesc(datetime_convert()),
1034 dbesc($contact->statusnet_profile_url),
1035 dbesc(normalise_link($contact->statusnet_profile_url)),
1036 dbesc(statusnet_address($contact)),
1037 dbesc(normalise_link($contact->statusnet_profile_url)),
1040 dbesc($contact->name),
1041 dbesc($contact->screen_name),
1042 dbesc($contact->profile_image_url),
1043 dbesc(NETWORK_STATUSNET),
1044 intval(CONTACT_IS_FRIEND),
1046 dbesc($contact->location),
1047 dbesc($contact->description),
1051 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
1052 dbesc($contact->statusnet_profile_url),
1054 dbesc(NETWORK_STATUSNET));
1060 $contact_id = $r[0]['id'];
1062 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1064 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
1066 q("UPDATE `contact` SET `photo` = '%s',
1069 `avatar-date` = '%s'
1074 dbesc(datetime_convert()),
1078 // update profile photos once every two weeks as we have no notification of when they change.
1079 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1080 $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours'));
1082 // check that we have all the photos, this has been known to fail on occasion
1083 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1084 logger("statusnet_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
1086 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1088 q("UPDATE `contact` SET `photo` = '%s',
1093 `avatar-date` = '%s',
1105 dbesc(datetime_convert()),
1106 dbesc(datetime_convert()),
1107 dbesc(datetime_convert()),
1108 dbesc($contact->statusnet_profile_url),
1109 dbesc(normalise_link($contact->statusnet_profile_url)),
1110 dbesc(statusnet_address($contact)),
1111 dbesc($contact->name),
1112 dbesc($contact->screen_name),
1113 dbesc($contact->location),
1114 dbesc($contact->description),
1123 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1125 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1126 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1127 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1128 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1129 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1131 require_once "addon/statusnet/codebird.php";
1133 $cb = \Codebird\Codebird::getInstance();
1134 $cb->setConsumerKey($ckey, $csecret);
1135 $cb->setToken($otoken, $osecret);
1137 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1146 $parameters = array();
1148 if ($screen_name != "") {
1149 $parameters["screen_name"] = $screen_name;
1152 if ($user_id != "") {
1153 $parameters["user_id"] = $user_id;
1156 // Fetching user data
1157 $user = $cb->users_show($parameters);
1159 if (!is_object($user)) {
1163 $contact_id = statusnet_fetch_contact($uid, $user, true);
1168 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1170 require_once "include/html2bbcode.php";
1172 logger("statusnet_createpost: start", LOGGER_DEBUG);
1174 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1175 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1177 $postarray = array();
1178 $postarray['network'] = NETWORK_STATUSNET;
1179 $postarray['gravity'] = 0;
1180 $postarray['uid'] = $uid;
1181 $postarray['wall'] = 0;
1183 if (is_object($post->retweeted_status)) {
1184 $content = $post->retweeted_status;
1185 statusnet_fetch_contact($uid, $content->user, false);
1190 $postarray['uri'] = $hostname . "::" . $content->id;
1192 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1193 dbesc($postarray['uri']),
1203 if ($content->in_reply_to_status_id != "") {
1205 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1207 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1212 $postarray['thr-parent'] = $r[0]["uri"];
1213 $postarray['parent-uri'] = $r[0]["parent-uri"];
1214 $postarray['parent'] = $r[0]["parent"];
1215 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1217 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1222 $postarray['thr-parent'] = $r[0]['uri'];
1223 $postarray['parent-uri'] = $r[0]['parent-uri'];
1224 $postarray['parent'] = $r[0]['parent'];
1225 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1227 $postarray['thr-parent'] = $postarray['uri'];
1228 $postarray['parent-uri'] = $postarray['uri'];
1229 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1234 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1236 if ($content->user->id == $own_url) {
1237 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1241 $contactid = $r[0]["id"];
1243 $postarray['owner-name'] = $r[0]["name"];
1244 $postarray['owner-link'] = $r[0]["url"];
1245 $postarray['owner-avatar'] = $r[0]["photo"];
1250 // Don't create accounts of people who just comment something
1251 $create_user = false;
1253 $postarray['parent-uri'] = $postarray['uri'];
1254 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1257 if ($contactid == 0) {
1258 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1259 $postarray['owner-name'] = $post->user->name;
1260 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1261 $postarray['owner-avatar'] = $post->user->profile_image_url;
1263 if (($contactid == 0) && !$only_existing_contact) {
1264 $contactid = $self['id'];
1265 } elseif ($contactid <= 0) {
1269 $postarray['contact-id'] = $contactid;
1271 $postarray['verb'] = ACTIVITY_POST;
1273 $postarray['author-name'] = $content->user->name;
1274 $postarray['author-link'] = $content->user->statusnet_profile_url;
1275 $postarray['author-avatar'] = $content->user->profile_image_url;
1277 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1278 $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1280 $postarray['plink'] = $hostname . $content->id;
1281 $postarray['app'] = strip_tags($content->source);
1283 if ($content->user->protected) {
1284 $postarray['private'] = 1;
1285 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1288 $postarray['body'] = html2bbcode($content->statusnet_html);
1290 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1291 $postarray['body'] = $converted["body"];
1292 $postarray['tag'] = $converted["tags"];
1294 $postarray['created'] = datetime_convert('UTC', 'UTC', $content->created_at);
1295 $postarray['edited'] = datetime_convert('UTC', 'UTC', $content->created_at);
1297 if (is_string($content->place->name)) {
1298 $postarray["location"] = $content->place->name;
1301 if (is_string($content->place->full_name)) {
1302 $postarray["location"] = $content->place->full_name;
1305 if (is_array($content->geo->coordinates)) {
1306 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1309 if (is_array($content->coordinates->coordinates)) {
1310 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1313 logger("statusnet_createpost: end", LOGGER_DEBUG);
1318 function statusnet_checknotification(App $a, $uid, $own_url, $top_item, $postarray)
1320 // This function necer worked and need cleanup
1321 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1325 if (!count($user)) {
1330 if (link_compare($user[0]["url"], $postarray['author-link'])) {
1334 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1339 if (!count($own_user)) {
1343 // Is it me from GNU Social?
1344 if (link_compare($own_user[0]["url"], $postarray['author-link'])) {
1348 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1349 dbesc($postarray['parent-uri']),
1353 if (count($myconv)) {
1354 foreach ($myconv as $conv) {
1355 // now if we find a match, it means we're in this conversation
1356 if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) {
1360 require_once 'include/enotify.php';
1362 $conv_parent = $conv['parent'];
1365 'type' => NOTIFY_COMMENT,
1366 'notify_flags' => $user[0]['notify-flags'],
1367 'language' => $user[0]['language'],
1368 'to_name' => $user[0]['username'],
1369 'to_email' => $user[0]['email'],
1370 'uid' => $user[0]['uid'],
1371 'item' => $postarray,
1372 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)),
1373 'source_name' => $postarray['author-name'],
1374 'source_link' => $postarray['author-link'],
1375 'source_photo' => $postarray['author-avatar'],
1376 'verb' => ACTIVITY_POST,
1378 'parent' => $conv_parent,
1381 // only send one notification
1387 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1389 $conversations = array();
1391 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1392 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1393 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1394 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1395 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1396 $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1398 // "create_user" is deactivated, since currently you cannot add users manually by now
1399 $create_user = true;
1401 logger("statusnet_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1403 require_once 'library/twitteroauth.php';
1404 require_once 'include/items.php';
1406 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1408 $own_contact = statusnet_fetch_own_contact($a, $uid);
1410 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1411 intval($own_contact),
1415 $nick = $r[0]["nick"];
1417 logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, LOGGER_DEBUG);
1421 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1427 logger("statusnet_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1431 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1434 logger("statusnet_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1438 $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1439 //$parameters["count"] = 200;
1442 // Fetching timeline
1443 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1446 $first_time = ($lastid == "");
1448 if ($lastid != "") {
1449 $parameters["since_id"] = $lastid;
1452 $items = $connection->get('statuses/home_timeline', $parameters);
1454 if (!is_array($items)) {
1455 if (is_object($items) && isset($items->error)) {
1456 $errormsg = $items->error;
1457 } elseif (is_object($items)) {
1458 $errormsg = print_r($items, true);
1459 } elseif (is_string($items) || is_float($items) || is_int($items)) {
1462 $errormsg = "Unknown error";
1465 logger("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, LOGGER_DEBUG);
1469 $posts = array_reverse($items);
1471 logger("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1473 if (count($posts)) {
1474 foreach ($posts as $post) {
1476 if ($post->id > $lastid) {
1477 $lastid = $post->id;
1484 if (isset($post->statusnet_conversation_id)) {
1485 if (!isset($conversations[$post->statusnet_conversation_id])) {
1486 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1487 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1490 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1492 if (trim($postarray['body']) == "") {
1496 $item = item_store($postarray);
1497 $postarray["id"] = $item;
1499 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1501 if ($item && !function_exists("check_item_notification")) {
1502 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1507 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1510 // Fetching mentions
1511 $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1512 $first_time = ($lastid == "");
1514 if ($lastid != "") {
1515 $parameters["since_id"] = $lastid;
1518 $items = $connection->get('statuses/mentions_timeline', $parameters);
1520 if (!is_array($items)) {
1521 logger("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1525 $posts = array_reverse($items);
1527 logger("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1529 if (count($posts)) {
1530 foreach ($posts as $post) {
1531 if ($post->id > $lastid) {
1532 $lastid = $post->id;
1539 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1541 if (isset($post->statusnet_conversation_id)) {
1542 if (!isset($conversations[$post->statusnet_conversation_id])) {
1543 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1544 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1547 if (trim($postarray['body']) == "") {
1551 $item = item_store($postarray);
1552 $postarray["id"] = $item;
1554 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1556 if ($item && function_exists("check_item_notification")) {
1557 check_item_notification($item, $uid, NOTIFY_TAGSELF);
1561 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1562 dbesc($postarray['uri']),
1566 $item = $r[0]['id'];
1567 $parent_id = $r[0]['parent'];
1570 if (($item != 0) && !function_exists("check_item_notification")) {
1571 require_once 'include/enotify.php';
1573 'type' => NOTIFY_TAGSELF,
1574 'notify_flags' => $u[0]['notify-flags'],
1575 'language' => $u[0]['language'],
1576 'to_name' => $u[0]['username'],
1577 'to_email' => $u[0]['email'],
1578 'uid' => $u[0]['uid'],
1579 'item' => $postarray,
1580 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)),
1581 'source_name' => $postarray['author-name'],
1582 'source_link' => $postarray['author-link'],
1583 'source_photo' => $postarray['author-avatar'],
1584 'verb' => ACTIVITY_TAG,
1586 'parent' => $parent_id,
1592 PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1595 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1597 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1598 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1599 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1600 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1601 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1602 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1604 require_once 'library/twitteroauth.php';
1606 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1608 $parameters["count"] = 200;
1610 $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1611 if (is_array($items)) {
1612 $posts = array_reverse($items);
1614 foreach ($posts AS $post) {
1615 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1617 if (trim($postarray['body']) == "") {
1621 $item = item_store($postarray);
1622 $postarray["id"] = $item;
1624 logger('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1626 if ($item && !function_exists("check_item_notification")) {
1627 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1633 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1635 require_once "include/items.php";
1636 require_once "include/network.php";
1638 $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
1640 $URLSearchString = "^\[\]";
1641 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1649 foreach ($matches AS $match) {
1650 $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
1652 logger("statusnet_convertmsg: expanding url " . $match[1], LOGGER_DEBUG);
1654 $expanded_url = original_url($match[1]);
1656 logger("statusnet_convertmsg: fetching data for " . $expanded_url, LOGGER_DEBUG);
1658 $oembed_data = OEmbed::fetchURL($expanded_url, true);
1660 logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG);
1663 $type = $oembed_data->type;
1666 if ($oembed_data->type == "video") {
1667 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1668 $type = $oembed_data->type;
1669 $footerurl = $expanded_url;
1670 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1672 $body = str_replace($search, $footerlink, $body);
1673 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia) {
1674 $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1675 } elseif ($oembed_data->type != "link") {
1676 $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1678 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1680 $tempfile = tempnam(get_temppath(), "cache");
1681 file_put_contents($tempfile, $img_str);
1682 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1685 if (substr($mime, 0, 6) == "image/") {
1687 $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body);
1689 $type = $oembed_data->type;
1690 $footerurl = $expanded_url;
1691 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1693 $body = str_replace($search, $footerlink, $body);
1698 if ($footerurl != "") {
1699 $footer = add_page_info($footerurl);
1702 if (($footerlink != "") && (trim($footer) != "")) {
1703 $removedlink = trim(str_replace($footerlink, "", $body));
1705 if (($removedlink == "") || strstr($body, $removedlink)) {
1706 $body = $removedlink;
1714 return array("body" => $body, "tags" => "");
1719 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1721 foreach ($matches as $mtch) {
1722 if (strlen($str_tags)) {
1726 if ($mtch[1] == "#") {
1727 // Replacing the hash tags that are directed to the GNU Social server with internal links
1728 $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1729 $frdchash = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($mtch[3]) . ']' . $mtch[3] . '[/url]';
1730 $body = str_replace($snhash, $frdchash, $body);
1732 $str_tags .= $frdchash;
1734 $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1737 // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1738 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1742 return array("body" => $body, "tags" => $str_tags);
1745 function statusnet_fetch_own_contact(App $a, $uid)
1747 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1748 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1749 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1750 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1751 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1752 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1756 if ($own_url == "") {
1757 require_once 'library/twitteroauth.php';
1759 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1761 // Fetching user data
1762 $user = $connection->get('account/verify_credentials');
1764 PConfig::set($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1766 $contact_id = statusnet_fetch_contact($uid, $user, true);
1768 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1769 intval($uid), dbesc($own_url));
1771 $contact_id = $r[0]["id"];
1773 PConfig::delete($uid, 'statusnet', 'own_url');
1779 function statusnet_is_retweet(App $a, $uid, $body)
1781 $body = trim($body);
1783 // Skip if it isn't a pure repeated messages
1784 // Does it start with a share?
1785 if (strpos($body, "[share") > 0) {
1789 // Does it end with a share?
1790 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1794 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1795 // Skip if there is no shared message in there
1796 if ($body == $attributes) {
1801 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1802 if ($matches[1] != "") {
1803 $link = $matches[1];
1806 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1807 if ($matches[1] != "") {
1808 $link = $matches[1];
1811 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1812 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1813 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1814 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1815 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1816 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1818 $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link);
1824 logger('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1826 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1828 $result = $connection->post('statuses/retweet/' . $id);
1830 logger('statusnet_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1832 return isset($result->id);