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