]> git.mxchange.org Git - friendica-addons.git/blob - appnet/appnet.php
Appnet: Now you can add a central oauth configuration as well.
[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                 $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8'));
346
347                 $text = $pre.$mid.$post;
348
349                 if ($mid != "")
350                         $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid);
351
352                 $start = $pos + 1;
353         }
354
355         if (isset($postdata["url"]) AND isset($postdata["title"])) {
356                 $postdata["title"] = shortenmsg($postdata["title"], 90);
357                 $text = shortenmsg($text, 256 - strlen($postdata["title"]));
358                 $text .= "\n[".$postdata["title"]."](".$postdata["url"].")";
359         } elseif (isset($postdata["url"])) {
360                 $postdata["url"] = short_link($postdata["url"]);
361                 $text = shortenmsg($text, 240);
362                 $text .= " [".$postdata["url"]."](".$postdata["url"].")";
363         } else
364                 $text = shortenmsg($text, 256);
365
366         krsort($entities);
367         foreach ($entities AS $entity) {
368                 if (iconv_strlen($text) >= $entity["pos"] + $entity["len"]) {
369                         $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8");
370                         $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8");
371
372                         $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post;
373                 }
374         }
375
376         return($text);
377 }
378
379 function appnet_send(&$a,&$b) {
380
381         logger('appnet_send: invoked for post '.$b['id']." ".$b['app']);
382
383         if (!get_pconfig($b["uid"],'appnet','import')) {
384                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
385                         return;
386         }
387
388         if($b['parent'] != $b['id']) {
389                 logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA);
390
391                 // Looking if its a reply to an app.net post
392                 if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) {
393                         logger("appnet_send: no app.net post ".$b["parent"]);
394                         return;
395                 }
396
397                 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
398                         dbesc($b["thr-parent"]),
399                         intval($b["uid"]));
400
401                 if(!count($r)) {
402                         logger("appnet_send: no parent found ".$b["thr-parent"]);
403                         return;
404                 } else {
405                         $iscomment = true;
406                         $orig_post = $r[0];
407                 }
408
409                 $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]);
410                 $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]";
411                 $nicknameplain = "@".$nicknameplain;
412
413                 logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
414                 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
415                         $b["body"] = $nickname." ".$b["body"];
416
417                 logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA);
418         } else {
419                 $iscomment = false;
420
421                 if($b['private'] OR !strstr($b['postopts'],'appnet'))
422                         return;
423         }
424
425         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
426                 appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete");
427
428         if($b['verb'] == ACTIVITY_LIKE) {
429                 logger("appnet_send: ".print_r($b, true), LOGGER_DEBUG);
430                 logger("appnet_send: parameter 2 ".substr($b["thr-parent"], 5), LOGGER_DEBUG);
431                 if ($b['deleted'])
432                         appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "unlike");
433                 else
434                         appnet_action($a, $b["uid"], substr($b["thr-parent"], 5), "like");
435                 return;
436         }
437
438         if($b['deleted'] || ($b['created'] !== $b['edited']))
439                 return;
440
441         $token = get_pconfig($b['uid'],'appnet','token');
442
443         if($token) {
444
445                 // If it's a repeated message from app.net then do a native repost and exit
446                 if (appnet_is_repost($a, $b['uid'], $b['body']))
447                         return;
448
449
450                 require_once 'addon/appnet/AppDotNet.php';
451
452                 $clientId     = get_pconfig($b["uid"],'appnet','clientid');
453                 $clientSecret = get_pconfig($b["uid"],'appnet','clientsecret');
454
455                 $app = new AppDotNet($clientId, $clientSecret);
456                 $app->setAccessToken($token);
457
458                 $data = array();
459
460                 require_once("include/plaintext.php");
461                 require_once("include/network.php");
462
463                 $post = plaintext($a, $b, 256, false, 6);
464                 logger("appnet_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG);
465
466                 if (isset($post["image"])) {
467                         $img_str = fetch_url($post['image'],true, $redirects, 10);
468                         $tempfile = tempnam(get_config("system","temppath"), "cache");
469                         file_put_contents($tempfile, $img_str);
470
471                         try {
472                                 $photoFile = $app->createFile($tempfile, array(type => "com.github.jdolitsky.appdotnetphp.photo"));
473
474                                 $data["annotations"][] = array(
475                                                                 "type" => "net.app.core.oembed",
476                                                                 "value" => array(
477                                                                         "+net.app.core.file" => array(
478                                                                                 "file_id" => $photoFile["id"],
479                                                                                 "file_token" => $photoFile["file_token"],
480                                                                                 "format" => "oembed")
481                                                                         )
482                                                                 );
483                         }
484                         catch (AppDotNetException $e) {
485                                 logger("appnet_send: Error creating file ".$e->getMessage());
486                         }
487
488                         unlink($tempfile);
489                 }
490
491                 // Adding a link to the original post, if it is a root post
492                 if($b['parent'] == $b['id'])
493                         $data["annotations"][] = array(
494                                                         "type" => "net.app.core.crosspost",
495                                                         "value" => array("canonical_url" => $b["plink"])
496                                                         );
497
498                 // Adding the original post
499                 $attached_data = get_attached_data($b["body"]);
500                 $attached_data["post-uri"] = $b["uri"];
501                 $attached_data["post-title"] = $b["title"];
502                 $attached_data["post-body"] = substr($b["body"], 0, 4000); // To-Do: Better shortening
503                 $attached_data["post-tag"] = $b["tag"];
504                 $attached_data["author-name"] = $b["author-name"];
505                 $attached_data["author-link"] = $b["author-link"];
506                 $attached_data["author-avatar"] = $b["author-avatar"];
507
508                 $data["annotations"][] = array(
509                                                 "type" => "com.friendica.post",
510                                                 "value" => $attached_data
511                                                 );
512
513                 if (isset($post["url"]) AND !isset($post["title"])) {
514                         $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $post["url"]);
515                         $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
516
517                         if (strlen($display_url) > 26)
518                                 $display_url = substr($display_url, 0, 25)."…";
519
520                         $post["title"] = $display_url;
521                 }
522
523                 $text = appnet_create_entities($a, $b, $post);
524
525                 $data["entities"]["parse_markdown_links"] = true;
526
527                 if ($iscomment)
528                         $data["reply_to"] = substr($orig_post["uri"], 5);
529
530                 try {
531                         logger("appnet_send: sending message ".$b["id"]." ".$text." ".print_r($data, true), LOGGER_DEBUG);
532                         $ret = $app->createPost($text, $data);
533                         logger("appnet_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG);
534                         if ($iscomment) {
535                                 logger('appnet_send: Update extid '.$ret["id"]." for post id ".$b['id']);
536                                 q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d",
537                                         dbesc("adn::".$ret["id"]),
538                                         intval($b['id'])
539                                 );
540                         }
541                 }
542                 catch (AppDotNetException $e) {
543                         logger("appnet_send: Error sending message ".$b["id"]." ".$e->getMessage());
544                 }
545         }
546 }
547
548 function appnet_action($a, $uid, $pid, $action) {
549         require_once 'addon/appnet/AppDotNet.php';
550
551         $token        = get_pconfig($uid,'appnet','token');
552         $clientId     = get_pconfig($uid,'appnet','clientid');
553         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
554
555         $app = new AppDotNet($clientId, $clientSecret);
556         $app->setAccessToken($token);
557
558         logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
559
560         try {
561                 switch ($action) {
562                         case "delete":
563                                 $result = $app->deletePost($pid);
564                                 break;
565                         case "like":
566                                 $result = $app->starPost($pid);
567                                 break;
568                         case "unlike":
569                                 $result = $app->unstarPost($pid);
570                                 break;
571                 }
572                 logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
573         }
574         catch (AppDotNetException $e) {
575                 logger("appnet_action: Error sending action ".$action." pid ".$pid." ".$e->getMessage(), LOGGER_DEBUG);
576         }
577 }
578
579 function appnet_is_repost($a, $uid, $body) {
580         $body = trim($body);
581
582         // Skip if it isn't a pure repeated messages
583         // Does it start with a share?
584         if (strpos($body, "[share") > 0)
585                 return(false);
586
587         // Does it end with a share?
588         if (strlen($body) > (strrpos($body, "[/share]") + 8))
589                 return(false);
590
591         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
592         // Skip if there is no shared message in there
593         if ($body == $attributes)
594                 return(false);
595
596         $link = "";
597         preg_match("/link='(.*?)'/ism", $attributes, $matches);
598         if ($matches[1] != "")
599                 $link = $matches[1];
600
601         preg_match('/link="(.*?)"/ism', $attributes, $matches);
602         if ($matches[1] != "")
603                 $link = $matches[1];
604
605         $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link);
606         if ($id == $link)
607                 return(false);
608
609         logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG);
610
611         require_once 'addon/appnet/AppDotNet.php';
612
613         $token        = get_pconfig($uid,'appnet','token');
614         $clientId     = get_pconfig($uid,'appnet','clientid');
615         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
616
617         $app = new AppDotNet($clientId, $clientSecret);
618         $app->setAccessToken($token);
619
620         try {
621                 $result = $app->repost($id);
622                 logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG);
623                 return true;
624         }
625         catch (AppDotNetException $e) {
626                 logger('appnet_is_repost: error doing repost '.$e->getMessage(), LOGGER_DEBUG);
627                 return false;
628         }
629 }
630
631 function appnet_fetchstream($a, $uid) {
632         require_once("addon/appnet/AppDotNet.php");
633         require_once('include/items.php');
634
635         $token = get_pconfig($uid,'appnet','token');
636         $clientId     = get_pconfig($uid,'appnet','clientid');
637         $clientSecret = get_pconfig($uid,'appnet','clientsecret');
638
639         $app = new AppDotNet($clientId, $clientSecret);
640         $app->setAccessToken($token);
641
642         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
643                 intval($uid));
644
645         if(count($r))
646                 $me = $r[0];
647         else {
648                 logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG);
649                 return;
650         }
651
652         $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1",
653                 intval($uid)
654         );
655
656         if(count($user))
657                 $user = $user[0];
658         else {
659                 logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG);
660                 return;
661         }
662
663         $ownid = get_pconfig($uid,'appnet','ownid');
664
665         // Fetch stream
666         $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
667                         "include_html" => false, "include_post_annotations" => true);
668
669         $lastid  = get_pconfig($uid, 'appnet', 'laststreamid');
670
671         if ($lastid <> "")
672                 $param["since_id"] = $lastid;
673
674         try {
675                 $stream = $app->getUserStream($param);
676         }
677         catch (AppDotNetException $e) {
678                 logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".$e->getMessage());
679         }
680
681         $stream = array_reverse($stream);
682         foreach ($stream AS $post) {
683                 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true);
684
685                 $item = item_store($postarray);
686                 logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item);
687
688                 $lastid = $post["id"];
689
690                 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
691                         $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread`
692                                 INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid`
693                                 WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item));
694
695                         if (count($r)) {
696                                 require_once('include/enotify.php');
697                                 notification(array(
698                                         'type'         => NOTIFY_COMMENT,
699                                         'notify_flags' => $user['notify-flags'],
700                                         'language'     => $user['language'],
701                                         'to_name'      => $user['username'],
702                                         'to_email'     => $user['email'],
703                                         'uid'          => $user['uid'],
704                                         'item'         => $postarray,
705                                         'link'         => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
706                                         'source_name'  => $postarray['author-name'],
707                                         'source_link'  => $postarray['author-link'],
708                                         'source_photo' => $postarray['author-avatar'],
709                                         'verb'         => ACTIVITY_POST,
710                                         'otype'        => 'item',
711                                         'parent'       => $r[0]["parent"],
712                                 ));
713                         }
714                 }
715         }
716
717         set_pconfig($uid, 'appnet', 'laststreamid', $lastid);
718
719         // Fetch mentions
720         $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
721                         "include_html" => false, "include_post_annotations" => true);
722
723         $lastid  = get_pconfig($uid, 'appnet', 'lastmentionid');
724
725         if ($lastid <> "")
726                 $param["since_id"] = $lastid;
727
728         try {
729                 $mentions = $app->getUserMentions("me", $param);
730         }
731         catch (AppDotNetException $e) {
732                 logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".$e->getMessage());
733         }
734
735         $mentions = array_reverse($mentions);
736         foreach ($mentions AS $post) {
737                 $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false);
738
739                 if (isset($postarray["id"]))
740                         $item = $postarray["id"];
741                 elseif (isset($postarray["body"])) {
742                         $item = item_store($postarray);
743                         logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item);
744                 } else
745                         $item = 0;
746
747                 $lastid = $post["id"];
748
749                 if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) {
750                         require_once('include/enotify.php');
751                         notification(array(
752                                 'type'         => NOTIFY_TAGSELF,
753                                 'notify_flags' => $user['notify-flags'],
754                                 'language'     => $user['language'],
755                                 'to_name'      => $user['username'],
756                                 'to_email'     => $user['email'],
757                                 'uid'          => $user['uid'],
758                                 'item'         => $postarray,
759                                 'link'         => $a->get_baseurl() . '/display/' . $user['nickname'] . '/' . $item,
760                                 'source_name'  => $postarray['author-name'],
761                                 'source_link'  => $postarray['author-link'],
762                                 'source_photo' => $postarray['author-avatar'],
763                                 'verb'         => ACTIVITY_TAG,
764                                 'otype'        => 'item'
765                         ));
766                 }
767         }
768
769         set_pconfig($uid, 'appnet', 'lastmentionid', $lastid);
770
771
772 /* To-Do
773         $param = array("interaction_actions" => "star");
774         $interactions = $app->getMyInteractions($param);
775         foreach ($interactions AS $interaction)
776                 appnet_dolike($a, $uid, $interaction);
777 */
778 }
779
780 function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true) {
781         require_once('include/items.php');
782
783         if ($post["machine_only"])
784                 return;
785
786         if ($post["is_deleted"])
787                 return;
788
789         $postarray = array();
790         $postarray['gravity'] = 0;
791         $postarray['uid'] = $uid;
792         $postarray['wall'] = 0;
793         $postarray['verb'] = ACTIVITY_POST;
794         $postarray['network'] =  dbesc(NETWORK_APPNET);
795         $postarray['uri'] = "adn::".$post["id"];
796
797         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
798                 dbesc($postarray['uri']),
799                 intval($uid)
800                 );
801
802         if (count($r))
803                 return($r[0]);
804
805         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
806                 dbesc($postarray['uri']),
807                 intval($uid)
808                 );
809
810         if (count($r))
811                 return($r[0]);
812
813         $postarray['parent-uri'] = "adn::".$post["thread_id"];
814         if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) {
815                 $postarray['thr-parent'] = "adn::".$post["reply_to"];
816
817                 // Complete the thread if the parent doesn't exists
818                 if ($threadcompletion) {
819                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
820                                 dbesc($postarray['thr-parent']),
821                                 intval($uid)
822                                 );
823                         if (!count($r)) {
824                                 require_once("addon/appnet/AppDotNet.php");
825
826                                 $token = get_pconfig($uid,'appnet','token');
827                                 $clientId     = get_pconfig($uid,'appnet','clientid');
828                                 $clientSecret = get_pconfig($uid,'appnet','clientsecret');
829
830                                 $app = new AppDotNet($clientId, $clientSecret);
831                                 $app->setAccessToken($token);
832
833                                 $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true,
834                                                 "include_html" => false, "include_post_annotations" => true);
835                                 try {
836                                         $thread = $app->getPostReplies($post["thread_id"], $param);
837                                 }
838                                 catch (AppDotNetException $e) {
839                                         logger("appnet_createpost: Error fetching thread for user ".$uid." ".$e->getMessage());
840                                 }
841                                 $thread = array_reverse($thread);
842                                 foreach ($thread AS $tpost) {
843                                         $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, $createuser, false);
844                                         $item = item_store($threadpost);
845                                 }
846                         }
847                 }
848         } else
849                 $postarray['thr-parent'] = $postarray['uri'];
850
851         $postarray['plink'] = $post["canonical_url"];
852
853         if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) {
854                 $postarray['owner-name'] = $post["user"]["name"];
855                 $postarray['owner-link'] = $post["user"]["canonical_url"];
856                 $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"];
857                 $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser);
858         } else {
859                 $postarray['owner-name'] = $me["name"];
860                 $postarray['owner-link'] = $me["url"];
861                 $postarray['owner-avatar'] = $me["thumb"];
862                 $postarray['contact-id'] = $me["id"];
863         }
864
865         $links = array();
866
867         if (is_array($post["repost_of"])) {
868                 $postarray['author-name'] = $post["repost_of"]["user"]["name"];
869                 $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"];
870                 $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"];
871
872                 $content = $post["repost_of"];
873         } else {
874                 $postarray['author-name'] = $postarray['owner-name'];
875                 $postarray['author-link'] = $postarray['owner-link'];
876                 $postarray['author-avatar'] = $postarray['owner-avatar'];
877
878                 $content = $post;
879         }
880
881         if (is_array($content["entities"])) {
882                 $converted = appnet_expand_entities($a, $content["text"], $content["entities"]);
883                 $postarray['body'] = $converted["body"];
884                 $postarray['tag'] = $converted["tags"];
885         } else
886                 $postarray['body'] = $content["text"];
887
888         if (sizeof($content["entities"]["links"]))
889                 foreach($content["entities"]["links"] AS $link) {
890                         $url = normalise_link($link["url"]);
891                         $links[$url] = $link["url"];
892                 }
893
894         if (sizeof($content["annotations"]))
895                 foreach($content["annotations"] AS $annotation) {
896                         if ($annotation[type] == "net.app.core.oembed") {
897                                 if (isset($annotation["value"]["embeddable_url"])) {
898                                         $url = normalise_link($annotation["value"]["embeddable_url"]);
899                                         if (isset($links[$url]))
900                                                 unset($links[$url]);
901                                 }
902                         } elseif ($annotation[type] == "com.friendica.post") {
903                                 // Nur zum Testen deaktiviert
904                                 //$links = array();
905                                 //if (isset($annotation["value"]["post-title"]))
906                                 //      $postarray['title'] = $annotation["value"]["post-title"];
907
908                                 //if (isset($annotation["value"]["post-body"]))
909                                 //      $postarray['body'] = $annotation["value"]["post-body"];
910
911                                 //if (isset($annotation["value"]["post-tag"]))
912                                 //      $postarray['tag'] = $annotation["value"]["post-tag"];
913
914                                 if (isset($annotation["value"]["author-name"]))
915                                         $postarray['author-name'] = $annotation["value"]["author-name"];
916
917                                 if (isset($annotation["value"]["author-link"]))
918                                         $postarray['author-link'] = $annotation["value"]["author-link"];
919
920                                 if (isset($annotation["value"]["author-avatar"]))
921                                         $postarray['author-avatar'] = $annotation["value"]["author-avatar"];
922                         }
923
924                 }
925
926         $page_info = "";
927
928         if (is_array($content["annotations"])) {
929                 $photo = appnet_expand_annotations($a, $content["annotations"]);
930                 if (($photo["large"] != "") AND ($photo["url"] != ""))
931                         $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]";
932                 elseif ($photo["url"] != "")
933                         $page_info = "\n[img]".$photo["url"]."[/img]";
934         } else
935                 $photo = array("url" => "", "large" => "");
936
937         if (sizeof($links)) {
938                 $link = array_pop($links);
939                 $url = "[url=".$link."]".$link."[/url]";
940
941                 $removedlink = trim(str_replace($url, "", $postarray['body']));
942
943                 if (($removedlink == "") OR strstr($postarray['body'], $removedlink))
944                         $postarray['body'] = $removedlink;
945
946                 $page_info = add_page_info($link, false, $photo["url"]);
947         }
948
949         $postarray['body'] .= $page_info;
950
951         $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]);
952         $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]);
953
954         $postarray['app'] = $post["source"]["name"];
955
956         return($postarray);
957 }
958
959 function appnet_expand_entities($a, $body, $entities) {
960
961         if (!function_exists('substr_unicode')) {
962                 function substr_unicode($str, $s, $l = null) {
963                         return join("", array_slice(
964                                 preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
965                 }
966         }
967
968         $tags_arr = array();
969         $replace = array();
970
971         foreach ($entities["mentions"] AS $mention) {
972                 $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]";
973                 $tags_arr["@".$mention["name"]] = $url;
974                 $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url);
975         }
976
977         foreach ($entities["hashtags"] AS $hashtag) {
978                 $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]";
979                 $tags_arr["#".$hashtag["name"]] = $url;
980                 $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url);
981         }
982
983         foreach ($entities["links"] AS $links) {
984                 $url = "[url=".$links["url"]."]".$links["text"]."[/url]";
985                 if (isset($links["amended_len"]) AND ($links["amended_len"] > $links["len"]))
986                         $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url);
987                 else
988                         $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url);
989         }
990
991
992         if (sizeof($replace)) {
993                 krsort($replace);
994                 foreach ($replace AS $entity) {
995                         $pre = substr_unicode($body, 0, $entity["pos"]);
996                         $post = substr_unicode($body, $entity["pos"] + $entity["len"]);
997                         //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8");
998                         //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8");
999
1000                         $body = $pre.$entity["replace"].$post;
1001                 }
1002         }
1003
1004         return(array("body" => $body, "tags" => implode($tags_arr, ",")));
1005 }
1006
1007 function appnet_expand_annotations($a, $annotations) {
1008         $photo = array("url" => "", "large" => "");
1009         foreach ($annotations AS $annotation) {
1010                 if (($annotation[type] == "net.app.core.oembed") AND
1011                         ($annotation["value"]["type"] == "photo")) {
1012                         if ($annotation["value"]["url"] != "")
1013                                 $photo["url"] = $annotation["value"]["url"];
1014
1015                         if ($annotation["value"]["thumbnail_large_url"] != "")
1016                                 $photo["large"] = $annotation["value"]["thumbnail_large_url"];
1017
1018                         //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != ""))
1019                         //      $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]";
1020                         //elseif ($annotation["value"]["url"] != "")
1021                         //      $embedded = "\n[img]".$annotation["value"]["url"]."[/img]";
1022                 }
1023         }
1024         return $photo;
1025 }
1026
1027 function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) {
1028         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1029                 intval($uid), dbesc("adn::".$contact["id"]));
1030
1031         if(!count($r) AND !$create_user)
1032                 return($me);
1033
1034
1035         if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
1036                 logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
1037                 return(-1);
1038         }
1039
1040         if(!count($r)) {
1041                 // create contact record
1042                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1043                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1044                                         `writable`, `blocked`, `readonly`, `pending` )
1045                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
1046                         intval($uid),
1047                         dbesc(datetime_convert()),
1048                         dbesc($contact["canonical_url"]),
1049                         dbesc(normalise_link($contact["canonical_url"])),
1050                         dbesc($contact["username"]."@app.net"),
1051                         dbesc("adn::".$contact["id"]),
1052                         dbesc(''),
1053                         dbesc("adn::".$contact["id"]),
1054                         dbesc($contact["name"]),
1055                         dbesc($contact["username"]),
1056                         dbesc($contact["avatar_image"]["url"]),
1057                         dbesc(NETWORK_APPNET),
1058                         intval(CONTACT_IS_FRIEND),
1059                         intval(1),
1060                         intval(1)
1061                 );
1062
1063                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1064                         dbesc("adn::".$contact["id"]),
1065                         intval($uid)
1066                         );
1067
1068                 if(! count($r))
1069                         return(false);
1070
1071                 $contact_id  = $r[0]['id'];
1072
1073                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1074                         intval($uid)
1075                 );
1076
1077                 if($g && intval($g[0]['def_gid'])) {
1078                         require_once('include/group.php');
1079                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
1080                 }
1081
1082                 require_once("Photo.php");
1083
1084                 $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id);
1085
1086                 q("UPDATE `contact` SET `photo` = '%s',
1087                                         `thumb` = '%s',
1088                                         `micro` = '%s',
1089                                         `name-date` = '%s',
1090                                         `uri-date` = '%s',
1091                                         `avatar-date` = '%s'
1092                                 WHERE `id` = %d",
1093                         dbesc($photos[0]),
1094                         dbesc($photos[1]),
1095                         dbesc($photos[2]),
1096                         dbesc(datetime_convert()),
1097                         dbesc(datetime_convert()),
1098                         dbesc(datetime_convert()),
1099                         intval($contact_id)
1100                 );
1101
1102         } else {
1103                 // update profile photos once every two weeks as we have no notification of when they change.
1104
1105                 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1106                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
1107
1108                 // check that we have all the photos, this has been known to fail on occasion
1109
1110                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
1111
1112                         logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG);
1113
1114                         require_once("Photo.php");
1115
1116                         $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']);
1117
1118                         q("UPDATE `contact` SET `photo` = '%s',
1119                                                 `thumb` = '%s',
1120                                                 `micro` = '%s',
1121                                                 `name-date` = '%s',
1122                                                 `uri-date` = '%s',
1123                                                 `avatar-date` = '%s',
1124                                                 `url` = '%s',
1125                                                 `nurl` = '%s',
1126                                                 `addr` = '%s',
1127                                                 `name` = '%s',
1128                                                 `nick` = '%s'
1129                                         WHERE `id` = %d",
1130                                 dbesc($photos[0]),
1131                                 dbesc($photos[1]),
1132                                 dbesc($photos[2]),
1133                                 dbesc(datetime_convert()),
1134                                 dbesc(datetime_convert()),
1135                                 dbesc(datetime_convert()),
1136                                 dbesc($contact["canonical_url"]),
1137                                 dbesc(normalise_link($contact["canonical_url"])),
1138                                 dbesc($contact["username"]."@app.net"),
1139                                 dbesc($contact["name"]),
1140                                 dbesc($contact["username"]),
1141                                 intval($r[0]['id'])
1142                         );
1143                 }
1144         }
1145
1146         return($r[0]["id"]);
1147 }
1148
1149 function appnet_cron($a,$b) {
1150         $last = get_config('appnet','last_poll');
1151
1152         $poll_interval = intval(get_config('appnet','poll_interval'));
1153         if(! $poll_interval)
1154                 $poll_interval = APPNET_DEFAULT_POLL_INTERVAL;
1155
1156         if($last) {
1157                 $next = $last + ($poll_interval * 60);
1158                 if($next > time()) {
1159                         logger('appnet_cron: poll intervall not reached');
1160                         return;
1161                 }
1162         }
1163         logger('appnet_cron: cron_start');
1164
1165         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
1166         if(count($r)) {
1167                 foreach($r as $rr) {
1168                         logger('appnet_cron: importing timeline from user '.$rr['uid']);
1169                         appnet_fetchstream($a, $rr["uid"]);
1170                 }
1171         }
1172
1173         logger('appnet_cron: cron_end');
1174
1175         set_config('appnet','last_poll', time());
1176 }