4 * Name: App.net Connector
5 * Description: app.net postings import and export
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
11 Some marker in the post so that reimported posts can be treated better. (BBCode over app.net?)
14 define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
16 function appnet_install() {
17 register_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
18 register_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
19 register_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
20 register_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
21 register_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
22 register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post');
26 function appnet_uninstall() {
27 unregister_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
28 unregister_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
29 unregister_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
30 unregister_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
31 unregister_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
32 unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
35 function appnet_module() {}
37 function appnet_content(&$a) {
39 notice( t('Permission denied.') . EOL);
43 require_once("mod/settings.php");
46 if (isset($a->argv[1]))
47 switch ($a->argv[1]) {
49 $o = appnet_connect($a);
52 $o = print_r($a->argv, true);
56 $o = appnet_connect($a);
61 function appnet_connect(&$a) {
62 require_once 'addon/appnet/AppDotNet.php';
64 $clientId = get_pconfig(local_user(),'appnet','clientid');
65 $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
67 $app = new AppDotNet($clientId, $clientSecret);
70 $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
72 logger("appnet_connect: authenticated");
73 $o .= t("You are now authenticated to app.net. ");
74 set_pconfig(local_user(),'appnet','token', $token);
76 catch (AppDotNetException $e) {
77 $o .= t("<p>Error fetching token. Please try again.</p>");
80 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
85 function appnet_jot_nets(&$a,&$b) {
89 $post = get_pconfig(local_user(),'appnet','post');
90 if(intval($post) == 1) {
91 $defpost = get_pconfig(local_user(),'appnet','post_by_default');
92 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
93 $b .= '<div class="profile-jot-net"><input type="checkbox" name="appnet_enable"' . $selected . ' value="1" /> '
94 . t('Post to app.net') . '</div>';
98 function appnet_settings(&$a,&$s) {
99 require_once 'addon/appnet/AppDotNet.php';
104 $token = get_pconfig(local_user(),'appnet','token');
105 $app_clientId = get_pconfig(local_user(),'appnet','clientid');
106 $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
108 /* Add our stylesheet to the page so we can make our settings look nice */
109 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
111 $enabled = get_pconfig(local_user(),'appnet','post');
112 $checked = (($enabled) ? ' checked="checked" ' : '');
114 $css = (($enabled) ? '' : '-disabled');
116 $def_enabled = get_pconfig(local_user(),'appnet','post_by_default');
117 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
119 $importenabled = get_pconfig(local_user(),'appnet','import');
120 $importchecked = (($importenabled) ? ' checked="checked" ' : '');
122 $ownid = get_pconfig(local_user(),'appnet','ownid');
124 $s .= '<span id="settings_appnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
125 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Export').'</h3>';
127 $s .= '<div id="settings_appnet_expanded" class="settings-block" style="display: none;">';
128 $s .= '<span class="fakelink" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
129 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Export').'</h3>';
133 $app = new AppDotNet($app_clientId, $app_clientSecret);
134 $app->setAccessToken($token);
137 $userdata = $app->getUser();
139 if ($ownid != $userdata["id"])
140 set_pconfig(local_user(),'appnet','ownid', $userdata["id"]);
142 $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>';
143 $s .= '<div id="appnet-enable-wrapper">';
144 $s .= '<label id="appnet-enable-label" for="appnet-checkbox">' . t('Enable App.net Post Plugin') . '</label>';
145 $s .= '<input id="appnet-checkbox" type="checkbox" name="appnet" value="1" ' . $checked . '/>';
146 $s .= '</div><div class="clear"></div>';
148 $s .= '<div id="appnet-bydefault-wrapper">';
149 $s .= '<label id="appnet-bydefault-label" for="appnet-bydefault">' . t('Post to App.net by default') . '</label>';
150 $s .= '<input id="appnet-bydefault" type="checkbox" name="appnet_bydefault" value="1" ' . $def_checked . '/>';
151 $s .= '</div><div class="clear"></div>';
153 $s .= '<label id="appnet-import-label" for="appnet-import">'.t('Import the remote timeline').'</label>';
154 $s .= '<input id="appnet-import" type="checkbox" name="appnet_import" value="1" '. $importchecked . '/>';
155 $s .= '<div class="clear"></div>';
158 catch (AppDotNetException $e) {
159 $s .= t("<p>Error fetching user profile. Please clear the configuration and try again.</p>");
161 //$s .= print_r($userdata, true);
163 } elseif (($app_clientId == '') OR ($app_clientSecret == '')) {
164 $s .= t("<p>You have two ways to connect to App.net.</p>");
166 $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. ');
167 $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
168 $s .= '<div id="appnet-clientid-wrapper">';
169 $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
170 $s .= '<input id="appnet-clientid" type="text" name="clientid" value="'.$app_clientId.'" />';
171 $s .= '</div><div class="clear"></div>';
172 $s .= '<div id="appnet-clientsecret-wrapper">';
173 $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
174 $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="'.$app_clientSecret.'" />';
175 $s .= '</div><div class="clear"></div>';
177 $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
178 $s .= t("Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.</p>");
179 $s .= '<div id="appnet-token-wrapper">';
180 $s .= '<label id="appnet-token-label" for="appnet-token">' . t('Token') . '</label>';
181 $s .= '<input id="appnet-token" type="text" name="token" value="'.$token.'" />';
182 $s .= '</div><div class="clear"></div>';
185 $app = new AppDotNet($app_clientId, $app_clientSecret);
187 $scope = array('basic', 'stream', 'write_post',
188 'public_messages', 'messages');
190 $url = $app->getAuthUrl($a->get_baseurl().'/appnet/connect', $scope);
191 $s .= '<div class="clear"></div>';
192 $s .= '<a href="'.$url.'">'.t("Sign in using App.net").'</a>';
195 if (($app_clientId != '') OR ($app_clientSecret != '') OR ($token !='')) {
196 $s .= '<div id="appnet-disconnect-wrapper">';
197 $s .= '<label id="appnet-disconnect-label" for="appnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
199 $s .= '<input id="appnet-disconnect" type="checkbox" name="appnet-disconnect" value="1" />';
200 $s .= '</div><div class="clear"></div>';
203 /* provide a submit button */
204 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="appnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
209 function appnet_settings_post(&$a,&$b) {
211 if(x($_POST,'appnet-submit')) {
213 if (isset($_POST['appnet-disconnect'])) {
214 del_pconfig(local_user(), 'appnet', 'clientsecret');
215 del_pconfig(local_user(), 'appnet', 'clientid');
216 del_pconfig(local_user(), 'appnet', 'token');
217 del_pconfig(local_user(), 'appnet', 'post');
218 del_pconfig(local_user(), 'appnet', 'post_by_default');
219 del_pconfig(local_user(), 'appnet', 'import');
222 if (isset($_POST["clientsecret"]))
223 set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']);
225 if (isset($_POST["clientid"]))
226 set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']);
228 if (isset($_POST["token"]) AND ($_POST["token"] != ""))
229 set_pconfig(local_user(),'appnet','token', $_POST['token']);
231 set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet']));
232 set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault']));
233 set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import']));
237 function appnet_post_local(&$a,&$b) {
241 if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) {
242 $appnet_post = intval(get_pconfig(local_user(),'appnet','post'));
243 $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0);
245 // if API is used, default to the chosen settings
246 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default')))
252 if(strlen($b['postopts']))
253 $b['postopts'] .= ',';
255 $b['postopts'] .= 'appnet';
259 function appnet_send(&$a,&$b) {
261 logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
263 if (!get_pconfig($b["uid"],'appnet','import')) {
264 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
268 if($b['parent'] != $b['id']) {
269 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
271 // Looking if its a reply to an app.net post
272 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
273 logger("appnet_send: no app.net post ".$b["parent"]);
277 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
278 dbesc($b["thr-parent"]),
282 logger("appnet_send: no parent found ".$b["thr-parent"]);
289 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
290 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
291 $nicknameplain = "@".$nicknameplain;
293 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
294 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
295 $b["body"] = $nickname." ".$b["body"];
297 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
301 if($b['private'] OR !strstr($b['postopts'],'appnet'))
305 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
306 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
308 if($b['verb'] == ACTIVITY_LIKE) {
309 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
310 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
312 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
314 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
318 if($b['deleted'] || ($b['created'] !== $b['edited']))
321 $token = get_pconfig($b['uid'],'appnet','token');
325 // If it's a repeated message from app.net then do a native repost and exit
326 if (appnet_is_repost($a, $b['uid'], $b['body']))
330 require_once 'addon/appnet/AppDotNet.php';
332 $clientId = get_pconfig($b["uid"],'appnet','clientid');
333 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
335 $app = new AppDotNet($clientId, $clientSecret);
336 $app->setAccessToken($token);
340 require_once("include/plaintext.php");
341 require_once("include/network.php");
343 $post = plaintext($a, $b, 256, false);
344 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
346 if (isset($post["image"])) {
347 $img_str = fetch_url($post['image'],true, $redirects, 10);
348 $tempfile = tempnam(get_config("system","temppath"), "cache");
349 file_put_contents($tempfile, $img_str);
352 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
354 $data["annotations"][] = array(
355 "type" => "net.app.core.oembed",
357 "+net.app.core.file" => array(
358 "file_id" => $photoFile["id"],
359 "file_token" => $photoFile["file_token"],
360 "format" => "oembed")
364 catch (AppDotNetException $e) {
365 logger("appnet_send: Error creating file");
371 // Adding a link to the original post, if it is a root post
372 if($b['parent'] == $b['id'])
373 $data["annotations"][] = array(
374 "type" => "net.app.core.crosspost",
375 "value" => array("canonical_url" => $b["plink"])
378 // Adding the original post
379 $data["annotations"][] = array(
380 "type" => "com.friendica.post",
383 "title" => $b["title"],
384 "body" => substr($b["body"], 0, 4000), // To-Do: Better shortening
386 "author-name" => $b["author-name"],
387 "author-link" => $b["author-link"],
388 "author-avatar" => $b["author-avatar"],
394 // Alle Links verkürzen
396 if (isset($post["url"]) AND !isset($post["title"])) {
397 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
398 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
400 if (strlen($display_url) > 26)
401 $display_url = substr($display_url, 0, 25)."…";
403 $post["title"] = $display_url;
406 if (isset($post["url"]) AND isset($post["title"])) {
407 $post["title"] = shortenmsg($post["title"], 90);
408 $post["text"] = shortenmsg($post["text"], 256 - strlen($post["title"]));
409 $post["text"] .= "\n[".$post["title"]."](".$post["url"].")";
410 } elseif (isset($post["url"])) {
411 $post["url"] = short_link($post["url"]);
412 $post["text"] = shortenmsg($post["text"], 240);
413 $post["text"] .= " ".$post["url"];
417 $data["entities"]["parse_links"] = true;
418 $data["entities"]["parse_markdown_links"] = true;
421 $data["reply_to"] = substr($orig_post["uri"], 5);
424 $ret = $app->createPost($post["text"], $data);
425 logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
428 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
429 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
430 dbesc("adn::".$ret["id"]),
435 catch (AppDotNetException $e) {
436 logger("appnet_send: Error sending message ".$b["id"]);
441 function appnet_action($a, $uid, $pid, $action) {
442 require_once 'addon/appnet/AppDotNet.php';
444 $token = get_pconfig($uid,'appnet','token');
445 $clientId = get_pconfig($uid,'appnet','clientid');
446 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
448 $app = new AppDotNet($clientId, $clientSecret);
449 $app->setAccessToken($token);
451 logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
456 $result = $app->deletePost($pid);
459 $result = $app->starPost($pid);
462 $result = $app->unstarPost($pid);
465 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
467 catch (AppDotNetException $e) {
468 logger("appnet_action: Error sending action ".$action." pid ".$pid, LOGGER_DEBUG);
472 function appnet_is_repost($a, $uid, $body) {
475 // Skip if it isn't a pure repeated messages
476 // Does it start with a share?
477 if (strpos($body, "[share") > 0)
480 // Does it end with a share?
481 if (strlen($body) > (strrpos($body, "[/share]") + 8))
484 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
485 // Skip if there is no shared message in there
486 if ($body == $attributes)
490 preg_match("/link='(.*?)'/ism", $attributes, $matches);
491 if ($matches[1] != "")
494 preg_match('/link="(.*?)"/ism', $attributes, $matches);
495 if ($matches[1] != "")
498 $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
502 logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
504 require_once 'addon/appnet/AppDotNet.php';
506 $token = get_pconfig($uid,'appnet','token');
507 $clientId = get_pconfig($uid,'appnet','clientid');
508 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
510 $app = new AppDotNet($clientId, $clientSecret);
511 $app->setAccessToken($token);
514 $result = $app->repost($id);
515 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
518 catch (AppDotNetException $e) {
519 logger('appnet_is_repost: error doing repost', LOGGER_DEBUG);
524 function appnet_fetchstream($a, $uid) {
525 require_once("addon/appnet/AppDotNet.php");
526 require_once('include/items.php');
528 $token = get_pconfig($uid,'appnet','token');
529 $clientId = get_pconfig($uid,'appnet','clientid');
530 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
532 $app = new AppDotNet($clientId, $clientSecret);
533 $app->setAccessToken($token);
535 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
541 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
545 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
552 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
556 $ownid = get_pconfig($uid,'appnet','ownid');
559 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
560 "include_html" => false, "include_post_annotations" => true);
562 $lastid = get_pconfig($uid, 'appnet', 'laststreamid');
565 $param["since_id"] = $lastid;
568 $stream = $app->getUserStream($param);
570 catch (AppDotNetException $e) {
571 logger("appnet_fetchstream: Error fetching stream for user ".$uid);
574 $stream = array_reverse($stream);
575 foreach ($stream AS $post) {
576 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
578 $item = item_store($postarray);
579 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
581 $lastid = $post["id"];
583 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
584 $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
585 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
586 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
589 require_once('include/enotify.php');
591 'type' => NOTIFY_COMMENT,
592 'notify_flags' => $user['notify-flags'],
593 'language' => $user['language'],
594 'to_name' => $user['username'],
595 'to_email' => $user['email'],
596 'uid' => $user['uid'],
597 'item' => $postarray,
598 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
599 'source_name' => $postarray['author-name'],
600 'source_link' => $postarray['author-link'],
601 'source_photo' => $postarray['author-avatar'],
602 'verb' => ACTIVITY_POST,
604 'parent' => $r[0]["parent"],
610 set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
613 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
614 "include_html" => false, "include_post_annotations" => true);
616 $lastid = get_pconfig($uid, 'appnet', 'lastmentionid');
619 $param["since_id"] = $lastid;
622 $mentions = $app->getUserMentions("me", $param);
624 catch (AppDotNetException $e) {
625 logger("appnet_fetchstream: Error fetching mentions for user ".$uid);
628 $mentions = array_reverse($mentions);
629 foreach ($mentions AS $post) {
630 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
632 if (isset($postarray["id"]))
633 $item = $postarray["id"];
634 elseif (isset($postarray["body"])) {
635 $item = item_store($postarray);
636 logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
640 $lastid = $post["id"];
642 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
643 require_once('include/enotify.php');
645 'type' => NOTIFY_TAGSELF,
646 'notify_flags' => $user['notify-flags'],
647 'language' => $user['language'],
648 'to_name' => $user['username'],
649 'to_email' => $user['email'],
650 'uid' => $user['uid'],
651 'item' => $postarray,
652 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
653 'source_name' => $postarray['author-name'],
654 'source_link' => $postarray['author-link'],
655 'source_photo' => $postarray['author-avatar'],
656 'verb' => ACTIVITY_TAG,
662 set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
666 $param = array("interaction_actions" => "star");
667 $interactions = $app->getMyInteractions($param);
668 foreach ($interactions AS $interaction)
669 appnet_dolike($a, $uid, $interaction);
673 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true) {
674 require_once('include/items.php');
676 if ($post["machine_only"])
679 if ($post["is_deleted"])
682 $postarray = array();
683 $postarray['gravity'] = 0;
684 $postarray['uid'] = $uid;
685 $postarray['wall'] = 0;
686 $postarray['verb'] = ACTIVITY_POST;
687 $postarray['network'] = dbesc(NETWORK_APPNET);
688 $postarray['uri'] = "adn::".$post["id"];
690 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
691 dbesc($postarray['uri']),
698 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
699 dbesc($postarray['uri']),
706 $postarray['parent-uri'] = "adn::".$post["thread_id"];
707 if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
708 $postarray['thr-parent'] = "adn::".$post["reply_to"];
710 // Complete the thread if the parent doesn't exists
711 if ($threadcompletion) {
712 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
713 dbesc($postarray['thr-parent']),
717 require_once("addon/appnet/AppDotNet.php");
719 $token = get_pconfig($uid,'appnet','token');
720 $clientId = get_pconfig($uid,'appnet','clientid');
721 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
723 $app = new AppDotNet($clientId, $clientSecret);
724 $app->setAccessToken($token);
726 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
727 "include_html" => false, "include_post_annotations" => true);
729 $thread = $app->getPostReplies($post["thread_id"], $param);
731 catch (AppDotNetException $e) {
732 logger("appnet_createpost: Error fetching thread for user ".$uid);
734 $thread = array_reverse($thread);
735 foreach ($thread AS $tpost) {
736 $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, $createuser, false);
737 $item = item_store($threadpost);
742 $postarray['thr-parent'] = $postarray['uri'];
744 $postarray['plink'] = $post["canonical_url"];
746 if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
747 $postarray['owner-name'] = $post["user"]["name"];
748 $postarray['owner-link'] = $post["user"]["canonical_url"];
749 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
750 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
752 $postarray['owner-name'] = $me["name"];
753 $postarray['owner-link'] = $me["url"];
754 $postarray['owner-avatar'] = $me["thumb"];
755 $postarray['contact-id'] = $me["id"];
760 if (is_array($post["repost_of"])) {
761 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
762 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
763 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
765 $content = $post["repost_of"];
767 $postarray['author-name'] = $postarray['owner-name'];
768 $postarray['author-link'] = $postarray['owner-link'];
769 $postarray['author-avatar'] = $postarray['owner-avatar'];
774 if (is_array($content["entities"])) {
775 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
776 $postarray['body'] = $converted["body"];
777 $postarray['tag'] = $converted["tags"];
779 $postarray['body'] = $content["text"];
781 if (is_array($content["annotations"]))
782 $postarray['body'] = appnet_expand_annotations($a, $postarray['body'], $content["annotations"]);
784 if (sizeof($content["entities"]["links"]))
785 foreach($content["entities"]["links"] AS $link) {
786 $url = normalise_link($link["url"]);
787 $links[$url] = $link["url"];
790 if (sizeof($content["annotations"]))
791 foreach($content["annotations"] AS $annotation) {
792 if ($annotation[type] == "net.app.core.oembed") {
793 if (isset($annotation["value"]["embeddable_url"])) {
794 $url = normalise_link($annotation["value"]["embeddable_url"]);
795 if (isset($links[$url]))
798 } elseif ($annotation[type] == "com.friendica.post") {
800 if (isset($annotation["value"]["embeddable_url"]))
801 $postarray['title'] = $annotation["value"]["title"];
803 if (isset($annotation["value"]["body"]))
804 $postarray['body'] = $annotation["value"]["body"];
806 if (isset($annotation["value"]["tag"]))
807 $postarray['tag'] = $annotation["value"]["tag"];
809 if (isset($annotation["value"]["author-name"]))
810 $postarray['author-name'] = $annotation["value"]["author-name"];
812 if (isset($annotation["value"]["author-link"]))
813 $postarray['author-link'] = $annotation["value"]["author-link"];
815 if (isset($annotation["value"]["author-avatar"]))
816 $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
821 if (sizeof($links)) {
822 $link = array_pop($links);
823 $url = "[url=".$link."]".$link."[/url]";
825 $removedlink = trim(str_replace($url, "", $postarray['body']));
827 if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
828 $postarray['body'] = $removedlink;
830 $postarray['body'] .= add_page_info($link);
833 $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
834 $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
836 $postarray['app'] = $post["source"]["name"];
839 //print_r($postarray);
843 function appnet_expand_entities($a, $body, $entities) {
845 if (!function_exists('substr_unicode')) {
846 function substr_unicode($str, $s, $l = null) {
847 return join("", array_slice(
848 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
855 foreach ($entities["mentions"] AS $mention) {
856 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
857 $tags_arr["@".$mention["name"]] = $url;
858 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
861 foreach ($entities["hashtags"] AS $hashtag) {
862 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
863 $tags_arr["#".$hashtag["name"]] = $url;
864 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
867 foreach ($entities["links"] AS $links) {
868 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
869 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
873 if (sizeof($replace)) {
875 foreach ($replace AS $entity) {
876 $pre = substr_unicode($body, 0, $entity["pos"]);
877 $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
879 $body = $pre.$entity["replace"].$post;
883 return(array("body" => $body, "tags" => implode($tags_arr, ",")));
886 function appnet_expand_annotations($a, $body, $annotations) {
887 foreach ($annotations AS $annotation) {
888 if ($annotation["value"]["type"] == "photo") {
889 if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
890 $body .= "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
891 elseif ($annotation["value"]["url"] != "")
892 $body .= "\n[img]".$annotation["value"]["url"]."[/img]";
898 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
899 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
900 intval($uid), dbesc("adn::".$contact["id"]));
902 if(!count($r) AND !$create_user)
906 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
907 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
912 // create contact record
913 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
914 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
915 `writable`, `blocked`, `readonly`, `pending` )
916 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
918 dbesc(datetime_convert()),
919 dbesc($contact["canonical_url"]),
920 dbesc(normalise_link($contact["canonical_url"])),
921 dbesc($contact["username"]."@app.net"),
922 dbesc("adn::".$contact["id"]),
924 dbesc("adn::".$contact["id"]),
925 dbesc($contact["name"]),
926 dbesc($contact["username"]),
927 dbesc($contact["avatar_image"]["url"]),
928 dbesc(NETWORK_APPNET),
929 intval(CONTACT_IS_FRIEND),
934 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
935 dbesc("adn::".$contact["id"]),
942 $contact_id = $r[0]['id'];
944 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
948 if($g && intval($g[0]['def_gid'])) {
949 require_once('include/group.php');
950 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
953 require_once("Photo.php");
955 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
957 q("UPDATE `contact` SET `photo` = '%s',
967 dbesc(datetime_convert()),
968 dbesc(datetime_convert()),
969 dbesc(datetime_convert()),
974 // update profile photos once every two weeks as we have no notification of when they change.
976 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
977 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
978 $update_photo = true;
979 // check that we have all the photos, this has been known to fail on occasion
981 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
983 logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
985 require_once("Photo.php");
987 $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
989 q("UPDATE `contact` SET `photo` = '%s',
994 `avatar-date` = '%s',
1004 dbesc(datetime_convert()),
1005 dbesc(datetime_convert()),
1006 dbesc(datetime_convert()),
1007 dbesc($contact["canonical_url"]),
1008 dbesc(normalise_link($contact["canonical_url"])),
1009 dbesc($contact["username"]."@app.net"),
1010 dbesc($contact["name"]),
1011 dbesc($contact["username"]),
1017 return($r[0]["id"]);
1020 function appnet_cron($a,$b) {
1021 $last = get_config('appnet','last_poll');
1023 $poll_interval = intval(get_config('appnet','poll_interval'));
1024 if(! $poll_interval)
1025 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1028 $next = $last + ($poll_interval * 60);
1029 if($next > time()) {
1030 logger('appnet_cron: poll intervall not reached');
1034 logger('appnet_cron: cron_start');
1036 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1038 foreach($r as $rr) {
1039 logger('appnet_cron: importing timeline from user '.$rr['uid']);
1040 appnet_fetchstream($a, $rr["uid"]);
1044 logger('appnet_cron: cron_end');
1046 set_config('appnet','last_poll', time());