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', 'post_taglinks');
172 del_pconfig(local_user(), 'statusnet', 'lastid');
173 del_pconfig(local_user(), 'statusnet', 'mirror_posts');
174 del_pconfig(local_user(), 'statusnet', 'intelligent_shortening');
175 del_pconfig(local_user(), 'statusnet', 'import');
176 del_pconfig(local_user(), 'statusnet', 'create_user');
177 del_pconfig(local_user(), 'statusnet', 'own_id');
179 if (isset($_POST['statusnet-preconf-apiurl'])) {
181 * If the user used one of the preconfigured StatusNet server credentials
182 * use them. All the data are available in the global config.
183 * Check the API Url never the less and blame the admin if it's not working ^^
185 $globalsn = get_config('statusnet', 'sites');
186 foreach ( $globalsn as $asn) {
187 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
188 $apibase = $asn['apiurl'];
189 $c = fetch_url( $apibase . 'statusnet/version.xml' );
190 if (strlen($c) > 0) {
191 set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
192 set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
193 set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
194 set_pconfig(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
196 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
200 goaway($a->get_baseurl().'/settings/connectors');
202 if (isset($_POST['statusnet-consumersecret'])) {
203 // check if we can reach the API of the StatusNet server
204 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
205 // resign quickly after this one try to fix the path ;-)
206 $apibase = $_POST['statusnet-baseapi'];
207 $c = fetch_url( $apibase . 'statusnet/version.xml' );
208 if (strlen($c) > 0) {
209 // ok the API path is correct, let's save the settings
210 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
211 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
212 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
213 set_pconfig(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
215 // the API path is not correct, maybe missing trailing / ?
216 $apibase = $apibase . '/';
217 $c = fetch_url( $apibase . 'statusnet/version.xml' );
218 if (strlen($c) > 0) {
219 // ok the API path is now correct, let's save the settings
220 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
221 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
222 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
224 // still not the correct API base, let's do noting
225 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
228 goaway($a->get_baseurl().'/settings/connectors');
230 if (isset($_POST['statusnet-pin'])) {
231 // if the user supplied us with a PIN from StatusNet, let the magic of OAuth happen
232 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
233 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
234 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
235 // the token and secret for which the PIN was generated were hidden in the settings
236 // form as token and token2, we need a new connection to StatusNet using these token
237 // and secret to request a Access Token with the PIN
238 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
239 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
240 // ok, now that we have the Access Token, save them in the user config
241 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
242 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
243 set_pconfig(local_user(),'statusnet', 'post', 1);
244 set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
245 // reload the Addon Settings page, if we don't do it see Bug #42
246 goaway($a->get_baseurl().'/settings/connectors');
248 // if no PIN is supplied in the POST variables, the user has changed the setting
249 // to post a dent for every new __public__ posting to the wall
250 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
251 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
252 set_pconfig(local_user(),'statusnet','post_taglinks',intval($_POST['statusnet-sendtaglinks']));
253 set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
254 set_pconfig(local_user(), 'statusnet', 'intelligent_shortening', intval($_POST['statusnet-shortening']));
255 set_pconfig(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
256 set_pconfig(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
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 $linksenabled = get_pconfig(local_user(),'statusnet','post_taglinks');
280 $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
281 $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
282 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
283 $shorteningenabled = get_pconfig(local_user(),'statusnet','intelligent_shortening');
284 $shorteningchecked = (($shorteningenabled) ? ' checked="checked" ' : '');
285 $importenabled = get_pconfig(local_user(),'statusnet','import');
286 $importchecked = (($importenabled) ? ' checked="checked" ' : '');
287 $create_userenabled = get_pconfig(local_user(),'statusnet','create_user');
288 $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
290 $css = (($enabled) ? '' : '-disabled');
292 $globalshortening = get_config('statusnet','intelligent_shortening');
295 $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
296 $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('StatusNet Import/Export/Mirror').'</h3>';
298 $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
299 $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
300 $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('StatusNet Import/Export/Mirror').'</h3>';
303 if ( (!$ckey) && (!$csecret) ) {
307 $globalsn = get_config('statusnet', 'sites');
309 * lets check if we have one or more globally configured StatusNet
310 * server OAuth credentials in the configuration. If so offer them
311 * with a little explanation to the user as choice - otherwise
312 * ignore this option entirely.
314 if (! $globalsn == null) {
315 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
316 $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>';
317 $s .= '<div id="statusnet-preconf-wrapper">';
318 foreach ($globalsn as $asn) {
319 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
321 $s .= '<p></p><div class="clear"></div></div>';
322 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
324 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
325 $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>';
326 $s .= '<div id="statusnet-consumer-wrapper">';
327 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
328 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
329 $s .= '<div class="clear"></div>';
330 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
331 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
332 $s .= '<div class="clear"></div>';
333 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
334 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
335 $s .= '<div class="clear"></div>';
336 $s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('StatusNet application name').'</label>';
337 $s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
338 $s .= '<p></p><div class="clear"></div>';
339 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
343 * ok we have a consumer key pair now look into the OAuth stuff
345 if ( (!$otoken) && (!$osecret) ) {
347 * the user has not yet connected the account to statusnet
348 * get a temporary OAuth key/secret pair and display a button with
349 * which the user can request a PIN to connect the account to a
350 * account at statusnet
352 $connection = new StatusNetOAuth($api, $ckey, $csecret);
353 $request_token = $connection->getRequestToken('oob');
354 $token = $request_token['oauth_token'];
356 * make some nice form
358 $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>';
359 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
360 $s .= '<div id="statusnet-pin-wrapper">';
361 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
362 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
363 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
364 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
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>';
367 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
368 $s .= '<div id="statusnet-cancel-wrapper">';
369 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
370 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
371 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
372 $s .= '</div><div class="clear"></div>';
373 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
376 * we have an OAuth key / secret pair for the user
377 * so let's give a chance to disable the postings to statusnet
379 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
380 $details = $connection->get('account/verify_credentials');
381 $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>';
382 $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>';
383 if ($a->user['hidewall']) {
384 $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>';
386 $s .= '<div id="statusnet-enable-wrapper">';
387 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
388 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
389 $s .= '<div class="clear"></div>';
390 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
391 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
392 $s .= '<div class="clear"></div>';
394 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
395 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
396 $s .= '<div class="clear"></div>';
398 if (!$globalshortening) {
399 $s .= '<label id="statusnet-shortening-label" for="statusnet-shortening">'.t('Shortening method that optimizes the post').'</label>';
400 $s .= '<input id="statusnet-shortening" type="checkbox" name="statusnet-shortening" value="1" '. $shorteningchecked . '/>';
401 $s .= '<div class="clear"></div>';
403 $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
404 $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
405 $s .= '<div class="clear"></div>';
409 $s .= '<label id="statusnet-import-label" for="statusnet-import">'.t('Import the remote timeline').'</label>';
410 $s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
411 $s .= '<div class="clear"></div>';
413 $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.t('Automatically create contacts').'</label>';
414 $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
415 $s .= '<div class="clear"></div>';
417 $s .= '<div id="statusnet-disconnect-wrapper">';
418 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
419 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
420 $s .= '</div><div class="clear"></div>';
421 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
424 $s .= '</div><div class="clear"></div>';
428 function statusnet_post_local(&$a,&$b) {
432 if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
434 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
435 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
437 // if API is used, default to the chosen settings
438 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
439 $statusnet_enable = 1;
441 if(! $statusnet_enable)
444 if(strlen($b['postopts']))
445 $b['postopts'] .= ',';
446 $b['postopts'] .= 'statusnet';
450 if (! function_exists( 'short_link' )) {
451 function short_link($url) {
452 require_once('library/slinky.php');
453 $slinky = new Slinky( $url );
454 $yourls_url = get_config('yourls','url1');
456 $yourls_username = get_config('yourls','username1');
457 $yourls_password = get_config('yourls', 'password1');
458 $yourls_ssl = get_config('yourls', 'ssl1');
459 $yourls = new Slinky_YourLS();
460 $yourls->set( 'username', $yourls_username );
461 $yourls->set( 'password', $yourls_password );
462 $yourls->set( 'ssl', $yourls_ssl );
463 $yourls->set( 'yourls-url', $yourls_url );
464 $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
467 // setup a cascade of shortening services
468 // try to get a short link from these services
469 // in the order ur1.ca, trim, id.gd, tinyurl
470 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
472 return $slinky->short();
475 function statusnet_shortenmsg($b, $max_char) {
476 require_once("include/api.php");
477 require_once("include/bbcode.php");
478 require_once("include/html2plain.php");
480 $b['body'] = bb_CleanPictureLinks($b['body']);
482 // Looking for the first image
483 $cleaned_body = api_clean_plain_items($b['body']);
485 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$cleaned_body,$matches))
486 $image = $matches[3];
489 if(preg_match("/\[img\](.*?)\[\/img\]/is",$cleaned_body,$matches))
490 $image = $matches[1];
492 $multipleimages = (strpos($cleaned_body, "[img") != strrpos($cleaned_body, "[img"));
494 // When saved into the database the content is sent through htmlspecialchars
495 // That means that we have to decode all image-urls
496 $image = htmlspecialchars_decode($image);
499 if ($b["title"] != "")
500 $body = $b["title"]."\n\n".$body;
502 if (strpos($body, "[bookmark") !== false) {
503 // splitting the text in two parts:
504 // before and after the bookmark
505 $pos = strpos($body, "[bookmark");
506 $body1 = substr($body, 0, $pos);
507 $body2 = substr($body, $pos);
509 // Removing all quotes after the bookmark
510 // they are mostly only the content after the bookmark.
511 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
512 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
513 $body = $body1.$body2;
516 // Add some newlines so that the message could be cut better
517 $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
518 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
520 // remove the recycle signs and the names since they aren't helpful on statusnet
522 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
523 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
525 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
526 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
528 // remove the share element
529 //$body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
531 // At first convert the text to html
532 $html = bbcode(api_clean_plain_items($body), false, false, 2);
534 // Then convert it to plain text
535 //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
536 $msg = trim(html2plain($html, 0, true));
537 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
539 // Removing multiple newlines
540 while (strpos($msg, "\n\n\n") !== false)
541 $msg = str_replace("\n\n\n", "\n\n", $msg);
543 // Removing multiple spaces
544 while (strpos($msg, " ") !== false)
545 $msg = str_replace(" ", " ", $msg);
550 $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
555 // look for bookmark-bbcode and handle it with priority
556 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
559 $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
561 // If there is no bookmark element then take the first link
563 $links = collecturls($html);
564 if (sizeof($links) > 0) {
566 $link = current($links);
568 $multiplelinks = (sizeof($links) > 1);
573 $msglink = $b["plink"];
574 else if ($link != "")
576 else if ($multipleimages)
577 $msglink = $b["plink"];
578 else if ($image != "")
581 if (($msglink == "") and strlen($msg) > $max_char)
582 $msglink = $b["plink"];
584 // If the message is short enough then don't modify it. (if the link exists in the original message)
585 if ((strlen(trim($origmsg)) <= $max_char) AND (($msglink == "") OR strpos($origmsg, $msglink)))
586 return(array("msg"=>trim($origmsg), "image"=>""));
588 // If the message is short enough and contains a picture then post the picture as well
589 if ((strlen(trim($origmsg)) <= ($max_char - 20)) AND strpos($origmsg, $msglink))
590 return(array("msg"=>trim($origmsg), "image"=>$image));
592 // If the message is short enough and the link exists in the original message don't modify it as well
593 if ((strlen(trim($origmsg)) <= $max_char) AND strpos($origmsg, $msglink))
594 return(array("msg"=>trim($origmsg), "image"=>""));
596 // Preserve the unshortened link
597 $orig_link = $msglink;
599 if (strlen($msglink) > 20)
600 $msglink = short_link($msglink);
602 if (strlen(trim($msg." ".$msglink)) > $max_char) {
603 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
604 $lastchar = substr($msg, -1);
605 $msg = substr($msg, 0, -1);
606 $pos = strrpos($msg, "\n");
608 $msg = substr($msg, 0, $pos);
609 else if ($lastchar != "\n")
610 $msg = substr($msg, 0, -3)."...";
612 //$msg = str_replace("\n", " ", $msg);
614 // Removing multiple spaces - again
615 while (strpos($msg, " ") !== false)
616 $msg = str_replace(" ", " ", $msg);
618 //return(array("msg"=>trim($msg."\n".$msglink), "image"=>$image));
620 // Looking if the link points to an image
621 $img_str = fetch_url($orig_link);
623 $tempfile = tempnam(get_config("system","temppath"), "cache");
624 file_put_contents($tempfile, $img_str);
625 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
628 if (($image == $orig_link) OR (substr($mime, 0, 6) == "image/"))
629 return(array("msg"=>trim($msg), "image"=>$orig_link));
630 else if (($image != $orig_link) AND ($image != "") AND (strlen($msg." ".$msglink) <= ($max_char - 20)))
631 return(array("msg"=>trim($msg." ".$msglink)."\n", "image"=>$image));
633 return(array("msg"=>trim($msg." ".$msglink), "image"=>""));
636 function statusnet_action($a, $uid, $pid, $action) {
637 $api = get_pconfig($uid, 'statusnet', 'baseapi');
638 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
639 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
640 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
641 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
643 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
645 logger("statusnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
649 $result = $connection->post("statuses/destroy/".$pid);
652 $result = $connection->post("favorites/create/".$pid);
655 $result = $connection->post("favorites/destroy/".$pid);
658 logger("statusnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
661 function statusnet_post_hook(&$a,&$b) {
667 if (!get_pconfig($b["uid"],'statusnet','import')) {
668 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
672 $api = get_pconfig($b["uid"], 'statusnet', 'baseapi');
673 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
675 if($b['parent'] != $b['id']) {
676 logger("statusnet_post_hook: parameter ".print_r($b, true), LOGGER_DATA);
678 // Looking if its a reply to a statusnet post
679 $hostlength = strlen($hostname) + 2;
680 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname."::") AND (substr($b["extid"], 0, $hostlength) != $hostname."::")
681 AND (substr($b["thr-parent"], 0, $hostlength) != $hostname."::")) {
682 logger("statusnet_post_hook: no statusnet post ".$b["parent"]);
686 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
687 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
688 WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
689 dbesc($b["thr-parent"]),
693 logger("statusnet_post_hook: no parent found ".$b["thr-parent"]);
700 $nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
701 $nicknameplain = "@".$orig_post["contact_nick"];
703 logger("statusnet_post_hook: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
704 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
705 $b["body"] = $nickname." ".$b["body"];
707 logger("statusnet_post_hook: parent found ".print_r($orig_post, true), LOGGER_DEBUG);
711 if($b['private'] OR !strstr($b['postopts'],'statusnet'))
715 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
716 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
718 if($b['verb'] == ACTIVITY_LIKE) {
719 logger("statusnet_post_hook: parameter 2 ".substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
721 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
723 statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
727 if($b['deleted'] || ($b['created'] !== $b['edited']))
730 // if posts comes from statusnet don't send it back
731 if($b['app'] == "StatusNet")
734 logger('statusnet post invoked');
736 load_pconfig($b['uid'], 'statusnet');
738 $api = get_pconfig($b['uid'], 'statusnet', 'baseapi');
739 $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
740 $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
741 $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
742 $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
743 $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
745 // Global setting overrides this
746 if (get_config('statusnet','intelligent_shortening'))
747 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
749 if($ckey && $csecret && $otoken && $osecret) {
751 // If it's a repeated message from statusnet then do a native retweet and exit
752 if (statusnet_is_retweet($a, $b['uid'], $b['body']))
755 require_once('include/bbcode.php');
756 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
757 $max_char = $dent->get_maxlength(); // max. length for a dent
758 // we will only work with up to two times the length of the dent
759 // we can later send to StatusNet. This way we can "gain" some
760 // information during shortening of potential links but do not
761 // shorten all the links in a 200000 character long essay.
764 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
765 if (!$intelligent_shortening) {
766 if (! $b['title']=='') {
767 $tmp = $b['title'].": \n".$b['body'];
768 // $tmp = substr($tmp, 0, 4*$max_char);
770 $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
772 // if [url=bla][img]blub.png[/img][/url] get blub.png
773 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
774 // preserve links to images, videos and audios
775 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
776 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
777 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
778 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
779 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
780 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
781 $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
782 // if a #tag is linked, don't send the [url] over to SN
783 // that is, don't send if the option is not set in the
784 // connector settings
785 if ($linksenabled=='0') {
787 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
789 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
791 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
792 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
794 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
795 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
797 // preserve links to webpages
798 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
799 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
800 // find all http or https links in the body of the entry and
801 // apply the shortener if the link is longer then 20 characters
802 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
803 preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls );
804 foreach ($allurls as $url) {
805 foreach ($url as $u) {
807 $sl = short_link($u);
808 $tmp = str_replace( $u, $sl, $tmp );
813 // ok, all the links we want to send out are save, now strip
814 // away the remaining bbcode
815 //$msg = strip_tags(bbcode($tmp, false, false));
816 $msg = bbcode($tmp, false, false, true);
817 $msg = str_replace(array('<br>','<br />'),"\n",$msg);
818 $msg = strip_tags($msg);
820 // quotes not working - let's try this
821 $msg = html_entity_decode($msg);
823 if (( strlen($msg) > $max_char) && $max_char > 0) {
824 $shortlink = short_link( $b['plink'] );
825 // the new message will be shortened such that "... $shortlink"
826 // will fit into the character limit
827 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
828 $msg = str_replace(array('<br>','<br />'),' ',$msg);
829 $e = explode(' ', $msg);
830 // remove the last word from the cut down message to
831 // avoid sending cut words to the MicroBlog
833 $msg = implode(' ', $e);
834 $msg .= '... ' . $shortlink;
838 $postdata = array('status' => $msg);
840 /* $msgarr = statusnet_shortenmsg($b, $max_char);
841 $msg = $msgarr["msg"];
842 $image = $msgarr["image"];
844 require_once("include/plaintext.php");
845 require_once("include/network.php");
846 $msgarr = plaintext($a, $b, $max_char, true);
847 $msg = $msgarr["text"];
849 if (($msg == "") AND isset($msgarr["title"]))
850 $msg = shortenmsg($msgarr["title"], $max_char - 50);
854 if (isset($msgarr["url"])) {
855 if ((strlen($msgarr["url"]) > 20) AND
856 ((strlen($msg." ".$msgarr["url"]) > $max_char)))
857 $msg .= " ".short_link($msgarr["url"]);
859 $msg .= " ".$msgarr["url"];
860 } elseif (isset($msgarr["image"]))
861 $image = $msgarr["image"];
864 $img_str = fetch_url($image);
865 $tempfile = tempnam(get_config("system","temppath"), "cache");
866 file_put_contents($tempfile, $img_str);
867 $postdata = array("status" => $msg, "media[]" => $tempfile);
869 $postdata = array("status"=>$msg);
872 // and now dent it :-)
876 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
877 logger('statusnet_post send reply '.print_r($postdata, true), LOGGER_DEBUG);
880 // New code that is able to post pictures
881 require_once("addon/statusnet/codebird.php");
882 $cb = \CodebirdSN\CodebirdSN::getInstance();
883 $cb->setAPIEndpoint($api);
884 $cb->setConsumerKey($ckey, $csecret);
885 $cb->setToken($otoken, $osecret);
886 $result = $cb->statuses_update($postdata);
887 //$result = $dent->post('statuses/update', $postdata);
888 logger('statusnet_post send, result: ' . print_r($result, true).
889 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
890 if ($result->error) {
891 logger('Send to StatusNet failed: "'.$result->error.'"');
892 } elseif ($iscomment) {
893 logger('statusnet_post: Update extid '.$result->id." for post id ".$b['id']);
894 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
895 dbesc($hostname."::".$result->id),
896 dbesc($result->text),
906 function statusnet_plugin_admin_post(&$a){
910 foreach($_POST['sitename'] as $id=>$sitename){
911 $sitename=trim($sitename);
912 $apiurl=trim($_POST['apiurl'][$id]);
913 if (! (substr($apiurl, -1)=='/'))
915 $secret=trim($_POST['secret'][$id]);
916 $key=trim($_POST['key'][$id]);
917 $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
922 !x($_POST['delete'][$id])){
925 'sitename' => $sitename,
927 'consumersecret' => $secret,
928 'consumerkey' => $key,
929 'applicationname' => $applicationname
934 $sites = set_config('statusnet','sites', $sites);
938 function statusnet_plugin_admin(&$a, &$o){
940 $sites = get_config('statusnet','sites');
942 if (is_array($sites)){
943 foreach($sites as $id=>$s){
944 $sitesform[] = Array(
945 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
946 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29") ),
947 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
948 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
949 'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
950 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
954 /* empty form to add new site */
956 $sitesform[] = Array(
957 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
958 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29") ),
959 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
960 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
961 'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
964 $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
965 $o = replace_macros($t, array(
966 '$submit' => t('Save Settings'),
967 '$sites' => $sitesform,
971 function statusnet_cron($a,$b) {
972 $last = get_config('statusnet','last_poll');
974 $poll_interval = intval(get_config('statusnet','poll_interval'));
976 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
979 $next = $last + ($poll_interval * 60);
981 logger('statusnet: poll intervall not reached');
985 logger('statusnet: cron_start');
987 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
990 logger('statusnet: fetching for user '.$rr['uid']);
991 statusnet_fetchtimeline($a, $rr['uid']);
995 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
998 logger('statusnet: importing timeline from user '.$rr['uid']);
999 statusnet_fetchhometimeline($a, $rr["uid"]);
1003 logger('statusnet: cron_end');
1005 set_config('statusnet','last_poll', time());
1008 function statusnet_fetchtimeline($a, $uid) {
1009 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1010 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1011 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1012 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1013 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1014 $lastid = get_pconfig($uid, 'statusnet', 'lastid');
1016 require_once('mod/item.php');
1017 require_once('include/items.php');
1019 // get the application name for the SN app
1020 // 1st try personal config, then system config and fallback to the
1021 // hostname of the node if neither one is set.
1022 $application_name = get_pconfig( $uid, 'statusnet', 'application_name');
1023 if ($application_name == "")
1024 $application_name = get_config('statusnet', 'application_name');
1025 if ($application_name == "")
1026 $application_name = $a->get_hostname();
1028 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1030 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
1032 $first_time = ($lastid == "");
1035 $parameters["since_id"] = $lastid;
1037 $items = $connection->get('statuses/user_timeline', $parameters);
1039 if (!is_array($items))
1042 $posts = array_reverse($items);
1044 if (count($posts)) {
1045 foreach ($posts as $post) {
1046 if ($post->id > $lastid)
1047 $lastid = $post->id;
1052 if ($post->source == "activity")
1055 if (is_object($post->retweeted_status))
1058 if ($post->in_reply_to_status_id != "")
1061 if (!strpos($post->source, $application_name)) {
1062 $_SESSION["authenticated"] = true;
1063 $_SESSION["uid"] = $uid;
1066 $_REQUEST["type"] = "wall";
1067 $_REQUEST["api_source"] = true;
1068 $_REQUEST["profile_uid"] = $uid;
1069 $_REQUEST["source"] = "StatusNet";
1071 //$_REQUEST["date"] = $post->created_at;
1073 $_REQUEST["title"] = "";
1075 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
1076 if (is_string($post->place->name))
1077 $_REQUEST["location"] = $post->place->name;
1079 if (is_string($post->place->full_name))
1080 $_REQUEST["location"] = $post->place->full_name;
1082 if (is_array($post->geo->coordinates))
1083 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
1085 if (is_array($post->coordinates->coordinates))
1086 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
1088 //print_r($_REQUEST);
1089 if ($_REQUEST["body"] != "") {
1090 logger('statusnet: posting for user '.$uid);
1097 set_pconfig($uid, 'statusnet', 'lastid', $lastid);
1100 function statusnet_address($contact) {
1101 $hostname = normalise_link($contact->statusnet_profile_url);
1102 $nickname = $contact->screen_name;
1104 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
1106 $address = $contact->screen_name."@".$hostname;
1111 function statusnet_fetch_contact($uid, $contact, $create_user) {
1112 // Check if the unique contact is existing
1113 // To-Do: only update once a while
1114 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
1115 dbesc(normalise_link($contact->statusnet_profile_url)));
1118 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
1119 dbesc(normalise_link($contact->statusnet_profile_url)),
1120 dbesc($contact->name),
1121 dbesc($contact->screen_name),
1122 dbesc($contact->profile_image_url));
1124 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
1125 dbesc($contact->name),
1126 dbesc($contact->screen_name),
1127 dbesc($contact->profile_image_url),
1128 dbesc(normalise_link($contact->statusnet_profile_url)));
1130 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1131 intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)));
1133 if(!count($r) AND !$create_user)
1136 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
1137 logger("statusnet_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
1142 // create contact record
1143 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1144 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1145 `writable`, `blocked`, `readonly`, `pending` )
1146 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1148 dbesc(datetime_convert()),
1149 dbesc($contact->statusnet_profile_url),
1150 dbesc(normalise_link($contact->statusnet_profile_url)),
1151 dbesc(statusnet_address($contact)),
1152 dbesc(normalise_link($contact->statusnet_profile_url)),
1155 dbesc($contact->name),
1156 dbesc($contact->screen_name),
1157 dbesc($contact->profile_image_url),
1158 dbesc(NETWORK_STATUSNET),
1159 intval(CONTACT_IS_FRIEND),
1164 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1165 dbesc($contact->statusnet_profile_url),
1172 $contact_id = $r[0]['id'];
1174 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1178 if($g && intval($g[0]['def_gid'])) {
1179 require_once('include/group.php');
1180 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1183 require_once("Photo.php");
1185 $photos = import_profile_photo($contact->profile_image_url,$uid,$contact_id);
1187 q("UPDATE `contact` SET `photo` = '%s',
1192 `avatar-date` = '%s'
1197 dbesc(datetime_convert()),
1198 dbesc(datetime_convert()),
1199 dbesc(datetime_convert()),
1204 // update profile photos once every two weeks as we have no notification of when they change.
1206 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1207 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1209 // check that we have all the photos, this has been known to fail on occasion
1211 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1213 logger("statusnet_fetch_contact: Updating contact ".$contact->screen_name, LOGGER_DEBUG);
1215 require_once("Photo.php");
1217 $photos = import_profile_photo($contact->profile_image_url, $uid, $r[0]['id']);
1219 q("UPDATE `contact` SET `photo` = '%s',
1224 `avatar-date` = '%s',
1234 dbesc(datetime_convert()),
1235 dbesc(datetime_convert()),
1236 dbesc(datetime_convert()),
1237 dbesc($contact->statusnet_profile_url),
1238 dbesc(normalise_link($contact->statusnet_profile_url)),
1239 dbesc(statusnet_address($contact)),
1240 dbesc($contact->name),
1241 dbesc($contact->screen_name),
1247 return($r[0]["id"]);
1250 function statusnet_fetchuser($a, $uid, $screen_name = "", $user_id = "") {
1251 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1252 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1253 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1254 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1255 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1257 require_once("addon/statusnet/codebird.php");
1259 $cb = \Codebird\Codebird::getInstance();
1260 $cb->setConsumerKey($ckey, $csecret);
1261 $cb->setToken($otoken, $osecret);
1263 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1271 $parameters = array();
1273 if ($screen_name != "")
1274 $parameters["screen_name"] = $screen_name;
1277 $parameters["user_id"] = $user_id;
1279 // Fetching user data
1280 $user = $cb->users_show($parameters);
1282 if (!is_object($user))
1285 $contact_id = statusnet_fetch_contact($uid, $user, true);
1290 function statusnet_createpost($a, $uid, $post, $self, $create_user, $only_existing_contact) {
1292 require_once("include/html2bbcode.php");
1294 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1295 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1297 $postarray = array();
1298 $postarray['network'] = NETWORK_STATUSNET;
1299 $postarray['gravity'] = 0;
1300 $postarray['uid'] = $uid;
1301 $postarray['wall'] = 0;
1302 $postarray['uri'] = $hostname."::".$post->id;
1304 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1305 dbesc($postarray['uri']),
1314 if ($post->in_reply_to_status_id != "") {
1316 $parent = $hostname."::".$post->in_reply_to_status_id;
1318 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1323 $postarray['thr-parent'] = $r[0]["uri"];
1324 $postarray['parent-uri'] = $r[0]["parent-uri"];
1326 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1331 $postarray['thr-parent'] = $r[0]['uri'];
1332 $postarray['parent-uri'] = $r[0]['parent-uri'];
1334 $postarray['thr-parent'] = $postarray['uri'];
1335 $postarray['parent-uri'] = $postarray['uri'];
1340 $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1342 if ($post->user->id == $own_url) {
1343 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1347 $contactid = $r[0]["id"];
1349 $postarray['owner-name'] = $r[0]["name"];
1350 $postarray['owner-link'] = $r[0]["url"];
1351 $postarray['owner-avatar'] = $r[0]["photo"];
1356 $postarray['parent-uri'] = $postarray['uri'];
1358 if ($contactid == 0) {
1359 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1360 $postarray['owner-name'] = $post->user->name;
1361 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1362 $postarray['owner-avatar'] = $post->user->profile_image_url;
1364 if(($contactid == 0) AND !$only_existing_contact)
1365 $contactid = $self['id'];
1366 elseif ($contactid <= 0)
1369 $postarray['contact-id'] = $contactid;
1371 $postarray['verb'] = ACTIVITY_POST;
1372 $postarray['author-name'] = $postarray['owner-name'];
1373 $postarray['author-link'] = $postarray['owner-link'];
1374 $postarray['author-avatar'] = $postarray['owner-avatar'];
1376 // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1377 $hostname = str_replace("/api/", "/notice/", get_pconfig($uid, 'statusnet', 'baseapi'));
1379 $postarray['plink'] = $hostname.$post->id;
1380 $postarray['app'] = strip_tags($post->source);
1382 if ($post->user->protected) {
1383 $postarray['private'] = 1;
1384 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1387 $postarray['body'] = html2bbcode($post->statusnet_html);
1389 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1390 $postarray['body'] = $converted["body"];
1391 $postarray['tag'] = $converted["tags"];
1393 $postarray['created'] = datetime_convert('UTC','UTC',$post->created_at);
1394 $postarray['edited'] = datetime_convert('UTC','UTC',$post->created_at);
1396 if (is_string($post->place->name))
1397 $postarray["location"] = $post->place->name;
1399 if (is_string($post->place->full_name))
1400 $postarray["location"] = $post->place->full_name;
1402 if (is_array($post->geo->coordinates))
1403 $postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
1405 if (is_array($post->coordinates->coordinates))
1406 $postarray["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
1408 if (is_object($post->retweeted_status)) {
1409 $postarray['body'] = html2bbcode($post->retweeted_status->statusnet_html);
1411 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1412 $postarray['body'] = $converted["body"];
1413 $postarray['tag'] = $converted["tags"];
1415 statusnet_fetch_contact($uid, $post->retweeted_status->user, false);
1417 // Let retweets look like wall-to-wall posts
1418 $postarray['author-name'] = $post->retweeted_status->user->name;
1419 $postarray['author-link'] = $post->retweeted_status->user->statusnet_profile_url;
1420 $postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url;
1425 function statusnet_checknotification($a, $uid, $own_url, $top_item, $postarray) {
1427 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1435 if (link_compare($user[0]["url"], $postarray['author-link']))
1438 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1443 if(!count($own_user))
1446 // Is it me from statusnet?
1447 if (link_compare($own_user[0]["url"], $postarray['author-link']))
1450 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1451 dbesc($postarray['parent-uri']),
1455 if(count($myconv)) {
1457 foreach($myconv as $conv) {
1458 // now if we find a match, it means we're in this conversation
1460 if(!link_compare($conv['author-link'],$user[0]["url"]) AND !link_compare($conv['author-link'],$own_user[0]["url"]))
1463 require_once('include/enotify.php');
1465 $conv_parent = $conv['parent'];
1468 'type' => NOTIFY_COMMENT,
1469 'notify_flags' => $user[0]['notify-flags'],
1470 'language' => $user[0]['language'],
1471 'to_name' => $user[0]['username'],
1472 'to_email' => $user[0]['email'],
1473 'uid' => $user[0]['uid'],
1474 'item' => $postarray,
1475 'link' => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1476 'source_name' => $postarray['author-name'],
1477 'source_link' => $postarray['author-link'],
1478 'source_photo' => $postarray['author-avatar'],
1479 'verb' => ACTIVITY_POST,
1481 'parent' => $conv_parent,
1484 // only send one notification
1490 function statusnet_fetchhometimeline($a, $uid) {
1491 $conversations = array();
1493 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1494 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1495 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1496 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1497 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1498 $create_user = get_pconfig($uid, 'statusnet', 'create_user');
1500 // "create_user" is deactivated, since currently you cannot add users manually by now
1501 $create_user = true;
1503 logger("statusnet_fetchhometimeline: Fetching for user ".$uid, LOGGER_DEBUG);
1505 require_once('library/twitteroauth.php');
1506 require_once('include/items.php');
1508 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1510 $own_contact = statusnet_fetch_own_contact($a, $uid);
1512 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1513 intval($own_contact),
1517 $nick = $r[0]["nick"];
1519 logger("statusnet_fetchhometimeline: Own statusnet contact not found for user ".$uid, LOGGER_DEBUG);
1523 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1529 logger("statusnet_fetchhometimeline: Own contact not found for user ".$uid, LOGGER_DEBUG);
1533 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1536 logger("statusnet_fetchhometimeline: Own user not found for user ".$uid, LOGGER_DEBUG);
1540 $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1541 //$parameters["count"] = 200;
1544 // Fetching timeline
1545 $lastid = get_pconfig($uid, 'statusnet', 'lasthometimelineid');
1548 $first_time = ($lastid == "");
1551 $parameters["since_id"] = $lastid;
1553 $items = $connection->get('statuses/home_timeline', $parameters);
1555 if (!is_array($items)) {
1556 logger("statusnet_fetchhometimeline: Error fetching home timeline: ".print_r($items, true), LOGGER_DEBUG);
1560 $posts = array_reverse($items);
1562 logger("statusnet_fetchhometimeline: Fetching timeline for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1564 if (count($posts)) {
1565 foreach ($posts as $post) {
1567 if ($post->id > $lastid)
1568 $lastid = $post->id;
1573 if (isset($post->statusnet_conversation_id)) {
1574 if (!isset($conversations[$post->statusnet_conversation_id])) {
1575 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1576 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1579 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1581 if (trim($postarray['body']) == "")
1584 $item = item_store($postarray);
1586 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted home timeline item '.$item);
1589 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1594 set_pconfig($uid, 'statusnet', 'lasthometimelineid', $lastid);
1596 // Fetching mentions
1597 $lastid = get_pconfig($uid, 'statusnet', 'lastmentionid');
1598 $first_time = ($lastid == "");
1601 $parameters["since_id"] = $lastid;
1603 $items = $connection->get('statuses/mentions_timeline', $parameters);
1605 if (!is_array($items)) {
1606 logger("statusnet_fetchhometimeline: Error fetching mentions: ".print_r($items, true), LOGGER_DEBUG);
1610 $posts = array_reverse($items);
1612 logger("statusnet_fetchhometimeline: Fetching mentions for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1614 if (count($posts)) {
1615 foreach ($posts as $post) {
1616 if ($post->id > $lastid)
1617 $lastid = $post->id;
1622 $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1624 if (isset($post->statusnet_conversation_id)) {
1625 if (!isset($conversations[$post->statusnet_conversation_id])) {
1626 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1627 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1630 if (trim($postarray['body']) != "") {
1633 $item = item_store($postarray);
1635 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted mention timeline item '.$item);
1639 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1640 dbesc($postarray['uri']),
1644 $item = $r[0]['id'];
1647 require_once('include/enotify.php');
1649 'type' => NOTIFY_TAGSELF,
1650 'notify_flags' => $u[0]['notify-flags'],
1651 'language' => $u[0]['language'],
1652 'to_name' => $u[0]['username'],
1653 'to_email' => $u[0]['email'],
1654 'uid' => $u[0]['uid'],
1655 'item' => $postarray,
1656 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item,
1657 'source_name' => $postarray['author-name'],
1658 'source_link' => $postarray['author-link'],
1659 'source_photo' => $postarray['author-avatar'],
1660 'verb' => ACTIVITY_TAG,
1667 set_pconfig($uid, 'statusnet', 'lastmentionid', $lastid);
1670 function statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $conversation) {
1671 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1672 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1673 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1674 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1675 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1677 require_once('library/twitteroauth.php');
1679 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1681 $parameters["count"] = 200;
1683 $items = $connection->get('statusnet/conversation/'.$conversation, $parameters);
1684 if (is_array($items)) {
1685 $posts = array_reverse($items);
1687 foreach($posts AS $post) {
1688 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1690 if (trim($postarray['body']) == "")
1693 //print_r($postarray);
1694 $item = item_store($postarray);
1696 logger('statusnet_complete_conversation: User '.$self["nick"].' posted home timeline item '.$item);
1699 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1704 function statusnet_convertmsg($a, $body, $no_tags = false) {
1706 require_once("include/oembed.php");
1707 require_once("include/items.php");
1708 require_once("include/network.php");
1710 $URLSearchString = "^\[\]";
1711 $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body,$matches,PREG_SET_ORDER);
1718 foreach ($matches AS $match) {
1719 $search = "[url=".$match[1]."]".$match[2]."[/url]";
1721 $expanded_url = original_url($match[1]);
1723 $oembed_data = oembed_fetch_url($expanded_url);
1726 $type = $oembed_data->type;
1728 if ($oembed_data->type == "video")
1729 $body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1730 elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia)
1731 $body = str_replace($search, "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]", $body);
1732 elseif ($oembed_data->type != "link")
1733 $body = str_replace($search, "[url=".$expanded_url."]".$expanded_url."[/url]", $body);
1735 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1737 $tempfile = tempnam(get_config("system","temppath"), "cache");
1738 file_put_contents($tempfile, $img_str);
1739 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1742 if (substr($mime, 0, 6) == "image/") {
1744 $body = str_replace($search, "[img]".$expanded_url."[/img]", $body);
1746 $type = $oembed_data->type;
1747 $footerurl = $expanded_url;
1748 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1750 $body = str_replace($search, $expanded_url, $body);
1755 if ($footerurl != "")
1756 $footer = add_page_info($footerurl);
1758 if (($footerlink != "") AND (trim($footer) != "")) {
1759 $removedlink = trim(str_replace($footerlink, "", $body));
1761 if (strstr($body, $removedlink))
1762 $body = $removedlink;
1769 return(array("body" => $body, "tags" => ""));
1773 $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$body,$matches,PREG_SET_ORDER);
1775 foreach($matches as $mtch) {
1776 if(strlen($str_tags))
1779 if ($mtch[1] == "#") {
1780 // Replacing the hash tags that are directed to the statusnet server with internal links
1781 $snhash = "#[url=".$mtch[2]."]".$mtch[3]."[/url]";
1782 $frdchash = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($mtch[3]).']'.$mtch[3].'[/url]';
1783 $body = str_replace($snhash, $frdchash, $body);
1785 $str_tags .= $frdchash;
1787 $str_tags .= "@[url=".$mtch[2]."]".$mtch[3]."[/url]";
1789 // There is a problem with links with to statusnet groups, so these links are stored with "@" like friendica groups
1790 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1794 return(array("body"=>$body, "tags"=>$str_tags));
1798 function statusnet_fetch_own_contact($a, $uid) {
1799 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1800 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1801 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1802 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1803 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1804 $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1808 if ($own_url == "") {
1809 require_once('library/twitteroauth.php');
1811 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1813 // Fetching user data
1814 $user = $connection->get('account/verify_credentials');
1816 set_pconfig($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1818 $contact_id = statusnet_fetch_contact($uid, $user, true);
1821 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1822 intval($uid), dbesc($own_url));
1824 $contact_id = $r[0]["id"];
1826 del_pconfig($uid, 'statusnet', 'own_url');
1829 return($contact_id);
1832 function statusnet_is_retweet($a, $uid, $body) {
1833 $body = trim($body);
1835 // Skip if it isn't a pure repeated messages
1836 // Does it start with a share?
1837 if (strpos($body, "[share") > 0)
1840 // Does it end with a share?
1841 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1844 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1845 // Skip if there is no shared message in there
1846 if ($body == $attributes)
1850 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1851 if ($matches[1] != "")
1852 $link = $matches[1];
1854 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1855 if ($matches[1] != "")
1856 $link = $matches[1];
1858 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
1859 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1860 $api = get_pconfig($uid, 'statusnet', 'baseapi');
1861 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
1862 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1863 $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1865 $id = preg_replace("=https?://".$hostname."/notice/(.*)=ism", "$1", $link);
1870 logger('statusnet_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG);
1872 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1874 $result = $connection->post('statuses/retweet/'.$id);
1876 logger('statusnet_is_retweet: result '.print_r($result, true), LOGGER_DEBUG);
1877 return(isset($result->id));