4 * Name: App.net Connector
5 * Description: Bidirectional (posting and reading) connector for app.net.
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
12 - Use embedded pictures for the attachment information (large attachment)
13 - Sound links must be handled
14 - https://alpha.app.net/sr_rolando/post/32365203 - double pictures
15 - https://alpha.app.net/opendev/post/34396399 - location data
18 require_once('include/enotify.php');
19 require_once("include/socgraph.php");
21 define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
23 function appnet_install() {
24 register_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
25 register_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
26 register_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
27 register_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
28 register_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
29 register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post');
30 register_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body');
31 register_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification');
35 function appnet_uninstall() {
36 unregister_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local');
37 unregister_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send');
38 unregister_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets');
39 unregister_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron');
40 unregister_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings');
41 unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
42 unregister_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body');
43 unregister_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification');
46 function appnet_module() {}
48 function appnet_content(&$a) {
50 notice( t('Permission denied.') . EOL);
54 require_once("mod/settings.php");
57 if (isset($a->argv[1]))
58 switch ($a->argv[1]) {
60 $o = appnet_connect($a);
63 $o = print_r($a->argv, true);
67 $o = appnet_connect($a);
72 function appnet_check_item_notification($a, &$notification_data) {
73 $own_id = get_pconfig($notification_data["uid"], 'appnet', 'ownid');
75 $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
76 intval($notification_data["uid"]),
77 dbesc("adn::".$own_id)
81 $notification_data["profiles"][] = $own_user[0]["url"];
84 function appnet_plugin_admin(&$a, &$o){
85 $t = get_markup_template( "admin.tpl", "addon/appnet/" );
87 $o = replace_macros($t, array(
88 '$submit' => t('Save Settings'),
89 // name, label, value, help, [extra values]
90 '$clientid' => array('clientid', t('Client ID'), get_config('appnet', 'clientid' ), ''),
91 '$clientsecret' => array('clientsecret', t('Client Secret'), get_config('appnet', 'clientsecret' ), ''),
95 function appnet_plugin_admin_post(&$a){
96 $clientid = ((x($_POST,'clientid')) ? notags(trim($_POST['clientid'])) : '');
97 $clientsecret = ((x($_POST,'clientsecret')) ? notags(trim($_POST['clientsecret'])): '');
98 set_config('appnet','clientid',$clientid);
99 set_config('appnet','clientsecret',$clientsecret);
100 info( t('Settings updated.'). EOL );
103 function appnet_connect(&$a) {
104 require_once 'addon/appnet/AppDotNet.php';
106 $clientId = get_config('appnet','clientid');
107 $clientSecret = get_config('appnet','clientsecret');
109 if (($clientId == "") OR ($clientSecret == "")) {
110 $clientId = get_pconfig(local_user(),'appnet','clientid');
111 $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
114 $app = new AppDotNet($clientId, $clientSecret);
117 $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
119 logger("appnet_connect: authenticated");
120 $o .= t("You are now authenticated to app.net. ");
121 set_pconfig(local_user(),'appnet','token', $token);
123 catch (AppDotNetException $e) {
124 $o .= t("<p>Error fetching token. Please try again.</p>");
127 $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
132 function appnet_jot_nets(&$a,&$b) {
136 $post = get_pconfig(local_user(),'appnet','post');
137 if(intval($post) == 1) {
138 $defpost = get_pconfig(local_user(),'appnet','post_by_default');
139 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
140 $b .= '<div class="profile-jot-net"><input type="checkbox" name="appnet_enable"' . $selected . ' value="1" /> '
141 . t('Post to app.net') . '</div>';
145 function appnet_settings(&$a,&$s) {
146 require_once 'addon/appnet/AppDotNet.php';
151 $token = get_pconfig(local_user(),'appnet','token');
153 $app_clientId = get_config('appnet','clientid');
154 $app_clientSecret = get_config('appnet','clientsecret');
156 if (($app_clientId == "") OR ($app_clientSecret == "")) {
157 $app_clientId = get_pconfig(local_user(),'appnet','clientid');
158 $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
161 /* Add our stylesheet to the page so we can make our settings look nice */
162 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
164 $enabled = get_pconfig(local_user(),'appnet','post');
165 $checked = (($enabled) ? ' checked="checked" ' : '');
167 $css = (($enabled) ? '' : '-disabled');
169 $def_enabled = get_pconfig(local_user(),'appnet','post_by_default');
170 $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
172 $importenabled = get_pconfig(local_user(),'appnet','import');
173 $importchecked = (($importenabled) ? ' checked="checked" ' : '');
175 $ownid = get_pconfig(local_user(),'appnet','ownid');
177 $s .= '<span id="settings_appnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
178 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Import/Export').'</h3>';
180 $s .= '<div id="settings_appnet_expanded" class="settings-block" style="display: none;">';
181 $s .= '<span class="fakelink" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
182 $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Import/Export').'</h3>';
186 $app = new AppDotNet($app_clientId, $app_clientSecret);
187 $app->setAccessToken($token);
190 $userdata = $app->getUser();
192 if ($ownid != $userdata["id"])
193 set_pconfig(local_user(),'appnet','ownid', $userdata["id"]);
195 $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>';
196 $s .= '<div id="appnet-enable-wrapper">';
197 $s .= '<label id="appnet-enable-label" for="appnet-checkbox">' . t('Enable App.net Post Plugin') . '</label>';
198 $s .= '<input id="appnet-checkbox" type="checkbox" name="appnet" value="1" ' . $checked . '/>';
199 $s .= '</div><div class="clear"></div>';
201 $s .= '<div id="appnet-bydefault-wrapper">';
202 $s .= '<label id="appnet-bydefault-label" for="appnet-bydefault">' . t('Post to App.net by default') . '</label>';
203 $s .= '<input id="appnet-bydefault" type="checkbox" name="appnet_bydefault" value="1" ' . $def_checked . '/>';
204 $s .= '</div><div class="clear"></div>';
206 $s .= '<label id="appnet-import-label" for="appnet-import">'.t('Import the remote timeline').'</label>';
207 $s .= '<input id="appnet-import" type="checkbox" name="appnet_import" value="1" '. $importchecked . '/>';
208 $s .= '<div class="clear"></div>';
211 catch (AppDotNetException $e) {
212 $s .= t("<p>Error fetching user profile. Please clear the configuration and try again.</p>");
215 } elseif (($app_clientId == '') OR ($app_clientSecret == '')) {
216 $s .= t("<p>You have two ways to connect to App.net.</p>");
218 $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. ');
219 $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
220 $s .= '<div id="appnet-clientid-wrapper">';
221 $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
222 $s .= '<input id="appnet-clientid" type="text" name="clientid" value="" />';
223 $s .= '</div><div class="clear"></div>';
224 $s .= '<div id="appnet-clientsecret-wrapper">';
225 $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
226 $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="" />';
227 $s .= '</div><div class="clear"></div>';
229 $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
230 $s .= t("Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.</p>");
231 $s .= '<div id="appnet-token-wrapper">';
232 $s .= '<label id="appnet-token-label" for="appnet-token">' . t('Token') . '</label>';
233 $s .= '<input id="appnet-token" type="text" name="token" value="'.$token.'" />';
234 $s .= '</div><div class="clear"></div>';
237 $app = new AppDotNet($app_clientId, $app_clientSecret);
239 $scope = array('basic', 'stream', 'write_post',
240 'public_messages', 'messages');
242 $url = $app->getAuthUrl($a->get_baseurl().'/appnet/connect', $scope);
243 $s .= '<div class="clear"></div>';
244 $s .= '<a href="'.$url.'">'.t("Sign in using App.net").'</a>';
247 if (($app_clientId != '') OR ($app_clientSecret != '') OR ($token !='')) {
248 $s .= '<div id="appnet-disconnect-wrapper">';
249 $s .= '<label id="appnet-disconnect-label" for="appnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
251 $s .= '<input id="appnet-disconnect" type="checkbox" name="appnet-disconnect" value="1" />';
252 $s .= '</div><div class="clear"></div>';
255 /* provide a submit button */
256 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="appnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
261 function appnet_settings_post(&$a,&$b) {
263 if(x($_POST,'appnet-submit')) {
265 if (isset($_POST['appnet-disconnect'])) {
266 del_pconfig(local_user(), 'appnet', 'clientsecret');
267 del_pconfig(local_user(), 'appnet', 'clientid');
268 del_pconfig(local_user(), 'appnet', 'token');
269 del_pconfig(local_user(), 'appnet', 'post');
270 del_pconfig(local_user(), 'appnet', 'post_by_default');
271 del_pconfig(local_user(), 'appnet', 'import');
274 if (isset($_POST["clientsecret"]))
275 set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']);
277 if (isset($_POST["clientid"]))
278 set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']);
280 if (isset($_POST["token"]) AND ($_POST["token"] != ""))
281 set_pconfig(local_user(),'appnet','token', $_POST['token']);
283 set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet']));
284 set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault']));
285 set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import']));
289 function appnet_post_local(&$a,&$b) {
293 if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) {
294 $appnet_post = intval(get_pconfig(local_user(),'appnet','post'));
295 $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0);
297 // if API is used, default to the chosen settings
298 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default')))
304 if(strlen($b['postopts']))
305 $b['postopts'] .= ',';
307 $b['postopts'] .= 'appnet';
311 function appnet_create_entities($a, $b, $postdata) {
312 require_once("include/bbcode.php");
313 require_once("include/plaintext.php");
315 $bbcode = $b["body"];
316 $bbcode = bb_remove_share_information($bbcode, false, true);
318 // Change pure links in text to bbcode uris
319 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
321 $URLSearchString = "^\[\]";
323 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
324 $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'@$2',$bbcode);
325 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
326 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
327 $bbcode = preg_replace("/\[youtube\]https?:\/\/(.*?)\[\/youtube\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
328 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
329 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
330 $bbcode = preg_replace("/\[vimeo\]https?:\/\/(.*?)\[\/vimeo\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
331 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
332 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
333 //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
335 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
338 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER);
340 $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1',$bbcode);
342 $b["body"] = $bbcode;
346 // https://alpha.app.net/heluecht/post/32424376
347 // https://alpha.app.net/heluecht/post/32424307
349 $plaintext = plaintext($a, $b, 0, false, 6);
351 $text = $plaintext["text"];
356 foreach ($urls AS $url) {
357 $lenurl = iconv_strlen($url[1], "UTF-8");
358 $len = iconv_strlen($url[2], "UTF-8");
359 $pos = iconv_strpos($text, $url[1], $start, "UTF-8");
360 $pre = iconv_substr($text, 0, $pos, "UTF-8");
361 $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8");
364 $html = bbcode($mid, false, false, 6);
365 $mid = html2plain($html, 0, true);
367 $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8'));
369 $text = $pre.$mid.$post;
372 $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid);
377 if (isset($postdata["url"]) AND isset($postdata["title"]) AND ($postdata["type"] != "photo")) {
378 $postdata["title"] = shortenmsg($postdata["title"], 90);
379 $max = 256 - strlen($postdata["title"]);
380 $text = shortenmsg($text, $max);
381 $text .= "\n[".$postdata["title"]."](".$postdata["url"].")";
382 } elseif (isset($postdata["url"]) AND ($postdata["type"] != "photo")) {
383 $postdata["url"] = short_link($postdata["url"]);
385 $text = shortenmsg($text, $max);
386 $text .= " [".$postdata["url"]."](".$postdata["url"].")";
389 $text = shortenmsg($text, $max);
392 if (iconv_strlen($text, "UTF-8") < $max)
393 $max = iconv_strlen($text, "UTF-8");
396 foreach ($entities AS $entity) {
397 //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) {
398 if (($entity["pos"] + $entity["len"]) <= $max) {
399 $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8");
400 $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8");
402 $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post;
410 function appnet_send(&$a,&$b) {
412 logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
414 if (!get_pconfig($b["uid"],'appnet','import')) {
415 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
419 if($b['parent'] != $b['id']) {
420 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
422 // Looking if its a reply to an app.net post
423 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
424 logger("appnet_send: no app.net post ".$b["parent"]);
428 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
429 dbesc($b["thr-parent"]),
433 logger("appnet_send: no parent found ".$b["thr-parent"]);
440 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
441 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
442 $nicknameplain = "@".$nicknameplain;
444 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
445 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
446 $b["body"] = $nickname." ".$b["body"];
448 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
452 if($b['private'] OR !strstr($b['postopts'],'appnet'))
456 if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
457 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
459 if($b['verb'] == ACTIVITY_LIKE) {
460 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
461 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
463 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
465 appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
469 if($b['deleted'] || ($b['created'] !== $b['edited']))
472 $token = get_pconfig($b['uid'],'appnet','token');
476 // If it's a repeated message from app.net then do a native repost and exit
477 if (appnet_is_repost($a, $b['uid'], $b['body']))
481 require_once 'addon/appnet/AppDotNet.php';
483 $clientId = get_pconfig($b["uid"],'appnet','clientid');
484 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
486 $app = new AppDotNet($clientId, $clientSecret);
487 $app->setAccessToken($token);
491 require_once("include/plaintext.php");
492 require_once("include/network.php");
494 $post = plaintext($a, $b, 256, false, 6);
495 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
497 if (isset($post["image"])) {
498 $img_str = fetch_url($post['image'],true, $redirects, 10);
499 $tempfile = tempnam(get_temppath(), "cache");
500 file_put_contents($tempfile, $img_str);
503 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
505 $data["annotations"][] = array(
506 "type" => "net.app.core.oembed",
508 "+net.app.core.file" => array(
509 "file_id" => $photoFile["id"],
510 "file_token" => $photoFile["file_token"],
511 "format" => "oembed")
515 catch (AppDotNetException $e) {
516 logger("appnet_send: Error creating file ".appnet_error($e->getMessage()));
522 // Adding a link to the original post, if it is a root post
523 if($b['parent'] == $b['id'])
524 $data["annotations"][] = array(
525 "type" => "net.app.core.crosspost",
526 "value" => array("canonical_url" => $b["plink"])
529 // Adding the original post
530 $attached_data = get_attached_data($b["body"]);
531 $attached_data["post-uri"] = $b["uri"];
532 $attached_data["post-title"] = $b["title"];
533 $attached_data["post-body"] = substr($b["body"], 0, 4000); // To-Do: Better shortening
534 $attached_data["post-tag"] = $b["tag"];
535 $attached_data["author-name"] = $b["author-name"];
536 $attached_data["author-link"] = $b["author-link"];
537 $attached_data["author-avatar"] = $b["author-avatar"];
539 $data["annotations"][] = array(
540 "type" => "com.friendica.post",
541 "value" => $attached_data
544 if (isset($post["url"]) AND !isset($post["title"]) AND ($post["type"] != "photo")) {
545 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
546 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
548 if (strlen($display_url) > 26)
549 $display_url = substr($display_url, 0, 25)."…";
551 $post["title"] = $display_url;
554 $text = appnet_create_entities($a, $b, $post);
556 $data["entities"]["parse_markdown_links"] = true;
559 $data["reply_to"] = substr($orig_post["uri"], 5);
562 logger("appnet_send: sending message ".$b["id"]." ".$text." ".print_r($data, true), LOGGER_DEBUG);
563 $ret = $app->createPost($text, $data);
564 logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
566 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
567 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
568 dbesc("adn::".$ret["id"]),
573 catch (AppDotNetException $e) {
574 logger("appnet_send: Error sending message ".$b["id"]." ".appnet_error($e->getMessage()));
579 function appnet_action($a, $uid, $pid, $action) {
580 require_once 'addon/appnet/AppDotNet.php';
582 $token = get_pconfig($uid,'appnet','token');
583 $clientId = get_pconfig($uid,'appnet','clientid');
584 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
586 $app = new AppDotNet($clientId, $clientSecret);
587 $app->setAccessToken($token);
589 logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
594 $result = $app->deletePost($pid);
597 $result = $app->starPost($pid);
600 $result = $app->unstarPost($pid);
603 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
605 catch (AppDotNetException $e) {
606 logger("appnet_action: Error sending action ".$action." pid ".$pid." ".appnet_error($e->getMessage()), LOGGER_DEBUG);
610 function appnet_is_repost($a, $uid, $body) {
613 // Skip if it isn't a pure repeated messages
614 // Does it start with a share?
615 if (strpos($body, "[share") > 0)
618 // Does it end with a share?
619 if (strlen($body) > (strrpos($body, "[/share]") + 8))
622 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
623 // Skip if there is no shared message in there
624 if ($body == $attributes)
628 preg_match("/link='(.*?)'/ism", $attributes, $matches);
629 if ($matches[1] != "")
632 preg_match('/link="(.*?)"/ism', $attributes, $matches);
633 if ($matches[1] != "")
636 $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
640 logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
642 require_once 'addon/appnet/AppDotNet.php';
644 $token = get_pconfig($uid,'appnet','token');
645 $clientId = get_pconfig($uid,'appnet','clientid');
646 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
648 $app = new AppDotNet($clientId, $clientSecret);
649 $app->setAccessToken($token);
652 $result = $app->repost($id);
653 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
656 catch (AppDotNetException $e) {
657 logger('appnet_is_repost: error doing repost '.appnet_error($e->getMessage()), LOGGER_DEBUG);
662 function appnet_fetchstream($a, $uid) {
663 require_once("addon/appnet/AppDotNet.php");
664 require_once('include/items.php');
666 $token = get_pconfig($uid,'appnet','token');
667 $clientId = get_pconfig($uid,'appnet','clientid');
668 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
670 $app = new AppDotNet($clientId, $clientSecret);
671 $app->setAccessToken($token);
673 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
679 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
683 $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
690 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
694 $ownid = get_pconfig($uid,'appnet','ownid');
697 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
698 "include_html" => false, "include_post_annotations" => true);
700 $lastid = get_pconfig($uid, 'appnet', 'laststreamid');
703 $param["since_id"] = $lastid;
706 $stream = $app->getUserStream($param);
708 catch (AppDotNetException $e) {
709 logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".appnet_error($e->getMessage()));
713 if (!is_array($stream))
716 $stream = array_reverse($stream);
717 foreach ($stream AS $post) {
718 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
720 $item = item_store($postarray);
721 $postarray["id"] = $item;
723 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
725 $lastid = $post["id"];
727 if (($item != 0) AND ($postarray['contact-id'] != $me["id"]) AND !function_exists("check_item_notification")) {
728 $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
729 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
730 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
733 require_once('include/enotify.php');
735 'type' => NOTIFY_COMMENT,
736 'notify_flags' => $user['notify-flags'],
737 'language' => $user['language'],
738 'to_name' => $user['username'],
739 'to_email' => $user['email'],
740 'uid' => $user['uid'],
741 'item' => $postarray,
742 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
743 'source_name' => $postarray['author-name'],
744 'source_link' => $postarray['author-link'],
745 'source_photo' => $postarray['author-avatar'],
746 'verb' => ACTIVITY_POST,
748 'parent' => $r[0]["parent"],
754 set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
757 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
758 "include_html" => false, "include_post_annotations" => true);
760 $lastid = get_pconfig($uid, 'appnet', 'lastmentionid');
763 $param["since_id"] = $lastid;
766 $mentions = $app->getUserMentions("me", $param);
768 catch (AppDotNetException $e) {
769 logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".appnet_error($e->getMessage()));
773 if (!is_array($mentions))
776 $mentions = array_reverse($mentions);
777 foreach ($mentions AS $post) {
778 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
780 if (isset($postarray["id"])) {
781 $item = $postarray["id"];
782 $parent_id = $postarray['parent'];
783 } elseif (isset($postarray["body"])) {
784 $item = item_store($postarray);
785 $postarray["id"] = $item;
788 logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
790 if ($item AND function_exists("check_item_notification"))
791 check_item_notification($item, $uid, NOTIFY_TAGSELF);
798 // Fetch the parent and id
799 if (($parent_id == 0) AND ($postarray['uri'] != "")) {
800 $r = q("SELECT `id`, `parent` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
801 dbesc($postarray['uri']),
807 $parent_id = $r[0]['parent'];
811 $lastid = $post["id"];
813 //if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
814 if (($item != 0) AND !function_exists("check_item_notification")) {
815 require_once('include/enotify.php');
817 'type' => NOTIFY_TAGSELF,
818 'notify_flags' => $user['notify-flags'],
819 'language' => $user['language'],
820 'to_name' => $user['username'],
821 'to_email' => $user['email'],
822 'uid' => $user['uid'],
823 'item' => $postarray,
824 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
825 'source_name' => $postarray['author-name'],
826 'source_link' => $postarray['author-link'],
827 'source_photo' => $postarray['author-avatar'],
828 'verb' => ACTIVITY_TAG,
830 'parent' => $parent_id,
835 set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
839 $param = array("interaction_actions" => "star");
840 $interactions = $app->getMyInteractions($param);
841 foreach ($interactions AS $interaction)
842 appnet_dolike($a, $uid, $interaction);
846 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true, $nodupcheck = false) {
847 require_once('include/items.php');
849 if ($post["machine_only"])
852 if ($post["is_deleted"])
855 $postarray = array();
856 $postarray['gravity'] = 0;
857 $postarray['uid'] = $uid;
858 $postarray['wall'] = 0;
859 $postarray['verb'] = ACTIVITY_POST;
860 $postarray['network'] = dbesc(NETWORK_APPNET);
861 if (is_array($post["repost_of"])) {
862 // You can't reply to reposts. So use the original id and thread-id
863 $postarray['uri'] = "adn::".$post["repost_of"]["id"];
864 $postarray['parent-uri'] = "adn::".$post["repost_of"]["thread_id"];
866 $postarray['uri'] = "adn::".$post["id"];
867 $postarray['parent-uri'] = "adn::".$post["thread_id"];
871 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
872 dbesc($postarray['uri']),
879 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
880 dbesc($postarray['uri']),
888 if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
889 $postarray['thr-parent'] = "adn::".$post["reply_to"];
891 // Complete the thread (if the parent doesn't exists)
892 if ($threadcompletion) {
893 //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
894 // dbesc($postarray['thr-parent']),
898 logger("appnet_createpost: completing thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
900 require_once("addon/appnet/AppDotNet.php");
902 $token = get_pconfig($uid,'appnet','token');
903 $clientId = get_pconfig($uid,'appnet','clientid');
904 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
906 $app = new AppDotNet($clientId, $clientSecret);
907 $app->setAccessToken($token);
909 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
910 "include_html" => false, "include_post_annotations" => true);
912 $thread = $app->getPostReplies($post["thread_id"], $param);
914 catch (AppDotNetException $e) {
915 logger("appnet_createpost: Error fetching thread for user ".$uid." ".appnet_error($e->getMessage()));
917 $thread = array_reverse($thread);
919 logger("appnet_createpost: fetched ".count($thread)." items for thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
921 foreach ($thread AS $tpost) {
922 $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, false, false);
923 $item = item_store($threadpost);
924 $threadpost["id"] = $item;
926 logger("appnet_createpost: stored post ".$post["id"]." thread ".$post["thread_id"]." in item ".$item, LOGGER_DEBUG);
930 // Don't create accounts of people who just comment something
933 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
935 $postarray['thr-parent'] = $postarray['uri'];
936 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
939 if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
940 $postarray['owner-name'] = $post["user"]["name"];
941 $postarray['owner-link'] = $post["user"]["canonical_url"];
942 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
943 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
945 $postarray['owner-name'] = $me["name"];
946 $postarray['owner-link'] = $me["url"];
947 $postarray['owner-avatar'] = $me["thumb"];
948 $postarray['contact-id'] = $me["id"];
953 if (is_array($post["repost_of"])) {
954 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
955 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
956 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
958 $content = $post["repost_of"];
960 $postarray['author-name'] = $postarray['owner-name'];
961 $postarray['author-link'] = $postarray['owner-link'];
962 $postarray['author-avatar'] = $postarray['owner-avatar'];
967 $postarray['plink'] = $content["canonical_url"];
969 if (is_array($content["entities"])) {
970 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
971 $postarray['body'] = $converted["body"];
972 $postarray['tag'] = $converted["tags"];
974 $postarray['body'] = $content["text"];
976 if (sizeof($content["entities"]["links"]))
977 foreach($content["entities"]["links"] AS $link) {
978 $url = normalise_link($link["url"]);
979 $links[$url] = $link["url"];
982 /* if (sizeof($content["annotations"]))
983 foreach($content["annotations"] AS $annotation) {
984 if ($annotation[type] == "net.app.core.oembed") {
985 if (isset($annotation["value"]["embeddable_url"])) {
986 $url = normalise_link($annotation["value"]["embeddable_url"]);
987 if (isset($links[$url]))
990 } elseif ($annotation[type] == "com.friendica.post") {
992 //if (isset($annotation["value"]["post-title"]))
993 // $postarray['title'] = $annotation["value"]["post-title"];
995 //if (isset($annotation["value"]["post-body"]))
996 // $postarray['body'] = $annotation["value"]["post-body"];
998 //if (isset($annotation["value"]["post-tag"]))
999 // $postarray['tag'] = $annotation["value"]["post-tag"];
1001 if (isset($annotation["value"]["author-name"]))
1002 $postarray['author-name'] = $annotation["value"]["author-name"];
1004 if (isset($annotation["value"]["author-link"]))
1005 $postarray['author-link'] = $annotation["value"]["author-link"];
1007 if (isset($annotation["value"]["author-avatar"]))
1008 $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
1015 if (is_array($content["annotations"])) {
1016 $photo = appnet_expand_annotations($a, $content["annotations"]);
1017 if (($photo["large"] != "") AND ($photo["url"] != ""))
1018 $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]";
1019 elseif ($photo["url"] != "")
1020 $page_info = "\n[img]".$photo["url"]."[/img]";
1022 if ($photo["url"] != "")
1023 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
1026 $photo = array("url" => "", "large" => "");
1028 if (sizeof($links)) {
1029 $link = array_pop($links);
1030 $url = str_replace(array('/', '.'), array('\/', '\.'), $link);
1032 $page_info = add_page_info($link, false, $photo["url"]);
1034 if (trim($page_info) != "") {
1035 $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $postarray['body']);
1036 if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
1037 $postarray['body'] = $removedlink;
1041 $postarray['body'] .= $page_info;
1043 $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
1044 $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
1046 $postarray['app'] = $post["source"]["name"];
1051 function appnet_expand_entities($a, $body, $entities) {
1053 if (!function_exists('substr_unicode')) {
1054 function substr_unicode($str, $s, $l = null) {
1055 return join("", array_slice(
1056 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
1060 $tags_arr = array();
1063 foreach ($entities["mentions"] AS $mention) {
1064 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
1065 $tags_arr["@".$mention["name"]] = $url;
1066 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
1069 foreach ($entities["hashtags"] AS $hashtag) {
1070 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
1071 $tags_arr["#".$hashtag["name"]] = $url;
1072 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
1075 foreach ($entities["links"] AS $links) {
1076 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
1077 if (isset($links["amended_len"]) AND ($links["amended_len"] > $links["len"]))
1078 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url);
1080 $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
1084 if (sizeof($replace)) {
1086 foreach ($replace AS $entity) {
1087 $pre = substr_unicode($body, 0, $entity["pos"]);
1088 $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
1089 //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8");
1090 //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8");
1092 $body = $pre.$entity["replace"].$post;
1096 return(array("body" => $body, "tags" => implode($tags_arr, ",")));
1099 function appnet_expand_annotations($a, $annotations) {
1100 $photo = array("url" => "", "large" => "");
1101 foreach ($annotations AS $annotation) {
1102 if (($annotation[type] == "net.app.core.oembed") AND
1103 ($annotation["value"]["type"] == "photo")) {
1104 if ($annotation["value"]["url"] != "")
1105 $photo["url"] = $annotation["value"]["url"];
1107 if ($annotation["value"]["thumbnail_large_url"] != "")
1108 $photo["large"] = $annotation["value"]["thumbnail_large_url"];
1110 //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
1111 // $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
1112 //elseif ($annotation["value"]["url"] != "")
1113 // $embedded = "\n[img]".$annotation["value"]["url"]."[/img]";
1119 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
1121 if (function_exists("update_gcontact"))
1122 update_gcontact(array("url" => $contact["canonical_url"], "generation" => 2,
1123 "network" => NETWORK_APPNET, "photo" => $contact["avatar_image"]["url"],
1124 "name" => $contact["name"], "nick" => $contact["username"],
1125 "about" => $contact["description"]["text"], "hide" => true,
1126 "addr" => $contact["username"]."@app.net"));
1129 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
1130 dbesc(normalise_link($contact["canonical_url"])));
1133 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
1134 dbesc(normalise_link($contact["canonical_url"])),
1135 dbesc($contact["name"]),
1136 dbesc($contact["username"]),
1137 dbesc($contact["avatar_image"]["url"]));
1139 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
1140 dbesc($contact["name"]),
1141 dbesc($contact["username"]),
1142 dbesc($contact["avatar_image"]["url"]),
1143 dbesc(normalise_link($contact["canonical_url"])));
1145 if (DB_UPDATE_VERSION >= "1177")
1146 q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'",
1148 dbesc($contact["description"]["text"]),
1149 dbesc(normalise_link($contact["canonical_url"])));
1152 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1153 intval($uid), dbesc("adn::".$contact["id"]));
1155 if(!count($r) AND !$create_user)
1158 if ($contact["canonical_url"] == "")
1161 if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
1162 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
1168 if ($contact["name"] == "")
1169 $contact["name"] = $contact["username"];
1171 if ($contact["username"] == "")
1172 $contact["username"] = $contact["name"];
1174 // create contact record
1175 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1176 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1177 `writable`, `blocked`, `readonly`, `pending` )
1178 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1180 dbesc(datetime_convert()),
1181 dbesc($contact["canonical_url"]),
1182 dbesc(normalise_link($contact["canonical_url"])),
1183 dbesc($contact["username"]."@app.net"),
1184 dbesc("adn::".$contact["id"]),
1186 dbesc("adn::".$contact["id"]),
1187 dbesc($contact["name"]),
1188 dbesc($contact["username"]),
1189 dbesc($contact["avatar_image"]["url"]),
1190 dbesc(NETWORK_APPNET),
1191 intval(CONTACT_IS_FRIEND),
1196 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1197 dbesc("adn::".$contact["id"]),
1204 $contact_id = $r[0]['id'];
1206 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1210 if($g && intval($g[0]['def_gid'])) {
1211 require_once('include/group.php');
1212 group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1215 require_once("Photo.php");
1217 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
1219 q("UPDATE `contact` SET `photo` = '%s',
1224 `avatar-date` = '%s'
1229 dbesc(datetime_convert()),
1230 dbesc(datetime_convert()),
1231 dbesc(datetime_convert()),
1235 if (DB_UPDATE_VERSION >= "1177")
1236 q("UPDATE `contact` SET `location` = '%s',
1240 dbesc($contact["description"]["text"]),
1244 // update profile photos once every two weeks as we have no notification of when they change.
1246 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1247 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1249 // check that we have all the photos, this has been known to fail on occasion
1251 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1253 logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
1255 require_once("Photo.php");
1257 $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
1259 q("UPDATE `contact` SET `photo` = '%s',
1264 `avatar-date` = '%s',
1274 dbesc(datetime_convert()),
1275 dbesc(datetime_convert()),
1276 dbesc(datetime_convert()),
1277 dbesc($contact["canonical_url"]),
1278 dbesc(normalise_link($contact["canonical_url"])),
1279 dbesc($contact["username"]."@app.net"),
1280 dbesc($contact["name"]),
1281 dbesc($contact["username"]),
1284 if (DB_UPDATE_VERSION >= "1177")
1285 q("UPDATE `contact` SET `location` = '%s',
1289 dbesc($contact["description"]["text"]),
1295 return($r[0]["id"]);
1298 function appnet_prepare_body(&$a,&$b) {
1299 if ($b["item"]["network"] != NETWORK_APPNET)
1302 if ($b["preview"]) {
1304 require_once("include/plaintext.php");
1306 $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"];
1308 $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
1309 dbesc($item["thr-parent"]),
1310 intval(local_user()));
1315 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
1316 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
1317 $nicknameplain = "@".$nicknameplain;
1319 if ((strpos($item["body"], $nickname) === false) AND (strpos($item["body"], $nicknameplain) === false))
1320 $item["body"] = $nickname." ".$item["body"];
1325 $msgarr = plaintext($a, $item, $max_char, true);
1326 $msg = appnet_create_entities($a, $item, $msgarr);
1328 require_once("library/markdown.php");
1329 $msg = Markdown($msg);
1335 function appnet_cron($a,$b) {
1336 $last = get_config('appnet','last_poll');
1338 $poll_interval = intval(get_config('appnet','poll_interval'));
1339 if(! $poll_interval)
1340 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1343 $next = $last + ($poll_interval * 60);
1344 if($next > time()) {
1345 logger('appnet_cron: poll intervall not reached');
1349 logger('appnet_cron: cron_start');
1351 $abandon_days = intval(get_config('system','account_abandon_days'));
1352 if ($abandon_days < 1)
1355 $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
1357 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1359 foreach($r as $rr) {
1360 if ($abandon_days != 0) {
1361 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
1362 if (!count($user)) {
1363 logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
1368 logger('appnet_cron: importing timeline from user '.$rr['uid']);
1369 appnet_fetchstream($a, $rr["uid"]);
1373 logger('appnet_cron: cron_end');
1375 set_config('appnet','last_poll', time());
1378 function appnet_error($msg) {
1380 $pos = strrpos($msg, "\r\n\r\n");
1385 $msg = substr($msg, $pos + 4);
1387 $error = json_decode($msg);
1392 if (isset($error->meta->error_message))
1393 return($error->meta->error_message);
1395 return(print_r($error));