3 * Name: GNU Social Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for GNU Social.
6 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions are met:
14 * * Redistributions of source code must retain the above copyright notice,
15 * this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above
17 * * copyright notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the distribution.
19 * * Neither the name of the <organization> nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
27 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
31 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
32 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * We have to alter the TwitterOAuth class a little bit to work with any GNU Social
39 * installation abroad. Basically it's only make the API path variable and be happy.
41 * Thank you guys for the Twitter compatible API!
44 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
46 require_once 'library/twitteroauth.php';
47 require_once 'include/enotify.php';
49 use Friendica\Core\Config;
50 use Friendica\Core\PConfig;
51 use Friendica\Model\GlobalContact;
52 use Friendica\Object\Photo;
54 class StatusNetOAuth extends TwitterOAuth {
55 function get_maxlength() {
56 $config = $this->get($this->host . 'statusnet/config.json');
57 return $config->site->textlimit;
59 function accessTokenURL() { return $this->host.'oauth/access_token'; }
60 function authenticateURL() { return $this->host.'oauth/authenticate'; }
61 function authorizeURL() { return $this->host.'oauth/authorize'; }
62 function requestTokenURL() { return $this->host.'oauth/request_token'; }
63 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
64 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
65 $this->host = $apipath;
68 * Make an HTTP request
72 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
74 function http($url, $method, $postfields = NULL) {
75 $this->http_info = array();
78 $prx = Config::get('system','proxy');
80 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
81 curl_setopt($ci, CURLOPT_PROXY, $prx);
82 $prxusr = Config::get('system','proxyuser');
84 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
86 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
87 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
88 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
89 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
90 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
91 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
92 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
93 curl_setopt($ci, CURLOPT_HEADER, FALSE);
97 curl_setopt($ci, CURLOPT_POST, TRUE);
98 if (!empty($postfields)) {
99 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
103 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
104 if (!empty($postfields)) {
105 $url = "{$url}?{$postfields}";
109 curl_setopt($ci, CURLOPT_URL, $url);
110 $response = curl_exec($ci);
111 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
112 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
119 function statusnet_install() {
120 // we need some hooks, for the configuration and for sending tweets
121 register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
122 register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
123 register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
124 register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
125 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
126 register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
127 register_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
128 register_hook('check_item_notification','addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
129 logger("installed GNU Social");
133 function statusnet_uninstall() {
134 unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
135 unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
136 unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
137 unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
138 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
139 unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
140 unregister_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
141 unregister_hook('check_item_notification','addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
143 // old setting - remove only
144 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
145 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
146 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
150 function statusnet_check_item_notification($a, &$notification_data) {
151 $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
154 function statusnet_jot_nets(&$a,&$b) {
158 $statusnet_post = PConfig::get(local_user(),'statusnet','post');
159 if(intval($statusnet_post) == 1) {
160 $statusnet_defpost = PConfig::get(local_user(),'statusnet','post_by_default');
161 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
162 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
163 . t('Post to GNU Social') . '</div>';
167 function statusnet_settings_post ($a,$post) {
170 // don't check GNU Social settings if GNU Social submit button is not clicked
171 if (!x($_POST,'statusnet-submit'))
174 if (isset($_POST['statusnet-disconnect'])) {
176 * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration
178 PConfig::delete(local_user(), 'statusnet', 'consumerkey');
179 PConfig::delete(local_user(), 'statusnet', 'consumersecret');
180 PConfig::delete(local_user(), 'statusnet', 'post');
181 PConfig::delete(local_user(), 'statusnet', 'post_by_default');
182 PConfig::delete(local_user(), 'statusnet', 'oauthtoken');
183 PConfig::delete(local_user(), 'statusnet', 'oauthsecret');
184 PConfig::delete(local_user(), 'statusnet', 'baseapi');
185 PConfig::delete(local_user(), 'statusnet', 'lastid');
186 PConfig::delete(local_user(), 'statusnet', 'mirror_posts');
187 PConfig::delete(local_user(), 'statusnet', 'import');
188 PConfig::delete(local_user(), 'statusnet', 'create_user');
189 PConfig::delete(local_user(), 'statusnet', 'own_id');
191 if (isset($_POST['statusnet-preconf-apiurl'])) {
193 * If the user used one of the preconfigured GNU Social server credentials
194 * use them. All the data are available in the global config.
195 * Check the API Url never the less and blame the admin if it's not working ^^
197 $globalsn = Config::get('statusnet', 'sites');
198 foreach ( $globalsn as $asn) {
199 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
200 $apibase = $asn['apiurl'];
201 $c = fetch_url( $apibase . 'statusnet/version.xml' );
202 if (strlen($c) > 0) {
203 PConfig::set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
204 PConfig::set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
205 PConfig::set(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
206 //PConfig::set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
208 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
212 goaway($a->get_baseurl().'/settings/connectors');
214 if (isset($_POST['statusnet-consumersecret'])) {
215 // check if we can reach the API of the GNU Social server
216 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
217 // resign quickly after this one try to fix the path ;-)
218 $apibase = $_POST['statusnet-baseapi'];
219 $c = fetch_url( $apibase . 'statusnet/version.xml' );
220 if (strlen($c) > 0) {
221 // ok the API path is correct, let's save the settings
222 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
223 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
224 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase );
225 //PConfig::set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
227 // the API path is not correct, maybe missing trailing / ?
228 $apibase = $apibase . '/';
229 $c = fetch_url( $apibase . 'statusnet/version.xml' );
230 if (strlen($c) > 0) {
231 // ok the API path is now correct, let's save the settings
232 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
233 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
234 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase );
236 // still not the correct API base, let's do noting
237 notice( t('We could not contact the GNU Social API with the Path you entered.').EOL );
240 goaway($a->get_baseurl().'/settings/connectors');
242 if (isset($_POST['statusnet-pin'])) {
243 // if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
244 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
245 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey' );
246 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret' );
247 // the token and secret for which the PIN was generated were hidden in the settings
248 // form as token and token2, we need a new connection to GNU Social using these token
249 // and secret to request a Access Token with the PIN
250 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
251 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
252 // ok, now that we have the Access Token, save them in the user config
253 PConfig::set(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
254 PConfig::set(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
255 PConfig::set(local_user(),'statusnet', 'post', 1);
256 PConfig::set(local_user(),'statusnet', 'post_taglinks', 1);
257 // reload the Addon Settings page, if we don't do it see Bug #42
258 goaway($a->get_baseurl().'/settings/connectors');
260 // if no PIN is supplied in the POST variables, the user has changed the setting
261 // to post a dent for every new __public__ posting to the wall
262 PConfig::set(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
263 PConfig::set(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
264 PConfig::set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
265 PConfig::set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
266 PConfig::set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
268 if (!intval($_POST['statusnet-mirror']))
269 PConfig::delete(local_user(),'statusnet','lastid');
271 info( t('GNU Social settings updated.') . EOL);
274 function statusnet_settings(&$a,&$s) {
277 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
279 * 1) Check that we have a base api url and a consumer key & secret
280 * 2) If no OAuthtoken & stuff is present, generate button to get some
281 * allow the user to cancel the connection process at this step
282 * 3) Checkbox for "Send public notices (respect size limitation)
284 $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
285 $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
286 $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
287 $otoken = PConfig::get(local_user(), 'statusnet', 'oauthtoken');
288 $osecret = PConfig::get(local_user(), 'statusnet', 'oauthsecret');
289 $enabled = PConfig::get(local_user(), 'statusnet', 'post');
290 $checked = (($enabled) ? ' checked="checked" ' : '');
291 $defenabled = PConfig::get(local_user(),'statusnet','post_by_default');
292 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
293 $mirrorenabled = PConfig::get(local_user(),'statusnet','mirror_posts');
294 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
295 $import = PConfig::get(local_user(),'statusnet','import');
296 $importselected = array("", "", "");
297 $importselected[$import] = ' selected="selected"';
298 //$importenabled = PConfig::get(local_user(),'statusnet','import');
299 //$importchecked = (($importenabled) ? ' checked="checked" ' : '');
300 $create_userenabled = PConfig::get(local_user(),'statusnet','create_user');
301 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
303 $css = (($enabled) ? '' : '-disabled');
305 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
306 $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('GNU Social Import/Export/Mirror').'</h3>';
308 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
309 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
310 $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('GNU Social Import/Export/Mirror').'</h3>';
313 if ( (!$ckey) && (!$csecret) ) {
317 $globalsn = Config::get('statusnet', 'sites');
319 * lets check if we have one or more globally configured GNU Social
320 * server OAuth credentials in the configuration. If so offer them
321 * with a little explanation to the user as choice - otherwise
322 * ignore this option entirely.
324 if (! $globalsn == null) {
325 $s .= '<h4>' . t('Globally Available GNU Social OAuthKeys') . '</h4>';
326 $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>';
327 $s .= '<div id="statusnet-preconf-wrapper">';
328 foreach ($globalsn as $asn) {
329 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
331 $s .= '<p></p><div class="clear"></div></div>';
332 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
334 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
335 $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>';
336 $s .= '<div id="statusnet-consumer-wrapper">';
337 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
338 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
339 $s .= '<div class="clear"></div>';
340 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
341 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
342 $s .= '<div class="clear"></div>';
343 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
344 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
345 $s .= '<div class="clear"></div>';
346 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('GNU Socialapplication name').'</label>';
347 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
348 $s .= '<p></p><div class="clear"></div>';
349 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
353 * ok we have a consumer key pair now look into the OAuth stuff
355 if ( (!$otoken) && (!$osecret) ) {
357 * the user has not yet connected the account to GNU Social
358 * get a temporary OAuth key/secret pair and display a button with
359 * which the user can request a PIN to connect the account to a
360 * account at GNU Social
362 $connection = new StatusNetOAuth($api, $ckey, $csecret);
363 $request_token = $connection->getRequestToken('oob');
364 $token = $request_token['oauth_token'];
366 * make some nice form
368 $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>';
369 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with GNU Social') .'"></a>';
370 $s .= '<div id="statusnet-pin-wrapper">';
371 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from GNU Social here') .'</label>';
372 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
373 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
374 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
375 $s .= '</div><div class="clear"></div>';
376 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
377 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
378 $s .= '<div id="statusnet-cancel-wrapper">';
379 $s .= '<p>'.t('Current GNU Social API is').': '.$api.'</p>';
380 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel GNU Social Connection') . '</label>';
381 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
382 $s .= '</div><div class="clear"></div>';
383 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
386 * we have an OAuth key / secret pair for the user
387 * so let's give a chance to disable the postings to GNU Social
389 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
390 $details = $connection->get('account/verify_credentials');
391 $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>';
392 $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>';
393 if ($a->user['hidewall']) {
394 $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>';
396 $s .= '<div id="statusnet-enable-wrapper">';
397 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to GNU Social') .'</label>';
398 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
399 $s .= '<div class="clear"></div>';
400 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to GNU Social by default') .'</label>';
401 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
402 $s .= '<div class="clear"></div>';
404 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from GNU Social that are no replies or repeated messages').'</label>';
405 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
407 $s .= '<div class="clear"></div>';
410 $s .= '<label id="statusnet-import-label" for="statusnet-import">'.t('Import the remote timeline').'</label>';
411 //$s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
413 $s .= '<select name="statusnet-import" id="statusnet-import" />';
414 $s .= '<option value="0" '.$importselected[0].'>'.t("Disabled").'</option>';
415 $s .= '<option value="1" '.$importselected[1].'>'.t("Full Timeline").'</option>';
416 $s .= '<option value="2" '.$importselected[2].'>'.t("Only Mentions").'</option>';
418 $s .= '<div class="clear"></div>';
420 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.t('Automatically create contacts').'</label>';
421 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
422 $s .= '<div class="clear"></div>';
424 $s .= '<div id="statusnet-disconnect-wrapper">';
425 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
426 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
427 $s .= '</div><div class="clear"></div>';
428 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
431 $s .= '</div><div class="clear"></div>';
435 function statusnet_post_local(&$a, &$b) {
440 if (!local_user() || (local_user() != $b['uid'])) {
444 $statusnet_post = PConfig::get(local_user(),'statusnet','post');
445 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
447 // if API is used, default to the chosen settings
448 if ($b['api_source'] && intval(PConfig::get(local_user(),'statusnet','post_by_default'))) {
449 $statusnet_enable = 1;
452 if (!$statusnet_enable) {
456 if (strlen($b['postopts'])) {
457 $b['postopts'] .= ',';
460 $b['postopts'] .= 'statusnet';
463 function statusnet_action($a, $uid, $pid, $action) {
464 $api = PConfig::get($uid, 'statusnet', 'baseapi');
465 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
466 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
467 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
468 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
470 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
472 logger("statusnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
476 $result = $connection->post("statuses/destroy/".$pid);
479 $result = $connection->post("favorites/create/".$pid);
482 $result = $connection->post("favorites/destroy/".$pid);
485 logger("statusnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
488 function statusnet_post_hook(&$a,&$b) {
494 if (!PConfig::get($b["uid"],'statusnet','import')) {
495 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
499 $api = PConfig::get($b["uid"], 'statusnet', 'baseapi');
500 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
502 if($b['parent'] != $b['id']) {
503 logger("statusnet_post_hook: parameter ".print_r($b, true), LOGGER_DATA);
505 // Looking if its a reply to a GNU Social post
506 $hostlength = strlen($hostname) + 2;
507 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname."::") && (substr($b["extid"], 0, $hostlength) != $hostname."::")
508 && (substr($b["thr-parent"], 0, $hostlength) != $hostname."::")) {
509 logger("statusnet_post_hook: no GNU Social post ".$b["parent"]);
513 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
514 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
515 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
516 dbesc($b["thr-parent"]),
520 logger("statusnet_post_hook: no parent found ".$b["thr-parent"]);
527 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
528 //$nicknameplain = "@".$orig_post["contact_nick"];
530 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
532 $nickname = "@[url=".$orig_post["author-link"]."]".$nick."[/url]";
533 $nicknameplain = "@".$nick;
535 logger("statusnet_post_hook: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
536 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false))
537 $b["body"] = $nickname." ".$b["body"];
539 logger("statusnet_post_hook: parent found ".print_r($orig_post, true), LOGGER_DEBUG);
543 if($b['private'] || !strstr($b['postopts'],'statusnet'))
546 // Dont't post if the post doesn't belong to us.
547 // This is a check for forum postings
548 $self = dba::select('contact', array('id'), array('uid' => $b['uid'], 'self' => true), array('limit' => 1));
549 if ($b['contact-id'] != $self['id']) {
554 if (($b['verb'] == ACTIVITY_POST) && $b['deleted'])
555 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
557 if($b['verb'] == ACTIVITY_LIKE) {
558 logger("statusnet_post_hook: parameter 2 ".substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
560 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
562 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
566 if($b['deleted'] || ($b['created'] !== $b['edited']))
569 // if posts comes from GNU Social don't send it back
570 if($b['extid'] == NETWORK_STATUSNET)
573 if($b['app'] == "StatusNet")
576 logger('GNU Socialpost invoked');
578 PConfig::load($b['uid'], 'statusnet');
580 $api = PConfig::get($b['uid'], 'statusnet', 'baseapi');
581 $ckey = PConfig::get($b['uid'], 'statusnet', 'consumerkey');
582 $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret');
583 $otoken = PConfig::get($b['uid'], 'statusnet', 'oauthtoken');
584 $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret');
586 if($ckey && $csecret && $otoken && $osecret) {
588 // If it's a repeated message from GNU Social then do a native retweet and exit
589 if (statusnet_is_retweet($a, $b['uid'], $b['body']))
592 require_once('include/bbcode.php');
593 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
594 $max_char = $dent->get_maxlength(); // max. length for a dent
596 PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char);
599 require_once("include/plaintext.php");
600 require_once("include/network.php");
601 $msgarr = plaintext($a, $b, $max_char, true, 7);
602 $msg = $msgarr["text"];
604 if (($msg == "") && isset($msgarr["title"]))
605 $msg = shortenmsg($msgarr["title"], $max_char - 50);
609 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
610 if ((strlen($msgarr["url"]) > 20) &&
611 ((strlen($msg." \n".$msgarr["url"]) > $max_char)))
612 $msg .= " \n".short_link($msgarr["url"]);
614 $msg .= " \n".$msgarr["url"];
615 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video"))
616 $image = $msgarr["image"];
619 $img_str = fetch_url($image);
620 $tempfile = tempnam(get_temppath(), "cache");
621 file_put_contents($tempfile, $img_str);
622 $postdata = array("status" => $msg, "media[]" => $tempfile);
624 $postdata = array("status"=>$msg);
626 // and now dent it :-)
630 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
631 logger('statusnet_post send reply '.print_r($postdata, true), LOGGER_DEBUG);
634 // New code that is able to post pictures
635 require_once("addon/statusnet/codebird.php");
636 $cb = \CodebirdSN\CodebirdSN::getInstance();
637 $cb->setAPIEndpoint($api);
638 $cb->setConsumerKey($ckey, $csecret);
639 $cb->setToken($otoken, $osecret);
640 $result = $cb->statuses_update($postdata);
641 //$result = $dent->post('statuses/update', $postdata);
642 logger('statusnet_post send, result: ' . print_r($result, true).
643 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
646 PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
648 if ($result->error) {
649 logger('Send to GNU Social failed: "'.$result->error.'"');
650 } elseif ($iscomment) {
651 logger('statusnet_post: Update extid '.$result->id." for post id ".$b['id']);
652 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
653 dbesc($hostname."::".$result->id),
654 dbesc($result->text),
664 function statusnet_plugin_admin_post(&$a){
668 foreach($_POST['sitename'] as $id=>$sitename){
669 $sitename=trim($sitename);
670 $apiurl=trim($_POST['apiurl'][$id]);
671 if (! (substr($apiurl, -1)=='/'))
673 $secret=trim($_POST['secret'][$id]);
674 $key=trim($_POST['key'][$id]);
675 //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
680 !x($_POST['delete'][$id])){
683 'sitename' => $sitename,
685 'consumersecret' => $secret,
686 'consumerkey' => $key,
687 //'applicationname' => $applicationname
692 $sites = Config::set('statusnet','sites', $sites);
696 function statusnet_plugin_admin(&$a, &$o){
698 $sites = Config::get('statusnet','sites');
700 if (is_array($sites)){
701 foreach($sites as $id=>$s){
702 $sitesform[] = Array(
703 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
704 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29") ),
705 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
706 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
707 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
708 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
712 /* empty form to add new site */
714 $sitesform[] = Array(
715 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
716 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29") ),
717 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
718 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
719 //'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
722 $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
723 $o = replace_macros($t, array(
724 '$submit' => t('Save Settings'),
725 '$sites' => $sitesform,
729 function statusnet_prepare_body(&$a,&$b) {
730 if ($b["item"]["network"] != NETWORK_STATUSNET)
734 $max_char = PConfig::get(local_user(),'statusnet','max_char');
735 if (intval($max_char) == 0)
738 require_once("include/plaintext.php");
740 $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"];
742 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
743 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
744 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
745 dbesc($item["thr-parent"]),
746 intval(local_user()));
750 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
751 //$nicknameplain = "@".$orig_post["contact_nick"];
753 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
755 $nickname = "@[url=".$orig_post["author-link"]."]".$nick."[/url]";
756 $nicknameplain = "@".$nick;
758 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false))
759 $item["body"] = $nickname." ".$item["body"];
763 $msgarr = plaintext($a, $item, $max_char, true, 7);
764 $msg = $msgarr["text"];
766 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo"))
767 $msg .= " ".$msgarr["url"];
769 if (isset($msgarr["image"]))
770 $msg .= " ".$msgarr["image"];
772 $b['html'] = nl2br(htmlspecialchars($msg));
776 function statusnet_cron($a,$b) {
777 $last = Config::get('statusnet','last_poll');
779 $poll_interval = intval(Config::get('statusnet','poll_interval'));
781 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
784 $next = $last + ($poll_interval * 60);
786 logger('statusnet: poll intervall not reached');
790 logger('statusnet: cron_start');
792 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
795 logger('statusnet: fetching for user '.$rr['uid']);
796 statusnet_fetchtimeline($a, $rr['uid']);
800 $abandon_days = intval(Config::get('system','account_abandon_days'));
801 if ($abandon_days < 1)
804 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
806 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
809 if ($abandon_days != 0) {
810 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
812 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
817 logger('statusnet: importing timeline from user '.$rr['uid']);
818 statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
822 logger('statusnet: cron_end');
824 Config::set('statusnet','last_poll', time());
827 function statusnet_fetchtimeline($a, $uid) {
828 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
829 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
830 $api = PConfig::get($uid, 'statusnet', 'baseapi');
831 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
832 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
833 $lastid = PConfig::get($uid, 'statusnet', 'lastid');
835 require_once('mod/item.php');
836 require_once('include/items.php');
838 // get the application name for the SN app
839 // 1st try personal config, then system config and fallback to the
840 // hostname of the node if neither one is set.
841 $application_name = PConfig::get( $uid, 'statusnet', 'application_name');
842 if ($application_name == "")
843 $application_name = Config::get('statusnet', 'application_name');
844 if ($application_name == "")
845 $application_name = $a->get_hostname();
847 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
849 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
851 $first_time = ($lastid == "");
854 $parameters["since_id"] = $lastid;
856 $items = $connection->get('statuses/user_timeline', $parameters);
858 if (!is_array($items))
861 $posts = array_reverse($items);
864 foreach ($posts as $post) {
865 if ($post->id > $lastid)
871 if ($post->source == "activity")
874 if (is_object($post->retweeted_status))
877 if ($post->in_reply_to_status_id != "")
880 if (!stristr($post->source, $application_name)) {
881 $_SESSION["authenticated"] = true;
882 $_SESSION["uid"] = $uid;
885 $_REQUEST["type"] = "wall";
886 $_REQUEST["api_source"] = true;
887 $_REQUEST["profile_uid"] = $uid;
888 //$_REQUEST["source"] = "StatusNet";
889 $_REQUEST["source"] = $post->source;
890 $_REQUEST["extid"] = NETWORK_STATUSNET;
892 if (isset($post->id)) {
893 $_REQUEST['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_STATUSNET.":".$post->id);
896 //$_REQUEST["date"] = $post->created_at;
898 $_REQUEST["title"] = "";
900 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
901 if (is_string($post->place->name))
902 $_REQUEST["location"] = $post->place->name;
904 if (is_string($post->place->full_name))
905 $_REQUEST["location"] = $post->place->full_name;
907 if (is_array($post->geo->coordinates))
908 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
910 if (is_array($post->coordinates->coordinates))
911 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
913 //print_r($_REQUEST);
914 if ($_REQUEST["body"] != "") {
915 logger('statusnet: posting for user '.$uid);
922 PConfig::set($uid, 'statusnet', 'lastid', $lastid);
925 function statusnet_address($contact) {
926 $hostname = normalise_link($contact->statusnet_profile_url);
927 $nickname = $contact->screen_name;
929 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
931 $address = $contact->screen_name."@".$hostname;
936 function statusnet_fetch_contact($uid, $contact, $create_user) {
937 if ($contact->statusnet_profile_url == "")
940 GlobalContact::update(array("url" => $contact->statusnet_profile_url,
941 "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url,
942 "name" => $contact->name, "nick" => $contact->screen_name,
943 "location" => $contact->location, "about" => $contact->description,
944 "addr" => statusnet_address($contact), "generation" => 3));
946 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1",
947 intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)), dbesc(NETWORK_STATUSNET));
949 if(!count($r) && !$create_user)
952 if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
953 logger("statusnet_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
958 // create contact record
959 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
960 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
961 `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
962 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
964 dbesc(datetime_convert()),
965 dbesc($contact->statusnet_profile_url),
966 dbesc(normalise_link($contact->statusnet_profile_url)),
967 dbesc(statusnet_address($contact)),
968 dbesc(normalise_link($contact->statusnet_profile_url)),
971 dbesc($contact->name),
972 dbesc($contact->screen_name),
973 dbesc($contact->profile_image_url),
974 dbesc(NETWORK_STATUSNET),
975 intval(CONTACT_IS_FRIEND),
977 dbesc($contact->location),
978 dbesc($contact->description),
982 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
983 dbesc($contact->statusnet_profile_url),
985 dbesc(NETWORK_STATUSNET));
990 $contact_id = $r[0]['id'];
992 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
996 if($g && intval($g[0]['def_gid'])) {
997 require_once('include/group.php');
998 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1001 require_once("Photo.php");
1003 $photos = Photo::importProfilePhoto($contact->profile_image_url,$uid,$contact_id);
1005 q("UPDATE `contact` SET `photo` = '%s',
1008 `avatar-date` = '%s'
1013 dbesc(datetime_convert()),
1017 // update profile photos once every two weeks as we have no notification of when they change.
1019 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1020 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1022 // check that we have all the photos, this has been known to fail on occasion
1024 if((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1026 logger("statusnet_fetch_contact: Updating contact ".$contact->screen_name, LOGGER_DEBUG);
1028 require_once("Photo.php");
1030 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1032 q("UPDATE `contact` SET `photo` = '%s',
1037 `avatar-date` = '%s',
1049 dbesc(datetime_convert()),
1050 dbesc(datetime_convert()),
1051 dbesc(datetime_convert()),
1052 dbesc($contact->statusnet_profile_url),
1053 dbesc(normalise_link($contact->statusnet_profile_url)),
1054 dbesc(statusnet_address($contact)),
1055 dbesc($contact->name),
1056 dbesc($contact->screen_name),
1057 dbesc($contact->location),
1058 dbesc($contact->description),
1064 return($r[0]["id"]);
1067 function statusnet_fetchuser($a, $uid, $screen_name = "", $user_id = "") {
1068 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1069 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1070 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1071 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1072 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1074 require_once("addon/statusnet/codebird.php");
1076 $cb = \Codebird\Codebird::getInstance();
1077 $cb->setConsumerKey($ckey, $csecret);
1078 $cb->setToken($otoken, $osecret);
1080 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1088 $parameters = array();
1090 if ($screen_name != "")
1091 $parameters["screen_name"] = $screen_name;
1094 $parameters["user_id"] = $user_id;
1096 // Fetching user data
1097 $user = $cb->users_show($parameters);
1099 if (!is_object($user))
1102 $contact_id = statusnet_fetch_contact($uid, $user, true);
1107 function statusnet_createpost($a, $uid, $post, $self, $create_user, $only_existing_contact) {
1109 require_once("include/html2bbcode.php");
1111 logger("statusnet_createpost: start", LOGGER_DEBUG);
1113 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1114 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1116 $postarray = array();
1117 $postarray['network'] = NETWORK_STATUSNET;
1118 $postarray['gravity'] = 0;
1119 $postarray['uid'] = $uid;
1120 $postarray['wall'] = 0;
1122 if (is_object($post->retweeted_status)) {
1123 $content = $post->retweeted_status;
1124 statusnet_fetch_contact($uid, $content->user, false);
1128 $postarray['uri'] = $hostname."::".$content->id;
1130 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1131 dbesc($postarray['uri']),
1140 if ($content->in_reply_to_status_id != "") {
1142 $parent = $hostname."::".$content->in_reply_to_status_id;
1144 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1149 $postarray['thr-parent'] = $r[0]["uri"];
1150 $postarray['parent-uri'] = $r[0]["parent-uri"];
1151 $postarray['parent'] = $r[0]["parent"];
1152 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1154 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1159 $postarray['thr-parent'] = $r[0]['uri'];
1160 $postarray['parent-uri'] = $r[0]['parent-uri'];
1161 $postarray['parent'] = $r[0]['parent'];
1162 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1164 $postarray['thr-parent'] = $postarray['uri'];
1165 $postarray['parent-uri'] = $postarray['uri'];
1166 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1171 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1173 if ($content->user->id == $own_url) {
1174 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1178 $contactid = $r[0]["id"];
1180 $postarray['owner-name'] = $r[0]["name"];
1181 $postarray['owner-link'] = $r[0]["url"];
1182 $postarray['owner-avatar'] = $r[0]["photo"];
1186 // Don't create accounts of people who just comment something
1187 $create_user = false;
1189 $postarray['parent-uri'] = $postarray['uri'];
1190 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1193 if ($contactid == 0) {
1194 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1195 $postarray['owner-name'] = $post->user->name;
1196 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1197 $postarray['owner-avatar'] = $post->user->profile_image_url;
1199 if(($contactid == 0) && !$only_existing_contact)
1200 $contactid = $self['id'];
1201 elseif ($contactid <= 0)
1204 $postarray['contact-id'] = $contactid;
1206 $postarray['verb'] = ACTIVITY_POST;
1208 $postarray['author-name'] = $content->user->name;
1209 $postarray['author-link'] = $content->user->statusnet_profile_url;
1210 $postarray['author-avatar'] = $content->user->profile_image_url;
1212 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1213 $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1215 $postarray['plink'] = $hostname.$content->id;
1216 $postarray['app'] = strip_tags($content->source);
1218 if ($content->user->protected) {
1219 $postarray['private'] = 1;
1220 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1223 $postarray['body'] = html2bbcode($content->statusnet_html);
1225 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1226 $postarray['body'] = $converted["body"];
1227 $postarray['tag'] = $converted["tags"];
1229 $postarray['created'] = datetime_convert('UTC','UTC',$content->created_at);
1230 $postarray['edited'] = datetime_convert('UTC','UTC',$content->created_at);
1232 if (is_string($content->place->name))
1233 $postarray["location"] = $content->place->name;
1235 if (is_string($content->place->full_name))
1236 $postarray["location"] = $content->place->full_name;
1238 if (is_array($content->geo->coordinates))
1239 $postarray["coord"] = $content->geo->coordinates[0]." ".$content->geo->coordinates[1];
1241 if (is_array($content->coordinates->coordinates))
1242 $postarray["coord"] = $content->coordinates->coordinates[1]." ".$content->coordinates->coordinates[0];
1244 /*if (is_object($post->retweeted_status)) {
1245 $postarray['body'] = html2bbcode($post->retweeted_status->statusnet_html);
1247 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1248 $postarray['body'] = $converted["body"];
1249 $postarray['tag'] = $converted["tags"];
1251 statusnet_fetch_contact($uid, $post->retweeted_status->user, false);
1253 // Let retweets look like wall-to-wall posts
1254 $postarray['author-name'] = $post->retweeted_status->user->name;
1255 $postarray['author-link'] = $post->retweeted_status->user->statusnet_profile_url;
1256 $postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url;
1258 logger("statusnet_createpost: end", LOGGER_DEBUG);
1262 function statusnet_checknotification($a, $uid, $own_url, $top_item, $postarray) {
1264 // This function necer worked and need cleanup
1266 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1274 if (link_compare($user[0]["url"], $postarray['author-link']))
1277 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1282 if(!count($own_user))
1285 // Is it me from GNU Social?
1286 if (link_compare($own_user[0]["url"], $postarray['author-link']))
1289 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1290 dbesc($postarray['parent-uri']),
1294 if(count($myconv)) {
1296 foreach($myconv as $conv) {
1297 // now if we find a match, it means we're in this conversation
1299 if(!link_compare($conv['author-link'],$user[0]["url"]) && !link_compare($conv['author-link'],$own_user[0]["url"]))
1302 require_once('include/enotify.php');
1304 $conv_parent = $conv['parent'];
1307 'type' => NOTIFY_COMMENT,
1308 'notify_flags' => $user[0]['notify-flags'],
1309 'language' => $user[0]['language'],
1310 'to_name' => $user[0]['username'],
1311 'to_email' => $user[0]['email'],
1312 'uid' => $user[0]['uid'],
1313 'item' => $postarray,
1314 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($top_item)),
1315 'source_name' => $postarray['author-name'],
1316 'source_link' => $postarray['author-link'],
1317 'source_photo' => $postarray['author-avatar'],
1318 'verb' => ACTIVITY_POST,
1320 'parent' => $conv_parent,
1323 // only send one notification
1329 function statusnet_fetchhometimeline($a, $uid, $mode = 1) {
1330 $conversations = array();
1332 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1333 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1334 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1335 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1336 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1337 $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1339 // "create_user" is deactivated, since currently you cannot add users manually by now
1340 $create_user = true;
1342 logger("statusnet_fetchhometimeline: Fetching for user ".$uid, LOGGER_DEBUG);
1344 require_once('library/twitteroauth.php');
1345 require_once('include/items.php');
1347 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1349 $own_contact = statusnet_fetch_own_contact($a, $uid);
1351 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1352 intval($own_contact),
1356 $nick = $r[0]["nick"];
1358 logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user ".$uid, LOGGER_DEBUG);
1362 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1368 logger("statusnet_fetchhometimeline: Own contact not found for user ".$uid, LOGGER_DEBUG);
1372 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1375 logger("statusnet_fetchhometimeline: Own user not found for user ".$uid, LOGGER_DEBUG);
1379 $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1380 //$parameters["count"] = 200;
1383 // Fetching timeline
1384 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1387 $first_time = ($lastid == "");
1390 $parameters["since_id"] = $lastid;
1392 $items = $connection->get('statuses/home_timeline', $parameters);
1394 if (!is_array($items)) {
1395 if (is_object($items) && isset($items->error))
1396 $errormsg = $items->error;
1397 elseif (is_object($items))
1398 $errormsg = print_r($items, true);
1399 elseif (is_string($items) || is_float($items) || is_int($items))
1402 $errormsg = "Unknown error";
1404 logger("statusnet_fetchhometimeline: Error fetching home timeline: ".$errormsg, LOGGER_DEBUG);
1408 $posts = array_reverse($items);
1410 logger("statusnet_fetchhometimeline: Fetching timeline for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1412 if (count($posts)) {
1413 foreach ($posts as $post) {
1415 if ($post->id > $lastid)
1416 $lastid = $post->id;
1421 if (isset($post->statusnet_conversation_id)) {
1422 if (!isset($conversations[$post->statusnet_conversation_id])) {
1423 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1424 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1427 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1429 if (trim($postarray['body']) == "")
1432 $item = item_store($postarray);
1433 $postarray["id"] = $item;
1435 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted home timeline item '.$item);
1437 if ($item && !function_exists("check_item_notification"))
1438 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1443 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1446 // Fetching mentions
1447 $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1448 $first_time = ($lastid == "");
1451 $parameters["since_id"] = $lastid;
1453 $items = $connection->get('statuses/mentions_timeline', $parameters);
1455 if (!is_array($items)) {
1456 logger("statusnet_fetchhometimeline: Error fetching mentions: ".print_r($items, true), LOGGER_DEBUG);
1460 $posts = array_reverse($items);
1462 logger("statusnet_fetchhometimeline: Fetching mentions for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1464 if (count($posts)) {
1465 foreach ($posts as $post) {
1466 if ($post->id > $lastid)
1467 $lastid = $post->id;
1472 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1474 if (isset($post->statusnet_conversation_id)) {
1475 if (!isset($conversations[$post->statusnet_conversation_id])) {
1476 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1477 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1480 if (trim($postarray['body']) != "") {
1483 $item = item_store($postarray);
1484 $postarray["id"] = $item;
1486 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted mention timeline item '.$item);
1488 if ($item && function_exists("check_item_notification"))
1489 check_item_notification($item, $uid, NOTIFY_TAGSELF);
1493 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1494 dbesc($postarray['uri']),
1498 $item = $r[0]['id'];
1499 $parent_id = $r[0]['parent'];
1502 if (($item != 0) && !function_exists("check_item_notification")) {
1503 require_once('include/enotify.php');
1505 'type' => NOTIFY_TAGSELF,
1506 'notify_flags' => $u[0]['notify-flags'],
1507 'language' => $u[0]['language'],
1508 'to_name' => $u[0]['username'],
1509 'to_email' => $u[0]['email'],
1510 'uid' => $u[0]['uid'],
1511 'item' => $postarray,
1512 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
1513 'source_name' => $postarray['author-name'],
1514 'source_link' => $postarray['author-link'],
1515 'source_photo' => $postarray['author-avatar'],
1516 'verb' => ACTIVITY_TAG,
1518 'parent' => $parent_id,
1524 PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1527 function statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $conversation) {
1528 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1529 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1530 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1531 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1532 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1533 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1535 require_once('library/twitteroauth.php');
1537 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1539 $parameters["count"] = 200;
1541 $items = $connection->get('statusnet/conversation/'.$conversation, $parameters);
1542 if (is_array($items)) {
1543 $posts = array_reverse($items);
1545 foreach($posts AS $post) {
1546 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1548 if (trim($postarray['body']) == "")
1551 //print_r($postarray);
1552 $item = item_store($postarray);
1553 $postarray["id"] = $item;
1555 logger('statusnet_complete_conversation: User '.$self["nick"].' posted home timeline item '.$item);
1557 if ($item && !function_exists("check_item_notification"))
1558 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1563 function statusnet_convertmsg($a, $body, $no_tags = false) {
1565 require_once("include/oembed.php");
1566 require_once("include/items.php");
1567 require_once("include/network.php");
1569 $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism","$1.$2.$3.$4/$5",$body);
1571 $URLSearchString = "^\[\]";
1572 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body,$matches,PREG_SET_ORDER);
1580 foreach ($matches AS $match) {
1581 $search = "[url=".$match[1]."]".$match[2]."[/url]";
1583 logger("statusnet_convertmsg: expanding url ".$match[1], LOGGER_DEBUG);
1585 $expanded_url = original_url($match[1]);
1587 logger("statusnet_convertmsg: fetching data for ".$expanded_url, LOGGER_DEBUG);
1589 $oembed_data = oembed_fetch_url($expanded_url, true);
1591 logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG);
1594 $type = $oembed_data->type;
1595 if ($oembed_data->type == "video") {
1596 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1597 $type = $oembed_data->type;
1598 $footerurl = $expanded_url;
1599 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1601 $body = str_replace($search, $footerlink, $body);
1602 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia)
1603 $body = str_replace($search, "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]", $body);
1604 elseif ($oembed_data->type != "link")
1605 $body = str_replace($search, "[url=".$expanded_url."]".$expanded_url."[/url]", $body);
1607 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1609 $tempfile = tempnam(get_temppath(), "cache");
1610 file_put_contents($tempfile, $img_str);
1611 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1614 if (substr($mime, 0, 6) == "image/") {
1616 $body = str_replace($search, "[img]".$expanded_url."[/img]", $body);
1618 $type = $oembed_data->type;
1619 $footerurl = $expanded_url;
1620 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1622 $body = str_replace($search, $footerlink, $body);
1627 if ($footerurl != "")
1628 $footer = add_page_info($footerurl);
1630 if (($footerlink != "") && (trim($footer) != "")) {
1631 $removedlink = trim(str_replace($footerlink, "", $body));
1633 if (($removedlink == "") || strstr($body, $removedlink))
1634 $body = $removedlink;
1641 return(array("body" => $body, "tags" => ""));
1645 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$body,$matches,PREG_SET_ORDER);
1647 foreach($matches as $mtch) {
1648 if(strlen($str_tags))
1651 if ($mtch[1] == "#") {
1652 // Replacing the hash tags that are directed to the GNU Social server with internal links
1653 $snhash = "#[url=".$mtch[2]."]".$mtch[3]."[/url]";
1654 $frdchash = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($mtch[3]).']'.$mtch[3].'[/url]';
1655 $body = str_replace($snhash, $frdchash, $body);
1657 $str_tags .= $frdchash;
1659 $str_tags .= "@[url=".$mtch[2]."]".$mtch[3]."[/url]";
1661 // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1662 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1666 return(array("body"=>$body, "tags"=>$str_tags));
1670 function statusnet_fetch_own_contact($a, $uid) {
1671 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1672 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1673 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1674 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1675 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1676 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1680 if ($own_url == "") {
1681 require_once('library/twitteroauth.php');
1683 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1685 // Fetching user data
1686 $user = $connection->get('account/verify_credentials');
1688 PConfig::set($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1690 $contact_id = statusnet_fetch_contact($uid, $user, true);
1693 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1694 intval($uid), dbesc($own_url));
1696 $contact_id = $r[0]["id"];
1698 PConfig::delete($uid, 'statusnet', 'own_url');
1701 return($contact_id);
1704 function statusnet_is_retweet($a, $uid, $body) {
1705 $body = trim($body);
1707 // Skip if it isn't a pure repeated messages
1708 // Does it start with a share?
1709 if (strpos($body, "[share") > 0)
1712 // Does it end with a share?
1713 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1716 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1717 // Skip if there is no shared message in there
1718 if ($body == $attributes)
1722 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1723 if ($matches[1] != "")
1724 $link = $matches[1];
1726 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1727 if ($matches[1] != "")
1728 $link = $matches[1];
1730 $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
1731 $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1732 $api = PConfig::get($uid, 'statusnet', 'baseapi');
1733 $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
1734 $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1735 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1737 $id = preg_replace("=https?://".$hostname."/notice/(.*)=ism", "$1", $link);
1742 logger('statusnet_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG);
1744 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1746 $result = $connection->post('statuses/retweet/'.$id);
1748 logger('statusnet_is_retweet: result '.print_r($result, true), LOGGER_DEBUG);
1749 return(isset($result->id));