]> git.mxchange.org Git - friendica-addons.git/blob - appnet/appnet.php
Merge pull request #234 from fabrixxm/securemail
[friendica-addons.git] / appnet / appnet.php
1 <?php
2
3 /**
4  * Name: App.net Connector
5  * Description: app.net postings import and export
6  * Version: 0.2
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  */
9
10 /*
11  To-Do:
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
16 */
17
18 define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
19
20 function appnet_install() {
21         register_hook('post_local',             'addon/appnet/appnet.php', 'appnet_post_local');
22         register_hook('notifier_normal',        'addon/appnet/appnet.php', 'appnet_send');
23         register_hook('jot_networks',           'addon/appnet/appnet.php', 'appnet_jot_nets');
24         register_hook('cron',                   'addon/appnet/appnet.php', 'appnet_cron');
25         register_hook('connector_settings',     'addon/appnet/appnet.php', 'appnet_settings');
26         register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post');
27         register_hook('prepare_body',           'addon/appnet/appnet.php', 'appnet_prepare_body');
28 }
29
30
31 function appnet_uninstall() {
32         unregister_hook('post_local',       'addon/appnet/appnet.php', 'appnet_post_local');
33         unregister_hook('notifier_normal',  'addon/appnet/appnet.php', 'appnet_send');
34         unregister_hook('jot_networks',     'addon/appnet/appnet.php', 'appnet_jot_nets');
35         unregister_hook('cron',                 'addon/appnet/appnet.php', 'appnet_cron');
36         unregister_hook('connector_settings',   'addon/appnet/appnet.php', 'appnet_settings');
37         unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post');
38         unregister_hook('prepare_body',         'addon/appnet/appnet.php', 'appnet_prepare_body');
39 }
40
41 function appnet_module() {}
42
43 function appnet_content(&$a) {
44         if(! local_user()) {
45                 notice( t('Permission denied.') . EOL);
46                 return '';
47         }
48
49         require_once("mod/settings.php");
50         settings_init($a);
51
52         if (isset($a->argv[1]))
53                 switch ($a->argv[1]) {
54                         case "connect":
55                                 $o = appnet_connect($a);
56                                 break;
57                         default:
58                                 $o = print_r($a->argv, true);
59                                 break;
60                 }
61         else
62                 $o = appnet_connect($a);
63
64         return $o;
65 }
66
67 function appnet_plugin_admin(&$a, &$o){
68         $t = get_markup_template( "admin.tpl", "addon/appnet/" );
69
70         $o = replace_macros($t, array(
71                 '$submit' => t('Save Settings'),
72                                                                 // name, label, value, help, [extra values]
73                 '$clientid' => array('clientid', t('Client ID'),  get_config('appnet', 'clientid' ), ''),
74                 '$clientsecret' => array('clientsecret', t('Client Secret'),  get_config('appnet', 'clientsecret' ), ''),
75         ));
76 }
77
78 function appnet_plugin_admin_post(&$a){
79         $clientid     =       ((x($_POST,'clientid'))              ? notags(trim($_POST['clientid']))   : '');
80         $clientsecret =       ((x($_POST,'clientsecret'))   ? notags(trim($_POST['clientsecret'])): '');
81         set_config('appnet','clientid',$clientid);
82         set_config('appnet','clientsecret',$clientsecret);
83         info( t('Settings updated.'). EOL );
84 }
85
86 function appnet_connect(&$a) {
87         require_once 'addon/appnet/AppDotNet.php';
88
89         $clientId     = get_config('appnet','clientid');
90         $clientSecret = get_config('appnet','clientsecret');
91
92         if (($clientId == "") OR ($clientSecret == "")) {
93                 $clientId     = get_pconfig(local_user(),'appnet','clientid');
94                 $clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
95         }
96
97         $app = new AppDotNet($clientId, $clientSecret);
98
99         try {
100                 $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect');
101
102                 logger("appnet_connect: authenticated");
103                 $o .= t("You are now authenticated to app.net. ");
104                 set_pconfig(local_user(),'appnet','token', $token);
105         }
106         catch (AppDotNetException $e) {
107                 $o .= t("<p>Error fetching token. Please try again.</p>");
108         }
109
110         $o .= '<br /><a href="'.$a->get_baseurl().'/settings/connectors">'.t("return to the connector page").'</a>';
111
112         return($o);
113 }
114
115 function appnet_jot_nets(&$a,&$b) {
116         if(! local_user())
117                 return;
118
119         $post = get_pconfig(local_user(),'appnet','post');
120         if(intval($post) == 1) {
121                 $defpost = get_pconfig(local_user(),'appnet','post_by_default');
122                 $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : '');
123                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="appnet_enable"' . $selected . ' value="1" /> '
124                         . t('Post to app.net') . '</div>';
125     }
126 }
127
128 function appnet_settings(&$a,&$s) {
129         require_once 'addon/appnet/AppDotNet.php';
130
131         if(! local_user())
132                 return;
133
134         $token = get_pconfig(local_user(),'appnet','token');
135
136         $app_clientId     = get_config('appnet','clientid');
137         $app_clientSecret = get_config('appnet','clientsecret');
138
139         if (($app_clientId == "") OR ($app_clientSecret == "")) {
140                 $app_clientId     = get_pconfig(local_user(),'appnet','clientid');
141                 $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret');
142         }
143
144         /* Add our stylesheet to the page so we can make our settings look nice */
145         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/appnet/appnet.css' . '" media="all" />' . "\r\n";
146
147         $enabled = get_pconfig(local_user(),'appnet','post');
148         $checked = (($enabled) ? ' checked="checked" ' : '');
149
150         $css = (($enabled) ? '' : '-disabled');
151
152         $def_enabled = get_pconfig(local_user(),'appnet','post_by_default');
153         $def_checked = (($def_enabled) ? ' checked="checked" ' : '');
154
155         $importenabled = get_pconfig(local_user(),'appnet','import');
156         $importchecked = (($importenabled) ? ' checked="checked" ' : '');
157
158         $ownid =  get_pconfig(local_user(),'appnet','ownid');
159
160         $s .= '<span id="settings_appnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
161         $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Import/Export').'</h3>';
162         $s .= '</span>';
163         $s .= '<div id="settings_appnet_expanded" class="settings-block" style="display: none;">';
164         $s .= '<span class="fakelink" onclick="openClose(\'settings_appnet_expanded\'); openClose(\'settings_appnet_inflated\');">';
165         $s .= '<img class="connector'.$css.'" src="images/appnet.png" /><h3 class="connector">'. t('App.net Import/Export').'</h3>';
166         $s .= '</span>';
167
168         if ($token != "") {
169                 $app = new AppDotNet($app_clientId, $app_clientSecret);
170                 $app->setAccessToken($token);
171
172                 try {
173                         $userdata = $app->getUser();
174
175                         if ($ownid != $userdata["id"])
176                                 set_pconfig(local_user(),'appnet','ownid', $userdata["id"]);
177
178                         $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>';
179                         $s .= '<div id="appnet-enable-wrapper">';
180                         $s .= '<label id="appnet-enable-label" for="appnet-checkbox">' . t('Enable App.net Post Plugin') . '</label>';
181                         $s .= '<input id="appnet-checkbox" type="checkbox" name="appnet" value="1" ' . $checked . '/>';
182                         $s .= '</div><div class="clear"></div>';
183
184                         $s .= '<div id="appnet-bydefault-wrapper">';
185                         $s .= '<label id="appnet-bydefault-label" for="appnet-bydefault">' . t('Post to App.net by default') . '</label>';
186                         $s .= '<input id="appnet-bydefault" type="checkbox" name="appnet_bydefault" value="1" ' . $def_checked . '/>';
187                         $s .= '</div><div class="clear"></div>';
188
189                         $s .= '<label id="appnet-import-label" for="appnet-import">'.t('Import the remote timeline').'</label>';
190                         $s .= '<input id="appnet-import" type="checkbox" name="appnet_import" value="1" '. $importchecked . '/>';
191                         $s .= '<div class="clear"></div>';
192
193                 }
194                 catch (AppDotNetException $e) {
195                         $s .= t("<p>Error fetching user profile. Please clear the configuration and try again.</p>");
196                 }
197
198         } elseif (($app_clientId == '') OR ($app_clientSecret == '')) {
199                 $s .= t("<p>You have two ways to connect to App.net.</p>");
200                 $s .= "<hr />";
201                 $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. ');
202                 $s .= sprintf(t("Use '%s' as Redirect URI<p>"), $a->get_baseurl().'/appnet/connect');
203                 $s .= '<div id="appnet-clientid-wrapper">';
204                 $s .= '<label id="appnet-clientid-label" for="appnet-clientid">' . t('Client ID') . '</label>';
205                 $s .= '<input id="appnet-clientid" type="text" name="clientid" value="" />';
206                 $s .= '</div><div class="clear"></div>';
207                 $s .= '<div id="appnet-clientsecret-wrapper">';
208                 $s .= '<label id="appnet-clientsecret-label" for="appnet-clientsecret">' . t('Client Secret') . '</label>';
209                 $s .= '<input id="appnet-clientsecret" type="text" name="clientsecret" value="" />';
210                 $s .= '</div><div class="clear"></div>';
211                 $s .= "<hr />";
212                 $s .= t('<p>Second way: fetch a token at <a href="http://dev-lite.jonathonduerig.com/">http://dev-lite.jonathonduerig.com/</a>. ');
213                 $s .= t("Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.</p>");
214                 $s .= '<div id="appnet-token-wrapper">';
215                 $s .= '<label id="appnet-token-label" for="appnet-token">' . t('Token') . '</label>';
216                 $s .= '<input id="appnet-token" type="text" name="token" value="'.$token.'" />';
217                 $s .= '</div><div class="clear"></div>';
218
219         } else {
220                 $app = new AppDotNet($app_clientId, $app_clientSecret);
221
222                 $scope =  array('basic', 'stream', 'write_post',
223                                 'public_messages', 'messages');
224
225                 $url = $app->getAuthUrl($a->get_baseurl().'/appnet/connect', $scope);
226                 $s .= '<div class="clear"></div>';
227                 $s .= '<a href="'.$url.'">'.t("Sign in using App.net").'</a>';
228         }
229
230         if (($app_clientId != '') OR ($app_clientSecret != '') OR ($token !='')) {
231                 $s .= '<div id="appnet-disconnect-wrapper">';
232                 $s .= '<label id="appnet-disconnect-label" for="appnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
233
234                 $s .= '<input id="appnet-disconnect" type="checkbox" name="appnet-disconnect" value="1" />';
235                 $s .= '</div><div class="clear"></div>';
236         }
237
238         /* provide a submit button */
239         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="appnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
240
241         $s .= '</div>';
242 }
243
244 function appnet_settings_post(&$a,&$b) {
245
246         if(x($_POST,'appnet-submit')) {
247
248                 if (isset($_POST['appnet-disconnect'])) {
249                         del_pconfig(local_user(), 'appnet', 'clientsecret');
250                         del_pconfig(local_user(), 'appnet', 'clientid');
251                         del_pconfig(local_user(), 'appnet', 'token');
252                         del_pconfig(local_user(), 'appnet', 'post');
253                         del_pconfig(local_user(), 'appnet', 'post_by_default');
254                         del_pconfig(local_user(), 'appnet', 'import');
255                 }
256
257                 if (isset($_POST["clientsecret"]))
258                         set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']);
259
260                 if (isset($_POST["clientid"]))
261                         set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']);
262
263                 if (isset($_POST["token"]) AND ($_POST["token"] != ""))
264                         set_pconfig(local_user(),'appnet','token', $_POST['token']);
265
266                 set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet']));
267                 set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault']));
268                 set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import']));
269         }
270 }
271
272 function appnet_post_local(&$a,&$b) {
273         if($b['edit'])
274                 return;
275
276         if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) {
277                 $appnet_post = intval(get_pconfig(local_user(),'appnet','post'));
278                 $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0);
279
280                 // if API is used, default to the chosen settings
281                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default')))
282                         $appnet_enable = 1;
283
284                 if(! $appnet_enable)
285                         return;
286
287                 if(strlen($b['postopts']))
288                         $b['postopts'] .= ',';
289
290                 $b['postopts'] .= 'appnet';
291         }
292 }
293
294 function appnet_create_entities($a, $b, $postdata) {
295         require_once("include/bbcode.php");
296         require_once("include/plaintext.php");
297
298         $bbcode = $b["body"];
299         $bbcode = bb_remove_share_information($bbcode, false, true);
300
301         // Change pure links in text to bbcode uris
302         $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
303
304         $URLSearchString = "^\[\]";
305
306         $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
307         $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'@$2',$bbcode);
308         $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
309         $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
310         $bbcode = preg_replace("/\[youtube\]https?:\/\/(.*?)\[\/youtube\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
311         $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
312                                '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
313         $bbcode = preg_replace("/\[vimeo\]https?:\/\/(.*?)\[\/vimeo\]/ism",'[url=https://$1]https://$1[/url]',$bbcode);
314         $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
315                                 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
316         //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
317
318         $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
319
320
321         preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER);
322
323         $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1',$bbcode);
324
325         $b["body"] = $bbcode;
326
327         // To-Do:
328         // Bilder
329         // https://alpha.app.net/heluecht/post/32424376
330         // https://alpha.app.net/heluecht/post/32424307
331
332         $plaintext = plaintext($a, $b, 0, false, 6);
333
334         $text = $plaintext["text"];
335
336         $start = 0;
337         $entities = array();
338
339         foreach ($urls AS $url) {
340                 $lenurl = iconv_strlen($url[1], "UTF-8");
341                 $len = iconv_strlen($url[2], "UTF-8");
342                 $pos = iconv_strpos($text, $url[1], $start, "UTF-8");
343                 $pre = iconv_substr($text, 0, $pos, "UTF-8");
344                 $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8");
345
346                 $mid = $url[2];
347                 $html = bbcode($mid, false, false, 6);
348                 $mid = html2plain($html, 0, true);
349
350                 $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8'));
351
352                 $text = $pre.$mid.$post;
353
354                 if ($mid != "")
355                         $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid);
356
357                 $start = $pos + 1;
358         }
359
360         if (isset($postdata["url"]) AND isset($postdata["title"])) {
361                 $postdata["title"] = shortenmsg($postdata["title"], 90);
362                 $max = 256 - strlen($postdata["title"]);
363                 $text = shortenmsg($text, $max);
364                 $text .= "\n[".$postdata["title"]."](".$postdata["url"].")";
365         } elseif (isset($postdata["url"])) {
366                 $postdata["url"] = short_link($postdata["url"]);
367                 $max = 240;
368                 $text = shortenmsg($text, $max);
369                 $text .= " [".$postdata["url"]."](".$postdata["url"].")";
370         } else {
371                 $max = 256;
372                 $text = shortenmsg($text, $max);
373         }
374
375         if (iconv_strlen($text, "UTF-8") < $max)
376                 $max = iconv_strlen($text, "UTF-8");
377
378         krsort($entities);
379         foreach ($entities AS $entity) {
380                 //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) {
381                 if (($entity["pos"] + $entity["len"]) <= $max) {
382                         $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8");
383                         $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8");
384
385                         $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post;
386                 }
387         }
388
389
390         return($text);
391 }
392
393 function appnet_send(&$a,&$b) {
394
395         logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
396
397         if (!get_pconfig($b["uid"],'appnet','import')) {
398                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
399                         return;
400         }
401
402         if($b['parent'] != $b['id']) {
403                 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
404
405                 // Looking if its a reply to an app.net post
406                 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
407                         logger("appnet_send: no app.net post ".$b["parent"]);
408                         return;
409                 }
410
411                 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
412                         dbesc($b["thr-parent"]),
413                         intval($b["uid"]));
414
415                 if(!count($r)) {
416                         logger("appnet_send: no parent found ".$b["thr-parent"]);
417                         return;
418                 } else {
419                         $iscomment = true;
420                         $orig_post = $r[0];
421                 }
422
423                 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
424                 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
425                 $nicknameplain = "@".$nicknameplain;
426
427                 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
428                 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
429                         $b["body"] = $nickname." ".$b["body"];
430
431                 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
432         } else {
433                 $iscomment = false;
434
435                 if($b['private'] OR !strstr($b['postopts'],'appnet'))
436                         return;
437         }
438
439         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
440                 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
441
442         if($b['verb'] == ACTIVITY_LIKE) {
443                 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
444                 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
445                 if ($b['deleted'])
446                         appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
447                 else
448                         appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
449                 return;
450         }
451
452         if($b['deleted'] || ($b['created'] !== $b['edited']))
453                 return;
454
455         $token = get_pconfig($b['uid'],'appnet','token');
456
457         if($token) {
458
459                 // If it's a repeated message from app.net then do a native repost and exit
460                 if (appnet_is_repost($a, $b['uid'], $b['body']))
461                         return;
462
463
464                 require_once 'addon/appnet/AppDotNet.php';
465
466                 $clientId     = get_pconfig($b["uid"],'appnet','clientid');
467                 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
468
469                 $app = new AppDotNet($clientId, $clientSecret);
470                 $app->setAccessToken($token);
471
472                 $data = array();
473
474                 require_once("include/plaintext.php");
475                 require_once("include/network.php");
476
477                 $post = plaintext($a, $b, 256, false, 6);
478                 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
479
480                 if (isset($post["image"])) {
481                         $img_str = fetch_url($post['image'],true, $redirects, 10);
482                         $tempfile = tempnam(get_temppath(), "cache");
483                         file_put_contents($tempfile, $img_str);
484
485                         try {
486                                 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
487
488                                 $data["annotations"][] = array(
489                                                                 "type" => "net.app.core.oembed",
490                                                                 "value" => array(
491                                                                         "+net.app.core.file" => array(
492                                                                                 "file_id" => $photoFile["id"],
493                                                                                 "file_token" => $photoFile["file_token"],
494                                                                                 "format" => "oembed")
495                                                                         )
496                                                                 );
497                         }
498                         catch (AppDotNetException $e) {
499                                 logger("appnet_send: Error creating file ".appnet_error($e->getMessage()));
500                         }
501
502                         unlink($tempfile);
503                 }
504
505                 // Adding a link to the original post, if it is a root post
506                 if($b['parent'] == $b['id'])
507                         $data["annotations"][] = array(
508                                                         "type" => "net.app.core.crosspost",
509                                                         "value" => array("canonical_url" => $b["plink"])
510                                                         );
511
512                 // Adding the original post
513                 $attached_data = get_attached_data($b["body"]);
514                 $attached_data["post-uri"] = $b["uri"];
515                 $attached_data["post-title"] = $b["title"];
516                 $attached_data["post-body"] = substr($b["body"], 0, 4000); // To-Do: Better shortening
517                 $attached_data["post-tag"] = $b["tag"];
518                 $attached_data["author-name"] = $b["author-name"];
519                 $attached_data["author-link"] = $b["author-link"];
520                 $attached_data["author-avatar"] = $b["author-avatar"];
521
522                 $data["annotations"][] = array(
523                                                 "type" => "com.friendica.post",
524                                                 "value" => $attached_data
525                                                 );
526
527                 if (isset($post["url"]) AND !isset($post["title"])) {
528                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
529                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
530
531                         if (strlen($display_url) > 26)
532                                 $display_url = substr($display_url, 0, 25)."…";
533
534                         $post["title"] = $display_url;
535                 }
536
537                 $text = appnet_create_entities($a, $b, $post);
538
539                 $data["entities"]["parse_markdown_links"] = true;
540
541                 if ($iscomment)
542                         $data["reply_to"] = substr($orig_post["uri"], 5);
543
544                 try {
545                         logger("appnet_send: sending message ".$b["id"]." ".$text." ".print_r($data, true), LOGGER_DEBUG);
546                         $ret = $app->createPost($text, $data);
547                         logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
548                         if ($iscomment) {
549                                 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
550                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
551                                         dbesc("adn::".$ret["id"]),
552                                         intval($b['id'])
553                                 );
554                         }
555                 }
556                 catch (AppDotNetException $e) {
557                         logger("appnet_send: Error sending message ".$b["id"]." ".appnet_error($e->getMessage()));
558                 }
559         }
560 }
561
562 function appnet_action($a, $uid, $pid, $action) {
563         require_once 'addon/appnet/AppDotNet.php';
564
565         $token        = get_pconfig($uid,'appnet','token');
566         $clientId     = get_pconfig($uid,'appnet','clientid');
567         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
568
569         $app = new AppDotNet($clientId, $clientSecret);
570         $app->setAccessToken($token);
571
572         logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
573
574         try {
575                 switch ($action) {
576                         case "delete":
577                                 $result = $app->deletePost($pid);
578                                 break;
579                         case "like":
580                                 $result = $app->starPost($pid);
581                                 break;
582                         case "unlike":
583                                 $result = $app->unstarPost($pid);
584                                 break;
585                 }
586                 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
587         }
588         catch (AppDotNetException $e) {
589                 logger("appnet_action: Error sending action ".$action." pid ".$pid." ".appnet_error($e->getMessage()), LOGGER_DEBUG);
590         }
591 }
592
593 function appnet_is_repost($a, $uid, $body) {
594         $body = trim($body);
595
596         // Skip if it isn't a pure repeated messages
597         // Does it start with a share?
598         if (strpos($body, "[share") > 0)
599                 return(false);
600
601         // Does it end with a share?
602         if (strlen($body) > (strrpos($body, "[/share]") + 8))
603                 return(false);
604
605         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
606         // Skip if there is no shared message in there
607         if ($body == $attributes)
608                 return(false);
609
610         $link = "";
611         preg_match("/link='(.*?)'/ism", $attributes, $matches);
612         if ($matches[1] != "")
613                 $link = $matches[1];
614
615         preg_match('/link="(.*?)"/ism', $attributes, $matches);
616         if ($matches[1] != "")
617                 $link = $matches[1];
618
619         $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
620         if ($id == $link)
621                 return(false);
622
623         logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
624
625         require_once 'addon/appnet/AppDotNet.php';
626
627         $token        = get_pconfig($uid,'appnet','token');
628         $clientId     = get_pconfig($uid,'appnet','clientid');
629         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
630
631         $app = new AppDotNet($clientId, $clientSecret);
632         $app->setAccessToken($token);
633
634         try {
635                 $result = $app->repost($id);
636                 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
637                 return true;
638         }
639         catch (AppDotNetException $e) {
640                 logger('appnet_is_repost: error doing repost '.appnet_error($e->getMessage()), LOGGER_DEBUG);
641                 return false;
642         }
643 }
644
645 function appnet_fetchstream($a, $uid) {
646         require_once("addon/appnet/AppDotNet.php");
647         require_once('include/items.php');
648
649         $token = get_pconfig($uid,'appnet','token');
650         $clientId     = get_pconfig($uid,'appnet','clientid');
651         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
652
653         $app = new AppDotNet($clientId, $clientSecret);
654         $app->setAccessToken($token);
655
656         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
657                 intval($uid));
658
659         if(count($r))
660                 $me = $r[0];
661         else {
662                 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
663                 return;
664         }
665
666         $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
667                 intval($uid)
668         );
669
670         if(count($user))
671                 $user = $user[0];
672         else {
673                 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
674                 return;
675         }
676
677         $ownid = get_pconfig($uid,'appnet','ownid');
678
679         // Fetch stream
680         $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
681                         "include_html" => false, "include_post_annotations" => true);
682
683         $lastid  = get_pconfig($uid, 'appnet', 'laststreamid');
684
685         if ($lastid <> "")
686                 $param["since_id"] = $lastid;
687
688         try {
689                 $stream = $app->getUserStream($param);
690         }
691         catch (AppDotNetException $e) {
692                 logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".appnet_error($e->getMessage()));
693         }
694
695         $stream = array_reverse($stream);
696         foreach ($stream AS $post) {
697                 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
698
699                 $item = item_store($postarray);
700                 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
701
702                 $lastid = $post["id"];
703
704                 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
705                         $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
706                                 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
707                                 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
708
709                         if (count($r)) {
710                                 require_once('include/enotify.php');
711                                 notification(array(
712                                         'type'         => NOTIFY_COMMENT,
713                                         'notify_flags' => $user['notify-flags'],
714                                         'language'     => $user['language'],
715                                         'to_name'      => $user['username'],
716                                         'to_email'     => $user['email'],
717                                         'uid'          => $user['uid'],
718                                         'item'         => $postarray,
719                                         'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
720                                         'source_name'  => $postarray['author-name'],
721                                         'source_link'  => $postarray['author-link'],
722                                         'source_photo' => $postarray['author-avatar'],
723                                         'verb'         => ACTIVITY_POST,
724                                         'otype'        => 'item',
725                                         'parent'       => $r[0]["parent"],
726                                 ));
727                         }
728                 }
729         }
730
731         set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
732
733         // Fetch mentions
734         $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
735                         "include_html" => false, "include_post_annotations" => true);
736
737         $lastid  = get_pconfig($uid, 'appnet', 'lastmentionid');
738
739         if ($lastid <> "")
740                 $param["since_id"] = $lastid;
741
742         try {
743                 $mentions = $app->getUserMentions("me", $param);
744         }
745         catch (AppDotNetException $e) {
746                 logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".appnet_error($e->getMessage()));
747         }
748
749         $mentions = array_reverse($mentions);
750         foreach ($mentions AS $post) {
751                 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
752
753                 if (isset($postarray["id"])) {
754                         $item = $postarray["id"];
755                         $parent_id = $postarray['parent'];
756                 } elseif (isset($postarray["body"])) {
757                         $item = item_store($postarray);
758                         $parent_id = 0;
759                         logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
760                 } else {
761                         $item = 0;
762                         $parent_id = 0;
763                 }
764
765                 // Fetch the parent and id
766                 if (($parent_id == 0) AND ($postarray['uri'] != "")) {
767                         $r = q("SELECT `id`, `parent` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
768                                 dbesc($postarray['uri']),
769                                 intval($uid)
770                         );
771
772                         if (count($r)) {
773                                 $item = $r[0]['id'];
774                                 $parent_id = $r[0]['parent'];
775                         }
776                 }
777
778                 $lastid = $post["id"];
779
780                 //if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
781                 if ($item != 0) {
782                         require_once('include/enotify.php');
783                         notification(array(
784                                 'type'         => NOTIFY_TAGSELF,
785                                 'notify_flags' => $user['notify-flags'],
786                                 'language'     => $user['language'],
787                                 'to_name'      => $user['username'],
788                                 'to_email'     => $user['email'],
789                                 'uid'          => $user['uid'],
790                                 'item'         => $postarray,
791                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)),
792                                 'source_name'  => $postarray['author-name'],
793                                 'source_link'  => $postarray['author-link'],
794                                 'source_photo' => $postarray['author-avatar'],
795                                 'verb'         => ACTIVITY_TAG,
796                                 'otype'        => 'item',
797                                 'parent'       => $parent_id,
798                         ));
799                 }
800         }
801
802         set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
803
804
805 /* To-Do
806         $param = array("interaction_actions" => "star");
807         $interactions = $app->getMyInteractions($param);
808         foreach ($interactions AS $interaction)
809                 appnet_dolike($a, $uid, $interaction);
810 */
811 }
812
813 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true, $nodupcheck = false) {
814         require_once('include/items.php');
815
816         if ($post["machine_only"])
817                 return;
818
819         if ($post["is_deleted"])
820                 return;
821
822         $postarray = array();
823         $postarray['gravity'] = 0;
824         $postarray['uid'] = $uid;
825         $postarray['wall'] = 0;
826         $postarray['verb'] = ACTIVITY_POST;
827         $postarray['network'] =  dbesc(NETWORK_APPNET);
828         if (is_array($post["repost_of"])) {
829                 // You can't reply to reposts. So use the original id and thread-id
830                 $postarray['uri'] = "adn::".$post["repost_of"]["id"];
831                 $postarray['parent-uri'] = "adn::".$post["repost_of"]["thread_id"];
832         } else {
833                 $postarray['uri'] = "adn::".$post["id"];
834                 $postarray['parent-uri'] = "adn::".$post["thread_id"];
835         }
836
837         if (!$nodupcheck) {
838                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
839                         dbesc($postarray['uri']),
840                         intval($uid)
841                         );
842
843                 if (count($r))
844                         return($r[0]);
845
846                 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
847                         dbesc($postarray['uri']),
848                         intval($uid)
849                         );
850
851                 if (count($r))
852                         return($r[0]);
853         }
854
855         if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
856                 $postarray['thr-parent'] = "adn::".$post["reply_to"];
857
858                 // Complete the thread (if the parent doesn't exists)
859                 if ($threadcompletion) {
860                         //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
861                         //      dbesc($postarray['thr-parent']),
862                         //      intval($uid)
863                         //      );
864                         //if (!count($r)) {
865                                 logger("appnet_createpost: completing thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
866
867                                 require_once("addon/appnet/AppDotNet.php");
868
869                                 $token = get_pconfig($uid,'appnet','token');
870                                 $clientId     = get_pconfig($uid,'appnet','clientid');
871                                 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
872
873                                 $app = new AppDotNet($clientId, $clientSecret);
874                                 $app->setAccessToken($token);
875
876                                 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
877                                                 "include_html" => false, "include_post_annotations" => true);
878                                 try {
879                                         $thread = $app->getPostReplies($post["thread_id"], $param);
880                                 }
881                                 catch (AppDotNetException $e) {
882                                         logger("appnet_createpost: Error fetching thread for user ".$uid." ".appnet_error($e->getMessage()));
883                                 }
884                                 $thread = array_reverse($thread);
885
886                                 logger("appnet_createpost: fetched ".count($thread)." items for thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG);
887
888                                 foreach ($thread AS $tpost) {
889                                         $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, false, false);
890                                         $item = item_store($threadpost);
891                                         logger("appnet_createpost: stored post ".$post["id"]." thread ".$post["thread_id"]." in item ".$item, LOGGER_DEBUG);
892                                 }
893                         //}
894                 }
895                 // Don't create accounts of people who just comment something
896                 $createuser = false;
897
898                 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
899         } else {
900                 $postarray['thr-parent'] = $postarray['uri'];
901                 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
902         }
903
904         if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
905                 $postarray['owner-name'] = $post["user"]["name"];
906                 $postarray['owner-link'] = $post["user"]["canonical_url"];
907                 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
908                 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
909         } else {
910                 $postarray['owner-name'] = $me["name"];
911                 $postarray['owner-link'] = $me["url"];
912                 $postarray['owner-avatar'] = $me["thumb"];
913                 $postarray['contact-id'] = $me["id"];
914         }
915
916         $links = array();
917
918         if (is_array($post["repost_of"])) {
919                 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
920                 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
921                 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
922
923                 $content = $post["repost_of"];
924         } else {
925                 $postarray['author-name'] = $postarray['owner-name'];
926                 $postarray['author-link'] = $postarray['owner-link'];
927                 $postarray['author-avatar'] = $postarray['owner-avatar'];
928
929                 $content = $post;
930         }
931
932         $postarray['plink'] = $content["canonical_url"];
933
934         if (is_array($content["entities"])) {
935                 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
936                 $postarray['body'] = $converted["body"];
937                 $postarray['tag'] = $converted["tags"];
938         } else
939                 $postarray['body'] = $content["text"];
940
941         if (sizeof($content["entities"]["links"]))
942                 foreach($content["entities"]["links"] AS $link) {
943                         $url = normalise_link($link["url"]);
944                         $links[$url] = $link["url"];
945                 }
946
947         /* if (sizeof($content["annotations"]))
948                 foreach($content["annotations"] AS $annotation) {
949                         if ($annotation[type] == "net.app.core.oembed") {
950                                 if (isset($annotation["value"]["embeddable_url"])) {
951                                         $url = normalise_link($annotation["value"]["embeddable_url"]);
952                                         if (isset($links[$url]))
953                                                 unset($links[$url]);
954                                 }
955                         } elseif ($annotation[type] == "com.friendica.post") {
956                                 //$links = array();
957                                 //if (isset($annotation["value"]["post-title"]))
958                                 //      $postarray['title'] = $annotation["value"]["post-title"];
959
960                                 //if (isset($annotation["value"]["post-body"]))
961                                 //      $postarray['body'] = $annotation["value"]["post-body"];
962
963                                 //if (isset($annotation["value"]["post-tag"]))
964                                 //      $postarray['tag'] = $annotation["value"]["post-tag"];
965
966                                 if (isset($annotation["value"]["author-name"]))
967                                         $postarray['author-name'] = $annotation["value"]["author-name"];
968
969                                 if (isset($annotation["value"]["author-link"]))
970                                         $postarray['author-link'] = $annotation["value"]["author-link"];
971
972                                 if (isset($annotation["value"]["author-avatar"]))
973                                         $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
974                         }
975
976                 } */
977
978         $page_info = "";
979
980         if (is_array($content["annotations"])) {
981                 $photo = appnet_expand_annotations($a, $content["annotations"]);
982                 if (($photo["large"] != "") AND ($photo["url"] != ""))
983                         $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]";
984                 elseif ($photo["url"] != "")
985                         $page_info = "\n[img]".$photo["url"]."[/img]";
986
987                 if ($photo["url"] != "")
988                         $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
989
990         } else
991                 $photo = array("url" => "", "large" => "");
992
993         if (sizeof($links)) {
994                 $link = array_pop($links);
995                 $url = str_replace(array('/', '.'), array('\/', '\.'), $link);
996
997                 $page_info = add_page_info($link, false, $photo["url"]);
998
999                 if (trim($page_info) != "") {
1000                         $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $postarray['body']);
1001                         if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
1002                                 $postarray['body'] = $removedlink;
1003                 }
1004         }
1005
1006         $postarray['body'] .= $page_info;
1007
1008         $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
1009         $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
1010
1011         $postarray['app'] = $post["source"]["name"];
1012
1013         return($postarray);
1014 }
1015
1016 function appnet_expand_entities($a, $body, $entities) {
1017
1018         if (!function_exists('substr_unicode')) {
1019                 function substr_unicode($str, $s, $l = null) {
1020                         return join("", array_slice(
1021                                 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
1022                 }
1023         }
1024
1025         $tags_arr = array();
1026         $replace = array();
1027
1028         foreach ($entities["mentions"] AS $mention) {
1029                 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
1030                 $tags_arr["@".$mention["name"]] = $url;
1031                 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
1032         }
1033
1034         foreach ($entities["hashtags"] AS $hashtag) {
1035                 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
1036                 $tags_arr["#".$hashtag["name"]] = $url;
1037                 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
1038         }
1039
1040         foreach ($entities["links"] AS $links) {
1041                 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
1042                 if (isset($links["amended_len"]) AND ($links["amended_len"] > $links["len"]))
1043                         $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url);
1044                 else
1045                         $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
1046         }
1047
1048
1049         if (sizeof($replace)) {
1050                 krsort($replace);
1051                 foreach ($replace AS $entity) {
1052                         $pre = substr_unicode($body, 0, $entity["pos"]);
1053                         $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
1054                         //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8");
1055                         //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8");
1056
1057                         $body = $pre.$entity["replace"].$post;
1058                 }
1059         }
1060
1061         return(array("body" => $body, "tags" => implode($tags_arr, ",")));
1062 }
1063
1064 function appnet_expand_annotations($a, $annotations) {
1065         $photo = array("url" => "", "large" => "");
1066         foreach ($annotations AS $annotation) {
1067                 if (($annotation[type] == "net.app.core.oembed") AND
1068                         ($annotation["value"]["type"] == "photo")) {
1069                         if ($annotation["value"]["url"] != "")
1070                                 $photo["url"] = $annotation["value"]["url"];
1071
1072                         if ($annotation["value"]["thumbnail_large_url"] != "")
1073                                 $photo["large"] = $annotation["value"]["thumbnail_large_url"];
1074
1075                         //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
1076                         //      $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
1077                         //elseif ($annotation["value"]["url"] != "")
1078                         //      $embedded = "\n[img]".$annotation["value"]["url"]."[/img]";
1079                 }
1080         }
1081         return $photo;
1082 }
1083
1084 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
1085
1086         $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
1087                         dbesc(normalise_link($contact["canonical_url"])));
1088
1089         if (count($r) == 0)
1090                 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
1091                         dbesc(normalise_link($contact["canonical_url"])),
1092                         dbesc($contact["name"]),
1093                         dbesc($contact["username"]),
1094                         dbesc($contact["avatar_image"]["url"]));
1095         else
1096                 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
1097                         dbesc($contact["name"]),
1098                         dbesc($contact["username"]),
1099                         dbesc($contact["avatar_image"]["url"]),
1100                         dbesc(normalise_link($contact["canonical_url"])));
1101
1102         if (DB_UPDATE_VERSION >= "1177")
1103                 q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'",
1104                         dbesc(""),
1105                         dbesc($contact["description"]["text"]),
1106                         dbesc(normalise_link($contact["canonical_url"])));
1107
1108
1109         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1110                 intval($uid), dbesc("adn::".$contact["id"]));
1111
1112         if(!count($r) AND !$create_user)
1113                 return($me["id"]);
1114
1115         if ($contact["canonical_url"] == "")
1116                 return($me["id"]);
1117
1118         if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
1119                 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
1120                 return(-1);
1121         }
1122
1123         if(!count($r)) {
1124
1125                 if ($contact["name"] == "")
1126                         $contact["name"] = $contact["username"];
1127
1128                 if ($contact["username"] == "")
1129                         $contact["username"] = $contact["name"];
1130
1131                 // create contact record
1132                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1133                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1134                                         `writable`, `blocked`, `readonly`, `pending` )
1135                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1136                         intval($uid),
1137                         dbesc(datetime_convert()),
1138                         dbesc($contact["canonical_url"]),
1139                         dbesc(normalise_link($contact["canonical_url"])),
1140                         dbesc($contact["username"]."@app.net"),
1141                         dbesc("adn::".$contact["id"]),
1142                         dbesc(''),
1143                         dbesc("adn::".$contact["id"]),
1144                         dbesc($contact["name"]),
1145                         dbesc($contact["username"]),
1146                         dbesc($contact["avatar_image"]["url"]),
1147                         dbesc(NETWORK_APPNET),
1148                         intval(CONTACT_IS_FRIEND),
1149                         intval(1),
1150                         intval(1)
1151                 );
1152
1153                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1154                         dbesc("adn::".$contact["id"]),
1155                         intval($uid)
1156                         );
1157
1158                 if(! count($r))
1159                         return(false);
1160
1161                 $contact_id  = $r[0]['id'];
1162
1163                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1164                         intval($uid)
1165                 );
1166
1167                 if($g && intval($g[0]['def_gid'])) {
1168                         require_once('include/group.php');
1169                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1170                 }
1171
1172                 require_once("Photo.php");
1173
1174                 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
1175
1176                 q("UPDATE `contact` SET `photo` = '%s',
1177                                         `thumb` = '%s',
1178                                         `micro` = '%s',
1179                                         `name-date` = '%s',
1180                                         `uri-date` = '%s',
1181                                         `avatar-date` = '%s'
1182                                 WHERE `id` = %d",
1183                         dbesc($photos[0]),
1184                         dbesc($photos[1]),
1185                         dbesc($photos[2]),
1186                         dbesc(datetime_convert()),
1187                         dbesc(datetime_convert()),
1188                         dbesc(datetime_convert()),
1189                         intval($contact_id)
1190                 );
1191
1192                 if (DB_UPDATE_VERSION >= "1177")
1193                         q("UPDATE `contact` SET `location` = '%s',
1194                                                 `about` = '%s'
1195                                         WHERE `id` = %d",
1196                                 dbesc(""),
1197                                 dbesc($contact["description"]["text"]),
1198                                 intval($contact_id)
1199                         );
1200         } else {
1201                 // update profile photos once every two weeks as we have no notification of when they change.
1202
1203                 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1204                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1205
1206                 // check that we have all the photos, this has been known to fail on occasion
1207
1208                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1209
1210                         logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
1211
1212                         require_once("Photo.php");
1213
1214                         $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
1215
1216                         q("UPDATE `contact` SET `photo` = '%s',
1217                                                 `thumb` = '%s',
1218                                                 `micro` = '%s',
1219                                                 `name-date` = '%s',
1220                                                 `uri-date` = '%s',
1221                                                 `avatar-date` = '%s',
1222                                                 `url` = '%s',
1223                                                 `nurl` = '%s',
1224                                                 `addr` = '%s',
1225                                                 `name` = '%s',
1226                                                 `nick` = '%s'
1227                                         WHERE `id` = %d",
1228                                 dbesc($photos[0]),
1229                                 dbesc($photos[1]),
1230                                 dbesc($photos[2]),
1231                                 dbesc(datetime_convert()),
1232                                 dbesc(datetime_convert()),
1233                                 dbesc(datetime_convert()),
1234                                 dbesc($contact["canonical_url"]),
1235                                 dbesc(normalise_link($contact["canonical_url"])),
1236                                 dbesc($contact["username"]."@app.net"),
1237                                 dbesc($contact["name"]),
1238                                 dbesc($contact["username"]),
1239                                 intval($r[0]['id'])
1240                         );
1241                         if (DB_UPDATE_VERSION >= "1177")
1242                                 q("UPDATE `contact` SET `location` = '%s',
1243                                                         `about` = '%s'
1244                                                 WHERE `id` = %d",
1245                                         dbesc(""),
1246                                         dbesc($contact["description"]["text"]),
1247                                         intval($r[0]['id'])
1248                                 );
1249                 }
1250         }
1251
1252         return($r[0]["id"]);
1253 }
1254
1255 function appnet_prepare_body(&$a,&$b) {
1256         if ($b["item"]["network"] != NETWORK_APPNET)
1257                 return;
1258
1259         if ($b["preview"]) {
1260                 $max_char = 256;
1261                 require_once("include/plaintext.php");
1262                 $item = $b["item"];
1263                 $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"];
1264
1265                 $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
1266                         dbesc($item["thr-parent"]),
1267                         intval(local_user()));
1268
1269                 if(count($r)) {
1270                         $orig_post = $r[0];
1271
1272                         $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
1273                         $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
1274                         $nicknameplain = "@".$nicknameplain;
1275
1276                         if ((strpos($item["body"], $nickname) === false) AND (strpos($item["body"], $nicknameplain) === false))
1277                                 $item["body"] = $nickname." ".$item["body"];
1278                 }
1279
1280
1281
1282                 $msgarr = plaintext($a, $item, $max_char, true);
1283                 $msg = appnet_create_entities($a, $item, $msgarr);
1284
1285                 require_once("library/markdown.php");
1286                 $msg = Markdown($msg);
1287
1288                 $b['html'] = $msg;
1289         }
1290 }
1291
1292 function appnet_cron($a,$b) {
1293         $last = get_config('appnet','last_poll');
1294
1295         $poll_interval = intval(get_config('appnet','poll_interval'));
1296         if(! $poll_interval)
1297                 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1298
1299         if($last) {
1300                 $next = $last + ($poll_interval * 60);
1301                 if($next > time()) {
1302                         logger('appnet_cron: poll intervall not reached');
1303                         return;
1304                 }
1305         }
1306         logger('appnet_cron: cron_start');
1307
1308         $abandon_days = intval(get_config('system','account_abandon_days'));
1309         if ($abandon_days < 1)
1310                 $abandon_days = 0;
1311
1312         $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
1313
1314         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1315         if(count($r)) {
1316                 foreach($r as $rr) {
1317                         if ($abandon_days != 0) {
1318                                 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
1319                                 if (!count($user)) {
1320                                         logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported');
1321                                         continue;
1322                                 }
1323                         }
1324
1325                         logger('appnet_cron: importing timeline from user '.$rr['uid']);
1326                         appnet_fetchstream($a, $rr["uid"]);
1327                 }
1328         }
1329
1330         logger('appnet_cron: cron_end');
1331
1332         set_config('appnet','last_poll', time());
1333 }
1334
1335 function appnet_error($msg) {
1336         $msg = trim($msg);
1337         $pos = strrpos($msg, "\r\n\r\n");
1338
1339         if (!$pos)
1340                 return($msg);
1341
1342         $msg = substr($msg, $pos + 4);
1343
1344         $error = json_decode($msg);
1345
1346         if ($error == NULL)
1347                 return($msg);
1348
1349         if (isset($error->meta->error_message))
1350                 return($error->meta->error_message);
1351         else
1352                 return(print_r($error));
1353 }