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\Core\Config;
50 use Friendica\Core\PConfig;
51 use Friendica\Model\GContact;
52 use Friendica\Model\Group;
53 use Friendica\Model\Photo;
54 use Friendica\Model\User;
56 class StatusNetOAuth extends TwitterOAuth
58 function get_maxlength()
60 $config = $this->get($this->host . 'statusnet/config.json');
61 return $config->site->textlimit;
64 function accessTokenURL()
66 return $this->host . 'oauth/access_token';
69 function authenticateURL()
71 return $this->host . 'oauth/authenticate';
74 function authorizeURL()
76 return $this->host . 'oauth/authorize';
79 function requestTokenURL()
81 return $this->host . 'oauth/request_token';
84 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL)
86 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
87 $this->host = $apipath;
91 * Make an HTTP request
95 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
97 function http($url, $method, $postfields = NULL)
99 $this->http_info = array();
102 $prx = Config::get('system', 'proxy');
104 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
105 curl_setopt($ci, CURLOPT_PROXY, $prx);
106 $prxusr = Config::get('system', 'proxyuser');
107 if (strlen($prxusr)) {
108 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
111 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
112 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
113 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
114 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
115 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
116 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
117 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
118 curl_setopt($ci, CURLOPT_HEADER, FALSE);
122 curl_setopt($ci, CURLOPT_POST, TRUE);
123 if (!empty($postfields)) {
124 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
128 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
129 if (!empty($postfields)) {
130 $url = "{$url}?{$postfields}";
134 curl_setopt($ci, CURLOPT_URL, $url);
135 $response = curl_exec($ci);
136 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
137 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
144 function statusnet_install()
146 // we need some hooks, for the configuration and for sending tweets
147 register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
148 register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
149 register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
150 register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
151 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
152 register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
153 register_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
154 register_hook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
155 logger("installed GNU Social");
158 function statusnet_uninstall()
160 unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
161 unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
162 unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
163 unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
164 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
165 unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
166 unregister_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
167 unregister_hook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
169 // old setting - remove only
170 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
171 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
172 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
175 function statusnet_check_item_notification(App $a, &$notification_data)
177 $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
180 function statusnet_jot_nets(App $a, &$b)
186 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
187 if (intval($statusnet_post) == 1) {
188 $statusnet_defpost = PConfig::get(local_user(), 'statusnet', 'post_by_default');
189 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
190 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
191 . t('Post to GNU Social') . '</div>';
195 function statusnet_settings_post(App $a, $post)
200 // don't check GNU Social settings if GNU Social submit button is not clicked
201 if (!x($_POST, 'statusnet-submit')) {
205 if (isset($_POST['statusnet-disconnect'])) {
207 * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration
209 PConfig::delete(local_user(), 'statusnet', 'consumerkey');
210 PConfig::delete(local_user(), 'statusnet', 'consumersecret');
211 PConfig::delete(local_user(), 'statusnet', 'post');
212 PConfig::delete(local_user(), 'statusnet', 'post_by_default');
213 PConfig::delete(local_user(), 'statusnet', 'oauthtoken');
214 PConfig::delete(local_user(), 'statusnet', 'oauthsecret');
215 PConfig::delete(local_user(), 'statusnet', 'baseapi');
216 PConfig::delete(local_user(), 'statusnet', 'lastid');
217 PConfig::delete(local_user(), 'statusnet', 'mirror_posts');
218 PConfig::delete(local_user(), 'statusnet', 'import');
219 PConfig::delete(local_user(), 'statusnet', 'create_user');
220 PConfig::delete(local_user(), 'statusnet', 'own_id');
222 if (isset($_POST['statusnet-preconf-apiurl'])) {
224 * If the user used one of the preconfigured GNU Social server credentials
225 * use them. All the data are available in the global config.
226 * Check the API Url never the less and blame the admin if it's not working ^^
228 $globalsn = Config::get('statusnet', 'sites');
229 foreach ($globalsn as $asn) {
230 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
231 $apibase = $asn['apiurl'];
232 $c = fetch_url($apibase . 'statusnet/version.xml');
233 if (strlen($c) > 0) {
234 PConfig::set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey']);
235 PConfig::set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret']);
236 PConfig::set(local_user(), 'statusnet', 'baseapi', $asn['apiurl']);
237 //PConfig::set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
239 notice(t('Please contact your site administrator.<br />The provided API URL is not valid.') . EOL . $asn['apiurl'] . EOL);
243 goaway($a->get_baseurl() . '/settings/connectors');
245 if (isset($_POST['statusnet-consumersecret'])) {
246 // check if we can reach the API of the GNU Social server
247 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
248 // resign quickly after this one try to fix the path ;-)
249 $apibase = $_POST['statusnet-baseapi'];
250 $c = fetch_url($apibase . 'statusnet/version.xml');
251 if (strlen($c) > 0) {
252 // ok the API path is correct, let's save the settings
253 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
254 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
255 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
256 //PConfig::set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
258 // the API path is not correct, maybe missing trailing / ?
259 $apibase = $apibase . '/';
260 $c = fetch_url($apibase . 'statusnet/version.xml');
261 if (strlen($c) > 0) {
262 // ok the API path is now correct, let's save the settings
263 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
264 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
265 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
267 // still not the correct API base, let's do noting
268 notice(t('We could not contact the GNU Social API with the Path you entered.') . EOL);
271 goaway($a->get_baseurl() . '/settings/connectors');
273 if (isset($_POST['statusnet-pin'])) {
274 // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
275 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
276 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
277 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
278 // the token and secret for which the PIN was generated were hidden in the settings
279 // form as token and token2, we need a new connection to GNU Social using these token
280 // and secret to request a Access Token with the PIN
281 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
282 $token = $connection->getAccessToken($_POST['statusnet-pin']);
283 // ok, now that we have the Access Token, save them in the user config
284 PConfig::set(local_user(), 'statusnet', 'oauthtoken', $token['oauth_token']);
285 PConfig::set(local_user(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
286 PConfig::set(local_user(), 'statusnet', 'post', 1);
287 PConfig::set(local_user(), 'statusnet', 'post_taglinks', 1);
288 // reload the Addon Settings page, if we don't do it see Bug #42
289 goaway($a->get_baseurl() . '/settings/connectors');
291 // if no PIN is supplied in the POST variables, the user has changed the setting
292 // to post a dent for every new __public__ posting to the wall
293 PConfig::set(local_user(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
294 PConfig::set(local_user(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
295 PConfig::set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
296 PConfig::set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
297 PConfig::set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
299 if (!intval($_POST['statusnet-mirror']))
300 PConfig::delete(local_user(), 'statusnet', 'lastid');
302 info(t('GNU Social settings updated.') . EOL);
309 function statusnet_settings(App $a, &$s)
314 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
316 * 1) Check that we have a base api url and a consumer key & secret
317 * 2) If no OAuthtoken & stuff is present, generate button to get some
318 * allow the user to cancel the connection process at this step
319 * 3) Checkbox for "Send public notices (respect size limitation)
321 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
322 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
323 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
324 $otoken = PConfig::get(local_user(), 'statusnet', 'oauthtoken');
325 $osecret = PConfig::get(local_user(), 'statusnet', 'oauthsecret');
326 $enabled = PConfig::get(local_user(), 'statusnet', 'post');
327 $checked = (($enabled) ? ' checked="checked" ' : '');
328 $defenabled = PConfig::get(local_user(), 'statusnet', 'post_by_default');
329 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
330 $mirrorenabled = PConfig::get(local_user(), 'statusnet', 'mirror_posts');
331 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
332 $import = PConfig::get(local_user(), 'statusnet', 'import');
333 $importselected = array("", "", "");
334 $importselected[$import] = ' selected="selected"';
335 //$importenabled = PConfig::get(local_user(),'statusnet','import');
336 //$importchecked = (($importenabled) ? ' checked="checked" ' : '');
337 $create_userenabled = PConfig::get(local_user(), 'statusnet', 'create_user');
338 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
340 $css = (($enabled) ? '' : '-disabled');
342 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
343 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . t('GNU Social Import/Export/Mirror') . '</h3>';
345 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
346 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
347 $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . t('GNU Social Import/Export/Mirror') . '</h3>';
350 if ((!$ckey) && (!$csecret)) {
354 $globalsn = Config::get('statusnet', 'sites');
356 * lets check if we have one or more globally configured GNU Social
357 * server OAuth credentials in the configuration. If so offer them
358 * with a little explanation to the user as choice - otherwise
359 * ignore this option entirely.
361 if (!$globalsn == null) {
362 $s .= '<h4>' . t('Globally Available GNU Social OAuthKeys') . '</h4>';
363 $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>';
364 $s .= '<div id="statusnet-preconf-wrapper">';
365 foreach ($globalsn as $asn) {
366 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="' . $asn['apiurl'] . '">' . $asn['sitename'] . '<br />';
368 $s .= '<p></p><div class="clear"></div></div>';
369 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
371 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
372 $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>';
373 $s .= '<div id="statusnet-consumer-wrapper">';
374 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">' . t('OAuth Consumer Key') . '</label>';
375 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
376 $s .= '<div class="clear"></div>';
377 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">' . t('OAuth Consumer Secret') . '</label>';
378 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
379 $s .= '<div class="clear"></div>';
380 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">' . t("Base API Path \x28remember the trailing /\x29") . '</label>';
381 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
382 $s .= '<div class="clear"></div>';
383 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('GNU Socialapplication name').'</label>';
384 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
385 $s .= '<p></p><div class="clear"></div>';
386 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
390 * ok we have a consumer key pair now look into the OAuth stuff
392 if ((!$otoken) && (!$osecret)) {
394 * the user has not yet connected the account to GNU Social
395 * get a temporary OAuth key/secret pair and display a button with
396 * which the user can request a PIN to connect the account to a
397 * account at GNU Social
399 $connection = new StatusNetOAuth($api, $ckey, $csecret);
400 $request_token = $connection->getRequestToken('oob');
401 $token = $request_token['oauth_token'];
403 * make some nice form
405 $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>';
406 $s .= '<a href="' . $connection->getAuthorizeURL($token, False) . '" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="' . t('Log in with GNU Social') . '"></a>';
407 $s .= '<div id="statusnet-pin-wrapper">';
408 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">' . t('Copy the security code from GNU Social here') . '</label>';
409 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
410 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="' . $token . '" />';
411 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="' . $request_token['oauth_token_secret'] . '" />';
412 $s .= '</div><div class="clear"></div>';
413 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
414 $s .= '<h4>' . t('Cancel Connection Process') . '</h4>';
415 $s .= '<div id="statusnet-cancel-wrapper">';
416 $s .= '<p>' . t('Current GNU Social API is') . ': ' . $api . '</p>';
417 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">' . t('Cancel GNU Social Connection') . '</label>';
418 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
419 $s .= '</div><div class="clear"></div>';
420 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
423 * we have an OAuth key / secret pair for the user
424 * so let's give a chance to disable the postings to GNU Social
426 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
427 $details = $connection->get('account/verify_credentials');
428 $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>';
429 $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>';
430 if ($a->user['hidewall']) {
431 $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>';
433 $s .= '<div id="statusnet-enable-wrapper">';
434 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">' . t('Allow posting to GNU Social') . '</label>';
435 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
436 $s .= '<div class="clear"></div>';
437 $s .= '<label id="statusnet-default-label" for="statusnet-default">' . t('Send public postings to GNU Social by default') . '</label>';
438 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
439 $s .= '<div class="clear"></div>';
441 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">' . t('Mirror all posts from GNU Social that are no replies or repeated messages') . '</label>';
442 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" ' . $mirrorchecked . '/>';
444 $s .= '<div class="clear"></div>';
447 $s .= '<label id="statusnet-import-label" for="statusnet-import">' . t('Import the remote timeline') . '</label>';
448 //$s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
450 $s .= '<select name="statusnet-import" id="statusnet-import" />';
451 $s .= '<option value="0" ' . $importselected[0] . '>' . t("Disabled") . '</option>';
452 $s .= '<option value="1" ' . $importselected[1] . '>' . t("Full Timeline") . '</option>';
453 $s .= '<option value="2" ' . $importselected[2] . '>' . t("Only Mentions") . '</option>';
455 $s .= '<div class="clear"></div>';
457 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.t('Automatically create contacts').'</label>';
458 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
459 $s .= '<div class="clear"></div>';
461 $s .= '<div id="statusnet-disconnect-wrapper">';
462 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">' . t('Clear OAuth configuration') . '</label>';
463 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
464 $s .= '</div><div class="clear"></div>';
465 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
468 $s .= '</div><div class="clear"></div>';
471 function statusnet_post_local(App $a, &$b)
477 if (!local_user() || (local_user() != $b['uid'])) {
481 $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
482 $statusnet_enable = (($statusnet_post && x($_REQUEST, 'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
484 // if API is used, default to the chosen settings
485 if ($b['api_source'] && intval(PConfig::get(local_user(), 'statusnet', 'post_by_default'))) {
486 $statusnet_enable = 1;
489 if (!$statusnet_enable) {
493 if (strlen($b['postopts'])) {
494 $b['postopts'] .= ',';
497 $b['postopts'] .= 'statusnet';
500 function statusnet_action(App $a, $uid, $pid, $action)
502 $api = PConfig::get($uid, 'statusnet', 'baseapi');
503 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
504 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
505 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
506 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
508 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
510 logger("statusnet_action '" . $action . "' ID: " . $pid, LOGGER_DATA);
514 $result = $connection->post("statuses/destroy/" . $pid);
517 $result = $connection->post("favorites/create/" . $pid);
520 $result = $connection->post("favorites/destroy/" . $pid);
523 logger("statusnet_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
526 function statusnet_post_hook(App $a, &$b)
531 if (!PConfig::get($b["uid"], 'statusnet', 'import')) {
532 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
536 $api = PConfig::get($b["uid"], 'statusnet', 'baseapi');
537 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
539 if ($b['parent'] != $b['id']) {
540 logger("statusnet_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
542 // Looking if its a reply to a GNU Social post
543 $hostlength = strlen($hostname) + 2;
544 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) {
545 logger("statusnet_post_hook: no GNU Social post " . $b["parent"]);
549 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
550 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
551 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1", dbesc($b["thr-parent"]), intval($b["uid"]));
554 logger("statusnet_post_hook: no parent found " . $b["thr-parent"]);
561 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
562 //$nicknameplain = "@".$orig_post["contact_nick"];
564 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
566 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
567 $nicknameplain = "@" . $nick;
569 logger("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
570 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false))
571 $b["body"] = $nickname . " " . $b["body"];
573 logger("statusnet_post_hook: parent found " . print_r($orig_post, true), LOGGER_DEBUG);
577 if ($b['private'] || !strstr($b['postopts'], 'statusnet'))
580 // Dont't post if the post doesn't belong to us.
581 // This is a check for forum postings
582 $self = dba::select('contact', array('id'), array('uid' => $b['uid'], 'self' => true), array('limit' => 1));
583 if ($b['contact-id'] != $self['id']) {
588 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
589 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
592 if ($b['verb'] == ACTIVITY_LIKE) {
593 logger("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
595 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
597 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
601 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
605 // if posts comes from GNU Social don't send it back
606 if ($b['extid'] == NETWORK_STATUSNET) {
610 if ($b['app'] == "StatusNet") {
614 logger('GNU Socialpost invoked');
616 PConfig::load($b['uid'], 'statusnet');
618 $api = PConfig::get($b['uid'], 'statusnet', 'baseapi');
619 $ckey = PConfig::get($b['uid'], 'statusnet', 'consumerkey');
620 $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret');
621 $otoken = PConfig::get($b['uid'], 'statusnet', 'oauthtoken');
622 $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret');
624 if ($ckey && $csecret && $otoken && $osecret) {
625 // If it's a repeated message from GNU Social then do a native retweet and exit
626 if (statusnet_is_retweet($a, $b['uid'], $b['body'])) {
630 require_once 'include/bbcode.php';
631 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
632 $max_char = $dent->get_maxlength(); // max. length for a dent
634 PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char);
637 require_once "include/plaintext.php";
638 require_once "include/network.php";
639 $msgarr = plaintext($a, $b, $max_char, true, 7);
640 $msg = $msgarr["text"];
642 if (($msg == "") && isset($msgarr["title"]))
643 $msg = shortenmsg($msgarr["title"], $max_char - 50);
647 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
648 if ((strlen($msgarr["url"]) > 20) &&
649 ((strlen($msg . " \n" . $msgarr["url"]) > $max_char))) {
650 $msg .= " \n" . short_link($msgarr["url"]);
652 $msg .= " \n" . $msgarr["url"];
654 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
655 $image = $msgarr["image"];
659 $img_str = fetch_url($image);
660 $tempfile = tempnam(get_temppath(), "cache");
661 file_put_contents($tempfile, $img_str);
662 $postdata = array("status" => $msg, "media[]" => $tempfile);
664 $postdata = array("status" => $msg);
667 // and now dent it :-)
670 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
671 logger('statusnet_post send reply ' . print_r($postdata, true), LOGGER_DEBUG);
674 // New code that is able to post pictures
675 require_once "addon/statusnet/codebird.php";
676 $cb = \CodebirdSN\CodebirdSN::getInstance();
677 $cb->setAPIEndpoint($api);
678 $cb->setConsumerKey($ckey, $csecret);
679 $cb->setToken($otoken, $osecret);
680 $result = $cb->statuses_update($postdata);
681 //$result = $dent->post('statuses/update', $postdata);
682 logger('statusnet_post send, result: ' . print_r($result, true) .
683 "\nmessage: " . $msg, LOGGER_DEBUG . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
685 if ($result->source) {
686 PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
689 if ($result->error) {
690 logger('Send to GNU Social failed: "' . $result->error . '"');
691 } elseif ($iscomment) {
692 logger('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
693 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
694 dbesc($hostname . "::" . $result->id),
695 dbesc($result->text),
700 if ($tempfile != "") {
706 function statusnet_plugin_admin_post(App $a)
710 foreach ($_POST['sitename'] as $id => $sitename) {
711 $sitename = trim($sitename);
712 $apiurl = trim($_POST['apiurl'][$id]);
713 if (!(substr($apiurl, -1) == '/')) {
714 $apiurl = $apiurl . '/';
716 $secret = trim($_POST['secret'][$id]);
717 $key = trim($_POST['key'][$id]);
718 //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
719 if ($sitename != "" &&
723 !x($_POST['delete'][$id])) {
726 'sitename' => $sitename,
728 'consumersecret' => $secret,
729 'consumerkey' => $key,
730 //'applicationname' => $applicationname
735 $sites = Config::set('statusnet', 'sites', $sites);
738 function statusnet_plugin_admin(App $a, &$o)
740 $sites = Config::get('statusnet', 'sites');
741 $sitesform = array();
742 if (is_array($sites)) {
743 foreach ($sites as $id => $s) {
744 $sitesform[] = Array(
745 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
746 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29")),
747 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
748 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
749 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
750 'delete' => Array("delete[$id]", "Delete", False, "Check to delete this preset"),
754 /* empty form to add new site */
756 $sitesform[] = Array(
757 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
758 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29")),
759 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
760 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
761 //'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
764 $t = get_markup_template("admin.tpl", "addon/statusnet/");
765 $o = replace_macros($t, array(
766 '$submit' => t('Save Settings'),
767 '$sites' => $sitesform,
771 function statusnet_prepare_body(App $a, &$b)
773 if ($b["item"]["network"] != NETWORK_STATUSNET) {
778 $max_char = PConfig::get(local_user(), 'statusnet', 'max_char');
779 if (intval($max_char) == 0) {
783 require_once "include/plaintext.php";
785 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
787 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
788 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
789 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
790 dbesc($item["thr-parent"]),
791 intval(local_user()));
795 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
796 //$nicknameplain = "@".$orig_post["contact_nick"];
798 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
800 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
801 $nicknameplain = "@" . $nick;
803 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
804 $item["body"] = $nickname . " " . $item["body"];
808 $msgarr = plaintext($a, $item, $max_char, true, 7);
809 $msg = $msgarr["text"];
811 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
812 $msg .= " " . $msgarr["url"];
815 if (isset($msgarr["image"])) {
816 $msg .= " " . $msgarr["image"];
819 $b['html'] = nl2br(htmlspecialchars($msg));
823 function statusnet_cron(App $a, $b)
825 $last = Config::get('statusnet', 'last_poll');
827 $poll_interval = intval(Config::get('statusnet', 'poll_interval'));
828 if (!$poll_interval) {
829 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
833 $next = $last + ($poll_interval * 60);
834 if ($next > time()) {
835 logger('statusnet: poll intervall not reached');
839 logger('statusnet: cron_start');
841 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
843 foreach ($r as $rr) {
844 logger('statusnet: fetching for user ' . $rr['uid']);
845 statusnet_fetchtimeline($a, $rr['uid']);
849 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
850 if ($abandon_days < 1) {
854 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
856 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
858 foreach ($r as $rr) {
859 if ($abandon_days != 0) {
860 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
862 logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
867 logger('statusnet: importing timeline from user ' . $rr['uid']);
868 statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
872 logger('statusnet: cron_end');
874 Config::set('statusnet', 'last_poll', time());
877 function statusnet_fetchtimeline(App $a, $uid)
879 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
880 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
881 $api = PConfig::get($uid, 'statusnet', 'baseapi');
882 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
883 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
884 $lastid = PConfig::get($uid, 'statusnet', 'lastid');
886 require_once 'mod/item.php';
887 require_once 'include/items.php';
889 // get the application name for the SN app
890 // 1st try personal config, then system config and fallback to the
891 // hostname of the node if neither one is set.
892 $application_name = PConfig::get($uid, 'statusnet', 'application_name');
893 if ($application_name == "") {
894 $application_name = Config::get('statusnet', 'application_name');
896 if ($application_name == "") {
897 $application_name = $a->get_hostname();
900 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
902 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
904 $first_time = ($lastid == "");
907 $parameters["since_id"] = $lastid;
910 $items = $connection->get('statuses/user_timeline', $parameters);
912 if (!is_array($items)) {
916 $posts = array_reverse($items);
919 foreach ($posts as $post) {
920 if ($post->id > $lastid)
927 if ($post->source == "activity") {
931 if (is_object($post->retweeted_status)) {
935 if ($post->in_reply_to_status_id != "") {
939 if (!stristr($post->source, $application_name)) {
940 $_SESSION["authenticated"] = true;
941 $_SESSION["uid"] = $uid;
944 $_REQUEST["type"] = "wall";
945 $_REQUEST["api_source"] = true;
946 $_REQUEST["profile_uid"] = $uid;
947 //$_REQUEST["source"] = "StatusNet";
948 $_REQUEST["source"] = $post->source;
949 $_REQUEST["extid"] = NETWORK_STATUSNET;
951 if (isset($post->id)) {
952 $_REQUEST['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_STATUSNET . ":" . $post->id);
955 //$_REQUEST["date"] = $post->created_at;
957 $_REQUEST["title"] = "";
959 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
960 if (is_string($post->place->name)) {
961 $_REQUEST["location"] = $post->place->name;
964 if (is_string($post->place->full_name)) {
965 $_REQUEST["location"] = $post->place->full_name;
968 if (is_array($post->geo->coordinates)) {
969 $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
972 if (is_array($post->coordinates->coordinates)) {
973 $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
976 //print_r($_REQUEST);
977 if ($_REQUEST["body"] != "") {
978 logger('statusnet: posting for user ' . $uid);
985 PConfig::set($uid, 'statusnet', 'lastid', $lastid);
988 function statusnet_address($contact)
990 $hostname = normalise_link($contact->statusnet_profile_url);
991 $nickname = $contact->screen_name;
993 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
995 $address = $contact->screen_name . "@" . $hostname;
1000 function statusnet_fetch_contact($uid, $contact, $create_user)
1002 if ($contact->statusnet_profile_url == "") {
1006 GContact::update(array("url" => $contact->statusnet_profile_url,
1007 "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url,
1008 "name" => $contact->name, "nick" => $contact->screen_name,
1009 "location" => $contact->location, "about" => $contact->description,
1010 "addr" => statusnet_address($contact), "generation" => 3));
1012 $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));
1014 if (!count($r) && !$create_user) {
1018 if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
1019 logger("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
1024 // create contact record
1025 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1026 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1027 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1028 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
1030 dbesc(datetime_convert()),
1031 dbesc($contact->statusnet_profile_url),
1032 dbesc(normalise_link($contact->statusnet_profile_url)),
1033 dbesc(statusnet_address($contact)),
1034 dbesc(normalise_link($contact->statusnet_profile_url)),
1037 dbesc($contact->name),
1038 dbesc($contact->screen_name),
1039 dbesc($contact->profile_image_url),
1040 dbesc(NETWORK_STATUSNET),
1041 intval(CONTACT_IS_FRIEND),
1043 dbesc($contact->location),
1044 dbesc($contact->description),
1048 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
1049 dbesc($contact->statusnet_profile_url),
1051 dbesc(NETWORK_STATUSNET));
1057 $contact_id = $r[0]['id'];
1059 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1061 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
1063 q("UPDATE `contact` SET `photo` = '%s',
1066 `avatar-date` = '%s'
1071 dbesc(datetime_convert()),
1075 // update profile photos once every two weeks as we have no notification of when they change.
1076 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1077 $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours'));
1079 // check that we have all the photos, this has been known to fail on occasion
1080 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1081 logger("statusnet_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
1083 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1085 q("UPDATE `contact` SET `photo` = '%s',
1090 `avatar-date` = '%s',
1102 dbesc(datetime_convert()),
1103 dbesc(datetime_convert()),
1104 dbesc(datetime_convert()),
1105 dbesc($contact->statusnet_profile_url),
1106 dbesc(normalise_link($contact->statusnet_profile_url)),
1107 dbesc(statusnet_address($contact)),
1108 dbesc($contact->name),
1109 dbesc($contact->screen_name),
1110 dbesc($contact->location),
1111 dbesc($contact->description),
1120 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1122 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1123 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1124 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1125 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1126 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1128 require_once "addon/statusnet/codebird.php";
1130 $cb = \Codebird\Codebird::getInstance();
1131 $cb->setConsumerKey($ckey, $csecret);
1132 $cb->setToken($otoken, $osecret);
1134 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1143 $parameters = array();
1145 if ($screen_name != "") {
1146 $parameters["screen_name"] = $screen_name;
1149 if ($user_id != "") {
1150 $parameters["user_id"] = $user_id;
1153 // Fetching user data
1154 $user = $cb->users_show($parameters);
1156 if (!is_object($user)) {
1160 $contact_id = statusnet_fetch_contact($uid, $user, true);
1165 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1167 require_once "include/html2bbcode.php";
1169 logger("statusnet_createpost: start", LOGGER_DEBUG);
1171 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1172 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1174 $postarray = array();
1175 $postarray['network'] = NETWORK_STATUSNET;
1176 $postarray['gravity'] = 0;
1177 $postarray['uid'] = $uid;
1178 $postarray['wall'] = 0;
1180 if (is_object($post->retweeted_status)) {
1181 $content = $post->retweeted_status;
1182 statusnet_fetch_contact($uid, $content->user, false);
1187 $postarray['uri'] = $hostname . "::" . $content->id;
1189 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1190 dbesc($postarray['uri']),
1200 if ($content->in_reply_to_status_id != "") {
1202 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1204 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1209 $postarray['thr-parent'] = $r[0]["uri"];
1210 $postarray['parent-uri'] = $r[0]["parent-uri"];
1211 $postarray['parent'] = $r[0]["parent"];
1212 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1214 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1219 $postarray['thr-parent'] = $r[0]['uri'];
1220 $postarray['parent-uri'] = $r[0]['parent-uri'];
1221 $postarray['parent'] = $r[0]['parent'];
1222 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1224 $postarray['thr-parent'] = $postarray['uri'];
1225 $postarray['parent-uri'] = $postarray['uri'];
1226 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1231 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1233 if ($content->user->id == $own_url) {
1234 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1238 $contactid = $r[0]["id"];
1240 $postarray['owner-name'] = $r[0]["name"];
1241 $postarray['owner-link'] = $r[0]["url"];
1242 $postarray['owner-avatar'] = $r[0]["photo"];
1247 // Don't create accounts of people who just comment something
1248 $create_user = false;
1250 $postarray['parent-uri'] = $postarray['uri'];
1251 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1254 if ($contactid == 0) {
1255 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1256 $postarray['owner-name'] = $post->user->name;
1257 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1258 $postarray['owner-avatar'] = $post->user->profile_image_url;
1260 if (($contactid == 0) && !$only_existing_contact) {
1261 $contactid = $self['id'];
1262 } elseif ($contactid <= 0) {
1266 $postarray['contact-id'] = $contactid;
1268 $postarray['verb'] = ACTIVITY_POST;
1270 $postarray['author-name'] = $content->user->name;
1271 $postarray['author-link'] = $content->user->statusnet_profile_url;
1272 $postarray['author-avatar'] = $content->user->profile_image_url;
1274 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1275 $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1277 $postarray['plink'] = $hostname . $content->id;
1278 $postarray['app'] = strip_tags($content->source);
1280 if ($content->user->protected) {
1281 $postarray['private'] = 1;
1282 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1285 $postarray['body'] = html2bbcode($content->statusnet_html);
1287 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1288 $postarray['body'] = $converted["body"];
1289 $postarray['tag'] = $converted["tags"];
1291 $postarray['created'] = datetime_convert('UTC', 'UTC', $content->created_at);
1292 $postarray['edited'] = datetime_convert('UTC', 'UTC', $content->created_at);
1294 if (is_string($content->place->name)) {
1295 $postarray["location"] = $content->place->name;
1298 if (is_string($content->place->full_name)) {
1299 $postarray["location"] = $content->place->full_name;
1302 if (is_array($content->geo->coordinates)) {
1303 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1306 if (is_array($content->coordinates->coordinates)) {
1307 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1310 logger("statusnet_createpost: end", LOGGER_DEBUG);
1315 function statusnet_checknotification(App $a, $uid, $own_url, $top_item, $postarray)
1317 // This function necer worked and need cleanup
1318 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1322 if (!count($user)) {
1327 if (link_compare($user[0]["url"], $postarray['author-link'])) {
1331 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1336 if (!count($own_user)) {
1340 // Is it me from GNU Social?
1341 if (link_compare($own_user[0]["url"], $postarray['author-link'])) {
1345 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1346 dbesc($postarray['parent-uri']),
1350 if (count($myconv)) {
1351 foreach ($myconv as $conv) {
1352 // now if we find a match, it means we're in this conversation
1353 if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) {
1357 require_once 'include/enotify.php';
1359 $conv_parent = $conv['parent'];
1362 'type' => NOTIFY_COMMENT,
1363 'notify_flags' => $user[0]['notify-flags'],
1364 'language' => $user[0]['language'],
1365 'to_name' => $user[0]['username'],
1366 'to_email' => $user[0]['email'],
1367 'uid' => $user[0]['uid'],
1368 'item' => $postarray,
1369 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)),
1370 'source_name' => $postarray['author-name'],
1371 'source_link' => $postarray['author-link'],
1372 'source_photo' => $postarray['author-avatar'],
1373 'verb' => ACTIVITY_POST,
1375 'parent' => $conv_parent,
1378 // only send one notification
1384 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1386 $conversations = array();
1388 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1389 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1390 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1391 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1392 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1393 $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1395 // "create_user" is deactivated, since currently you cannot add users manually by now
1396 $create_user = true;
1398 logger("statusnet_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1400 require_once 'library/twitteroauth.php';
1401 require_once 'include/items.php';
1403 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1405 $own_contact = statusnet_fetch_own_contact($a, $uid);
1407 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1408 intval($own_contact),
1412 $nick = $r[0]["nick"];
1414 logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, LOGGER_DEBUG);
1418 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1424 logger("statusnet_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1428 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1431 logger("statusnet_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1435 $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1436 //$parameters["count"] = 200;
1439 // Fetching timeline
1440 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1443 $first_time = ($lastid == "");
1445 if ($lastid != "") {
1446 $parameters["since_id"] = $lastid;
1449 $items = $connection->get('statuses/home_timeline', $parameters);
1451 if (!is_array($items)) {
1452 if (is_object($items) && isset($items->error)) {
1453 $errormsg = $items->error;
1454 } elseif (is_object($items)) {
1455 $errormsg = print_r($items, true);
1456 } elseif (is_string($items) || is_float($items) || is_int($items)) {
1459 $errormsg = "Unknown error";
1462 logger("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, LOGGER_DEBUG);
1466 $posts = array_reverse($items);
1468 logger("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1470 if (count($posts)) {
1471 foreach ($posts as $post) {
1473 if ($post->id > $lastid) {
1474 $lastid = $post->id;
1481 if (isset($post->statusnet_conversation_id)) {
1482 if (!isset($conversations[$post->statusnet_conversation_id])) {
1483 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1484 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1487 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1489 if (trim($postarray['body']) == "") {
1493 $item = item_store($postarray);
1494 $postarray["id"] = $item;
1496 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1498 if ($item && !function_exists("check_item_notification")) {
1499 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1504 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1507 // Fetching mentions
1508 $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1509 $first_time = ($lastid == "");
1511 if ($lastid != "") {
1512 $parameters["since_id"] = $lastid;
1515 $items = $connection->get('statuses/mentions_timeline', $parameters);
1517 if (!is_array($items)) {
1518 logger("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1522 $posts = array_reverse($items);
1524 logger("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1526 if (count($posts)) {
1527 foreach ($posts as $post) {
1528 if ($post->id > $lastid) {
1529 $lastid = $post->id;
1536 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1538 if (isset($post->statusnet_conversation_id)) {
1539 if (!isset($conversations[$post->statusnet_conversation_id])) {
1540 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1541 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1544 if (trim($postarray['body']) == "") {
1548 $item = item_store($postarray);
1549 $postarray["id"] = $item;
1551 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1553 if ($item && function_exists("check_item_notification")) {
1554 check_item_notification($item, $uid, NOTIFY_TAGSELF);
1558 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1559 dbesc($postarray['uri']),
1563 $item = $r[0]['id'];
1564 $parent_id = $r[0]['parent'];
1567 if (($item != 0) && !function_exists("check_item_notification")) {
1568 require_once 'include/enotify.php';
1570 'type' => NOTIFY_TAGSELF,
1571 'notify_flags' => $u[0]['notify-flags'],
1572 'language' => $u[0]['language'],
1573 'to_name' => $u[0]['username'],
1574 'to_email' => $u[0]['email'],
1575 'uid' => $u[0]['uid'],
1576 'item' => $postarray,
1577 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)),
1578 'source_name' => $postarray['author-name'],
1579 'source_link' => $postarray['author-link'],
1580 'source_photo' => $postarray['author-avatar'],
1581 'verb' => ACTIVITY_TAG,
1583 'parent' => $parent_id,
1589 PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1592 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1594 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1595 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1596 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1597 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1598 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1599 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1601 require_once 'library/twitteroauth.php';
1603 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1605 $parameters["count"] = 200;
1607 $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1608 if (is_array($items)) {
1609 $posts = array_reverse($items);
1611 foreach ($posts AS $post) {
1612 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1614 if (trim($postarray['body']) == "") {
1618 $item = item_store($postarray);
1619 $postarray["id"] = $item;
1621 logger('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1623 if ($item && !function_exists("check_item_notification")) {
1624 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1630 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1632 require_once "include/oembed.php";
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_fetch_url($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);