3 * Name: StatusNet Connector
4 * Description: Relay public postings to a connected StatusNet account
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 StatusNet
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');
48 class StatusNetOAuth extends TwitterOAuth {
49 function get_maxlength() {
50 $config = $this->get($this->host . 'statusnet/config.json');
51 return $config->site->textlimit;
53 function accessTokenURL() { return $this->host.'oauth/access_token'; }
54 function authenticateURL() { return $this->host.'oauth/authenticate'; }
55 function authorizeURL() { return $this->host.'oauth/authorize'; }
56 function requestTokenURL() { return $this->host.'oauth/request_token'; }
57 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
58 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
59 $this->host = $apipath;
62 * Make an HTTP request
66 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
68 function http($url, $method, $postfields = NULL) {
69 $this->http_info = array();
72 $prx = get_config('system','proxy');
74 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
75 curl_setopt($ci, CURLOPT_PROXY, $prx);
76 $prxusr = get_config('system','proxyuser');
78 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
80 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
81 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
82 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
83 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
84 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
85 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
86 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
87 curl_setopt($ci, CURLOPT_HEADER, FALSE);
91 curl_setopt($ci, CURLOPT_POST, TRUE);
92 if (!empty($postfields)) {
93 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
97 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
98 if (!empty($postfields)) {
99 $url = "{$url}?{$postfields}";
103 curl_setopt($ci, CURLOPT_URL, $url);
104 $response = curl_exec($ci);
105 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
106 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
113 function statusnet_install() {
114 // we need some hooks, for the configuration and for sending tweets
115 register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
116 register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
117 register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
118 register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
119 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
120 register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
121 logger("installed statusnet");
125 function statusnet_uninstall() {
126 unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
127 unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
128 unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
129 unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
130 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
131 unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
133 // old setting - remove only
134 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
135 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
136 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
140 function statusnet_jot_nets(&$a,&$b) {
144 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
145 if(intval($statusnet_post) == 1) {
146 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
147 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
148 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
149 . t('Post to StatusNet') . '</div>';
153 function statusnet_settings_post ($a,$post) {
156 // don't check statusnet settings if statusnet submit button is not clicked
157 if (!x($_POST,'statusnet-submit'))
160 if (isset($_POST['statusnet-disconnect'])) {
162 * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
164 del_pconfig(local_user(), 'statusnet', 'consumerkey');
165 del_pconfig(local_user(), 'statusnet', 'consumersecret');
166 del_pconfig(local_user(), 'statusnet', 'post');
167 del_pconfig(local_user(), 'statusnet', 'post_by_default');
168 del_pconfig(local_user(), 'statusnet', 'oauthtoken');
169 del_pconfig(local_user(), 'statusnet', 'oauthsecret');
170 del_pconfig(local_user(), 'statusnet', 'baseapi');
171 del_pconfig(local_user(), 'statusnet', 'lastid');
172 del_pconfig(local_user(), 'statusnet', 'mirror_posts');
173 del_pconfig(local_user(), 'statusnet', 'import');
174 del_pconfig(local_user(), 'statusnet', 'create_user');
175 del_pconfig(local_user(), 'statusnet', 'own_id');
177 if (isset($_POST['statusnet-preconf-apiurl'])) {
179 * If the user used one of the preconfigured StatusNet server credentials
180 * use them. All the data are available in the global config.
181 * Check the API Url never the less and blame the admin if it's not working ^^
183 $globalsn = get_config('statusnet', 'sites');
184 foreach ( $globalsn as $asn) {
185 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
186 $apibase = $asn['apiurl'];
187 $c = fetch_url( $apibase . 'statusnet/version.xml' );
188 if (strlen($c) > 0) {
189 set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
190 set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
191 set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
192 set_pconfig(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
194 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
198 goaway($a->get_baseurl().'/settings/connectors');
200 if (isset($_POST['statusnet-consumersecret'])) {
201 // check if we can reach the API of the StatusNet server
202 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
203 // resign quickly after this one try to fix the path ;-)
204 $apibase = $_POST['statusnet-baseapi'];
205 $c = fetch_url( $apibase . 'statusnet/version.xml' );
206 if (strlen($c) > 0) {
207 // ok the API path is correct, let's save the settings
208 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
209 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
210 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
211 set_pconfig(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
213 // the API path is not correct, maybe missing trailing / ?
214 $apibase = $apibase . '/';
215 $c = fetch_url( $apibase . 'statusnet/version.xml' );
216 if (strlen($c) > 0) {
217 // ok the API path is now correct, let's save the settings
218 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
219 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
220 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
222 // still not the correct API base, let's do noting
223 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
226 goaway($a->get_baseurl().'/settings/connectors');
228 if (isset($_POST['statusnet-pin'])) {
229 // if the user supplied us with a PIN from StatusNet, let the magic of OAuth happen
230 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
231 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
232 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
233 // the token and secret for which the PIN was generated were hidden in the settings
234 // form as token and token2, we need a new connection to StatusNet using these token
235 // and secret to request a Access Token with the PIN
236 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
237 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
238 // ok, now that we have the Access Token, save them in the user config
239 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
240 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
241 set_pconfig(local_user(),'statusnet', 'post', 1);
242 set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
243 // reload the Addon Settings page, if we don't do it see Bug #42
244 goaway($a->get_baseurl().'/settings/connectors');
246 // if no PIN is supplied in the POST variables, the user has changed the setting
247 // to post a dent for every new __public__ posting to the wall
248 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
249 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
250 set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
251 set_pconfig(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
252 set_pconfig(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
254 if (!intval($_POST['statusnet-mirror']))
255 del_pconfig(local_user(),'statusnet','lastid');
257 info( t('StatusNet settings updated.') . EOL);
260 function statusnet_settings(&$a,&$s) {
263 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
265 * 1) Check that we have a base api url and a consumer key & secret
266 * 2) If no OAuthtoken & stuff is present, generate button to get some
267 * allow the user to cancel the connection process at this step
268 * 3) Checkbox for "Send public notices (respect size limitation)
270 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
271 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey');
272 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret');
273 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken');
274 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret');
275 $enabled = get_pconfig(local_user(), 'statusnet', 'post');
276 $checked = (($enabled) ? ' checked="checked" ' : '');
277 $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
278 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
279 $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
280 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
281 $importenabled = get_pconfig(local_user(),'statusnet','import');
282 $importchecked = (($importenabled) ? ' checked="checked" ' : '');
283 $create_userenabled = get_pconfig(local_user(),'statusnet','create_user');
284 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
286 $css = (($enabled) ? '' : '-disabled');
288 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
289 $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('StatusNet Import/Export/Mirror').'</h3>';
291 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
292 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
293 $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('StatusNet Import/Export/Mirror').'</h3>';
296 if ( (!$ckey) && (!$csecret) ) {
300 $globalsn = get_config('statusnet', 'sites');
302 * lets check if we have one or more globally configured StatusNet
303 * server OAuth credentials in the configuration. If so offer them
304 * with a little explanation to the user as choice - otherwise
305 * ignore this option entirely.
307 if (! $globalsn == null) {
308 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
309 $s .= '<p>'. t("There are preconfigured OAuth key pairs for some StatusNet servers available. If you are useing one of them, please use these credentials. If not feel free to connect to any other StatusNet instance \x28see below\x29.") .'</p>';
310 $s .= '<div id="statusnet-preconf-wrapper">';
311 foreach ($globalsn as $asn) {
312 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
314 $s .= '<p></p><div class="clear"></div></div>';
315 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
317 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
318 $s .= '<p>'. t('No consumer key pair for StatusNet found. Register your Friendica Account as an desktop client on your StatusNet 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 StatusNet installation.') .'</p>';
319 $s .= '<div id="statusnet-consumer-wrapper">';
320 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
321 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
322 $s .= '<div class="clear"></div>';
323 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
324 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
325 $s .= '<div class="clear"></div>';
326 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
327 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
328 $s .= '<div class="clear"></div>';
329 $s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('StatusNet application name').'</label>';
330 $s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
331 $s .= '<p></p><div class="clear"></div>';
332 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
336 * ok we have a consumer key pair now look into the OAuth stuff
338 if ( (!$otoken) && (!$osecret) ) {
340 * the user has not yet connected the account to statusnet
341 * get a temporary OAuth key/secret pair and display a button with
342 * which the user can request a PIN to connect the account to a
343 * account at statusnet
345 $connection = new StatusNetOAuth($api, $ckey, $csecret);
346 $request_token = $connection->getRequestToken('oob');
347 $token = $request_token['oauth_token'];
349 * make some nice form
351 $s .= '<p>'. t('To connect to your StatusNet account click the button below to get a security code from StatusNet which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to StatusNet.') .'</p>';
352 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
353 $s .= '<div id="statusnet-pin-wrapper">';
354 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
355 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
356 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
357 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
358 $s .= '</div><div class="clear"></div>';
359 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
360 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
361 $s .= '<div id="statusnet-cancel-wrapper">';
362 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
363 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
364 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
365 $s .= '</div><div class="clear"></div>';
366 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
369 * we have an OAuth key / secret pair for the user
370 * so let's give a chance to disable the postings to statusnet
372 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
373 $details = $connection->get('account/verify_credentials');
374 $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>';
375 $s .= '<p>'. t('If enabled all your <strong>public</strong> postings can be posted to the associated StatusNet account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.') .'</p>';
376 if ($a->user['hidewall']) {
377 $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 StatusNet will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') .'</p>';
379 $s .= '<div id="statusnet-enable-wrapper">';
380 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
381 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
382 $s .= '<div class="clear"></div>';
383 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
384 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
385 $s .= '<div class="clear"></div>';
387 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
388 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
389 $s .= '<div class="clear"></div>';
392 $s .= '<label id="statusnet-import-label" for="statusnet-import">'.t('Import the remote timeline').'</label>';
393 $s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
394 $s .= '<div class="clear"></div>';
396 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.t('Automatically create contacts').'</label>';
397 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
398 $s .= '<div class="clear"></div>';
400 $s .= '<div id="statusnet-disconnect-wrapper">';
401 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
402 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
403 $s .= '</div><div class="clear"></div>';
404 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
407 $s .= '</div><div class="clear"></div>';
411 function statusnet_post_local(&$a,&$b) {
415 if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
417 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
418 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
420 // if API is used, default to the chosen settings
421 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
422 $statusnet_enable = 1;
424 if(! $statusnet_enable)
427 if(strlen($b['postopts']))
428 $b['postopts'] .= ',';
429 $b['postopts'] .= 'statusnet';
433 function statusnet_action($a, $uid, $pid, $action) {
434 $api = get_pconfig($uid, 'statusnet', 'baseapi');
435 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
436 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
437 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
438 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
440 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
442 logger("statusnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
446 $result = $connection->post("statuses/destroy/".$pid);
449 $result = $connection->post("favorites/create/".$pid);
452 $result = $connection->post("favorites/destroy/".$pid);
455 logger("statusnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
458 function statusnet_post_hook(&$a,&$b) {
464 if (!get_pconfig($b["uid"],'statusnet','import')) {
465 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
469 $api = get_pconfig($b["uid"], 'statusnet', 'baseapi');
470 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
472 if($b['parent'] != $b['id']) {
473 logger("statusnet_post_hook: parameter ".print_r($b, true), LOGGER_DATA);
475 // Looking if its a reply to a statusnet post
476 $hostlength = strlen($hostname) + 2;
477 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname."::") AND (substr($b["extid"], 0, $hostlength) != $hostname."::")
478 AND (substr($b["thr-parent"], 0, $hostlength) != $hostname."::")) {
479 logger("statusnet_post_hook: no statusnet post ".$b["parent"]);
483 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
484 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
485 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
486 dbesc($b["thr-parent"]),
490 logger("statusnet_post_hook: no parent found ".$b["thr-parent"]);
497 $nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
498 $nicknameplain = "@".$orig_post["contact_nick"];
500 logger("statusnet_post_hook: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
501 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
502 $b["body"] = $nickname." ".$b["body"];
504 logger("statusnet_post_hook: parent found ".print_r($orig_post, true), LOGGER_DEBUG);
508 if($b['private'] OR !strstr($b['postopts'],'statusnet'))
512 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
513 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
515 if($b['verb'] == ACTIVITY_LIKE) {
516 logger("statusnet_post_hook: parameter 2 ".substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
518 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
520 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
524 if($b['deleted'] || ($b['created'] !== $b['edited']))
527 // if posts comes from statusnet don't send it back
528 if($b['app'] == "StatusNet")
531 logger('statusnet post invoked');
533 load_pconfig($b['uid'], 'statusnet');
535 $api = get_pconfig($b['uid'], 'statusnet', 'baseapi');
536 $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
537 $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
538 $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
539 $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
541 if($ckey && $csecret && $otoken && $osecret) {
543 // If it's a repeated message from statusnet then do a native retweet and exit
544 if (statusnet_is_retweet($a, $b['uid'], $b['body']))
547 require_once('include/bbcode.php');
548 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
549 $max_char = $dent->get_maxlength(); // max. length for a dent
552 require_once("include/plaintext.php");
553 require_once("include/network.php");
554 $msgarr = plaintext($a, $b, $max_char, true);
555 $msg = $msgarr["text"];
557 if (($msg == "") AND isset($msgarr["title"]))
558 $msg = shortenmsg($msgarr["title"], $max_char - 50);
562 if (isset($msgarr["url"])) {
563 if ((strlen($msgarr["url"]) > 20) AND
564 ((strlen($msg." \n".$msgarr["url"]) > $max_char)))
565 $msg .= " \n".short_link($msgarr["url"]);
567 $msg .= " \n".$msgarr["url"];
568 } elseif (isset($msgarr["image"]))
569 $image = $msgarr["image"];
572 $img_str = fetch_url($image);
573 $tempfile = tempnam(get_config("system","temppath"), "cache");
574 file_put_contents($tempfile, $img_str);
575 $postdata = array("status" => $msg, "media[]" => $tempfile);
577 $postdata = array("status"=>$msg);
579 // and now dent it :-)
583 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
584 logger('statusnet_post send reply '.print_r($postdata, true), LOGGER_DEBUG);
587 // New code that is able to post pictures
588 require_once("addon/statusnet/codebird.php");
589 $cb = \CodebirdSN\CodebirdSN::getInstance();
590 $cb->setAPIEndpoint($api);
591 $cb->setConsumerKey($ckey, $csecret);
592 $cb->setToken($otoken, $osecret);
593 $result = $cb->statuses_update($postdata);
594 //$result = $dent->post('statuses/update', $postdata);
595 logger('statusnet_post send, result: ' . print_r($result, true).
596 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
597 if ($result->error) {
598 logger('Send to StatusNet failed: "'.$result->error.'"');
599 } elseif ($iscomment) {
600 logger('statusnet_post: Update extid '.$result->id." for post id ".$b['id']);
601 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
602 dbesc($hostname."::".$result->id),
603 dbesc($result->text),
613 function statusnet_plugin_admin_post(&$a){
617 foreach($_POST['sitename'] as $id=>$sitename){
618 $sitename=trim($sitename);
619 $apiurl=trim($_POST['apiurl'][$id]);
620 if (! (substr($apiurl, -1)=='/'))
622 $secret=trim($_POST['secret'][$id]);
623 $key=trim($_POST['key'][$id]);
624 $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
629 !x($_POST['delete'][$id])){
632 'sitename' => $sitename,
634 'consumersecret' => $secret,
635 'consumerkey' => $key,
636 'applicationname' => $applicationname
641 $sites = set_config('statusnet','sites', $sites);
645 function statusnet_plugin_admin(&$a, &$o){
647 $sites = get_config('statusnet','sites');
649 if (is_array($sites)){
650 foreach($sites as $id=>$s){
651 $sitesform[] = Array(
652 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
653 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29") ),
654 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
655 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
656 'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
657 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
661 /* empty form to add new site */
663 $sitesform[] = Array(
664 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
665 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29") ),
666 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
667 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
668 'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
671 $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
672 $o = replace_macros($t, array(
673 '$submit' => t('Save Settings'),
674 '$sites' => $sitesform,
678 function statusnet_cron($a,$b) {
679 $last = get_config('statusnet','last_poll');
681 $poll_interval = intval(get_config('statusnet','poll_interval'));
683 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
686 $next = $last + ($poll_interval * 60);
688 logger('statusnet: poll intervall not reached');
692 logger('statusnet: cron_start');
694 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
697 logger('statusnet: fetching for user '.$rr['uid']);
698 statusnet_fetchtimeline($a, $rr['uid']);
702 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
705 logger('statusnet: importing timeline from user '.$rr['uid']);
706 statusnet_fetchhometimeline($a, $rr["uid"]);
710 logger('statusnet: cron_end');
712 set_config('statusnet','last_poll', time());
715 function statusnet_fetchtimeline($a, $uid) {
716 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
717 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
718 $api = get_pconfig($uid, 'statusnet', 'baseapi');
719 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
720 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
721 $lastid = get_pconfig($uid, 'statusnet', 'lastid');
723 require_once('mod/item.php');
724 require_once('include/items.php');
726 // get the application name for the SN app
727 // 1st try personal config, then system config and fallback to the
728 // hostname of the node if neither one is set.
729 $application_name = get_pconfig( $uid, 'statusnet', 'application_name');
730 if ($application_name == "")
731 $application_name = get_config('statusnet', 'application_name');
732 if ($application_name == "")
733 $application_name = $a->get_hostname();
735 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
737 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
739 $first_time = ($lastid == "");
742 $parameters["since_id"] = $lastid;
744 $items = $connection->get('statuses/user_timeline', $parameters);
746 if (!is_array($items))
749 $posts = array_reverse($items);
752 foreach ($posts as $post) {
753 if ($post->id > $lastid)
759 if ($post->source == "activity")
762 if (is_object($post->retweeted_status))
765 if ($post->in_reply_to_status_id != "")
768 if (!strpos($post->source, $application_name)) {
769 $_SESSION["authenticated"] = true;
770 $_SESSION["uid"] = $uid;
773 $_REQUEST["type"] = "wall";
774 $_REQUEST["api_source"] = true;
775 $_REQUEST["profile_uid"] = $uid;
776 $_REQUEST["source"] = "StatusNet";
778 //$_REQUEST["date"] = $post->created_at;
780 $_REQUEST["title"] = "";
782 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
783 if (is_string($post->place->name))
784 $_REQUEST["location"] = $post->place->name;
786 if (is_string($post->place->full_name))
787 $_REQUEST["location"] = $post->place->full_name;
789 if (is_array($post->geo->coordinates))
790 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
792 if (is_array($post->coordinates->coordinates))
793 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
795 //print_r($_REQUEST);
796 if ($_REQUEST["body"] != "") {
797 logger('statusnet: posting for user '.$uid);
804 set_pconfig($uid, 'statusnet', 'lastid', $lastid);
807 function statusnet_address($contact) {
808 $hostname = normalise_link($contact->statusnet_profile_url);
809 $nickname = $contact->screen_name;
811 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
813 $address = $contact->screen_name."@".$hostname;
818 function statusnet_fetch_contact($uid, $contact, $create_user) {
819 // Check if the unique contact is existing
820 // To-Do: only update once a while
821 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
822 dbesc(normalise_link($contact->statusnet_profile_url)));
825 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
826 dbesc(normalise_link($contact->statusnet_profile_url)),
827 dbesc($contact->name),
828 dbesc($contact->screen_name),
829 dbesc($contact->profile_image_url));
831 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
832 dbesc($contact->name),
833 dbesc($contact->screen_name),
834 dbesc($contact->profile_image_url),
835 dbesc(normalise_link($contact->statusnet_profile_url)));
837 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
838 intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)));
840 if(!count($r) AND !$create_user)
843 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
844 logger("statusnet_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
849 // create contact record
850 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
851 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
852 `writable`, `blocked`, `readonly`, `pending` )
853 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
855 dbesc(datetime_convert()),
856 dbesc($contact->statusnet_profile_url),
857 dbesc(normalise_link($contact->statusnet_profile_url)),
858 dbesc(statusnet_address($contact)),
859 dbesc(normalise_link($contact->statusnet_profile_url)),
862 dbesc($contact->name),
863 dbesc($contact->screen_name),
864 dbesc($contact->profile_image_url),
865 dbesc(NETWORK_STATUSNET),
866 intval(CONTACT_IS_FRIEND),
871 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
872 dbesc($contact->statusnet_profile_url),
879 $contact_id = $r[0]['id'];
881 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
885 if($g && intval($g[0]['def_gid'])) {
886 require_once('include/group.php');
887 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
890 require_once("Photo.php");
892 $photos = import_profile_photo($contact->profile_image_url,$uid,$contact_id);
894 q("UPDATE `contact` SET `photo` = '%s',
904 dbesc(datetime_convert()),
905 dbesc(datetime_convert()),
906 dbesc(datetime_convert()),
911 // update profile photos once every two weeks as we have no notification of when they change.
913 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
914 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
916 // check that we have all the photos, this has been known to fail on occasion
918 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
920 logger("statusnet_fetch_contact: Updating contact ".$contact->screen_name, LOGGER_DEBUG);
922 require_once("Photo.php");
924 $photos = import_profile_photo($contact->profile_image_url, $uid, $r[0]['id']);
926 q("UPDATE `contact` SET `photo` = '%s',
931 `avatar-date` = '%s',
941 dbesc(datetime_convert()),
942 dbesc(datetime_convert()),
943 dbesc(datetime_convert()),
944 dbesc($contact->statusnet_profile_url),
945 dbesc(normalise_link($contact->statusnet_profile_url)),
946 dbesc(statusnet_address($contact)),
947 dbesc($contact->name),
948 dbesc($contact->screen_name),
957 function statusnet_fetchuser($a, $uid, $screen_name = "", $user_id = "") {
958 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
959 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
960 $api = get_pconfig($uid, 'statusnet', 'baseapi');
961 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
962 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
964 require_once("addon/statusnet/codebird.php");
966 $cb = \Codebird\Codebird::getInstance();
967 $cb->setConsumerKey($ckey, $csecret);
968 $cb->setToken($otoken, $osecret);
970 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
978 $parameters = array();
980 if ($screen_name != "")
981 $parameters["screen_name"] = $screen_name;
984 $parameters["user_id"] = $user_id;
986 // Fetching user data
987 $user = $cb->users_show($parameters);
989 if (!is_object($user))
992 $contact_id = statusnet_fetch_contact($uid, $user, true);
997 function statusnet_createpost($a, $uid, $post, $self, $create_user, $only_existing_contact) {
999 require_once("include/html2bbcode.php");
1001 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1002 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1004 $postarray = array();
1005 $postarray['network'] = NETWORK_STATUSNET;
1006 $postarray['gravity'] = 0;
1007 $postarray['uid'] = $uid;
1008 $postarray['wall'] = 0;
1009 $postarray['uri'] = $hostname."::".$post->id;
1011 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1012 dbesc($postarray['uri']),
1021 if ($post->in_reply_to_status_id != "") {
1023 $parent = $hostname."::".$post->in_reply_to_status_id;
1025 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1030 $postarray['thr-parent'] = $r[0]["uri"];
1031 $postarray['parent-uri'] = $r[0]["parent-uri"];
1033 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1038 $postarray['thr-parent'] = $r[0]['uri'];
1039 $postarray['parent-uri'] = $r[0]['parent-uri'];
1041 $postarray['thr-parent'] = $postarray['uri'];
1042 $postarray['parent-uri'] = $postarray['uri'];
1047 $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1049 if ($post->user->id == $own_url) {
1050 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1054 $contactid = $r[0]["id"];
1056 $postarray['owner-name'] = $r[0]["name"];
1057 $postarray['owner-link'] = $r[0]["url"];
1058 $postarray['owner-avatar'] = $r[0]["photo"];
1063 $postarray['parent-uri'] = $postarray['uri'];
1065 if ($contactid == 0) {
1066 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1067 $postarray['owner-name'] = $post->user->name;
1068 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1069 $postarray['owner-avatar'] = $post->user->profile_image_url;
1071 if(($contactid == 0) AND !$only_existing_contact)
1072 $contactid = $self['id'];
1073 elseif ($contactid <= 0)
1076 $postarray['contact-id'] = $contactid;
1078 $postarray['verb'] = ACTIVITY_POST;
1079 $postarray['author-name'] = $postarray['owner-name'];
1080 $postarray['author-link'] = $postarray['owner-link'];
1081 $postarray['author-avatar'] = $postarray['owner-avatar'];
1083 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1084 $hostname = str_replace("/api/", "/notice/", get_pconfig($uid, 'statusnet', 'baseapi'));
1086 $postarray['plink'] = $hostname.$post->id;
1087 $postarray['app'] = strip_tags($post->source);
1089 if ($post->user->protected) {
1090 $postarray['private'] = 1;
1091 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1094 $postarray['body'] = html2bbcode($post->statusnet_html);
1096 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1097 $postarray['body'] = $converted["body"];
1098 $postarray['tag'] = $converted["tags"];
1100 $postarray['created'] = datetime_convert('UTC','UTC',$post->created_at);
1101 $postarray['edited'] = datetime_convert('UTC','UTC',$post->created_at);
1103 if (is_string($post->place->name))
1104 $postarray["location"] = $post->place->name;
1106 if (is_string($post->place->full_name))
1107 $postarray["location"] = $post->place->full_name;
1109 if (is_array($post->geo->coordinates))
1110 $postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
1112 if (is_array($post->coordinates->coordinates))
1113 $postarray["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
1115 if (is_object($post->retweeted_status)) {
1116 $postarray['body'] = html2bbcode($post->retweeted_status->statusnet_html);
1118 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1119 $postarray['body'] = $converted["body"];
1120 $postarray['tag'] = $converted["tags"];
1122 statusnet_fetch_contact($uid, $post->retweeted_status->user, false);
1124 // Let retweets look like wall-to-wall posts
1125 $postarray['author-name'] = $post->retweeted_status->user->name;
1126 $postarray['author-link'] = $post->retweeted_status->user->statusnet_profile_url;
1127 $postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url;
1132 function statusnet_checknotification($a, $uid, $own_url, $top_item, $postarray) {
1134 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1142 if (link_compare($user[0]["url"], $postarray['author-link']))
1145 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1150 if(!count($own_user))
1153 // Is it me from statusnet?
1154 if (link_compare($own_user[0]["url"], $postarray['author-link']))
1157 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1158 dbesc($postarray['parent-uri']),
1162 if(count($myconv)) {
1164 foreach($myconv as $conv) {
1165 // now if we find a match, it means we're in this conversation
1167 if(!link_compare($conv['author-link'],$user[0]["url"]) AND !link_compare($conv['author-link'],$own_user[0]["url"]))
1170 require_once('include/enotify.php');
1172 $conv_parent = $conv['parent'];
1175 'type' => NOTIFY_COMMENT,
1176 'notify_flags' => $user[0]['notify-flags'],
1177 'language' => $user[0]['language'],
1178 'to_name' => $user[0]['username'],
1179 'to_email' => $user[0]['email'],
1180 'uid' => $user[0]['uid'],
1181 'item' => $postarray,
1182 'link' => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1183 'source_name' => $postarray['author-name'],
1184 'source_link' => $postarray['author-link'],
1185 'source_photo' => $postarray['author-avatar'],
1186 'verb' => ACTIVITY_POST,
1188 'parent' => $conv_parent,
1191 // only send one notification
1197 function statusnet_fetchhometimeline($a, $uid) {
1198 $conversations = array();
1200 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1201 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1202 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1203 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1204 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1205 $create_user = get_pconfig($uid, 'statusnet', 'create_user');
1207 // "create_user" is deactivated, since currently you cannot add users manually by now
1208 $create_user = true;
1210 logger("statusnet_fetchhometimeline: Fetching for user ".$uid, LOGGER_DEBUG);
1212 require_once('library/twitteroauth.php');
1213 require_once('include/items.php');
1215 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1217 $own_contact = statusnet_fetch_own_contact($a, $uid);
1219 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1220 intval($own_contact),
1224 $nick = $r[0]["nick"];
1226 logger("statusnet_fetchhometimeline: Own statusnet contact not found for user ".$uid, LOGGER_DEBUG);
1230 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1236 logger("statusnet_fetchhometimeline: Own contact not found for user ".$uid, LOGGER_DEBUG);
1240 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1243 logger("statusnet_fetchhometimeline: Own user not found for user ".$uid, LOGGER_DEBUG);
1247 $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1248 //$parameters["count"] = 200;
1251 // Fetching timeline
1252 $lastid = get_pconfig($uid, 'statusnet', 'lasthometimelineid');
1255 $first_time = ($lastid == "");
1258 $parameters["since_id"] = $lastid;
1260 $items = $connection->get('statuses/home_timeline', $parameters);
1262 if (!is_array($items)) {
1263 logger("statusnet_fetchhometimeline: Error fetching home timeline: ".print_r($items, true), LOGGER_DEBUG);
1267 $posts = array_reverse($items);
1269 logger("statusnet_fetchhometimeline: Fetching timeline for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1271 if (count($posts)) {
1272 foreach ($posts as $post) {
1274 if ($post->id > $lastid)
1275 $lastid = $post->id;
1280 if (isset($post->statusnet_conversation_id)) {
1281 if (!isset($conversations[$post->statusnet_conversation_id])) {
1282 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1283 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1286 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1288 if (trim($postarray['body']) == "")
1291 $item = item_store($postarray);
1293 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted home timeline item '.$item);
1296 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1301 set_pconfig($uid, 'statusnet', 'lasthometimelineid', $lastid);
1303 // Fetching mentions
1304 $lastid = get_pconfig($uid, 'statusnet', 'lastmentionid');
1305 $first_time = ($lastid == "");
1308 $parameters["since_id"] = $lastid;
1310 $items = $connection->get('statuses/mentions_timeline', $parameters);
1312 if (!is_array($items)) {
1313 logger("statusnet_fetchhometimeline: Error fetching mentions: ".print_r($items, true), LOGGER_DEBUG);
1317 $posts = array_reverse($items);
1319 logger("statusnet_fetchhometimeline: Fetching mentions for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1321 if (count($posts)) {
1322 foreach ($posts as $post) {
1323 if ($post->id > $lastid)
1324 $lastid = $post->id;
1329 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1331 if (isset($post->statusnet_conversation_id)) {
1332 if (!isset($conversations[$post->statusnet_conversation_id])) {
1333 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1334 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1337 if (trim($postarray['body']) != "") {
1340 $item = item_store($postarray);
1342 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted mention timeline item '.$item);
1346 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1347 dbesc($postarray['uri']),
1351 $item = $r[0]['id'];
1354 require_once('include/enotify.php');
1356 'type' => NOTIFY_TAGSELF,
1357 'notify_flags' => $u[0]['notify-flags'],
1358 'language' => $u[0]['language'],
1359 'to_name' => $u[0]['username'],
1360 'to_email' => $u[0]['email'],
1361 'uid' => $u[0]['uid'],
1362 'item' => $postarray,
1363 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item,
1364 'source_name' => $postarray['author-name'],
1365 'source_link' => $postarray['author-link'],
1366 'source_photo' => $postarray['author-avatar'],
1367 'verb' => ACTIVITY_TAG,
1374 set_pconfig($uid, 'statusnet', 'lastmentionid', $lastid);
1377 function statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $conversation) {
1378 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1379 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1380 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1381 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1382 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1384 require_once('library/twitteroauth.php');
1386 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1388 $parameters["count"] = 200;
1390 $items = $connection->get('statusnet/conversation/'.$conversation, $parameters);
1391 if (is_array($items)) {
1392 $posts = array_reverse($items);
1394 foreach($posts AS $post) {
1395 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1397 if (trim($postarray['body']) == "")
1400 //print_r($postarray);
1401 $item = item_store($postarray);
1403 logger('statusnet_complete_conversation: User '.$self["nick"].' posted home timeline item '.$item);
1406 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1411 function statusnet_convertmsg($a, $body, $no_tags = false) {
1413 require_once("include/oembed.php");
1414 require_once("include/items.php");
1415 require_once("include/network.php");
1417 $URLSearchString = "^\[\]";
1418 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body,$matches,PREG_SET_ORDER);
1426 foreach ($matches AS $match) {
1427 $search = "[url=".$match[1]."]".$match[2]."[/url]";
1429 $expanded_url = original_url($match[1]);
1431 $oembed_data = oembed_fetch_url($expanded_url, true);
1434 $type = $oembed_data->type;
1435 if ($oembed_data->type == "video") {
1436 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1437 $type = $oembed_data->type;
1438 $footerurl = $expanded_url;
1439 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1441 $body = str_replace($search, $footerlink, $body);
1442 } elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia)
1443 $body = str_replace($search, "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]", $body);
1444 elseif ($oembed_data->type != "link")
1445 $body = str_replace($search, "[url=".$expanded_url."]".$expanded_url."[/url]", $body);
1447 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1449 $tempfile = tempnam(get_config("system","temppath"), "cache");
1450 file_put_contents($tempfile, $img_str);
1451 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1454 if (substr($mime, 0, 6) == "image/") {
1456 $body = str_replace($search, "[img]".$expanded_url."[/img]", $body);
1458 $type = $oembed_data->type;
1459 $footerurl = $expanded_url;
1460 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1462 $body = str_replace($search, $footerlink, $body);
1467 if ($footerurl != "")
1468 $footer = add_page_info($footerurl);
1470 if (($footerlink != "") AND (trim($footer) != "")) {
1471 $removedlink = trim(str_replace($footerlink, "", $body));
1473 if (strstr($body, $removedlink))
1474 $body = $removedlink;
1481 return(array("body" => $body, "tags" => ""));
1485 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$body,$matches,PREG_SET_ORDER);
1487 foreach($matches as $mtch) {
1488 if(strlen($str_tags))
1491 if ($mtch[1] == "#") {
1492 // Replacing the hash tags that are directed to the statusnet server with internal links
1493 $snhash = "#[url=".$mtch[2]."]".$mtch[3]."[/url]";
1494 $frdchash = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($mtch[3]).']'.$mtch[3].'[/url]';
1495 $body = str_replace($snhash, $frdchash, $body);
1497 $str_tags .= $frdchash;
1499 $str_tags .= "@[url=".$mtch[2]."]".$mtch[3]."[/url]";
1501 // There is a problem with links with to statusnet groups, so these links are stored with "@" like friendica groups
1502 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1506 return(array("body"=>$body, "tags"=>$str_tags));
1510 function statusnet_fetch_own_contact($a, $uid) {
1511 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1512 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1513 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1514 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1515 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1516 $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1520 if ($own_url == "") {
1521 require_once('library/twitteroauth.php');
1523 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1525 // Fetching user data
1526 $user = $connection->get('account/verify_credentials');
1528 set_pconfig($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1530 $contact_id = statusnet_fetch_contact($uid, $user, true);
1533 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1534 intval($uid), dbesc($own_url));
1536 $contact_id = $r[0]["id"];
1538 del_pconfig($uid, 'statusnet', 'own_url');
1541 return($contact_id);
1544 function statusnet_is_retweet($a, $uid, $body) {
1545 $body = trim($body);
1547 // Skip if it isn't a pure repeated messages
1548 // Does it start with a share?
1549 if (strpos($body, "[share") > 0)
1552 // Does it end with a share?
1553 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1556 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1557 // Skip if there is no shared message in there
1558 if ($body == $attributes)
1562 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1563 if ($matches[1] != "")
1564 $link = $matches[1];
1566 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1567 if ($matches[1] != "")
1568 $link = $matches[1];
1570 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1571 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1572 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1573 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1574 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1575 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1577 $id = preg_replace("=https?://".$hostname."/notice/(.*)=ism", "$1", $link);
1582 logger('statusnet_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG);
1584 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1586 $result = $connection->post('statuses/retweet/'.$id);
1588 logger('statusnet_is_retweet: result '.print_r($result, true), LOGGER_DEBUG);
1589 return(isset($result->id));