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_plugin_admin(&$a, &$o){
65 $t = get_markup_template( "admin.tpl", "addon/appnet/" );
67 $o = replace_macros($t, array(
68 '$submit' => t('Save Settings'),
69 // name, label, value, help, [extra values]
70 '$clientid' => array('clientid', t('Client ID'), get_config('appnet', 'clientid' ), ''),
71 '$clientsecret' => array('clientsecret', t('Client Secret'), get_config('appnet', 'clientsecret' ), ''),
75 function appnet_plugin_admin_post(&$a){
76 $clientid = ((x($_POST,'clientid')) ? notags(trim($_POST['clientid'])) : '');
77 $clientsecret = ((x($_POST,'clientsecret')) ? notags(trim($_POST['clientsecret'])): '');
78 set_config('appnet','clientid',$clientid);
79 set_config('appnet','clientsecret',$clientsecret);
80 info( t('Settings updated.'). EOL );
83 function appnet_connect(&$a) {
84 require_once 'addon/appnet/AppDotNet.php';
86 $clientId = get_config('appnet','clientid');
87 $clientSecret = get_config('appnet','clientsecret');
89 if (($clientId == "") OR ($clientSecret == "")) {
90 $clientId = get_pconfig(local_user(),'appnet','clientid');
91 $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
94 $app = new AppDotNet($clientId, $clientSecret);
97 $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
99 logger("appnet_connect: authenticated");
100 $o .= t("You are now authenticated to app.net. ");
101 set_pconfig(local_user(),'appnet','token', $token);
103 catch (AppDotNetException $e) {
104 $o .= t("<p>Error fetching token. Please try again.</p>");
107 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
112 function appnet_jot_nets(&$a,&$b) {
116 $post = get_pconfig(local_user(),'appnet','post');
117 if(intval($post) == 1) {
118 $defpost = get_pconfig(local_user(),'appnet','post_by_default');
119 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
120 $b .= '<div class="profile-jot-net"><input type="checkbox" name="appnet_enable"' . $selected . ' value="1" /> '
121 . t('Post to app.net') . '</div>';
125 function appnet_settings(&$a,&$s) {
126 require_once 'addon/appnet/AppDotNet.php';
131 $token = get_pconfig(local_user(),'appnet','token');
133 $app_clientId = get_config('appnet','clientid');
134 $app_clientSecret = get_config('appnet','clientsecret');
136 if (($app_clientId == "") OR ($app_clientSecret == "")) {
137 $app_clientId = get_pconfig(local_user(),'appnet','clientid');
138 $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
141 /* Add our stylesheet to the page so we can make our settings look nice */
142 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
144 $enabled = get_pconfig(local_user(),'appnet','post');
145 $checked = (($enabled) ? ' checked="checked" ' : '');
147 $css = (($enabled) ? '' : '-disabled');
149 $def_enabled = get_pconfig(local_user(),'appnet','post_by_default');
150 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
152 $importenabled = get_pconfig(local_user(),'appnet','import');
153 $importchecked = (($importenabled) ? ' checked="checked" ' : '');
155 $ownid = get_pconfig(local_user(),'appnet','ownid');
157 $s .= '<span id="settings_appnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
158 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Import/Export').'</h3>';
160 $s .= '<div id="settings_appnet_expanded" class="settings-block" style="display: none;">';
161 $s .= '<span class="fakelink" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
162 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Import/Export').'</h3>';
166 $app = new AppDotNet($app_clientId, $app_clientSecret);
167 $app->setAccessToken($token);
170 $userdata = $app->getUser();
172 if ($ownid != $userdata["id"])
173 set_pconfig(local_user(),'appnet','ownid', $userdata["id"]);
175 $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>';
176 $s .= '<div id="appnet-enable-wrapper">';
177 $s .= '<label id="appnet-enable-label" for="appnet-checkbox">' . t('Enable App.net Post Plugin') . '</label>';
178 $s .= '<input id="appnet-checkbox" type="checkbox" name="appnet" value="1" ' . $checked . '/>';
179 $s .= '</div><div class="clear"></div>';
181 $s .= '<div id="appnet-bydefault-wrapper">';
182 $s .= '<label id="appnet-bydefault-label" for="appnet-bydefault">' . t('Post to App.net by default') . '</label>';
183 $s .= '<input id="appnet-bydefault" type="checkbox" name="appnet_bydefault" value="1" ' . $def_checked . '/>';
184 $s .= '</div><div class="clear"></div>';
186 $s .= '<label id="appnet-import-label" for="appnet-import">'.t('Import the remote timeline').'</label>';
187 $s .= '<input id="appnet-import" type="checkbox" name="appnet_import" value="1" '. $importchecked . '/>';
188 $s .= '<div class="clear"></div>';
191 catch (AppDotNetException $e) {
192 $s .= t("<p>Error fetching user profile. Please clear the configuration and try again.</p>");
195 } elseif (($app_clientId == '') OR ($app_clientSecret == '')) {
196 $s .= t("<p>You have two ways to connect to App.net.</p>");
198 $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. ');
199 $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
200 $s .= '<div id="appnet-clientid-wrapper">';
201 $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
202 $s .= '<input id="appnet-clientid" type="text" name="clientid" value="" />';
203 $s .= '</div><div class="clear"></div>';
204 $s .= '<div id="appnet-clientsecret-wrapper">';
205 $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
206 $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="" />';
207 $s .= '</div><div class="clear"></div>';
209 $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
210 $s .= t("Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.</p>");
211 $s .= '<div id="appnet-token-wrapper">';
212 $s .= '<label id="appnet-token-label" for="appnet-token">' . t('Token') . '</label>';
213 $s .= '<input id="appnet-token" type="text" name="token" value="'.$token.'" />';
214 $s .= '</div><div class="clear"></div>';
217 $app = new AppDotNet($app_clientId, $app_clientSecret);
219 $scope = array('basic', 'stream', 'write_post',
220 'public_messages', 'messages');
222 $url = $app->getAuthUrl($a->get_baseurl().'/appnet/connect', $scope);
223 $s .= '<div class="clear"></div>';
224 $s .= '<a href="'.$url.'">'.t("Sign in using App.net").'</a>';
227 if (($app_clientId != '') OR ($app_clientSecret != '') OR ($token !='')) {
228 $s .= '<div id="appnet-disconnect-wrapper">';
229 $s .= '<label id="appnet-disconnect-label" for="appnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
231 $s .= '<input id="appnet-disconnect" type="checkbox" name="appnet-disconnect" value="1" />';
232 $s .= '</div><div class="clear"></div>';
235 /* provide a submit button */
236 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="appnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
241 function appnet_settings_post(&$a,&$b) {
243 if(x($_POST,'appnet-submit')) {
245 if (isset($_POST['appnet-disconnect'])) {
246 del_pconfig(local_user(), 'appnet', 'clientsecret');
247 del_pconfig(local_user(), 'appnet', 'clientid');
248 del_pconfig(local_user(), 'appnet', 'token');
249 del_pconfig(local_user(), 'appnet', 'post');
250 del_pconfig(local_user(), 'appnet', 'post_by_default');
251 del_pconfig(local_user(), 'appnet', 'import');
254 if (isset($_POST["clientsecret"]))
255 set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']);
257 if (isset($_POST["clientid"]))
258 set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']);
260 if (isset($_POST["token"]) AND ($_POST["token"] != ""))
261 set_pconfig(local_user(),'appnet','token', $_POST['token']);
263 set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet']));
264 set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault']));
265 set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import']));
269 function appnet_post_local(&$a,&$b) {
273 if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) {
274 $appnet_post = intval(get_pconfig(local_user(),'appnet','post'));
275 $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0);
277 // if API is used, default to the chosen settings
278 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default')))
284 if(strlen($b['postopts']))
285 $b['postopts'] .= ',';
287 $b['postopts'] .= 'appnet';
291 function appnet_create_entities($a, $b, $postdata) {
292 require_once("include/bbcode.php");
293 require_once("include/plaintext.php");
295 $bbcode = $b["body"];
296 $bbcode = bb_remove_share_information($bbcode, false, true);
298 // Change pure links in text to bbcode uris
299 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
301 $URLSearchString = "^\[\]";
303 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
304 $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'@$2',$bbcode);
305 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
306 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
307 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
308 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
309 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
310 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
311 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
312 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
314 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
317 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER);
319 $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1',$bbcode);
321 $b["body"] = $bbcode;
325 // https://alpha.app.net/heluecht/post/32424376
326 // https://alpha.app.net/heluecht/post/32424307
328 $plaintext = plaintext($a, $b, 0, false, 6);
330 $text = $plaintext["text"];
335 foreach ($urls AS $url) {
336 $lenurl = iconv_strlen($url[1], "UTF-8");
337 $len = iconv_strlen($url[2], "UTF-8");
338 $pos = iconv_strpos($text, $url[1], $start, "UTF-8");
339 $pre = iconv_substr($text, 0, $pos, "UTF-8");
340 $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8");
343 $html = bbcode($mid, false, false, 6);
344 $mid = html2plain($html, 0, true);
345 $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8'));
347 $text = $pre.$mid.$post;
350 $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid);
355 if (isset($postdata["url"]) AND isset($postdata["title"])) {
356 $postdata["title"] = shortenmsg($postdata["title"], 90);
357 $text = shortenmsg($text, 256 - strlen($postdata["title"]));
358 $text .= "\n[".$postdata["title"]."](".$postdata["url"].")";
359 } elseif (isset($postdata["url"])) {
360 $postdata["url"] = short_link($postdata["url"]);
361 $text = shortenmsg($text, 240);
362 $text .= " [".$postdata["url"]."](".$postdata["url"].")";
364 $text = shortenmsg($text, 256);
367 foreach ($entities AS $entity) {
368 if (iconv_strlen($text) >= $entity["pos"] + $entity["len"]) {
369 $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8");
370 $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8");
372 $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post;
379 function appnet_send(&$a,&$b) {
381 logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
383 if (!get_pconfig($b["uid"],'appnet','import')) {
384 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
388 if($b['parent'] != $b['id']) {
389 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
391 // Looking if its a reply to an app.net post
392 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
393 logger("appnet_send: no app.net post ".$b["parent"]);
397 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
398 dbesc($b["thr-parent"]),
402 logger("appnet_send: no parent found ".$b["thr-parent"]);
409 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
410 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
411 $nicknameplain = "@".$nicknameplain;
413 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
414 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
415 $b["body"] = $nickname." ".$b["body"];
417 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
421 if($b['private'] OR !strstr($b['postopts'],'appnet'))
425 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
426 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
428 if($b['verb'] == ACTIVITY_LIKE) {
429 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
430 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
432 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
434 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
438 if($b['deleted'] || ($b['created'] !== $b['edited']))
441 $token = get_pconfig($b['uid'],'appnet','token');
445 // If it's a repeated message from app.net then do a native repost and exit
446 if (appnet_is_repost($a, $b['uid'], $b['body']))
450 require_once 'addon/appnet/AppDotNet.php';
452 $clientId = get_pconfig($b["uid"],'appnet','clientid');
453 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
455 $app = new AppDotNet($clientId, $clientSecret);
456 $app->setAccessToken($token);
460 require_once("include/plaintext.php");
461 require_once("include/network.php");
463 $post = plaintext($a, $b, 256, false, 6);
464 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
466 if (isset($post["image"])) {
467 $img_str = fetch_url($post['image'],true, $redirects, 10);
468 $tempfile = tempnam(get_config("system","temppath"), "cache");
469 file_put_contents($tempfile, $img_str);
472 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
474 $data["annotations"][] = array(
475 "type" => "net.app.core.oembed",
477 "+net.app.core.file" => array(
478 "file_id" => $photoFile["id"],
479 "file_token" => $photoFile["file_token"],
480 "format" => "oembed")
484 catch (AppDotNetException $e) {
485 logger("appnet_send: Error creating file ".$e->getMessage());
491 // Adding a link to the original post, if it is a root post
492 if($b['parent'] == $b['id'])
493 $data["annotations"][] = array(
494 "type" => "net.app.core.crosspost",
495 "value" => array("canonical_url" => $b["plink"])
498 // Adding the original post
499 $attached_data = get_attached_data($b["body"]);
500 $attached_data["post-uri"] = $b["uri"];
501 $attached_data["post-title"] = $b["title"];
502 $attached_data["post-body"] = substr($b["body"], 0, 4000); // To-Do: Better shortening
503 $attached_data["post-tag"] = $b["tag"];
504 $attached_data["author-name"] = $b["author-name"];
505 $attached_data["author-link"] = $b["author-link"];
506 $attached_data["author-avatar"] = $b["author-avatar"];
508 $data["annotations"][] = array(
509 "type" => "com.friendica.post",
510 "value" => $attached_data
513 if (isset($post["url"]) AND !isset($post["title"])) {
514 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
515 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
517 if (strlen($display_url) > 26)
518 $display_url = substr($display_url, 0, 25)."…";
520 $post["title"] = $display_url;
523 $text = appnet_create_entities($a, $b, $post);
525 $data["entities"]["parse_markdown_links"] = true;
528 $data["reply_to"] = substr($orig_post["uri"], 5);
531 logger("appnet_send: sending message ".$b["id"]." ".$text." ".print_r($data, true), LOGGER_DEBUG);
532 $ret = $app->createPost($text, $data);
533 logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
535 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
536 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
537 dbesc("adn::".$ret["id"]),
542 catch (AppDotNetException $e) {
543 logger("appnet_send: Error sending message ".$b["id"]." ".$e->getMessage());
548 function appnet_action($a, $uid, $pid, $action) {
549 require_once 'addon/appnet/AppDotNet.php';
551 $token = get_pconfig($uid,'appnet','token');
552 $clientId = get_pconfig($uid,'appnet','clientid');
553 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
555 $app = new AppDotNet($clientId, $clientSecret);
556 $app->setAccessToken($token);
558 logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
563 $result = $app->deletePost($pid);
566 $result = $app->starPost($pid);
569 $result = $app->unstarPost($pid);
572 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
574 catch (AppDotNetException $e) {
575 logger("appnet_action: Error sending action ".$action." pid ".$pid." ".$e->getMessage(), LOGGER_DEBUG);
579 function appnet_is_repost($a, $uid, $body) {
582 // Skip if it isn't a pure repeated messages
583 // Does it start with a share?
584 if (strpos($body, "[share") > 0)
587 // Does it end with a share?
588 if (strlen($body) > (strrpos($body, "[/share]") + 8))
591 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
592 // Skip if there is no shared message in there
593 if ($body == $attributes)
597 preg_match("/link='(.*?)'/ism", $attributes, $matches);
598 if ($matches[1] != "")
601 preg_match('/link="(.*?)"/ism', $attributes, $matches);
602 if ($matches[1] != "")
605 $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
609 logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
611 require_once 'addon/appnet/AppDotNet.php';
613 $token = get_pconfig($uid,'appnet','token');
614 $clientId = get_pconfig($uid,'appnet','clientid');
615 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
617 $app = new AppDotNet($clientId, $clientSecret);
618 $app->setAccessToken($token);
621 $result = $app->repost($id);
622 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
625 catch (AppDotNetException $e) {
626 logger('appnet_is_repost: error doing repost '.$e->getMessage(), LOGGER_DEBUG);
631 function appnet_fetchstream($a, $uid) {
632 require_once("addon/appnet/AppDotNet.php");
633 require_once('include/items.php');
635 $token = get_pconfig($uid,'appnet','token');
636 $clientId = get_pconfig($uid,'appnet','clientid');
637 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
639 $app = new AppDotNet($clientId, $clientSecret);
640 $app->setAccessToken($token);
642 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
648 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
652 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
659 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
663 $ownid = get_pconfig($uid,'appnet','ownid');
666 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
667 "include_html" => false, "include_post_annotations" => true);
669 $lastid = get_pconfig($uid, 'appnet', 'laststreamid');
672 $param["since_id"] = $lastid;
675 $stream = $app->getUserStream($param);
677 catch (AppDotNetException $e) {
678 logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".$e->getMessage());
681 $stream = array_reverse($stream);
682 foreach ($stream AS $post) {
683 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
685 $item = item_store($postarray);
686 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
688 $lastid = $post["id"];
690 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
691 $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
692 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
693 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
696 require_once('include/enotify.php');
698 'type' => NOTIFY_COMMENT,
699 'notify_flags' => $user['notify-flags'],
700 'language' => $user['language'],
701 'to_name' => $user['username'],
702 'to_email' => $user['email'],
703 'uid' => $user['uid'],
704 'item' => $postarray,
705 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
706 'source_name' => $postarray['author-name'],
707 'source_link' => $postarray['author-link'],
708 'source_photo' => $postarray['author-avatar'],
709 'verb' => ACTIVITY_POST,
711 'parent' => $r[0]["parent"],
717 set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
720 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
721 "include_html" => false, "include_post_annotations" => true);
723 $lastid = get_pconfig($uid, 'appnet', 'lastmentionid');
726 $param["since_id"] = $lastid;
729 $mentions = $app->getUserMentions("me", $param);
731 catch (AppDotNetException $e) {
732 logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".$e->getMessage());
735 $mentions = array_reverse($mentions);
736 foreach ($mentions AS $post) {
737 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
739 if (isset($postarray["id"]))
740 $item = $postarray["id"];
741 elseif (isset($postarray["body"])) {
742 $item = item_store($postarray);
743 logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
747 $lastid = $post["id"];
749 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
750 require_once('include/enotify.php');
752 'type' => NOTIFY_TAGSELF,
753 'notify_flags' => $user['notify-flags'],
754 'language' => $user['language'],
755 'to_name' => $user['username'],
756 'to_email' => $user['email'],
757 'uid' => $user['uid'],
758 'item' => $postarray,
759 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
760 'source_name' => $postarray['author-name'],
761 'source_link' => $postarray['author-link'],
762 'source_photo' => $postarray['author-avatar'],
763 'verb' => ACTIVITY_TAG,
769 set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
773 $param = array("interaction_actions" => "star");
774 $interactions = $app->getMyInteractions($param);
775 foreach ($interactions AS $interaction)
776 appnet_dolike($a, $uid, $interaction);
780 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true) {
781 require_once('include/items.php');
783 if ($post["machine_only"])
786 if ($post["is_deleted"])
789 $postarray = array();
790 $postarray['gravity'] = 0;
791 $postarray['uid'] = $uid;
792 $postarray['wall'] = 0;
793 $postarray['verb'] = ACTIVITY_POST;
794 $postarray['network'] = dbesc(NETWORK_APPNET);
795 $postarray['uri'] = "adn::".$post["id"];
797 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
798 dbesc($postarray['uri']),
805 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
806 dbesc($postarray['uri']),
813 $postarray['parent-uri'] = "adn::".$post["thread_id"];
814 if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
815 $postarray['thr-parent'] = "adn::".$post["reply_to"];
817 // Complete the thread if the parent doesn't exists
818 if ($threadcompletion) {
819 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
820 dbesc($postarray['thr-parent']),
824 require_once("addon/appnet/AppDotNet.php");
826 $token = get_pconfig($uid,'appnet','token');
827 $clientId = get_pconfig($uid,'appnet','clientid');
828 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
830 $app = new AppDotNet($clientId, $clientSecret);
831 $app->setAccessToken($token);
833 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
834 "include_html" => false, "include_post_annotations" => true);
836 $thread = $app->getPostReplies($post["thread_id"], $param);
838 catch (AppDotNetException $e) {
839 logger("appnet_createpost: Error fetching thread for user ".$uid." ".$e->getMessage());
841 $thread = array_reverse($thread);
842 foreach ($thread AS $tpost) {
843 $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, $createuser, false);
844 $item = item_store($threadpost);
849 $postarray['thr-parent'] = $postarray['uri'];
851 $postarray['plink'] = $post["canonical_url"];
853 if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
854 $postarray['owner-name'] = $post["user"]["name"];
855 $postarray['owner-link'] = $post["user"]["canonical_url"];
856 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
857 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
859 $postarray['owner-name'] = $me["name"];
860 $postarray['owner-link'] = $me["url"];
861 $postarray['owner-avatar'] = $me["thumb"];
862 $postarray['contact-id'] = $me["id"];
867 if (is_array($post["repost_of"])) {
868 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
869 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
870 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
872 $content = $post["repost_of"];
874 $postarray['author-name'] = $postarray['owner-name'];
875 $postarray['author-link'] = $postarray['owner-link'];
876 $postarray['author-avatar'] = $postarray['owner-avatar'];
881 if (is_array($content["entities"])) {
882 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
883 $postarray['body'] = $converted["body"];
884 $postarray['tag'] = $converted["tags"];
886 $postarray['body'] = $content["text"];
888 if (sizeof($content["entities"]["links"]))
889 foreach($content["entities"]["links"] AS $link) {
890 $url = normalise_link($link["url"]);
891 $links[$url] = $link["url"];
894 if (sizeof($content["annotations"]))
895 foreach($content["annotations"] AS $annotation) {
896 if ($annotation[type] == "net.app.core.oembed") {
897 if (isset($annotation["value"]["embeddable_url"])) {
898 $url = normalise_link($annotation["value"]["embeddable_url"]);
899 if (isset($links[$url]))
902 } elseif ($annotation[type] == "com.friendica.post") {
903 // Nur zum Testen deaktiviert
905 //if (isset($annotation["value"]["post-title"]))
906 // $postarray['title'] = $annotation["value"]["post-title"];
908 //if (isset($annotation["value"]["post-body"]))
909 // $postarray['body'] = $annotation["value"]["post-body"];
911 //if (isset($annotation["value"]["post-tag"]))
912 // $postarray['tag'] = $annotation["value"]["post-tag"];
914 if (isset($annotation["value"]["author-name"]))
915 $postarray['author-name'] = $annotation["value"]["author-name"];
917 if (isset($annotation["value"]["author-link"]))
918 $postarray['author-link'] = $annotation["value"]["author-link"];
920 if (isset($annotation["value"]["author-avatar"]))
921 $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
928 if (is_array($content["annotations"])) {
929 $photo = appnet_expand_annotations($a, $content["annotations"]);
930 if (($photo["large"] != "") AND ($photo["url"] != ""))
931 $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]";
932 elseif ($photo["url"] != "")
933 $page_info = "\n[img]".$photo["url"]."[/img]";
935 $photo = array("url" => "", "large" => "");
937 if (sizeof($links)) {
938 $link = array_pop($links);
939 $url = "[url=".$link."]".$link."[/url]";
941 $removedlink = trim(str_replace($url, "", $postarray['body']));
943 if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
944 $postarray['body'] = $removedlink;
946 $page_info = add_page_info($link, false, $photo["url"]);
949 $postarray['body'] .= $page_info;
951 $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
952 $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
954 $postarray['app'] = $post["source"]["name"];
959 function appnet_expand_entities($a, $body, $entities) {
961 if (!function_exists('substr_unicode')) {
962 function substr_unicode($str, $s, $l = null) {
963 return join("", array_slice(
964 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
971 foreach ($entities["mentions"] AS $mention) {
972 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
973 $tags_arr["@".$mention["name"]] = $url;
974 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
977 foreach ($entities["hashtags"] AS $hashtag) {
978 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
979 $tags_arr["#".$hashtag["name"]] = $url;
980 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
983 foreach ($entities["links"] AS $links) {
984 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
985 if (isset($links["amended_len"]) AND ($links["amended_len"] > $links["len"]))
986 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url);
988 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
992 if (sizeof($replace)) {
994 foreach ($replace AS $entity) {
995 $pre = substr_unicode($body, 0, $entity["pos"]);
996 $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
997 //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8");
998 //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8");
1000 $body = $pre.$entity["replace"].$post;
1004 return(array("body" => $body, "tags" => implode($tags_arr, ",")));
1007 function appnet_expand_annotations($a, $annotations) {
1008 $photo = array("url" => "", "large" => "");
1009 foreach ($annotations AS $annotation) {
1010 if (($annotation[type] == "net.app.core.oembed") AND
1011 ($annotation["value"]["type"] == "photo")) {
1012 if ($annotation["value"]["url"] != "")
1013 $photo["url"] = $annotation["value"]["url"];
1015 if ($annotation["value"]["thumbnail_large_url"] != "")
1016 $photo["large"] = $annotation["value"]["thumbnail_large_url"];
1018 //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
1019 // $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
1020 //elseif ($annotation["value"]["url"] != "")
1021 // $embedded = "\n[img]".$annotation["value"]["url"]."[/img]";
1027 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
1028 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1029 intval($uid), dbesc("adn::".$contact["id"]));
1031 if(!count($r) AND !$create_user)
1035 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
1036 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
1041 // create contact record
1042 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1043 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1044 `writable`, `blocked`, `readonly`, `pending` )
1045 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1047 dbesc(datetime_convert()),
1048 dbesc($contact["canonical_url"]),
1049 dbesc(normalise_link($contact["canonical_url"])),
1050 dbesc($contact["username"]."@app.net"),
1051 dbesc("adn::".$contact["id"]),
1053 dbesc("adn::".$contact["id"]),
1054 dbesc($contact["name"]),
1055 dbesc($contact["username"]),
1056 dbesc($contact["avatar_image"]["url"]),
1057 dbesc(NETWORK_APPNET),
1058 intval(CONTACT_IS_FRIEND),
1063 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1064 dbesc("adn::".$contact["id"]),
1071 $contact_id = $r[0]['id'];
1073 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1077 if($g && intval($g[0]['def_gid'])) {
1078 require_once('include/group.php');
1079 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1082 require_once("Photo.php");
1084 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
1086 q("UPDATE `contact` SET `photo` = '%s',
1091 `avatar-date` = '%s'
1096 dbesc(datetime_convert()),
1097 dbesc(datetime_convert()),
1098 dbesc(datetime_convert()),
1103 // update profile photos once every two weeks as we have no notification of when they change.
1105 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1106 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1108 // check that we have all the photos, this has been known to fail on occasion
1110 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1112 logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
1114 require_once("Photo.php");
1116 $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
1118 q("UPDATE `contact` SET `photo` = '%s',
1123 `avatar-date` = '%s',
1133 dbesc(datetime_convert()),
1134 dbesc(datetime_convert()),
1135 dbesc(datetime_convert()),
1136 dbesc($contact["canonical_url"]),
1137 dbesc(normalise_link($contact["canonical_url"])),
1138 dbesc($contact["username"]."@app.net"),
1139 dbesc($contact["name"]),
1140 dbesc($contact["username"]),
1146 return($r[0]["id"]);
1149 function appnet_cron($a,$b) {
1150 $last = get_config('appnet','last_poll');
1152 $poll_interval = intval(get_config('appnet','poll_interval'));
1153 if(! $poll_interval)
1154 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1157 $next = $last + ($poll_interval * 60);
1158 if($next > time()) {
1159 logger('appnet_cron: poll intervall not reached');
1163 logger('appnet_cron: cron_start');
1165 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1167 foreach($r as $rr) {
1168 logger('appnet_cron: importing timeline from user '.$rr['uid']);
1169 appnet_fetchstream($a, $rr["uid"]);
1173 logger('appnet_cron: cron_end');
1175 set_config('appnet','last_poll', time());