4 * Name: App.net Connector
5 * Description: app.net postings import and export
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
12 - Use embedded pictures for the attachment information (large attachment)
13 - Sound links must be handled
14 - https://alpha.app.net/sr_rolando/post/32365203 - double pictures
15 - https://alpha.app.net/opendev/post/34396399 - location data
18 define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
20 function appnet_install() {
21 register_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
22 register_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
23 register_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
24 register_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
25 register_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
26 register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post');
27 register_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body');
31 function appnet_uninstall() {
32 unregister_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
33 unregister_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
34 unregister_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
35 unregister_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
36 unregister_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
37 unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
38 unregister_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body');
41 function appnet_module() {}
43 function appnet_content(&$a) {
45 notice( t('Permission denied.') . EOL);
49 require_once("mod/settings.php");
52 if (isset($a->argv[1]))
53 switch ($a->argv[1]) {
55 $o = appnet_connect($a);
58 $o = print_r($a->argv, true);
62 $o = appnet_connect($a);
67 function appnet_plugin_admin(&$a, &$o){
68 $t = get_markup_template( "admin.tpl", "addon/appnet/" );
70 $o = replace_macros($t, array(
71 '$submit' => t('Save Settings'),
72 // name, label, value, help, [extra values]
73 '$clientid' => array('clientid', t('Client ID'), get_config('appnet', 'clientid' ), ''),
74 '$clientsecret' => array('clientsecret', t('Client Secret'), get_config('appnet', 'clientsecret' ), ''),
78 function appnet_plugin_admin_post(&$a){
79 $clientid = ((x($_POST,'clientid')) ? notags(trim($_POST['clientid'])) : '');
80 $clientsecret = ((x($_POST,'clientsecret')) ? notags(trim($_POST['clientsecret'])): '');
81 set_config('appnet','clientid',$clientid);
82 set_config('appnet','clientsecret',$clientsecret);
83 info( t('Settings updated.'). EOL );
86 function appnet_connect(&$a) {
87 require_once 'addon/appnet/AppDotNet.php';
89 $clientId = get_config('appnet','clientid');
90 $clientSecret = get_config('appnet','clientsecret');
92 if (($clientId == "") OR ($clientSecret == "")) {
93 $clientId = get_pconfig(local_user(),'appnet','clientid');
94 $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
97 $app = new AppDotNet($clientId, $clientSecret);
100 $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
102 logger("appnet_connect: authenticated");
103 $o .= t("You are now authenticated to app.net. ");
104 set_pconfig(local_user(),'appnet','token', $token);
106 catch (AppDotNetException $e) {
107 $o .= t("<p>Error fetching token. Please try again.</p>");
110 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
115 function appnet_jot_nets(&$a,&$b) {
119 $post = get_pconfig(local_user(),'appnet','post');
120 if(intval($post) == 1) {
121 $defpost = get_pconfig(local_user(),'appnet','post_by_default');
122 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
123 $b .= '<div class="profile-jot-net"><input type="checkbox" name="appnet_enable"' . $selected . ' value="1" /> '
124 . t('Post to app.net') . '</div>';
128 function appnet_settings(&$a,&$s) {
129 require_once 'addon/appnet/AppDotNet.php';
134 $token = get_pconfig(local_user(),'appnet','token');
136 $app_clientId = get_config('appnet','clientid');
137 $app_clientSecret = get_config('appnet','clientsecret');
139 if (($app_clientId == "") OR ($app_clientSecret == "")) {
140 $app_clientId = get_pconfig(local_user(),'appnet','clientid');
141 $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
144 /* Add our stylesheet to the page so we can make our settings look nice */
145 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
147 $enabled = get_pconfig(local_user(),'appnet','post');
148 $checked = (($enabled) ? ' checked="checked" ' : '');
150 $css = (($enabled) ? '' : '-disabled');
152 $def_enabled = get_pconfig(local_user(),'appnet','post_by_default');
153 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
155 $importenabled = get_pconfig(local_user(),'appnet','import');
156 $importchecked = (($importenabled) ? ' checked="checked" ' : '');
158 $ownid = get_pconfig(local_user(),'appnet','ownid');
160 $s .= '<span id="settings_appnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
161 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Import/Export').'</h3>';
163 $s .= '<div id="settings_appnet_expanded" class="settings-block" style="display: none;">';
164 $s .= '<span class="fakelink" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
165 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Import/Export').'</h3>';
169 $app = new AppDotNet($app_clientId, $app_clientSecret);
170 $app->setAccessToken($token);
173 $userdata = $app->getUser();
175 if ($ownid != $userdata["id"])
176 set_pconfig(local_user(),'appnet','ownid', $userdata["id"]);
178 $s .= '<div id="appnet-info" ><img id="appnet-avatar" src="'.$userdata["avatar_image"]["url"].'" /><p id="appnet-info-block">'. t('Currently connected to: ') .'<a href="'.$userdata["canonical_url"].'" target="_appnet">'.$userdata["username"].'</a><br /><em>'.$userdata["description"]["text"].'</em></p></div>';
179 $s .= '<div id="appnet-enable-wrapper">';
180 $s .= '<label id="appnet-enable-label" for="appnet-checkbox">' . t('Enable App.net Post Plugin') . '</label>';
181 $s .= '<input id="appnet-checkbox" type="checkbox" name="appnet" value="1" ' . $checked . '/>';
182 $s .= '</div><div class="clear"></div>';
184 $s .= '<div id="appnet-bydefault-wrapper">';
185 $s .= '<label id="appnet-bydefault-label" for="appnet-bydefault">' . t('Post to App.net by default') . '</label>';
186 $s .= '<input id="appnet-bydefault" type="checkbox" name="appnet_bydefault" value="1" ' . $def_checked . '/>';
187 $s .= '</div><div class="clear"></div>';
189 $s .= '<label id="appnet-import-label" for="appnet-import">'.t('Import the remote timeline').'</label>';
190 $s .= '<input id="appnet-import" type="checkbox" name="appnet_import" value="1" '. $importchecked . '/>';
191 $s .= '<div class="clear"></div>';
194 catch (AppDotNetException $e) {
195 $s .= t("<p>Error fetching user profile. Please clear the configuration and try again.</p>");
198 } elseif (($app_clientId == '') OR ($app_clientSecret == '')) {
199 $s .= t("<p>You have two ways to connect to App.net.</p>");
201 $s .= t('<p>First way: Register an application at <a href="https://account.app.net/developer/apps/">https://account.app.net/developer/apps/</a> and enter Client ID and Client Secret. ');
202 $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
203 $s .= '<div id="appnet-clientid-wrapper">';
204 $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
205 $s .= '<input id="appnet-clientid" type="text" name="clientid" value="" />';
206 $s .= '</div><div class="clear"></div>';
207 $s .= '<div id="appnet-clientsecret-wrapper">';
208 $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
209 $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="" />';
210 $s .= '</div><div class="clear"></div>';
212 $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
213 $s .= t("Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.</p>");
214 $s .= '<div id="appnet-token-wrapper">';
215 $s .= '<label id="appnet-token-label" for="appnet-token">' . t('Token') . '</label>';
216 $s .= '<input id="appnet-token" type="text" name="token" value="'.$token.'" />';
217 $s .= '</div><div class="clear"></div>';
220 $app = new AppDotNet($app_clientId, $app_clientSecret);
222 $scope = array('basic', 'stream', 'write_post',
223 'public_messages', 'messages');
225 $url = $app->getAuthUrl($a->get_baseurl().'/appnet/connect', $scope);
226 $s .= '<div class="clear"></div>';
227 $s .= '<a href="'.$url.'">'.t("Sign in using App.net").'</a>';
230 if (($app_clientId != '') OR ($app_clientSecret != '') OR ($token !='')) {
231 $s .= '<div id="appnet-disconnect-wrapper">';
232 $s .= '<label id="appnet-disconnect-label" for="appnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
234 $s .= '<input id="appnet-disconnect" type="checkbox" name="appnet-disconnect" value="1" />';
235 $s .= '</div><div class="clear"></div>';
238 /* provide a submit button */
239 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="appnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
244 function appnet_settings_post(&$a,&$b) {
246 if(x($_POST,'appnet-submit')) {
248 if (isset($_POST['appnet-disconnect'])) {
249 del_pconfig(local_user(), 'appnet', 'clientsecret');
250 del_pconfig(local_user(), 'appnet', 'clientid');
251 del_pconfig(local_user(), 'appnet', 'token');
252 del_pconfig(local_user(), 'appnet', 'post');
253 del_pconfig(local_user(), 'appnet', 'post_by_default');
254 del_pconfig(local_user(), 'appnet', 'import');
257 if (isset($_POST["clientsecret"]))
258 set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']);
260 if (isset($_POST["clientid"]))
261 set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']);
263 if (isset($_POST["token"]) AND ($_POST["token"] != ""))
264 set_pconfig(local_user(),'appnet','token', $_POST['token']);
266 set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet']));
267 set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault']));
268 set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import']));
272 function appnet_post_local(&$a,&$b) {
276 if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) {
277 $appnet_post = intval(get_pconfig(local_user(),'appnet','post'));
278 $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0);
280 // if API is used, default to the chosen settings
281 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default')))
287 if(strlen($b['postopts']))
288 $b['postopts'] .= ',';
290 $b['postopts'] .= 'appnet';
294 function appnet_create_entities($a, $b, $postdata) {
295 require_once("include/bbcode.php");
296 require_once("include/plaintext.php");
298 $bbcode = $b["body"];
299 $bbcode = bb_remove_share_information($bbcode, false, true);
301 // Change pure links in text to bbcode uris
302 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
304 $URLSearchString = "^\[\]";
306 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
307 $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'@$2',$bbcode);
308 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
309 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
310 $bbcode = preg_replace("/\[youtube\]https?:\/\/(.*?)\[\/youtube\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
311 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
312 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
313 $bbcode = preg_replace("/\[vimeo\]https?:\/\/(.*?)\[\/vimeo\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
314 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
315 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
316 //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
318 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
321 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER);
323 $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1',$bbcode);
325 $b["body"] = $bbcode;
329 // https://alpha.app.net/heluecht/post/32424376
330 // https://alpha.app.net/heluecht/post/32424307
332 $plaintext = plaintext($a, $b, 0, false, 6);
334 $text = $plaintext["text"];
339 foreach ($urls AS $url) {
340 $lenurl = iconv_strlen($url[1], "UTF-8");
341 $len = iconv_strlen($url[2], "UTF-8");
342 $pos = iconv_strpos($text, $url[1], $start, "UTF-8");
343 $pre = iconv_substr($text, 0, $pos, "UTF-8");
344 $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8");
347 $html = bbcode($mid, false, false, 6);
348 $mid = html2plain($html, 0, true);
350 $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8'));
352 $text = $pre.$mid.$post;
355 $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid);
360 if (isset($postdata["url"]) AND isset($postdata["title"])) {
361 $postdata["title"] = shortenmsg($postdata["title"], 90);
362 $max = 256 - strlen($postdata["title"]);
363 $text = shortenmsg($text, $max);
364 $text .= "\n[".$postdata["title"]."](".$postdata["url"].")";
365 } elseif (isset($postdata["url"])) {
366 $postdata["url"] = short_link($postdata["url"]);
368 $text = shortenmsg($text, $max);
369 $text .= " [".$postdata["url"]."](".$postdata["url"].")";
372 $text = shortenmsg($text, $max);
375 if (iconv_strlen($text, "UTF-8") < $max)
376 $max = iconv_strlen($text, "UTF-8");
379 foreach ($entities AS $entity) {
380 //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) {
381 if (($entity["pos"] + $entity["len"]) <= $max) {
382 $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8");
383 $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8");
385 $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post;
393 function appnet_send(&$a,&$b) {
395 logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
397 if (!get_pconfig($b["uid"],'appnet','import')) {
398 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
402 if($b['parent'] != $b['id']) {
403 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
405 // Looking if its a reply to an app.net post
406 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
407 logger("appnet_send: no app.net post ".$b["parent"]);
411 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
412 dbesc($b["thr-parent"]),
416 logger("appnet_send: no parent found ".$b["thr-parent"]);
423 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
424 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
425 $nicknameplain = "@".$nicknameplain;
427 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
428 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
429 $b["body"] = $nickname." ".$b["body"];
431 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
435 if($b['private'] OR !strstr($b['postopts'],'appnet'))
439 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
440 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
442 if($b['verb'] == ACTIVITY_LIKE) {
443 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
444 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
446 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
448 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
452 if($b['deleted'] || ($b['created'] !== $b['edited']))
455 $token = get_pconfig($b['uid'],'appnet','token');
459 // If it's a repeated message from app.net then do a native repost and exit
460 if (appnet_is_repost($a, $b['uid'], $b['body']))
464 require_once 'addon/appnet/AppDotNet.php';
466 $clientId = get_pconfig($b["uid"],'appnet','clientid');
467 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
469 $app = new AppDotNet($clientId, $clientSecret);
470 $app->setAccessToken($token);
474 require_once("include/plaintext.php");
475 require_once("include/network.php");
477 $post = plaintext($a, $b, 256, false, 6);
478 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
480 if (isset($post["image"])) {
481 $img_str = fetch_url($post['image'],true, $redirects, 10);
482 $tempfile = tempnam(get_temppath(), "cache");
483 file_put_contents($tempfile, $img_str);
486 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
488 $data["annotations"][] = array(
489 "type" => "net.app.core.oembed",
491 "+net.app.core.file" => array(
492 "file_id" => $photoFile["id"],
493 "file_token" => $photoFile["file_token"],
494 "format" => "oembed")
498 catch (AppDotNetException $e) {
499 logger("appnet_send: Error creating file ".appnet_error($e->getMessage()));
505 // Adding a link to the original post, if it is a root post
506 if($b['parent'] == $b['id'])
507 $data["annotations"][] = array(
508 "type" => "net.app.core.crosspost",
509 "value" => array("canonical_url" => $b["plink"])
512 // Adding the original post
513 $attached_data = get_attached_data($b["body"]);
514 $attached_data["post-uri"] = $b["uri"];
515 $attached_data["post-title"] = $b["title"];
516 $attached_data["post-body"] = substr($b["body"], 0, 4000); // To-Do: Better shortening
517 $attached_data["post-tag"] = $b["tag"];
518 $attached_data["author-name"] = $b["author-name"];
519 $attached_data["author-link"] = $b["author-link"];
520 $attached_data["author-avatar"] = $b["author-avatar"];
522 $data["annotations"][] = array(
523 "type" => "com.friendica.post",
524 "value" => $attached_data
527 if (isset($post["url"]) AND !isset($post["title"])) {
528 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
529 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
531 if (strlen($display_url) > 26)
532 $display_url = substr($display_url, 0, 25)."…";
534 $post["title"] = $display_url;
537 $text = appnet_create_entities($a, $b, $post);
539 $data["entities"]["parse_markdown_links"] = true;
542 $data["reply_to"] = substr($orig_post["uri"], 5);
545 logger("appnet_send: sending message ".$b["id"]." ".$text." ".print_r($data, true), LOGGER_DEBUG);
546 $ret = $app->createPost($text, $data);
547 logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
549 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
550 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
551 dbesc("adn::".$ret["id"]),
556 catch (AppDotNetException $e) {
557 logger("appnet_send: Error sending message ".$b["id"]." ".appnet_error($e->getMessage()));
562 function appnet_action($a, $uid, $pid, $action) {
563 require_once 'addon/appnet/AppDotNet.php';
565 $token = get_pconfig($uid,'appnet','token');
566 $clientId = get_pconfig($uid,'appnet','clientid');
567 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
569 $app = new AppDotNet($clientId, $clientSecret);
570 $app->setAccessToken($token);
572 logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
577 $result = $app->deletePost($pid);
580 $result = $app->starPost($pid);
583 $result = $app->unstarPost($pid);
586 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
588 catch (AppDotNetException $e) {
589 logger("appnet_action: Error sending action ".$action." pid ".$pid." ".appnet_error($e->getMessage()), LOGGER_DEBUG);
593 function appnet_is_repost($a, $uid, $body) {
596 // Skip if it isn't a pure repeated messages
597 // Does it start with a share?
598 if (strpos($body, "[share") > 0)
601 // Does it end with a share?
602 if (strlen($body) > (strrpos($body, "[/share]") + 8))
605 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
606 // Skip if there is no shared message in there
607 if ($body == $attributes)
611 preg_match("/link='(.*?)'/ism", $attributes, $matches);
612 if ($matches[1] != "")
615 preg_match('/link="(.*?)"/ism', $attributes, $matches);
616 if ($matches[1] != "")
619 $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
623 logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
625 require_once 'addon/appnet/AppDotNet.php';
627 $token = get_pconfig($uid,'appnet','token');
628 $clientId = get_pconfig($uid,'appnet','clientid');
629 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
631 $app = new AppDotNet($clientId, $clientSecret);
632 $app->setAccessToken($token);
635 $result = $app->repost($id);
636 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
639 catch (AppDotNetException $e) {
640 logger('appnet_is_repost: error doing repost '.appnet_error($e->getMessage()), LOGGER_DEBUG);
645 function appnet_fetchstream($a, $uid) {
646 require_once("addon/appnet/AppDotNet.php");
647 require_once('include/items.php');
649 $token = get_pconfig($uid,'appnet','token');
650 $clientId = get_pconfig($uid,'appnet','clientid');
651 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
653 $app = new AppDotNet($clientId, $clientSecret);
654 $app->setAccessToken($token);
656 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
662 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
666 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
673 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
677 $ownid = get_pconfig($uid,'appnet','ownid');
680 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
681 "include_html" => false, "include_post_annotations" => true);
683 $lastid = get_pconfig($uid, 'appnet', 'laststreamid');
686 $param["since_id"] = $lastid;
689 $stream = $app->getUserStream($param);
691 catch (AppDotNetException $e) {
692 logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".appnet_error($e->getMessage()));
695 $stream = array_reverse($stream);
696 foreach ($stream AS $post) {
697 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
699 $item = item_store($postarray);
700 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
702 $lastid = $post["id"];
704 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
705 $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
706 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
707 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
710 require_once('include/enotify.php');
712 'type' => NOTIFY_COMMENT,
713 'notify_flags' => $user['notify-flags'],
714 'language' => $user['language'],
715 'to_name' => $user['username'],
716 'to_email' => $user['email'],
717 'uid' => $user['uid'],
718 'item' => $postarray,
719 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
720 'source_name' => $postarray['author-name'],
721 'source_link' => $postarray['author-link'],
722 'source_photo' => $postarray['author-avatar'],
723 'verb' => ACTIVITY_POST,
725 'parent' => $r[0]["parent"],
731 set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
734 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
735 "include_html" => false, "include_post_annotations" => true);
737 $lastid = get_pconfig($uid, 'appnet', 'lastmentionid');
740 $param["since_id"] = $lastid;
743 $mentions = $app->getUserMentions("me", $param);
745 catch (AppDotNetException $e) {
746 logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".appnet_error($e->getMessage()));
749 $mentions = array_reverse($mentions);
750 foreach ($mentions AS $post) {
751 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
753 if (isset($postarray["id"])) {
754 $item = $postarray["id"];
755 $parent_id = $postarray['parent'];
756 } elseif (isset($postarray["body"])) {
757 $item = item_store($postarray);
759 logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
765 // Fetch the parent and id
766 if (($parent_id == 0) AND ($postarray['uri'] != "")) {
767 $r = q("SELECT `id`, `parent` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
768 dbesc($postarray['uri']),
774 $parent_id = $r[0]['parent'];
778 $lastid = $post["id"];
780 //if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
782 require_once('include/enotify.php');
784 'type' => NOTIFY_TAGSELF,
785 'notify_flags' => $user['notify-flags'],
786 'language' => $user['language'],
787 'to_name' => $user['username'],
788 'to_email' => $user['email'],
789 'uid' => $user['uid'],
790 'item' => $postarray,
791 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
792 'source_name' => $postarray['author-name'],
793 'source_link' => $postarray['author-link'],
794 'source_photo' => $postarray['author-avatar'],
795 'verb' => ACTIVITY_TAG,
797 'parent' => $parent_id,
802 set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
806 $param = array("interaction_actions" => "star");
807 $interactions = $app->getMyInteractions($param);
808 foreach ($interactions AS $interaction)
809 appnet_dolike($a, $uid, $interaction);
813 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true, $nodupcheck = false) {
814 require_once('include/items.php');
816 if ($post["machine_only"])
819 if ($post["is_deleted"])
822 $postarray = array();
823 $postarray['gravity'] = 0;
824 $postarray['uid'] = $uid;
825 $postarray['wall'] = 0;
826 $postarray['verb'] = ACTIVITY_POST;
827 $postarray['network'] = dbesc(NETWORK_APPNET);
828 if (is_array($post["repost_of"])) {
829 // You can't reply to reposts. So use the original id and thread-id
830 $postarray['uri'] = "adn::".$post["repost_of"]["id"];
831 $postarray['parent-uri'] = "adn::".$post["repost_of"]["thread_id"];
833 $postarray['uri'] = "adn::".$post["id"];
834 $postarray['parent-uri'] = "adn::".$post["thread_id"];
838 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
839 dbesc($postarray['uri']),
846 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
847 dbesc($postarray['uri']),
855 if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
856 $postarray['thr-parent'] = "adn::".$post["reply_to"];
858 // Complete the thread (if the parent doesn't exists)
859 if ($threadcompletion) {
860 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
861 // dbesc($postarray['thr-parent']),
865 logger("appnet_createpost: completing thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
867 require_once("addon/appnet/AppDotNet.php");
869 $token = get_pconfig($uid,'appnet','token');
870 $clientId = get_pconfig($uid,'appnet','clientid');
871 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
873 $app = new AppDotNet($clientId, $clientSecret);
874 $app->setAccessToken($token);
876 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
877 "include_html" => false, "include_post_annotations" => true);
879 $thread = $app->getPostReplies($post["thread_id"], $param);
881 catch (AppDotNetException $e) {
882 logger("appnet_createpost: Error fetching thread for user ".$uid." ".appnet_error($e->getMessage()));
884 $thread = array_reverse($thread);
886 logger("appnet_createpost: fetched ".count($thread)." items for thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
888 foreach ($thread AS $tpost) {
889 $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, false, false);
890 $item = item_store($threadpost);
891 logger("appnet_createpost: stored post ".$post["id"]." thread ".$post["thread_id"]." in item ".$item, LOGGER_DEBUG);
895 // Don't create accounts of people who just comment something
898 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
900 $postarray['thr-parent'] = $postarray['uri'];
901 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
904 if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
905 $postarray['owner-name'] = $post["user"]["name"];
906 $postarray['owner-link'] = $post["user"]["canonical_url"];
907 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
908 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
910 $postarray['owner-name'] = $me["name"];
911 $postarray['owner-link'] = $me["url"];
912 $postarray['owner-avatar'] = $me["thumb"];
913 $postarray['contact-id'] = $me["id"];
918 if (is_array($post["repost_of"])) {
919 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
920 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
921 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
923 $content = $post["repost_of"];
925 $postarray['author-name'] = $postarray['owner-name'];
926 $postarray['author-link'] = $postarray['owner-link'];
927 $postarray['author-avatar'] = $postarray['owner-avatar'];
932 $postarray['plink'] = $content["canonical_url"];
934 if (is_array($content["entities"])) {
935 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
936 $postarray['body'] = $converted["body"];
937 $postarray['tag'] = $converted["tags"];
939 $postarray['body'] = $content["text"];
941 if (sizeof($content["entities"]["links"]))
942 foreach($content["entities"]["links"] AS $link) {
943 $url = normalise_link($link["url"]);
944 $links[$url] = $link["url"];
947 /* if (sizeof($content["annotations"]))
948 foreach($content["annotations"] AS $annotation) {
949 if ($annotation[type] == "net.app.core.oembed") {
950 if (isset($annotation["value"]["embeddable_url"])) {
951 $url = normalise_link($annotation["value"]["embeddable_url"]);
952 if (isset($links[$url]))
955 } elseif ($annotation[type] == "com.friendica.post") {
957 //if (isset($annotation["value"]["post-title"]))
958 // $postarray['title'] = $annotation["value"]["post-title"];
960 //if (isset($annotation["value"]["post-body"]))
961 // $postarray['body'] = $annotation["value"]["post-body"];
963 //if (isset($annotation["value"]["post-tag"]))
964 // $postarray['tag'] = $annotation["value"]["post-tag"];
966 if (isset($annotation["value"]["author-name"]))
967 $postarray['author-name'] = $annotation["value"]["author-name"];
969 if (isset($annotation["value"]["author-link"]))
970 $postarray['author-link'] = $annotation["value"]["author-link"];
972 if (isset($annotation["value"]["author-avatar"]))
973 $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
980 if (is_array($content["annotations"])) {
981 $photo = appnet_expand_annotations($a, $content["annotations"]);
982 if (($photo["large"] != "") AND ($photo["url"] != ""))
983 $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]";
984 elseif ($photo["url"] != "")
985 $page_info = "\n[img]".$photo["url"]."[/img]";
987 if ($photo["url"] != "")
988 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
991 $photo = array("url" => "", "large" => "");
993 if (sizeof($links)) {
994 $link = array_pop($links);
995 $url = str_replace(array('/', '.'), array('\/', '\.'), $link);
997 $page_info = add_page_info($link, false, $photo["url"]);
999 if (trim($page_info) != "") {
1000 $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $postarray['body']);
1001 if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
1002 $postarray['body'] = $removedlink;
1006 $postarray['body'] .= $page_info;
1008 $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
1009 $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
1011 $postarray['app'] = $post["source"]["name"];
1016 function appnet_expand_entities($a, $body, $entities) {
1018 if (!function_exists('substr_unicode')) {
1019 function substr_unicode($str, $s, $l = null) {
1020 return join("", array_slice(
1021 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
1025 $tags_arr = array();
1028 foreach ($entities["mentions"] AS $mention) {
1029 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
1030 $tags_arr["@".$mention["name"]] = $url;
1031 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
1034 foreach ($entities["hashtags"] AS $hashtag) {
1035 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
1036 $tags_arr["#".$hashtag["name"]] = $url;
1037 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
1040 foreach ($entities["links"] AS $links) {
1041 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
1042 if (isset($links["amended_len"]) AND ($links["amended_len"] > $links["len"]))
1043 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url);
1045 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
1049 if (sizeof($replace)) {
1051 foreach ($replace AS $entity) {
1052 $pre = substr_unicode($body, 0, $entity["pos"]);
1053 $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
1054 //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8");
1055 //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8");
1057 $body = $pre.$entity["replace"].$post;
1061 return(array("body" => $body, "tags" => implode($tags_arr, ",")));
1064 function appnet_expand_annotations($a, $annotations) {
1065 $photo = array("url" => "", "large" => "");
1066 foreach ($annotations AS $annotation) {
1067 if (($annotation[type] == "net.app.core.oembed") AND
1068 ($annotation["value"]["type"] == "photo")) {
1069 if ($annotation["value"]["url"] != "")
1070 $photo["url"] = $annotation["value"]["url"];
1072 if ($annotation["value"]["thumbnail_large_url"] != "")
1073 $photo["large"] = $annotation["value"]["thumbnail_large_url"];
1075 //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
1076 // $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
1077 //elseif ($annotation["value"]["url"] != "")
1078 // $embedded = "\n[img]".$annotation["value"]["url"]."[/img]";
1084 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
1085 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1086 intval($uid), dbesc("adn::".$contact["id"]));
1088 if(!count($r) AND !$create_user)
1091 if ($contact["canonical_url"] == "")
1094 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
1095 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
1101 if ($contact["name"] == "")
1102 $contact["name"] = $contact["username"];
1104 if ($contact["username"] == "")
1105 $contact["username"] = $contact["name"];
1107 // create contact record
1108 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1109 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1110 `writable`, `blocked`, `readonly`, `pending` )
1111 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1113 dbesc(datetime_convert()),
1114 dbesc($contact["canonical_url"]),
1115 dbesc(normalise_link($contact["canonical_url"])),
1116 dbesc($contact["username"]."@app.net"),
1117 dbesc("adn::".$contact["id"]),
1119 dbesc("adn::".$contact["id"]),
1120 dbesc($contact["name"]),
1121 dbesc($contact["username"]),
1122 dbesc($contact["avatar_image"]["url"]),
1123 dbesc(NETWORK_APPNET),
1124 intval(CONTACT_IS_FRIEND),
1129 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1130 dbesc("adn::".$contact["id"]),
1137 $contact_id = $r[0]['id'];
1139 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1143 if($g && intval($g[0]['def_gid'])) {
1144 require_once('include/group.php');
1145 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1148 require_once("Photo.php");
1150 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
1152 q("UPDATE `contact` SET `photo` = '%s',
1157 `avatar-date` = '%s'
1162 dbesc(datetime_convert()),
1163 dbesc(datetime_convert()),
1164 dbesc(datetime_convert()),
1169 // update profile photos once every two weeks as we have no notification of when they change.
1171 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1172 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1174 // check that we have all the photos, this has been known to fail on occasion
1176 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1178 logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
1180 require_once("Photo.php");
1182 $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
1184 q("UPDATE `contact` SET `photo` = '%s',
1189 `avatar-date` = '%s',
1199 dbesc(datetime_convert()),
1200 dbesc(datetime_convert()),
1201 dbesc(datetime_convert()),
1202 dbesc($contact["canonical_url"]),
1203 dbesc(normalise_link($contact["canonical_url"])),
1204 dbesc($contact["username"]."@app.net"),
1205 dbesc($contact["name"]),
1206 dbesc($contact["username"]),
1212 return($r[0]["id"]);
1215 function appnet_prepare_body(&$a,&$b) {
1216 if ($b["item"]["network"] != NETWORK_APPNET)
1219 if ($b["preview"]) {
1221 require_once("include/plaintext.php");
1223 $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"];
1225 $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
1226 dbesc($item["thr-parent"]),
1227 intval(local_user()));
1232 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
1233 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
1234 $nicknameplain = "@".$nicknameplain;
1236 if ((strpos($item["body"], $nickname) === false) AND (strpos($item["body"], $nicknameplain) === false))
1237 $item["body"] = $nickname." ".$item["body"];
1242 $msgarr = plaintext($a, $item, $max_char, true);
1243 $msg = appnet_create_entities($a, $item, $msgarr);
1245 require_once("library/markdown.php");
1246 $msg = Markdown($msg);
1252 function appnet_cron($a,$b) {
1253 $last = get_config('appnet','last_poll');
1255 $poll_interval = intval(get_config('appnet','poll_interval'));
1256 if(! $poll_interval)
1257 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1260 $next = $last + ($poll_interval * 60);
1261 if($next > time()) {
1262 logger('appnet_cron: poll intervall not reached');
1266 logger('appnet_cron: cron_start');
1268 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1270 foreach($r as $rr) {
1271 logger('appnet_cron: importing timeline from user '.$rr['uid']);
1272 appnet_fetchstream($a, $rr["uid"]);
1276 logger('appnet_cron: cron_end');
1278 set_config('appnet','last_poll', time());
1281 function appnet_error($msg) {
1283 $pos = strrpos($msg, "\r\n\r\n");
1288 $msg = substr($msg, $pos + 4);
1290 $error = json_decode($msg);
1295 if (isset($error->meta->error_message))
1296 return($error->meta->error_message);
1298 return(print_r($error));