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\]https?:\/\/(.*?)\[\/youtube\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
308 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
309 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
310 $bbcode = preg_replace("/\[vimeo\]https?:\/\/(.*?)\[\/vimeo\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
311 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
312 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
313 //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
315 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
318 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER);
320 $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1',$bbcode);
322 $b["body"] = $bbcode;
326 // https://alpha.app.net/heluecht/post/32424376
327 // https://alpha.app.net/heluecht/post/32424307
329 $plaintext = plaintext($a, $b, 0, false, 6);
331 $text = $plaintext["text"];
336 foreach ($urls AS $url) {
337 $lenurl = iconv_strlen($url[1], "UTF-8");
338 $len = iconv_strlen($url[2], "UTF-8");
339 $pos = iconv_strpos($text, $url[1], $start, "UTF-8");
340 $pre = iconv_substr($text, 0, $pos, "UTF-8");
341 $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8");
344 $html = bbcode($mid, false, false, 6);
345 $mid = html2plain($html, 0, true);
347 $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8'));
349 $text = $pre.$mid.$post;
352 $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid);
357 if (isset($postdata["url"]) AND isset($postdata["title"])) {
358 $postdata["title"] = shortenmsg($postdata["title"], 90);
359 $max = 256 - strlen($postdata["title"]);
360 $text = shortenmsg($text, $max);
361 $text .= "\n[".$postdata["title"]."](".$postdata["url"].")";
362 } elseif (isset($postdata["url"])) {
363 $postdata["url"] = short_link($postdata["url"]);
365 $text = shortenmsg($text, $max);
366 $text .= " [".$postdata["url"]."](".$postdata["url"].")";
369 $text = shortenmsg($text, $max);
372 if (iconv_strlen($text, "UTF-8") < $max)
373 $max = iconv_strlen($text, "UTF-8");
376 foreach ($entities AS $entity) {
377 //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) {
378 if (($entity["pos"] + $entity["len"]) <= $max) {
379 $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8");
380 $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8");
382 $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post;
390 function appnet_send(&$a,&$b) {
392 logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
394 if (!get_pconfig($b["uid"],'appnet','import')) {
395 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
399 if($b['parent'] != $b['id']) {
400 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
402 // Looking if its a reply to an app.net post
403 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
404 logger("appnet_send: no app.net post ".$b["parent"]);
408 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
409 dbesc($b["thr-parent"]),
413 logger("appnet_send: no parent found ".$b["thr-parent"]);
420 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
421 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
422 $nicknameplain = "@".$nicknameplain;
424 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
425 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
426 $b["body"] = $nickname." ".$b["body"];
428 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
432 if($b['private'] OR !strstr($b['postopts'],'appnet'))
436 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
437 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
439 if($b['verb'] == ACTIVITY_LIKE) {
440 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
441 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
443 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
445 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
449 if($b['deleted'] || ($b['created'] !== $b['edited']))
452 $token = get_pconfig($b['uid'],'appnet','token');
456 // If it's a repeated message from app.net then do a native repost and exit
457 if (appnet_is_repost($a, $b['uid'], $b['body']))
461 require_once 'addon/appnet/AppDotNet.php';
463 $clientId = get_pconfig($b["uid"],'appnet','clientid');
464 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
466 $app = new AppDotNet($clientId, $clientSecret);
467 $app->setAccessToken($token);
471 require_once("include/plaintext.php");
472 require_once("include/network.php");
474 $post = plaintext($a, $b, 256, false, 6);
475 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
477 if (isset($post["image"])) {
478 $img_str = fetch_url($post['image'],true, $redirects, 10);
479 $tempfile = tempnam(get_temppath(), "cache");
480 file_put_contents($tempfile, $img_str);
483 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
485 $data["annotations"][] = array(
486 "type" => "net.app.core.oembed",
488 "+net.app.core.file" => array(
489 "file_id" => $photoFile["id"],
490 "file_token" => $photoFile["file_token"],
491 "format" => "oembed")
495 catch (AppDotNetException $e) {
496 logger("appnet_send: Error creating file ".appnet_error($e->getMessage()));
502 // Adding a link to the original post, if it is a root post
503 if($b['parent'] == $b['id'])
504 $data["annotations"][] = array(
505 "type" => "net.app.core.crosspost",
506 "value" => array("canonical_url" => $b["plink"])
509 // Adding the original post
510 $attached_data = get_attached_data($b["body"]);
511 $attached_data["post-uri"] = $b["uri"];
512 $attached_data["post-title"] = $b["title"];
513 $attached_data["post-body"] = substr($b["body"], 0, 4000); // To-Do: Better shortening
514 $attached_data["post-tag"] = $b["tag"];
515 $attached_data["author-name"] = $b["author-name"];
516 $attached_data["author-link"] = $b["author-link"];
517 $attached_data["author-avatar"] = $b["author-avatar"];
519 $data["annotations"][] = array(
520 "type" => "com.friendica.post",
521 "value" => $attached_data
524 if (isset($post["url"]) AND !isset($post["title"])) {
525 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
526 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
528 if (strlen($display_url) > 26)
529 $display_url = substr($display_url, 0, 25)."…";
531 $post["title"] = $display_url;
534 $text = appnet_create_entities($a, $b, $post);
536 $data["entities"]["parse_markdown_links"] = true;
539 $data["reply_to"] = substr($orig_post["uri"], 5);
542 logger("appnet_send: sending message ".$b["id"]." ".$text." ".print_r($data, true), LOGGER_DEBUG);
543 $ret = $app->createPost($text, $data);
544 logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
546 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
547 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
548 dbesc("adn::".$ret["id"]),
553 catch (AppDotNetException $e) {
554 logger("appnet_send: Error sending message ".$b["id"]." ".appnet_error($e->getMessage()));
559 function appnet_action($a, $uid, $pid, $action) {
560 require_once 'addon/appnet/AppDotNet.php';
562 $token = get_pconfig($uid,'appnet','token');
563 $clientId = get_pconfig($uid,'appnet','clientid');
564 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
566 $app = new AppDotNet($clientId, $clientSecret);
567 $app->setAccessToken($token);
569 logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
574 $result = $app->deletePost($pid);
577 $result = $app->starPost($pid);
580 $result = $app->unstarPost($pid);
583 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
585 catch (AppDotNetException $e) {
586 logger("appnet_action: Error sending action ".$action." pid ".$pid." ".appnet_error($e->getMessage()), LOGGER_DEBUG);
590 function appnet_is_repost($a, $uid, $body) {
593 // Skip if it isn't a pure repeated messages
594 // Does it start with a share?
595 if (strpos($body, "[share") > 0)
598 // Does it end with a share?
599 if (strlen($body) > (strrpos($body, "[/share]") + 8))
602 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
603 // Skip if there is no shared message in there
604 if ($body == $attributes)
608 preg_match("/link='(.*?)'/ism", $attributes, $matches);
609 if ($matches[1] != "")
612 preg_match('/link="(.*?)"/ism', $attributes, $matches);
613 if ($matches[1] != "")
616 $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
620 logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
622 require_once 'addon/appnet/AppDotNet.php';
624 $token = get_pconfig($uid,'appnet','token');
625 $clientId = get_pconfig($uid,'appnet','clientid');
626 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
628 $app = new AppDotNet($clientId, $clientSecret);
629 $app->setAccessToken($token);
632 $result = $app->repost($id);
633 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
636 catch (AppDotNetException $e) {
637 logger('appnet_is_repost: error doing repost '.appnet_error($e->getMessage()), LOGGER_DEBUG);
642 function appnet_fetchstream($a, $uid) {
643 require_once("addon/appnet/AppDotNet.php");
644 require_once('include/items.php');
646 $token = get_pconfig($uid,'appnet','token');
647 $clientId = get_pconfig($uid,'appnet','clientid');
648 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
650 $app = new AppDotNet($clientId, $clientSecret);
651 $app->setAccessToken($token);
653 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
659 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
663 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
670 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
674 $ownid = get_pconfig($uid,'appnet','ownid');
677 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
678 "include_html" => false, "include_post_annotations" => true);
680 $lastid = get_pconfig($uid, 'appnet', 'laststreamid');
683 $param["since_id"] = $lastid;
686 $stream = $app->getUserStream($param);
688 catch (AppDotNetException $e) {
689 logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".appnet_error($e->getMessage()));
692 $stream = array_reverse($stream);
693 foreach ($stream AS $post) {
694 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
696 $item = item_store($postarray);
697 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
699 $lastid = $post["id"];
701 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
702 $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
703 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
704 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
707 require_once('include/enotify.php');
709 'type' => NOTIFY_COMMENT,
710 'notify_flags' => $user['notify-flags'],
711 'language' => $user['language'],
712 'to_name' => $user['username'],
713 'to_email' => $user['email'],
714 'uid' => $user['uid'],
715 'item' => $postarray,
716 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
717 'source_name' => $postarray['author-name'],
718 'source_link' => $postarray['author-link'],
719 'source_photo' => $postarray['author-avatar'],
720 'verb' => ACTIVITY_POST,
722 'parent' => $r[0]["parent"],
728 set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
731 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
732 "include_html" => false, "include_post_annotations" => true);
734 $lastid = get_pconfig($uid, 'appnet', 'lastmentionid');
737 $param["since_id"] = $lastid;
740 $mentions = $app->getUserMentions("me", $param);
742 catch (AppDotNetException $e) {
743 logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".appnet_error($e->getMessage()));
746 $mentions = array_reverse($mentions);
747 foreach ($mentions AS $post) {
748 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
750 if (isset($postarray["id"]))
751 $item = $postarray["id"];
752 elseif (isset($postarray["body"])) {
753 $item = item_store($postarray);
754 logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
758 $lastid = $post["id"];
760 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
761 require_once('include/enotify.php');
763 'type' => NOTIFY_TAGSELF,
764 'notify_flags' => $user['notify-flags'],
765 'language' => $user['language'],
766 'to_name' => $user['username'],
767 'to_email' => $user['email'],
768 'uid' => $user['uid'],
769 'item' => $postarray,
770 'link' => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
771 'source_name' => $postarray['author-name'],
772 'source_link' => $postarray['author-link'],
773 'source_photo' => $postarray['author-avatar'],
774 'verb' => ACTIVITY_TAG,
780 set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
784 $param = array("interaction_actions" => "star");
785 $interactions = $app->getMyInteractions($param);
786 foreach ($interactions AS $interaction)
787 appnet_dolike($a, $uid, $interaction);
791 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true) {
792 require_once('include/items.php');
794 if ($post["machine_only"])
797 if ($post["is_deleted"])
800 $postarray = array();
801 $postarray['gravity'] = 0;
802 $postarray['uid'] = $uid;
803 $postarray['wall'] = 0;
804 $postarray['verb'] = ACTIVITY_POST;
805 $postarray['network'] = dbesc(NETWORK_APPNET);
806 $postarray['uri'] = "adn::".$post["id"];
808 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
809 dbesc($postarray['uri']),
816 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
817 dbesc($postarray['uri']),
824 $postarray['parent-uri'] = "adn::".$post["thread_id"];
825 if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
826 $postarray['thr-parent'] = "adn::".$post["reply_to"];
828 // Complete the thread (if the parent doesn't exists)
829 if ($threadcompletion) {
830 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
831 // dbesc($postarray['thr-parent']),
835 logger("appnet_createpost: completing thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
837 require_once("addon/appnet/AppDotNet.php");
839 $token = get_pconfig($uid,'appnet','token');
840 $clientId = get_pconfig($uid,'appnet','clientid');
841 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
843 $app = new AppDotNet($clientId, $clientSecret);
844 $app->setAccessToken($token);
846 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
847 "include_html" => false, "include_post_annotations" => true);
849 $thread = $app->getPostReplies($post["thread_id"], $param);
851 catch (AppDotNetException $e) {
852 logger("appnet_createpost: Error fetching thread for user ".$uid." ".appnet_error($e->getMessage()));
854 $thread = array_reverse($thread);
856 logger("appnet_createpost: fetched ".count($thread)." items for thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
858 foreach ($thread AS $tpost) {
859 $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, false, false);
860 $item = item_store($threadpost);
861 logger("appnet_createpost: stored post ".$post["id"]." thread ".$post["thread_id"]." in item ".$item, LOGGER_DEBUG);
865 // Don't create accounts of people who just comment something
868 $postarray['thr-parent'] = $postarray['uri'];
870 $postarray['plink'] = $post["canonical_url"];
872 if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
873 $postarray['owner-name'] = $post["user"]["name"];
874 $postarray['owner-link'] = $post["user"]["canonical_url"];
875 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
876 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
878 $postarray['owner-name'] = $me["name"];
879 $postarray['owner-link'] = $me["url"];
880 $postarray['owner-avatar'] = $me["thumb"];
881 $postarray['contact-id'] = $me["id"];
886 if (is_array($post["repost_of"])) {
887 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
888 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
889 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
891 $content = $post["repost_of"];
893 $postarray['author-name'] = $postarray['owner-name'];
894 $postarray['author-link'] = $postarray['owner-link'];
895 $postarray['author-avatar'] = $postarray['owner-avatar'];
900 if (is_array($content["entities"])) {
901 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
902 $postarray['body'] = $converted["body"];
903 $postarray['tag'] = $converted["tags"];
905 $postarray['body'] = $content["text"];
907 if (sizeof($content["entities"]["links"]))
908 foreach($content["entities"]["links"] AS $link) {
909 $url = normalise_link($link["url"]);
910 $links[$url] = $link["url"];
913 if (sizeof($content["annotations"]))
914 foreach($content["annotations"] AS $annotation) {
915 if ($annotation[type] == "net.app.core.oembed") {
916 if (isset($annotation["value"]["embeddable_url"])) {
917 $url = normalise_link($annotation["value"]["embeddable_url"]);
918 if (isset($links[$url]))
921 } elseif ($annotation[type] == "com.friendica.post") {
922 // Nur zum Testen deaktiviert
924 //if (isset($annotation["value"]["post-title"]))
925 // $postarray['title'] = $annotation["value"]["post-title"];
927 //if (isset($annotation["value"]["post-body"]))
928 // $postarray['body'] = $annotation["value"]["post-body"];
930 //if (isset($annotation["value"]["post-tag"]))
931 // $postarray['tag'] = $annotation["value"]["post-tag"];
933 if (isset($annotation["value"]["author-name"]))
934 $postarray['author-name'] = $annotation["value"]["author-name"];
936 if (isset($annotation["value"]["author-link"]))
937 $postarray['author-link'] = $annotation["value"]["author-link"];
939 if (isset($annotation["value"]["author-avatar"]))
940 $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
947 if (is_array($content["annotations"])) {
948 $photo = appnet_expand_annotations($a, $content["annotations"]);
949 if (($photo["large"] != "") AND ($photo["url"] != ""))
950 $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]";
951 elseif ($photo["url"] != "")
952 $page_info = "\n[img]".$photo["url"]."[/img]";
954 $photo = array("url" => "", "large" => "");
956 if (sizeof($links)) {
957 $link = array_pop($links);
958 $url = "[url=".$link."]".$link."[/url]";
960 $removedlink = trim(str_replace($url, "", $postarray['body']));
962 if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
963 $postarray['body'] = $removedlink;
965 $page_info = add_page_info($link, false, $photo["url"]);
968 $postarray['body'] .= $page_info;
970 $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
971 $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
973 $postarray['app'] = $post["source"]["name"];
978 function appnet_expand_entities($a, $body, $entities) {
980 if (!function_exists('substr_unicode')) {
981 function substr_unicode($str, $s, $l = null) {
982 return join("", array_slice(
983 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
990 foreach ($entities["mentions"] AS $mention) {
991 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
992 $tags_arr["@".$mention["name"]] = $url;
993 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
996 foreach ($entities["hashtags"] AS $hashtag) {
997 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
998 $tags_arr["#".$hashtag["name"]] = $url;
999 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
1002 foreach ($entities["links"] AS $links) {
1003 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
1004 if (isset($links["amended_len"]) AND ($links["amended_len"] > $links["len"]))
1005 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url);
1007 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
1011 if (sizeof($replace)) {
1013 foreach ($replace AS $entity) {
1014 $pre = substr_unicode($body, 0, $entity["pos"]);
1015 $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
1016 //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8");
1017 //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8");
1019 $body = $pre.$entity["replace"].$post;
1023 return(array("body" => $body, "tags" => implode($tags_arr, ",")));
1026 function appnet_expand_annotations($a, $annotations) {
1027 $photo = array("url" => "", "large" => "");
1028 foreach ($annotations AS $annotation) {
1029 if (($annotation[type] == "net.app.core.oembed") AND
1030 ($annotation["value"]["type"] == "photo")) {
1031 if ($annotation["value"]["url"] != "")
1032 $photo["url"] = $annotation["value"]["url"];
1034 if ($annotation["value"]["thumbnail_large_url"] != "")
1035 $photo["large"] = $annotation["value"]["thumbnail_large_url"];
1037 //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
1038 // $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
1039 //elseif ($annotation["value"]["url"] != "")
1040 // $embedded = "\n[img]".$annotation["value"]["url"]."[/img]";
1046 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
1047 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1048 intval($uid), dbesc("adn::".$contact["id"]));
1050 if(!count($r) AND !$create_user)
1053 if ($contact["canonical_url"] == "")
1056 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
1057 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
1063 if ($contact["name"] == "")
1064 $contact["name"] = $contact["username"];
1066 if ($contact["username"] == "")
1067 $contact["username"] = $contact["name"];
1069 // create contact record
1070 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1071 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1072 `writable`, `blocked`, `readonly`, `pending` )
1073 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1075 dbesc(datetime_convert()),
1076 dbesc($contact["canonical_url"]),
1077 dbesc(normalise_link($contact["canonical_url"])),
1078 dbesc($contact["username"]."@app.net"),
1079 dbesc("adn::".$contact["id"]),
1081 dbesc("adn::".$contact["id"]),
1082 dbesc($contact["name"]),
1083 dbesc($contact["username"]),
1084 dbesc($contact["avatar_image"]["url"]),
1085 dbesc(NETWORK_APPNET),
1086 intval(CONTACT_IS_FRIEND),
1091 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1092 dbesc("adn::".$contact["id"]),
1099 $contact_id = $r[0]['id'];
1101 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1105 if($g && intval($g[0]['def_gid'])) {
1106 require_once('include/group.php');
1107 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1110 require_once("Photo.php");
1112 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
1114 q("UPDATE `contact` SET `photo` = '%s',
1119 `avatar-date` = '%s'
1124 dbesc(datetime_convert()),
1125 dbesc(datetime_convert()),
1126 dbesc(datetime_convert()),
1131 // update profile photos once every two weeks as we have no notification of when they change.
1133 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1134 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1136 // check that we have all the photos, this has been known to fail on occasion
1138 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1140 logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
1142 require_once("Photo.php");
1144 $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
1146 q("UPDATE `contact` SET `photo` = '%s',
1151 `avatar-date` = '%s',
1161 dbesc(datetime_convert()),
1162 dbesc(datetime_convert()),
1163 dbesc(datetime_convert()),
1164 dbesc($contact["canonical_url"]),
1165 dbesc(normalise_link($contact["canonical_url"])),
1166 dbesc($contact["username"]."@app.net"),
1167 dbesc($contact["name"]),
1168 dbesc($contact["username"]),
1174 return($r[0]["id"]);
1177 function appnet_cron($a,$b) {
1178 $last = get_config('appnet','last_poll');
1180 $poll_interval = intval(get_config('appnet','poll_interval'));
1181 if(! $poll_interval)
1182 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1185 $next = $last + ($poll_interval * 60);
1186 if($next > time()) {
1187 logger('appnet_cron: poll intervall not reached');
1191 logger('appnet_cron: cron_start');
1193 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1195 foreach($r as $rr) {
1196 logger('appnet_cron: importing timeline from user '.$rr['uid']);
1197 appnet_fetchstream($a, $rr["uid"]);
1201 logger('appnet_cron: cron_end');
1203 set_config('appnet','last_poll', time());
1206 function appnet_error($msg) {
1208 $pos = strrpos($msg, "\r\n\r\n");
1213 $msg = substr($msg, $pos + 4);
1215 $error = json_decode($msg);
1220 if (isset($error->meta->error_message))
1221 return($error->meta->error_message);
1223 return(print_r($error));