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"];
574 logger("statusnet_post_hook: parent found " . print_r($orig_post, true), LOGGER_DEBUG);
578 if ($b['private'] || !strstr($b['postopts'], 'statusnet'))
581 // Dont't post if the post doesn't belong to us.
582 // This is a check for forum postings
583 $self = dba::selectOne('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
584 if ($b['contact-id'] != $self['id']) {
589 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
590 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
593 if ($b['verb'] == ACTIVITY_LIKE) {
594 logger("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
596 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
598 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
602 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
606 // if posts comes from GNU Social don't send it back
607 if ($b['extid'] == NETWORK_STATUSNET) {
611 if ($b['app'] == "StatusNet") {
615 logger('GNU Socialpost invoked');
617 PConfig::load($b['uid'], 'statusnet');
619 $api = PConfig::get($b['uid'], 'statusnet', 'baseapi');
620 $ckey = PConfig::get($b['uid'], 'statusnet', 'consumerkey');
621 $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret');
622 $otoken = PConfig::get($b['uid'], 'statusnet', 'oauthtoken');
623 $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret');
625 if ($ckey && $csecret && $otoken && $osecret) {
626 // If it's a repeated message from GNU Social then do a native retweet and exit
627 if (statusnet_is_retweet($a, $b['uid'], $b['body'])) {
631 require_once 'include/bbcode.php';
632 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
633 $max_char = $dent->get_maxlength(); // max. length for a dent
635 PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char);
638 require_once "include/plaintext.php";
639 require_once "include/network.php";
640 $msgarr = plaintext($b, $max_char, true, 7);
641 $msg = $msgarr["text"];
643 if (($msg == "") && isset($msgarr["title"]))
644 $msg = shortenmsg($msgarr["title"], $max_char - 50);
648 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
649 if ((strlen($msgarr["url"]) > 20) &&
650 ((strlen($msg . " \n" . $msgarr["url"]) > $max_char))) {
651 $msg .= " \n" . short_link($msgarr["url"]);
653 $msg .= " \n" . $msgarr["url"];
655 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
656 $image = $msgarr["image"];
660 $img_str = fetch_url($image);
661 $tempfile = tempnam(get_temppath(), "cache");
662 file_put_contents($tempfile, $img_str);
663 $postdata = array("status" => $msg, "media[]" => $tempfile);
665 $postdata = array("status" => $msg);
668 // and now dent it :-)
671 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
672 logger('statusnet_post send reply ' . print_r($postdata, true), LOGGER_DEBUG);
675 // New code that is able to post pictures
676 require_once "addon/statusnet/codebird.php";
677 $cb = \CodebirdSN\CodebirdSN::getInstance();
678 $cb->setAPIEndpoint($api);
679 $cb->setConsumerKey($ckey, $csecret);
680 $cb->setToken($otoken, $osecret);
681 $result = $cb->statuses_update($postdata);
682 //$result = $dent->post('statuses/update', $postdata);
683 logger('statusnet_post send, result: ' . print_r($result, true) .
684 "\nmessage: " . $msg, LOGGER_DEBUG . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
686 if ($result->source) {
687 PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
690 if ($result->error) {
691 logger('Send to GNU Social failed: "' . $result->error . '"');
692 } elseif ($iscomment) {
693 logger('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
694 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
695 dbesc($hostname . "::" . $result->id),
696 dbesc($result->text),
701 if ($tempfile != "") {
707 function statusnet_plugin_admin_post(App $a)
711 foreach ($_POST['sitename'] as $id => $sitename) {
712 $sitename = trim($sitename);
713 $apiurl = trim($_POST['apiurl'][$id]);
714 if (!(substr($apiurl, -1) == '/')) {
715 $apiurl = $apiurl . '/';
717 $secret = trim($_POST['secret'][$id]);
718 $key = trim($_POST['key'][$id]);
719 //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
720 if ($sitename != "" &&
724 !x($_POST['delete'][$id])) {
727 'sitename' => $sitename,
729 'consumersecret' => $secret,
730 'consumerkey' => $key,
731 //'applicationname' => $applicationname
736 $sites = Config::set('statusnet', 'sites', $sites);
739 function statusnet_plugin_admin(App $a, &$o)
741 $sites = Config::get('statusnet', 'sites');
742 $sitesform = array();
743 if (is_array($sites)) {
744 foreach ($sites as $id => $s) {
745 $sitesform[] = Array(
746 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
747 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29")),
748 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
749 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
750 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
751 'delete' => Array("delete[$id]", "Delete", False, "Check to delete this preset"),
755 /* empty form to add new site */
757 $sitesform[] = Array(
758 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
759 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29")),
760 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
761 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
762 //'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
765 $t = get_markup_template("admin.tpl", "addon/statusnet/");
766 $o = replace_macros($t, array(
767 '$submit' => t('Save Settings'),
768 '$sites' => $sitesform,
772 function statusnet_prepare_body(App $a, &$b)
774 if ($b["item"]["network"] != NETWORK_STATUSNET) {
779 $max_char = PConfig::get(local_user(), 'statusnet', 'max_char');
780 if (intval($max_char) == 0) {
784 require_once "include/plaintext.php";
786 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
788 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
789 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
790 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
791 dbesc($item["thr-parent"]),
792 intval(local_user()));
796 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
797 //$nicknameplain = "@".$orig_post["contact_nick"];
799 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
801 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
802 $nicknameplain = "@" . $nick;
804 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
805 $item["body"] = $nickname . " " . $item["body"];
809 $msgarr = plaintext($item, $max_char, true, 7);
810 $msg = $msgarr["text"];
812 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
813 $msg .= " " . $msgarr["url"];
816 if (isset($msgarr["image"])) {
817 $msg .= " " . $msgarr["image"];
820 $b['html'] = nl2br(htmlspecialchars($msg));
824 function statusnet_cron(App $a, $b)
826 $last = Config::get('statusnet', 'last_poll');
828 $poll_interval = intval(Config::get('statusnet', 'poll_interval'));
829 if (!$poll_interval) {
830 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
834 $next = $last + ($poll_interval * 60);
835 if ($next > time()) {
836 logger('statusnet: poll intervall not reached');
840 logger('statusnet: cron_start');
842 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
844 foreach ($r as $rr) {
845 logger('statusnet: fetching for user ' . $rr['uid']);
846 statusnet_fetchtimeline($a, $rr['uid']);
850 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
851 if ($abandon_days < 1) {
855 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
857 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
859 foreach ($r as $rr) {
860 if ($abandon_days != 0) {
861 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
863 logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
868 logger('statusnet: importing timeline from user ' . $rr['uid']);
869 statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
873 logger('statusnet: cron_end');
875 Config::set('statusnet', 'last_poll', time());
878 function statusnet_fetchtimeline(App $a, $uid)
880 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
881 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
882 $api = PConfig::get($uid, 'statusnet', 'baseapi');
883 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
884 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
885 $lastid = PConfig::get($uid, 'statusnet', 'lastid');
887 require_once 'mod/item.php';
888 require_once 'include/items.php';
890 // get the application name for the SN app
891 // 1st try personal config, then system config and fallback to the
892 // hostname of the node if neither one is set.
893 $application_name = PConfig::get($uid, 'statusnet', 'application_name');
894 if ($application_name == "") {
895 $application_name = Config::get('statusnet', 'application_name');
897 if ($application_name == "") {
898 $application_name = $a->get_hostname();
901 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
903 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
905 $first_time = ($lastid == "");
908 $parameters["since_id"] = $lastid;
911 $items = $connection->get('statuses/user_timeline', $parameters);
913 if (!is_array($items)) {
917 $posts = array_reverse($items);
920 foreach ($posts as $post) {
921 if ($post->id > $lastid)
928 if ($post->source == "activity") {
932 if (is_object($post->retweeted_status)) {
936 if ($post->in_reply_to_status_id != "") {
940 if (!stristr($post->source, $application_name)) {
941 $_SESSION["authenticated"] = true;
942 $_SESSION["uid"] = $uid;
945 $_REQUEST["type"] = "wall";
946 $_REQUEST["api_source"] = true;
947 $_REQUEST["profile_uid"] = $uid;
948 //$_REQUEST["source"] = "StatusNet";
949 $_REQUEST["source"] = $post->source;
950 $_REQUEST["extid"] = NETWORK_STATUSNET;
952 if (isset($post->id)) {
953 $_REQUEST['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_STATUSNET . ":" . $post->id);
956 //$_REQUEST["date"] = $post->created_at;
958 $_REQUEST["title"] = "";
960 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
961 if (is_string($post->place->name)) {
962 $_REQUEST["location"] = $post->place->name;
965 if (is_string($post->place->full_name)) {
966 $_REQUEST["location"] = $post->place->full_name;
969 if (is_array($post->geo->coordinates)) {
970 $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
973 if (is_array($post->coordinates->coordinates)) {
974 $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
977 //print_r($_REQUEST);
978 if ($_REQUEST["body"] != "") {
979 logger('statusnet: posting for user ' . $uid);
986 PConfig::set($uid, 'statusnet', 'lastid', $lastid);
989 function statusnet_address($contact)
991 $hostname = normalise_link($contact->statusnet_profile_url);
992 $nickname = $contact->screen_name;
994 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
996 $address = $contact->screen_name . "@" . $hostname;
1001 function statusnet_fetch_contact($uid, $contact, $create_user)
1003 if ($contact->statusnet_profile_url == "") {
1007 GContact::update(array("url" => $contact->statusnet_profile_url,
1008 "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url,
1009 "name" => $contact->name, "nick" => $contact->screen_name,
1010 "location" => $contact->location, "about" => $contact->description,
1011 "addr" => statusnet_address($contact), "generation" => 3));
1013 $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));
1015 if (!count($r) && !$create_user) {
1019 if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
1020 logger("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
1025 // create contact record
1026 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1027 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1028 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1029 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
1031 dbesc(datetime_convert()),
1032 dbesc($contact->statusnet_profile_url),
1033 dbesc(normalise_link($contact->statusnet_profile_url)),
1034 dbesc(statusnet_address($contact)),
1035 dbesc(normalise_link($contact->statusnet_profile_url)),
1038 dbesc($contact->name),
1039 dbesc($contact->screen_name),
1040 dbesc($contact->profile_image_url),
1041 dbesc(NETWORK_STATUSNET),
1042 intval(CONTACT_IS_FRIEND),
1044 dbesc($contact->location),
1045 dbesc($contact->description),
1049 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
1050 dbesc($contact->statusnet_profile_url),
1052 dbesc(NETWORK_STATUSNET));
1058 $contact_id = $r[0]['id'];
1060 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1062 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
1064 q("UPDATE `contact` SET `photo` = '%s',
1067 `avatar-date` = '%s'
1072 dbesc(datetime_convert()),
1076 // update profile photos once every two weeks as we have no notification of when they change.
1077 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1078 $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours'));
1080 // check that we have all the photos, this has been known to fail on occasion
1081 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1082 logger("statusnet_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
1084 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1086 q("UPDATE `contact` SET `photo` = '%s',
1091 `avatar-date` = '%s',
1103 dbesc(datetime_convert()),
1104 dbesc(datetime_convert()),
1105 dbesc(datetime_convert()),
1106 dbesc($contact->statusnet_profile_url),
1107 dbesc(normalise_link($contact->statusnet_profile_url)),
1108 dbesc(statusnet_address($contact)),
1109 dbesc($contact->name),
1110 dbesc($contact->screen_name),
1111 dbesc($contact->location),
1112 dbesc($contact->description),
1121 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1123 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1124 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1125 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1126 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1127 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1129 require_once "addon/statusnet/codebird.php";
1131 $cb = \Codebird\Codebird::getInstance();
1132 $cb->setConsumerKey($ckey, $csecret);
1133 $cb->setToken($otoken, $osecret);
1135 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1144 $parameters = array();
1146 if ($screen_name != "") {
1147 $parameters["screen_name"] = $screen_name;
1150 if ($user_id != "") {
1151 $parameters["user_id"] = $user_id;
1154 // Fetching user data
1155 $user = $cb->users_show($parameters);
1157 if (!is_object($user)) {
1161 $contact_id = statusnet_fetch_contact($uid, $user, true);
1166 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1168 require_once "include/html2bbcode.php";
1170 logger("statusnet_createpost: start", LOGGER_DEBUG);
1172 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1173 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1175 $postarray = array();
1176 $postarray['network'] = NETWORK_STATUSNET;
1177 $postarray['gravity'] = 0;
1178 $postarray['uid'] = $uid;
1179 $postarray['wall'] = 0;
1181 if (is_object($post->retweeted_status)) {
1182 $content = $post->retweeted_status;
1183 statusnet_fetch_contact($uid, $content->user, false);
1188 $postarray['uri'] = $hostname . "::" . $content->id;
1190 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1191 dbesc($postarray['uri']),
1201 if ($content->in_reply_to_status_id != "") {
1203 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1205 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1210 $postarray['thr-parent'] = $r[0]["uri"];
1211 $postarray['parent-uri'] = $r[0]["parent-uri"];
1212 $postarray['parent'] = $r[0]["parent"];
1213 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1215 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1220 $postarray['thr-parent'] = $r[0]['uri'];
1221 $postarray['parent-uri'] = $r[0]['parent-uri'];
1222 $postarray['parent'] = $r[0]['parent'];
1223 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1225 $postarray['thr-parent'] = $postarray['uri'];
1226 $postarray['parent-uri'] = $postarray['uri'];
1227 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1232 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1234 if ($content->user->id == $own_url) {
1235 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1239 $contactid = $r[0]["id"];
1241 $postarray['owner-name'] = $r[0]["name"];
1242 $postarray['owner-link'] = $r[0]["url"];
1243 $postarray['owner-avatar'] = $r[0]["photo"];
1248 // Don't create accounts of people who just comment something
1249 $create_user = false;
1251 $postarray['parent-uri'] = $postarray['uri'];
1252 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1255 if ($contactid == 0) {
1256 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1257 $postarray['owner-name'] = $post->user->name;
1258 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1259 $postarray['owner-avatar'] = $post->user->profile_image_url;
1261 if (($contactid == 0) && !$only_existing_contact) {
1262 $contactid = $self['id'];
1263 } elseif ($contactid <= 0) {
1267 $postarray['contact-id'] = $contactid;
1269 $postarray['verb'] = ACTIVITY_POST;
1271 $postarray['author-name'] = $content->user->name;
1272 $postarray['author-link'] = $content->user->statusnet_profile_url;
1273 $postarray['author-avatar'] = $content->user->profile_image_url;
1275 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1276 $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1278 $postarray['plink'] = $hostname . $content->id;
1279 $postarray['app'] = strip_tags($content->source);
1281 if ($content->user->protected) {
1282 $postarray['private'] = 1;
1283 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1286 $postarray['body'] = html2bbcode($content->statusnet_html);
1288 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1289 $postarray['body'] = $converted["body"];
1290 $postarray['tag'] = $converted["tags"];
1292 $postarray['created'] = datetime_convert('UTC', 'UTC', $content->created_at);
1293 $postarray['edited'] = datetime_convert('UTC', 'UTC', $content->created_at);
1295 if (is_string($content->place->name)) {
1296 $postarray["location"] = $content->place->name;
1299 if (is_string($content->place->full_name)) {
1300 $postarray["location"] = $content->place->full_name;
1303 if (is_array($content->geo->coordinates)) {
1304 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1307 if (is_array($content->coordinates->coordinates)) {
1308 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1311 logger("statusnet_createpost: end", LOGGER_DEBUG);
1316 function statusnet_checknotification(App $a, $uid, $own_url, $top_item, $postarray)
1318 // This function necer worked and need cleanup
1319 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1323 if (!count($user)) {
1328 if (link_compare($user[0]["url"], $postarray['author-link'])) {
1332 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1337 if (!count($own_user)) {
1341 // Is it me from GNU Social?
1342 if (link_compare($own_user[0]["url"], $postarray['author-link'])) {
1346 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1347 dbesc($postarray['parent-uri']),
1351 if (count($myconv)) {
1352 foreach ($myconv as $conv) {
1353 // now if we find a match, it means we're in this conversation
1354 if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) {
1358 require_once 'include/enotify.php';
1360 $conv_parent = $conv['parent'];
1363 'type' => NOTIFY_COMMENT,
1364 'notify_flags' => $user[0]['notify-flags'],
1365 'language' => $user[0]['language'],
1366 'to_name' => $user[0]['username'],
1367 'to_email' => $user[0]['email'],
1368 'uid' => $user[0]['uid'],
1369 'item' => $postarray,
1370 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)),
1371 'source_name' => $postarray['author-name'],
1372 'source_link' => $postarray['author-link'],
1373 'source_photo' => $postarray['author-avatar'],
1374 'verb' => ACTIVITY_POST,
1376 'parent' => $conv_parent,
1379 // only send one notification
1385 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1387 $conversations = array();
1389 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1390 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1391 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1392 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1393 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1394 $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1396 // "create_user" is deactivated, since currently you cannot add users manually by now
1397 $create_user = true;
1399 logger("statusnet_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1401 require_once 'library/twitteroauth.php';
1402 require_once 'include/items.php';
1404 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1406 $own_contact = statusnet_fetch_own_contact($a, $uid);
1408 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1409 intval($own_contact),
1413 $nick = $r[0]["nick"];
1415 logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, LOGGER_DEBUG);
1419 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1425 logger("statusnet_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1429 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1432 logger("statusnet_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1436 $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1437 //$parameters["count"] = 200;
1440 // Fetching timeline
1441 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1444 $first_time = ($lastid == "");
1446 if ($lastid != "") {
1447 $parameters["since_id"] = $lastid;
1450 $items = $connection->get('statuses/home_timeline', $parameters);
1452 if (!is_array($items)) {
1453 if (is_object($items) && isset($items->error)) {
1454 $errormsg = $items->error;
1455 } elseif (is_object($items)) {
1456 $errormsg = print_r($items, true);
1457 } elseif (is_string($items) || is_float($items) || is_int($items)) {
1460 $errormsg = "Unknown error";
1463 logger("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, LOGGER_DEBUG);
1467 $posts = array_reverse($items);
1469 logger("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1471 if (count($posts)) {
1472 foreach ($posts as $post) {
1474 if ($post->id > $lastid) {
1475 $lastid = $post->id;
1482 if (isset($post->statusnet_conversation_id)) {
1483 if (!isset($conversations[$post->statusnet_conversation_id])) {
1484 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1485 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1488 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1490 if (trim($postarray['body']) == "") {
1494 $item = item_store($postarray);
1495 $postarray["id"] = $item;
1497 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1499 if ($item && !function_exists("check_item_notification")) {
1500 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1505 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1508 // Fetching mentions
1509 $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1510 $first_time = ($lastid == "");
1512 if ($lastid != "") {
1513 $parameters["since_id"] = $lastid;
1516 $items = $connection->get('statuses/mentions_timeline', $parameters);
1518 if (!is_array($items)) {
1519 logger("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1523 $posts = array_reverse($items);
1525 logger("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1527 if (count($posts)) {
1528 foreach ($posts as $post) {
1529 if ($post->id > $lastid) {
1530 $lastid = $post->id;
1537 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1539 if (isset($post->statusnet_conversation_id)) {
1540 if (!isset($conversations[$post->statusnet_conversation_id])) {
1541 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1542 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1545 if (trim($postarray['body']) == "") {
1549 $item = item_store($postarray);
1550 $postarray["id"] = $item;
1552 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1554 if ($item && function_exists("check_item_notification")) {
1555 check_item_notification($item, $uid, NOTIFY_TAGSELF);
1559 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1560 dbesc($postarray['uri']),
1564 $item = $r[0]['id'];
1565 $parent_id = $r[0]['parent'];
1568 if (($item != 0) && !function_exists("check_item_notification")) {
1569 require_once 'include/enotify.php';
1571 'type' => NOTIFY_TAGSELF,
1572 'notify_flags' => $u[0]['notify-flags'],
1573 'language' => $u[0]['language'],
1574 'to_name' => $u[0]['username'],
1575 'to_email' => $u[0]['email'],
1576 'uid' => $u[0]['uid'],
1577 'item' => $postarray,
1578 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)),
1579 'source_name' => $postarray['author-name'],
1580 'source_link' => $postarray['author-link'],
1581 'source_photo' => $postarray['author-avatar'],
1582 'verb' => ACTIVITY_TAG,
1584 'parent' => $parent_id,
1590 PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1593 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1595 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1596 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1597 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1598 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1599 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1600 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1602 require_once 'library/twitteroauth.php';
1604 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1606 $parameters["count"] = 200;
1608 $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1609 if (is_array($items)) {
1610 $posts = array_reverse($items);
1612 foreach ($posts AS $post) {
1613 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1615 if (trim($postarray['body']) == "") {
1619 $item = item_store($postarray);
1620 $postarray["id"] = $item;
1622 logger('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1624 if ($item && !function_exists("check_item_notification")) {
1625 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1631 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1633 require_once "include/items.php";
1634 require_once "include/network.php";
1636 $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
1638 $URLSearchString = "^\[\]";
1639 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1647 foreach ($matches AS $match) {
1648 $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
1650 logger("statusnet_convertmsg: expanding url " . $match[1], LOGGER_DEBUG);
1652 $expanded_url = original_url($match[1]);
1654 logger("statusnet_convertmsg: fetching data for " . $expanded_url, LOGGER_DEBUG);
1656 $oembed_data = OEmbed::fetchURL($expanded_url, true);
1658 logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG);
1661 $type = $oembed_data->type;
1664 if ($oembed_data->type == "video") {
1665 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1666 $type = $oembed_data->type;
1667 $footerurl = $expanded_url;
1668 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1670 $body = str_replace($search, $footerlink, $body);
1671 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia) {
1672 $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1673 } elseif ($oembed_data->type != "link") {
1674 $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1676 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1678 $tempfile = tempnam(get_temppath(), "cache");
1679 file_put_contents($tempfile, $img_str);
1680 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1683 if (substr($mime, 0, 6) == "image/") {
1685 $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body);
1687 $type = $oembed_data->type;
1688 $footerurl = $expanded_url;
1689 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1691 $body = str_replace($search, $footerlink, $body);
1696 if ($footerurl != "") {
1697 $footer = add_page_info($footerurl);
1700 if (($footerlink != "") && (trim($footer) != "")) {
1701 $removedlink = trim(str_replace($footerlink, "", $body));
1703 if (($removedlink == "") || strstr($body, $removedlink)) {
1704 $body = $removedlink;
1712 return array("body" => $body, "tags" => "");
1717 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1719 foreach ($matches as $mtch) {
1720 if (strlen($str_tags)) {
1724 if ($mtch[1] == "#") {
1725 // Replacing the hash tags that are directed to the GNU Social server with internal links
1726 $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1727 $frdchash = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($mtch[3]) . ']' . $mtch[3] . '[/url]';
1728 $body = str_replace($snhash, $frdchash, $body);
1730 $str_tags .= $frdchash;
1732 $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1735 // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1736 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1740 return array("body" => $body, "tags" => $str_tags);
1743 function statusnet_fetch_own_contact(App $a, $uid)
1745 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1746 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1747 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1748 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1749 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1750 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1754 if ($own_url == "") {
1755 require_once 'library/twitteroauth.php';
1757 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1759 // Fetching user data
1760 $user = $connection->get('account/verify_credentials');
1762 PConfig::set($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1764 $contact_id = statusnet_fetch_contact($uid, $user, true);
1766 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1767 intval($uid), dbesc($own_url));
1769 $contact_id = $r[0]["id"];
1771 PConfig::delete($uid, 'statusnet', 'own_url');
1777 function statusnet_is_retweet(App $a, $uid, $body)
1779 $body = trim($body);
1781 // Skip if it isn't a pure repeated messages
1782 // Does it start with a share?
1783 if (strpos($body, "[share") > 0) {
1787 // Does it end with a share?
1788 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1792 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1793 // Skip if there is no shared message in there
1794 if ($body == $attributes) {
1799 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1800 if ($matches[1] != "") {
1801 $link = $matches[1];
1804 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1805 if ($matches[1] != "") {
1806 $link = $matches[1];
1809 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1810 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1811 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1812 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1813 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1814 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1816 $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link);
1822 logger('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1824 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1826 $result = $connection->post('statuses/retweet/' . $id);
1828 logger('statusnet_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1830 return isset($result->id);