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
17 define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
19 function appnet_install() {
20 register_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
21 register_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
22 register_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
23 register_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
24 register_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
25 register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post');
29 function appnet_uninstall() {
30 unregister_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
31 unregister_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
32 unregister_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
33 unregister_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
34 unregister_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
35 unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
38 function appnet_module() {}
40 function appnet_content(&$a) {
42 notice( t('Permission denied.') . EOL);
46 require_once("mod/settings.php");
49 if (isset($a->argv[1]))
50 switch ($a->argv[1]) {
52 $o = appnet_connect($a);
55 $o = print_r($a->argv, true);
59 $o = appnet_connect($a);
64 function appnet_connect(&$a) {
65 require_once 'addon/appnet/AppDotNet.php';
67 $clientId = get_pconfig(local_user(),'appnet','clientid');
68 $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
70 $app = new AppDotNet($clientId, $clientSecret);
73 $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
75 logger("appnet_connect: authenticated");
76 $o .= t("You are now authenticated to app.net. ");
77 set_pconfig(local_user(),'appnet','token', $token);
79 catch (AppDotNetException $e) {
80 $o .= t("<p>Error fetching token. Please try again.</p>");
83 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
88 function appnet_jot_nets(&$a,&$b) {
92 $post = get_pconfig(local_user(),'appnet','post');
93 if(intval($post) == 1) {
94 $defpost = get_pconfig(local_user(),'appnet','post_by_default');
95 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
96 $b .= '<div class="profile-jot-net"><input type="checkbox" name="appnet_enable"' . $selected . ' value="1" /> '
97 . t('Post to app.net') . '</div>';
101 function appnet_settings(&$a,&$s) {
102 require_once 'addon/appnet/AppDotNet.php';
107 $token = get_pconfig(local_user(),'appnet','token');
108 $app_clientId = get_pconfig(local_user(),'appnet','clientid');
109 $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
111 /* Add our stylesheet to the page so we can make our settings look nice */
112 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
114 $enabled = get_pconfig(local_user(),'appnet','post');
115 $checked = (($enabled) ? ' checked="checked" ' : '');
117 $css = (($enabled) ? '' : '-disabled');
119 $def_enabled = get_pconfig(local_user(),'appnet','post_by_default');
120 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
122 $importenabled = get_pconfig(local_user(),'appnet','import');
123 $importchecked = (($importenabled) ? ' checked="checked" ' : '');
125 $ownid = get_pconfig(local_user(),'appnet','ownid');
127 $s .= '<span id="settings_appnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
128 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Export').'</h3>';
130 $s .= '<div id="settings_appnet_expanded" class="settings-block" style="display: none;">';
131 $s .= '<span class="fakelink" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
132 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Export').'</h3>';
136 $app = new AppDotNet($app_clientId, $app_clientSecret);
137 $app->setAccessToken($token);
140 $userdata = $app->getUser();
142 if ($ownid != $userdata["id"])
143 set_pconfig(local_user(),'appnet','ownid', $userdata["id"]);
145 $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>';
146 $s .= '<div id="appnet-enable-wrapper">';
147 $s .= '<label id="appnet-enable-label" for="appnet-checkbox">' . t('Enable App.net Post Plugin') . '</label>';
148 $s .= '<input id="appnet-checkbox" type="checkbox" name="appnet" value="1" ' . $checked . '/>';
149 $s .= '</div><div class="clear"></div>';
151 $s .= '<div id="appnet-bydefault-wrapper">';
152 $s .= '<label id="appnet-bydefault-label" for="appnet-bydefault">' . t('Post to App.net by default') . '</label>';
153 $s .= '<input id="appnet-bydefault" type="checkbox" name="appnet_bydefault" value="1" ' . $def_checked . '/>';
154 $s .= '</div><div class="clear"></div>';
156 $s .= '<label id="appnet-import-label" for="appnet-import">'.t('Import the remote timeline').'</label>';
157 $s .= '<input id="appnet-import" type="checkbox" name="appnet_import" value="1" '. $importchecked . '/>';
158 $s .= '<div class="clear"></div>';
161 catch (AppDotNetException $e) {
162 $s .= t("<p>Error fetching user profile. Please clear the configuration and try again.</p>");
165 } elseif (($app_clientId == '') OR ($app_clientSecret == '')) {
166 $s .= t("<p>You have two ways to connect to App.net.</p>");
168 $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. ');
169 $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
170 $s .= '<div id="appnet-clientid-wrapper">';
171 $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
172 $s .= '<input id="appnet-clientid" type="text" name="clientid" value="'.$app_clientId.'" />';
173 $s .= '</div><div class="clear"></div>';
174 $s .= '<div id="appnet-clientsecret-wrapper">';
175 $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
176 $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="'.$app_clientSecret.'" />';
177 $s .= '</div><div class="clear"></div>';
179 $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
180 $s .= t("Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.</p>");
181 $s .= '<div id="appnet-token-wrapper">';
182 $s .= '<label id="appnet-token-label" for="appnet-token">' . t('Token') . '</label>';
183 $s .= '<input id="appnet-token" type="text" name="token" value="'.$token.'" />';
184 $s .= '</div><div class="clear"></div>';
187 $app = new AppDotNet($app_clientId, $app_clientSecret);
189 $scope = array('basic', 'stream', 'write_post',
190 'public_messages', 'messages');
192 $url = $app->getAuthUrl($a->get_baseurl().'/appnet/connect', $scope);
193 $s .= '<div class="clear"></div>';
194 $s .= '<a href="'.$url.'">'.t("Sign in using App.net").'</a>';
197 if (($app_clientId != '') OR ($app_clientSecret != '') OR ($token !='')) {
198 $s .= '<div id="appnet-disconnect-wrapper">';
199 $s .= '<label id="appnet-disconnect-label" for="appnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
201 $s .= '<input id="appnet-disconnect" type="checkbox" name="appnet-disconnect" value="1" />';
202 $s .= '</div><div class="clear"></div>';
205 /* provide a submit button */
206 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="appnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
211 function appnet_settings_post(&$a,&$b) {
213 if(x($_POST,'appnet-submit')) {
215 if (isset($_POST['appnet-disconnect'])) {
216 del_pconfig(local_user(), 'appnet', 'clientsecret');
217 del_pconfig(local_user(), 'appnet', 'clientid');
218 del_pconfig(local_user(), 'appnet', 'token');
219 del_pconfig(local_user(), 'appnet', 'post');
220 del_pconfig(local_user(), 'appnet', 'post_by_default');
221 del_pconfig(local_user(), 'appnet', 'import');
224 if (isset($_POST["clientsecret"]))
225 set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']);
227 if (isset($_POST["clientid"]))
228 set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']);
230 if (isset($_POST["token"]) AND ($_POST["token"] != ""))
231 set_pconfig(local_user(),'appnet','token', $_POST['token']);
233 set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet']));
234 set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault']));
235 set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import']));
239 function appnet_post_local(&$a,&$b) {
243 if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) {
244 $appnet_post = intval(get_pconfig(local_user(),'appnet','post'));
245 $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0);
247 // if API is used, default to the chosen settings
248 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default')))
254 if(strlen($b['postopts']))
255 $b['postopts'] .= ',';
257 $b['postopts'] .= 'appnet';
261 function appnet_create_entities($a, $b, $postdata) {
262 require_once("include/bbcode.php");
263 require_once("include/plaintext.php");
265 $bbcode = $b["body"];
266 $bbcode = bb_remove_share_information($bbcode, false, true);
268 // Change pure links in text to bbcode uris
269 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
271 $URLSearchString = "^\[\]";
273 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
274 $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'@$2',$bbcode);
275 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
276 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
277 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
278 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
279 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
280 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
281 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
282 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
284 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
287 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER);
289 $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1',$bbcode);
291 $b["body"] = $bbcode;
295 // https://alpha.app.net/heluecht/post/32424376
296 // https://alpha.app.net/heluecht/post/32424307
298 $plaintext = plaintext($a, $b, 0, false, 6);
300 $text = $plaintext["text"];
305 foreach ($urls AS $url) {
306 $lenurl = iconv_strlen($url[1], "UTF-8");
307 $len = iconv_strlen($url[2], "UTF-8");
308 $pos = iconv_strpos($text, $url[1], $start, "UTF-8");
309 $pre = iconv_substr($text, 0, $pos, "UTF-8");
310 $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8");
313 $html = bbcode($mid, false, false, 6);
314 $mid = html2plain($html, 0, true);
315 $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8'));
317 $text = $pre.$mid.$post;
320 $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid);
325 if (isset($postdata["url"]) AND isset($postdata["title"])) {
326 $postdata["title"] = shortenmsg($postdata["title"], 90);
327 $text = shortenmsg($text, 256 - strlen($postdata["title"]));
328 $text .= "\n[".$postdata["title"]."](".$postdata["url"].")";
329 } elseif (isset($postdata["url"])) {
330 $postdata["url"] = short_link($postdata["url"]);
331 $text = shortenmsg($text, 240);
332 $text .= " [".$postdata["url"]."](".$postdata["url"].")";
334 $text = shortenmsg($text, 256);
337 foreach ($entities AS $entity) {
338 if (iconv_strlen($text) >= $entity["pos"] + $entity["len"]) {
339 $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8");
340 $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8");
342 $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post;
349 function appnet_send(&$a,&$b) {
351 logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
353 if (!get_pconfig($b["uid"],'appnet','import')) {
354 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
358 if($b['parent'] != $b['id']) {
359 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
361 // Looking if its a reply to an app.net post
362 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
363 logger("appnet_send: no app.net post ".$b["parent"]);
367 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
368 dbesc($b["thr-parent"]),
372 logger("appnet_send: no parent found ".$b["thr-parent"]);
379 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
380 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
381 $nicknameplain = "@".$nicknameplain;
383 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
384 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
385 $b["body"] = $nickname." ".$b["body"];
387 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
391 if($b['private'] OR !strstr($b['postopts'],'appnet'))
395 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
396 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
398 if($b['verb'] == ACTIVITY_LIKE) {
399 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
400 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
402 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
404 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
408 if($b['deleted'] || ($b['created'] !== $b['edited']))
411 $token = get_pconfig($b['uid'],'appnet','token');
415 // If it's a repeated message from app.net then do a native repost and exit
416 if (appnet_is_repost($a, $b['uid'], $b['body']))
420 require_once 'addon/appnet/AppDotNet.php';
422 $clientId = get_pconfig($b["uid"],'appnet','clientid');
423 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
425 $app = new AppDotNet($clientId, $clientSecret);
426 $app->setAccessToken($token);
430 require_once("include/plaintext.php");
431 require_once("include/network.php");
433 $post = plaintext($a, $b, 256, false, 6);
434 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
436 if (isset($post["image"])) {
437 $img_str = fetch_url($post['image'],true, $redirects, 10);
438 $tempfile = tempnam(get_config("system","temppath"), "cache");
439 file_put_contents($tempfile, $img_str);
442 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
444 $data["annotations"][] = array(
445 "type" => "net.app.core.oembed",
447 "+net.app.core.file" => array(
448 "file_id" => $photoFile["id"],
449 "file_token" => $photoFile["file_token"],
450 "format" => "oembed")
454 catch (AppDotNetException $e) {
455 logger("appnet_send: Error creating file ".$e->getMessage());
461 // Adding a link to the original post, if it is a root post
462 if($b['parent'] == $b['id'])
463 $data["annotations"][] = array(
464 "type" => "net.app.core.crosspost",
465 "value" => array("canonical_url" => $b["plink"])
468 // Adding the original post
469 $attached_data = get_attached_data($b["body"]);
470 $attached_data["post-uri"] = $b["uri"];
471 $attached_data["post-title"] = $b["title"];
472 $attached_data["post-body"] = substr($b["body"], 0, 4000); // To-Do: Better shortening
473 $attached_data["post-tag"] = $b["tag"];
474 $attached_data["author-name"] = $b["author-name"];
475 $attached_data["author-link"] = $b["author-link"];
476 $attached_data["author-avatar"] = $b["author-avatar"];
478 $data["annotations"][] = array(
479 "type" => "com.friendica.post",
480 "value" => $attached_data
483 if (isset($post["url"]) AND !isset($post["title"])) {
484 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
485 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
487 if (strlen($display_url) > 26)
488 $display_url = substr($display_url, 0, 25)."…";
490 $post["title"] = $display_url;
493 $text = appnet_create_entities($a, $b, $post);
495 $data["entities"]["parse_markdown_links"] = true;
498 $data["reply_to"] = substr($orig_post["uri"], 5);
501 logger("appnet_send: sending message ".$b["id"]." ".$text." ".print_r($data, true), LOGGER_DEBUG);
502 $ret = $app->createPost($text, $data);
503 logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
505 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
506 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
507 dbesc("adn::".$ret["id"]),
512 catch (AppDotNetException $e) {
513 logger("appnet_send: Error sending message ".$b["id"]." ".$e->getMessage());
518 function appnet_action($a, $uid, $pid, $action) {
519 require_once 'addon/appnet/AppDotNet.php';
521 $token = get_pconfig($uid,'appnet','token');
522 $clientId = get_pconfig($uid,'appnet','clientid');
523 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
525 $app = new AppDotNet($clientId, $clientSecret);
526 $app->setAccessToken($token);
528 logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
533 $result = $app->deletePost($pid);
536 $result = $app->starPost($pid);
539 $result = $app->unstarPost($pid);
542 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
544 catch (AppDotNetException $e) {
545 logger("appnet_action: Error sending action ".$action." pid ".$pid." ".$e->getMessage(), LOGGER_DEBUG);
549 function appnet_is_repost($a, $uid, $body) {
552 // Skip if it isn't a pure repeated messages
553 // Does it start with a share?
554 if (strpos($body, "[share") > 0)
557 // Does it end with a share?
558 if (strlen($body) > (strrpos($body, "[/share]") + 8))
561 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
562 // Skip if there is no shared message in there
563 if ($body == $attributes)
567 preg_match("/link='(.*?)'/ism", $attributes, $matches);
568 if ($matches[1] != "")
571 preg_match('/link="(.*?)"/ism', $attributes, $matches);
572 if ($matches[1] != "")
575 $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
579 logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
581 require_once 'addon/appnet/AppDotNet.php';
583 $token = get_pconfig($uid,'appnet','token');
584 $clientId = get_pconfig($uid,'appnet','clientid');
585 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
587 $app = new AppDotNet($clientId, $clientSecret);
588 $app->setAccessToken($token);
591 $result = $app->repost($id);
592 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
595 catch (AppDotNetException $e) {
596 logger('appnet_is_repost: error doing repost '.$e->getMessage(), LOGGER_DEBUG);
601 function appnet_fetchstream($a, $uid) {
602 require_once("addon/appnet/AppDotNet.php");
603 require_once('include/items.php');
605 $token = get_pconfig($uid,'appnet','token');
606 $clientId = get_pconfig($uid,'appnet','clientid');
607 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
609 $app = new AppDotNet($clientId, $clientSecret);
610 $app->setAccessToken($token);
612 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
618 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
622 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
629 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
633 $ownid = get_pconfig($uid,'appnet','ownid');
636 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
637 "include_html" => false, "include_post_annotations" => true);
639 $lastid = get_pconfig($uid, 'appnet', 'laststreamid');
642 $param["since_id"] = $lastid;
645 $stream = $app->getUserStream($param);
647 catch (AppDotNetException $e) {
648 logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".$e->getMessage());
651 $stream = array_reverse($stream);
652 foreach ($stream AS $post) {
653 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
655 $item = item_store($postarray);
656 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
658 $lastid = $post["id"];
660 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
661 $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
662 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
663 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
666 require_once('include/enotify.php');
668 'type' => NOTIFY_COMMENT,
669 'notify_flags' => $user['notify-flags'],
670 'language' => $user['language'],
671 'to_name' => $user['username'],
672 'to_email' => $user['email'],
673 'uid' => $user['uid'],
674 'item' => $postarray,
675 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
676 'source_name' => $postarray['author-name'],
677 'source_link' => $postarray['author-link'],
678 'source_photo' => $postarray['author-avatar'],
679 'verb' => ACTIVITY_POST,
681 'parent' => $r[0]["parent"],
687 set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
690 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
691 "include_html" => false, "include_post_annotations" => true);
693 $lastid = get_pconfig($uid, 'appnet', 'lastmentionid');
696 $param["since_id"] = $lastid;
699 $mentions = $app->getUserMentions("me", $param);
701 catch (AppDotNetException $e) {
702 logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".$e->getMessage());
705 $mentions = array_reverse($mentions);
706 foreach ($mentions AS $post) {
707 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
709 if (isset($postarray["id"]))
710 $item = $postarray["id"];
711 elseif (isset($postarray["body"])) {
712 $item = item_store($postarray);
713 logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
717 $lastid = $post["id"];
719 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
720 require_once('include/enotify.php');
722 'type' => NOTIFY_TAGSELF,
723 'notify_flags' => $user['notify-flags'],
724 'language' => $user['language'],
725 'to_name' => $user['username'],
726 'to_email' => $user['email'],
727 'uid' => $user['uid'],
728 'item' => $postarray,
729 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
730 'source_name' => $postarray['author-name'],
731 'source_link' => $postarray['author-link'],
732 'source_photo' => $postarray['author-avatar'],
733 'verb' => ACTIVITY_TAG,
739 set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
743 $param = array("interaction_actions" => "star");
744 $interactions = $app->getMyInteractions($param);
745 foreach ($interactions AS $interaction)
746 appnet_dolike($a, $uid, $interaction);
750 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true) {
751 require_once('include/items.php');
753 if ($post["machine_only"])
756 if ($post["is_deleted"])
759 $postarray = array();
760 $postarray['gravity'] = 0;
761 $postarray['uid'] = $uid;
762 $postarray['wall'] = 0;
763 $postarray['verb'] = ACTIVITY_POST;
764 $postarray['network'] = dbesc(NETWORK_APPNET);
765 $postarray['uri'] = "adn::".$post["id"];
767 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
768 dbesc($postarray['uri']),
775 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
776 dbesc($postarray['uri']),
783 $postarray['parent-uri'] = "adn::".$post["thread_id"];
784 if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
785 $postarray['thr-parent'] = "adn::".$post["reply_to"];
787 // Complete the thread if the parent doesn't exists
788 if ($threadcompletion) {
789 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
790 dbesc($postarray['thr-parent']),
794 require_once("addon/appnet/AppDotNet.php");
796 $token = get_pconfig($uid,'appnet','token');
797 $clientId = get_pconfig($uid,'appnet','clientid');
798 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
800 $app = new AppDotNet($clientId, $clientSecret);
801 $app->setAccessToken($token);
803 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
804 "include_html" => false, "include_post_annotations" => true);
806 $thread = $app->getPostReplies($post["thread_id"], $param);
808 catch (AppDotNetException $e) {
809 logger("appnet_createpost: Error fetching thread for user ".$uid." ".$e->getMessage());
811 $thread = array_reverse($thread);
812 foreach ($thread AS $tpost) {
813 $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, $createuser, false);
814 $item = item_store($threadpost);
819 $postarray['thr-parent'] = $postarray['uri'];
821 $postarray['plink'] = $post["canonical_url"];
823 if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
824 $postarray['owner-name'] = $post["user"]["name"];
825 $postarray['owner-link'] = $post["user"]["canonical_url"];
826 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
827 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
829 $postarray['owner-name'] = $me["name"];
830 $postarray['owner-link'] = $me["url"];
831 $postarray['owner-avatar'] = $me["thumb"];
832 $postarray['contact-id'] = $me["id"];
837 if (is_array($post["repost_of"])) {
838 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
839 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
840 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
842 $content = $post["repost_of"];
844 $postarray['author-name'] = $postarray['owner-name'];
845 $postarray['author-link'] = $postarray['owner-link'];
846 $postarray['author-avatar'] = $postarray['owner-avatar'];
851 if (is_array($content["entities"])) {
852 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
853 $postarray['body'] = $converted["body"];
854 $postarray['tag'] = $converted["tags"];
856 $postarray['body'] = $content["text"];
858 if (sizeof($content["entities"]["links"]))
859 foreach($content["entities"]["links"] AS $link) {
860 $url = normalise_link($link["url"]);
861 $links[$url] = $link["url"];
864 if (sizeof($content["annotations"]))
865 foreach($content["annotations"] AS $annotation) {
866 if ($annotation[type] == "net.app.core.oembed") {
867 if (isset($annotation["value"]["embeddable_url"])) {
868 $url = normalise_link($annotation["value"]["embeddable_url"]);
869 if (isset($links[$url]))
872 } elseif ($annotation[type] == "com.friendica.post") {
873 // Nur zum Testen deaktiviert
875 //if (isset($annotation["value"]["post-title"]))
876 // $postarray['title'] = $annotation["value"]["post-title"];
878 //if (isset($annotation["value"]["post-body"]))
879 // $postarray['body'] = $annotation["value"]["post-body"];
881 //if (isset($annotation["value"]["post-tag"]))
882 // $postarray['tag'] = $annotation["value"]["post-tag"];
884 if (isset($annotation["value"]["author-name"]))
885 $postarray['author-name'] = $annotation["value"]["author-name"];
887 if (isset($annotation["value"]["author-link"]))
888 $postarray['author-link'] = $annotation["value"]["author-link"];
890 if (isset($annotation["value"]["author-avatar"]))
891 $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
898 if (is_array($content["annotations"])) {
899 $photo = appnet_expand_annotations($a, $content["annotations"]);
900 if (($photo["large"] != "") AND ($photo["url"] != ""))
901 $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]";
902 elseif ($photo["url"] != "")
903 $page_info = "\n[img]".$photo["url"]."[/img]";
905 $photo = array("url" => "", "large" => "");
907 if (sizeof($links)) {
908 $link = array_pop($links);
909 $url = "[url=".$link."]".$link."[/url]";
911 $removedlink = trim(str_replace($url, "", $postarray['body']));
913 if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
914 $postarray['body'] = $removedlink;
916 $page_info = add_page_info($link, false, $photo["url"]);
919 $postarray['body'] .= $page_info;
921 $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
922 $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
924 $postarray['app'] = $post["source"]["name"];
929 function appnet_expand_entities($a, $body, $entities) {
931 if (!function_exists('substr_unicode')) {
932 function substr_unicode($str, $s, $l = null) {
933 return join("", array_slice(
934 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
941 foreach ($entities["mentions"] AS $mention) {
942 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
943 $tags_arr["@".$mention["name"]] = $url;
944 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
947 foreach ($entities["hashtags"] AS $hashtag) {
948 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
949 $tags_arr["#".$hashtag["name"]] = $url;
950 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
953 foreach ($entities["links"] AS $links) {
954 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
955 if (isset($links["amended_len"]) AND ($links["amended_len"] > $links["len"]))
956 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url);
958 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
962 if (sizeof($replace)) {
964 foreach ($replace AS $entity) {
965 $pre = substr_unicode($body, 0, $entity["pos"]);
966 $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
967 //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8");
968 //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8");
970 $body = $pre.$entity["replace"].$post;
974 return(array("body" => $body, "tags" => implode($tags_arr, ",")));
977 function appnet_expand_annotations($a, $annotations) {
978 $photo = array("url" => "", "large" => "");
979 foreach ($annotations AS $annotation) {
980 if (($annotation[type] == "net.app.core.oembed") AND
981 ($annotation["value"]["type"] == "photo")) {
982 if ($annotation["value"]["url"] != "")
983 $photo["url"] = $annotation["value"]["url"];
985 if ($annotation["value"]["thumbnail_large_url"] != "")
986 $photo["large"] = $annotation["value"]["thumbnail_large_url"];
988 //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
989 // $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
990 //elseif ($annotation["value"]["url"] != "")
991 // $embedded = "\n[img]".$annotation["value"]["url"]."[/img]";
997 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
998 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
999 intval($uid), dbesc("adn::".$contact["id"]));
1001 if(!count($r) AND !$create_user)
1005 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
1006 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
1011 // create contact record
1012 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1013 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1014 `writable`, `blocked`, `readonly`, `pending` )
1015 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1017 dbesc(datetime_convert()),
1018 dbesc($contact["canonical_url"]),
1019 dbesc(normalise_link($contact["canonical_url"])),
1020 dbesc($contact["username"]."@app.net"),
1021 dbesc("adn::".$contact["id"]),
1023 dbesc("adn::".$contact["id"]),
1024 dbesc($contact["name"]),
1025 dbesc($contact["username"]),
1026 dbesc($contact["avatar_image"]["url"]),
1027 dbesc(NETWORK_APPNET),
1028 intval(CONTACT_IS_FRIEND),
1033 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1034 dbesc("adn::".$contact["id"]),
1041 $contact_id = $r[0]['id'];
1043 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1047 if($g && intval($g[0]['def_gid'])) {
1048 require_once('include/group.php');
1049 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1052 require_once("Photo.php");
1054 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
1056 q("UPDATE `contact` SET `photo` = '%s',
1061 `avatar-date` = '%s'
1066 dbesc(datetime_convert()),
1067 dbesc(datetime_convert()),
1068 dbesc(datetime_convert()),
1073 // update profile photos once every two weeks as we have no notification of when they change.
1075 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1076 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1078 // check that we have all the photos, this has been known to fail on occasion
1080 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1082 logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
1084 require_once("Photo.php");
1086 $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
1088 q("UPDATE `contact` SET `photo` = '%s',
1093 `avatar-date` = '%s',
1103 dbesc(datetime_convert()),
1104 dbesc(datetime_convert()),
1105 dbesc(datetime_convert()),
1106 dbesc($contact["canonical_url"]),
1107 dbesc(normalise_link($contact["canonical_url"])),
1108 dbesc($contact["username"]."@app.net"),
1109 dbesc($contact["name"]),
1110 dbesc($contact["username"]),
1116 return($r[0]["id"]);
1119 function appnet_cron($a,$b) {
1120 $last = get_config('appnet','last_poll');
1122 $poll_interval = intval(get_config('appnet','poll_interval'));
1123 if(! $poll_interval)
1124 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1127 $next = $last + ($poll_interval * 60);
1128 if($next > time()) {
1129 logger('appnet_cron: poll intervall not reached');
1133 logger('appnet_cron: cron_start');
1135 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1137 foreach($r as $rr) {
1138 logger('appnet_cron: importing timeline from user '.$rr['uid']);
1139 appnet_fetchstream($a, $rr["uid"]);
1143 logger('appnet_cron: cron_end');
1145 set_config('appnet','last_poll', time());