]> git.mxchange.org Git - friendica.git/blob - include/ostatus.php
New function "dba::select" to fetch table rows
[friendica.git] / include / ostatus.php
1 <?php
2 /**
3  * @file include/ostatus.php
4  */
5
6 use \Friendica\Core\Config;
7
8 require_once("include/Contact.php");
9 require_once("include/threads.php");
10 require_once("include/html2bbcode.php");
11 require_once("include/bbcode.php");
12 require_once("include/items.php");
13 require_once("mod/share.php");
14 require_once("include/enotify.php");
15 require_once("include/socgraph.php");
16 require_once("include/Photo.php");
17 require_once("include/Scrape.php");
18 require_once("include/follow.php");
19 require_once("include/api.php");
20 require_once("mod/proxy.php");
21 require_once("include/xml.php");
22
23 /**
24  * @brief This class contain functions for the OStatus protocol
25  *
26  */
27 class ostatus {
28         const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
29         const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
30         const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
31
32         /**
33          * @brief Mix two paths together to possibly fix missing parts
34          *
35          * @param string $avatar Path to the avatar
36          * @param string $base Another path that is hopefully complete
37          *
38          * @return string fixed avatar path
39          */
40         public static function fix_avatar($avatar, $base) {
41                 $base_parts = parse_url($base);
42
43                 // Remove all parts that could create a problem
44                 unset($base_parts['path']);
45                 unset($base_parts['query']);
46                 unset($base_parts['fragment']);
47
48                 $avatar_parts = parse_url($avatar);
49
50                 // Now we mix them
51                 $parts = array_merge($base_parts, $avatar_parts);
52
53                 // And put them together again
54                 $scheme   = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
55                 $host     = isset($parts['host']) ? $parts['host'] : '';
56                 $port     = isset($parts['port']) ? ':' . $parts['port'] : '';
57                 $path     = isset($parts['path']) ? $parts['path'] : '';
58                 $query    = isset($parts['query']) ? '?' . $parts['query'] : '';
59                 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
60
61                 $fixed = $scheme.$host.$port.$path.$query.$fragment;
62
63                 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);
64
65                 return $fixed;
66         }
67
68         /**
69          * @brief Fetches author data
70          *
71          * @param object $xpath The xpath object
72          * @param object $context The xml context of the author detals
73          * @param array $importer user record of the importing user
74          * @param array $contact Called by reference, will contain the fetched contact
75          * @param bool $onlyfetch Only fetch the header without updating the contact entries
76          *
77          * @return array Array of author related entries for the item
78          */
79         private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
80
81                 $author = array();
82                 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
83                 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
84                 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
85
86                 $aliaslink = $author["author-link"];
87
88                 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
89                 if (is_object($alternate)) {
90                         foreach ($alternate AS $attributes) {
91                                 if (($attributes->name == "href") AND ($attributes->textContent != "")) {
92                                         $author["author-link"] = $attributes->textContent;
93                                 }
94                         }
95                 }
96
97                 $author["contact-id"] = $contact["id"];
98
99                 if ($author["author-link"] != "") {
100                         if ($aliaslink == "") {
101                                 $aliaslink = $author["author-link"];
102                         }
103
104                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
105                                 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
106                                 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
107                         if (dbm::is_result($r)) {
108                                 $contact = $r[0];
109                                 $author["contact-id"] = $r[0]["id"];
110                                 $author["author-link"] = $r[0]["url"];
111                         }
112                 } elseif ($addr != "") {
113                         // Should not happen
114                         $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `uid` = ? AND `addr` = ? AND `network` != ?",
115                                         $importer["uid"], $addr, NETWORK_STATUSNET);
116                         if (dbm::is_result($contact)) {
117                                 $author["contact-id"] = $contact["id"];
118                                 $author["author-link"] = $contact["url"];
119                         }
120                 }
121
122                 $avatarlist = array();
123                 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
124                 foreach($avatars AS $avatar) {
125                         $href = "";
126                         $width = 0;
127                         foreach($avatar->attributes AS $attributes) {
128                                 if ($attributes->name == "href")
129                                         $href = $attributes->textContent;
130                                 if ($attributes->name == "width")
131                                         $width = $attributes->textContent;
132                         }
133                         if (($width > 0) AND ($href != ""))
134                                 $avatarlist[$width] = $href;
135                 }
136                 if (count($avatarlist) > 0) {
137                         krsort($avatarlist);
138                         $author["author-avatar"] = self::fix_avatar(current($avatarlist), $author["author-link"]);
139                 }
140
141                 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
142                 if ($displayname != "")
143                         $author["author-name"] = $displayname;
144
145                 $author["owner-name"] = $author["author-name"];
146                 $author["owner-link"] = $author["author-link"];
147                 $author["owner-avatar"] = $author["author-avatar"];
148
149                 // Only update the contacts if it is an OStatus contact
150                 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
151
152                         // Update contact data
153
154                         // This query doesn't seem to work
155                         // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
156                         // if ($value != "")
157                         //      $contact["notify"] = $value;
158
159                         // This query doesn't seem to work as well - I hate these queries
160                         // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
161                         // if ($value != "")
162                         //      $contact["poll"] = $value;
163
164                         $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
165                         if ($value != "")
166                                 $contact["alias"] = $value;
167
168                         $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
169                         if ($value != "")
170                                 $contact["name"] = $value;
171
172                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
173                         if ($value != "")
174                                 $contact["nick"] = $value;
175
176                         $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
177                         if ($value != "")
178                                 $contact["about"] = html2bbcode($value);
179
180                         $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
181                         if ($value != "")
182                                 $contact["location"] = $value;
183
184                         if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
185                                 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
186
187                                 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
188
189                                 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
190                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
191                                         dbesc($contact["about"]), dbesc($contact["location"]),
192                                         dbesc(datetime_convert()), intval($contact["id"]));
193                         }
194
195                         if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
196                                 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
197
198                                 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
199                         }
200
201                         // Ensure that we are having this contact (with uid=0)
202                         $cid = get_contact($author["author-link"], 0);
203
204                         if ($cid) {
205                                 // Update it with the current values
206                                 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
207                                                 `about` = '%s', `location` = '%s',
208                                                 `success_update` = '%s', `last-update` = '%s'
209                                         WHERE `id` = %d",
210                                         dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
211                                         dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
212                                         dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
213
214                                 // Update the avatar
215                                 update_contact_avatar($author["author-avatar"], 0, $cid);
216                         }
217
218                         $contact["generation"] = 2;
219                         $contact["hide"] = false; // OStatus contacts are never hidden
220                         $contact["photo"] = $author["author-avatar"];
221                         $gcid = update_gcontact($contact);
222
223                         link_gcontact($gcid, $contact["uid"], $contact["id"]);
224                 }
225
226                 return($author);
227         }
228
229         /**
230          * @brief Fetches author data from a given XML string
231          *
232          * @param string $xml The XML
233          * @param array $importer user record of the importing user
234          *
235          * @return array Array of author related entries for the item
236          */
237         public static function salmon_author($xml, $importer) {
238
239                 if ($xml == "")
240                         return;
241
242                 $doc = new DOMDocument();
243                 @$doc->loadXML($xml);
244
245                 $xpath = new DomXPath($doc);
246                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
247                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
248                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
249                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
250                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
251                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
252                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
253                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
254
255                 $entries = $xpath->query('/atom:entry');
256
257                 foreach ($entries AS $entry) {
258                         // fetch the author
259                         $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
260                         return $author;
261                 }
262         }
263
264         /**
265          * @brief Read attributes from element
266          *
267          * @param object $element Element object
268          *
269          * @return array attributes
270          */
271         private static function read_attributes($element) {
272                 $attribute = array();
273
274                 foreach ($element->attributes AS $attributes) {
275                         $attribute[$attributes->name] = $attributes->textContent;
276                 }
277
278                 return $attribute;
279         }
280
281         /**
282          * @brief Imports an XML string containing OStatus elements
283          *
284          * @param string $xml The XML
285          * @param array $importer user record of the importing user
286          * @param $contact
287          * @param array $hub Called by reference, returns the fetched hub data
288          */
289         public static function import($xml,$importer,&$contact, &$hub) {
290                 /// @todo this function is too long. It has to be split in many parts
291
292                 logger("Import OStatus message", LOGGER_DEBUG);
293
294                 if ($xml == "") {
295                         return;
296                 }
297                 //$tempfile = tempnam(get_temppath(), "import");
298                 //file_put_contents($tempfile, $xml);
299
300                 $doc = new DOMDocument();
301                 @$doc->loadXML($xml);
302
303                 $xpath = new DomXPath($doc);
304                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
305                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
306                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
307                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
308                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
309                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
310                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
311                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
312
313                 $gub = "";
314                 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
315                 if (is_object($hub_attributes)) {
316                         foreach ($hub_attributes AS $hub_attribute) {
317                                 if ($hub_attribute->name == "href") {
318                                         $hub = $hub_attribute->textContent;
319                                         logger("Found hub ".$hub, LOGGER_DEBUG);
320                                 }
321                         }
322                 }
323                 $header = array();
324                 $header["uid"] = $importer["uid"];
325                 $header["network"] = NETWORK_OSTATUS;
326                 $header["type"] = "remote";
327                 $header["wall"] = 0;
328                 $header["origin"] = 0;
329                 $header["gravity"] = GRAVITY_PARENT;
330
331                 // it could either be a received post or a post we fetched by ourselves
332                 // depending on that, the first node is different
333                 $first_child = $doc->firstChild->tagName;
334
335                 if ($first_child == "feed") {
336                         $entries = $xpath->query('/atom:feed/atom:entry');
337                         $header["protocol"] = PROTOCOL_OSTATUS_FEED;
338                 } else {
339                         $entries = $xpath->query('/atom:entry');
340                         $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
341                 }
342                 $conversation = "";
343                 $conversationlist = array();
344                 $item_id = 0;
345
346                 // Reverse the order of the entries
347                 $entrylist = array();
348
349                 foreach ($entries AS $entry) {
350                         $entrylist[] = $entry;
351                 }
352                 foreach (array_reverse($entrylist) AS $entry) {
353
354                         $mention = false;
355
356                         // fetch the author
357                         if ($first_child == "feed") {
358                                 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
359                         } else {
360                                 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
361                         }
362                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
363                         if ($value != "") {
364                                 $nickname = $value;
365                         } else {
366                                 $nickname = $author["author-name"];
367                         }
368                         $item = array_merge($header, $author);
369
370                         // Now get the item
371                         $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
372
373                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
374                                 intval($importer["uid"]), dbesc($item["uri"]));
375                         if (dbm::is_result($r)) {
376                                 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
377                                 continue;
378                         }
379
380                         $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
381                         $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
382                         $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
383
384                         // Mastodon Content Warning
385                         if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
386                                 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
387
388                                 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
389                         }
390
391                         if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
392                                 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
393                                 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
394                         } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
395                                 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
396                         }
397                         $item["source"] = $xml;
398
399                         /// @TODO
400                         /// Delete a message
401                         if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
402                                 // ignore "Delete" messages (by now)
403                                 logger("Ignore delete message ".print_r($item, true));
404                                 continue;
405                         }
406
407                         if ($item["verb"] == ACTIVITY_JOIN) {
408                                 // ignore "Join" messages
409                                 logger("Ignore join message ".print_r($item, true));
410                                 continue;
411                         }
412
413                         if ($item["verb"] == ACTIVITY_FOLLOW) {
414                                 new_follower($importer, $contact, $item, $nickname);
415                                 continue;
416                         }
417
418                         if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
419                                 lose_follower($importer, $contact, $item, $dummy);
420                                 continue;
421                         }
422
423                         if ($item["verb"] == ACTIVITY_FAVORITE) {
424                                 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
425                                 logger("Favorite ".$orig_uri." ".print_r($item, true));
426
427                                 $item["verb"] = ACTIVITY_LIKE;
428                                 $item["parent-uri"] = $orig_uri;
429                                 $item["gravity"] = GRAVITY_LIKE;
430                         }
431
432                         if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
433                                 // Ignore "Unfavorite" message
434                                 logger("Ignore unfavorite message ".print_r($item, true));
435                                 continue;
436                         }
437
438                         // http://activitystrea.ms/schema/1.0/rsvp-yes
439                         if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
440                                 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
441                         }
442                         $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
443                         $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
444                         $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
445                         $item['conversation-uri'] = $conversation;
446
447                         $conv = $xpath->query('ostatus:conversation', $entry);
448                         if (is_object($conv->item(0))) {
449                                 foreach ($conv->item(0)->attributes AS $attributes) {
450                                         if ($attributes->name == "ref") {
451                                                 $item['conversation-uri'] = $attributes->textContent;
452                                         }
453                                         if ($attributes->name == "href") {
454                                                 $item['conversation-href'] = $attributes->textContent;
455                                         }
456                                 }
457                         }
458
459                         $related = "";
460
461                         $inreplyto = $xpath->query('thr:in-reply-to', $entry);
462                         if (is_object($inreplyto->item(0))) {
463                                 foreach ($inreplyto->item(0)->attributes AS $attributes) {
464                                         if ($attributes->name == "ref") {
465                                                 $item["parent-uri"] = $attributes->textContent;
466                                         }
467                                         if ($attributes->name == "href") {
468                                                 $related = $attributes->textContent;
469                                         }
470                                 }
471                         }
472
473                         $georsspoint = $xpath->query('georss:point', $entry);
474                         if ($georsspoint) {
475                                 $item["coord"] = $georsspoint->item(0)->nodeValue;
476                         }
477                         $categories = $xpath->query('atom:category', $entry);
478                         if ($categories) {
479                                 foreach ($categories AS $category) {
480                                         foreach ($category->attributes AS $attributes) {
481                                                 if ($attributes->name == "term") {
482                                                         $term = $attributes->textContent;
483                                                         if(strlen($item["tag"])) {
484                                                                 $item["tag"] .= ',';
485                                                         }
486                                                         $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
487                                                 }
488                                         }
489                                 }
490                         }
491
492                         $self = "";
493                         $enclosure = "";
494
495                         $links = $xpath->query('atom:link', $entry);
496                         if ($links) {
497                                 foreach ($links AS $link) {
498                                         $attribute = self::read_attributes($link);
499
500                                         if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
501                                                 switch ($attribute['rel']) {
502                                                         case "alternate":
503                                                                 $item["plink"] = $attribute['href'];
504                                                                 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
505                                                                         ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
506                                                                         $item["body"] .= add_page_info($attribute['href']);
507                                                                 }
508                                                                 break;
509                                                         case "ostatus:conversation":
510                                                                 $conversation = $attribute['href'];
511                                                                 $item['conversation-href'] = $conversation;
512                                                                 if (!isset($item['conversation-uri'])) {
513                                                                         $item['conversation-uri'] = $item['conversation-href'];
514                                                                 }
515                                                                 break;
516                                                         case "enclosure":
517                                                                 $enclosure = $attribute['href'];
518                                                                 if (strlen($item["attach"])) {
519                                                                         $item["attach"] .= ',';
520                                                                 }
521                                                                 if (!isset($attribute['length'])) {
522                                                                         $attribute['length'] = "0";
523                                                                 }
524                                                                 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
525                                                                 break;
526                                                         case "related":
527                                                                 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
528                                                                         if (!isset($item["parent-uri"])) {
529                                                                                 $item["parent-uri"] = $attribute['href'];
530                                                                         }
531                                                                         if ($related == "") {
532                                                                                 $related = $attribute['href'];
533                                                                         }
534                                                                 } else {
535                                                                         $item["body"] .= add_page_info($attribute['href']);
536                                                                 }
537                                                                 break;
538                                                         case "self":
539                                                                 $self = $attribute['href'];
540                                                                 break;
541                                                         case "mentioned":
542                                                                 // Notification check
543                                                                 if ($importer["nurl"] == normalise_link($attribute['href'])) {
544                                                                         $mention = true;
545                                                                 }
546                                                                 break;
547                                                 }
548                                         }
549                                 }
550                         }
551
552                         $local_id = "";
553                         $repeat_of = "";
554
555                         $notice_info = $xpath->query('statusnet:notice_info', $entry);
556                         if ($notice_info AND ($notice_info->length > 0)) {
557                                 foreach ($notice_info->item(0)->attributes AS $attributes) {
558                                         if ($attributes->name == "source") {
559                                                 $item["app"] = strip_tags($attributes->textContent);
560                                         }
561                                         if ($attributes->name == "local_id") {
562                                                 $local_id = $attributes->textContent;
563                                         }
564                                         if ($attributes->name == "repeat_of") {
565                                                 $repeat_of = $attributes->textContent;
566                                         }
567                                 }
568                         }
569
570                         // Is it a repeated post?
571                         if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
572                                 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
573
574                                 if (is_object($activityobjects)) {
575
576                                         $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
577                                         if (!isset($orig_uri)) {
578                                                 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
579                                         }
580                                         $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
581                                         if ($orig_links AND ($orig_links->length > 0)) {
582                                                 foreach ($orig_links->item(0)->attributes AS $attributes) {
583                                                         if ($attributes->name == "href") {
584                                                                 $orig_link = $attributes->textContent;
585                                                         }
586                                                 }
587                                         }
588                                         if (!isset($orig_link)) {
589                                                 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
590                                         }
591                                         if (!isset($orig_link)) {
592                                                 $orig_link =  self::convert_href($orig_uri);
593                                         }
594                                         $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
595                                         if (!isset($orig_body)) {
596                                                 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
597                                         }
598                                         $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
599                                         $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
600
601                                         $orig_contact = $contact;
602                                         $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
603
604                                         $item["author-name"] = $orig_author["author-name"];
605                                         $item["author-link"] = $orig_author["author-link"];
606                                         $item["author-avatar"] = $orig_author["author-avatar"];
607
608                                         $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
609                                         $item["created"] = $orig_created;
610                                         $item["edited"] = $orig_edited;
611
612                                         $item["uri"] = $orig_uri;
613
614                                         if (!isset($item["plink"])) {
615                                                 $item["plink"] = $orig_link;
616                                         }
617
618                                         $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
619
620                                         $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
621                                         if (!isset($item["object-type"])) {
622                                                 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
623                                         }
624
625                                         $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
626                                         if ($enclosures) {
627                                                 foreach ($enclosures AS $link) {
628                                                         $attribute = self::read_attributes($link);
629                                                         if ($href != "") {
630                                                                 $enclosure = $attribute['href'];
631                                                                 if (strlen($item["attach"])) {
632                                                                         $item["attach"] .= ',';
633                                                                 }
634                                                                 if (!isset($attribute['length'])) {
635                                                                         $attribute['length'] = "0";
636                                                                 }
637                                                                 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
638                                                         }
639                                                 }
640                                         }
641                                 }
642                         }
643
644                         //if ($enclosure != "")
645                         //      $item["body"] .= add_page_info($enclosure);
646
647                         if (isset($item["parent-uri"])) {
648                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
649                                         intval($importer["uid"]), dbesc($item["parent-uri"]));
650
651                                 // Only fetch missing stuff if it is a comment or reshare.
652                                 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
653                                         !dbm::is_result($r) AND ($related != "")) {
654                                         $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
655
656                                         if ($reply_path != $related) {
657                                                 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
658                                                 $reply_xml = fetch_url($reply_path);
659
660                                                 $reply_contact = $contact;
661                                                 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
662
663                                                 // After the import try to fetch the parent item again
664                                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
665                                                         intval($importer["uid"]), dbesc($item["parent-uri"]));
666                                         }
667                                 }
668                                 if (dbm::is_result($r)) {
669                                         $item["type"] = 'remote-comment';
670                                         $item["gravity"] = GRAVITY_COMMENT;
671                                 }
672                         } else {
673                                 $item["parent-uri"] = $item["uri"];
674                         }
675                         $item_id = self::completion($conversation, $importer["uid"], $item, $self);
676
677                         if (!$item_id) {
678                                 logger("Error storing item", LOGGER_DEBUG);
679                                 continue;
680                         }
681
682                         logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
683                 }
684         }
685
686         /**
687          * @brief Create an url out of an uri
688          *
689          * @param string $href URI in the format "parameter1:parameter1:..."
690          *
691          * @return string URL in the format http(s)://....
692          */
693         public static function convert_href($href) {
694                 $elements = explode(":",$href);
695
696                 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
697                         return $href;
698
699                 $server = explode(",", $elements[1]);
700                 $conversation = explode("=", $elements[2]);
701
702                 if ((count($elements) == 4) AND ($elements[2] == "post"))
703                         return "http://".$server[0]."/notice/".$elements[3];
704
705                 if ((count($conversation) != 2) OR ($conversation[1] ==""))
706                         return $href;
707
708                 if ($elements[3] == "objectType=thread")
709                         return "http://".$server[0]."/conversation/".$conversation[1];
710                 else
711                         return "http://".$server[0]."/notice/".$conversation[1];
712
713                 return $href;
714         }
715
716         /**
717          * @brief Checks if there are entries in conversations that aren't present on our side
718          *
719          * @param bool $mentions Fetch conversations where we are mentioned
720          * @param bool $override Override the interval setting
721          */
722         public static function check_conversations($mentions = false, $override = false) {
723                 $last = get_config('system','ostatus_last_poll');
724
725                 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
726                 if (!$poll_interval) {
727                         $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
728                 }
729
730                 // Don't poll if the interval is set negative
731                 if (($poll_interval < 0) AND !$override) {
732                         return;
733                 }
734
735                 if (!$mentions) {
736                         $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
737                         if (!$poll_timeframe) {
738                                 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
739                         }
740                 } else {
741                         $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
742                         if (!$poll_timeframe) {
743                                 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
744                         }
745                 }
746
747
748                 if ($last AND !$override) {
749                         $next = $last + ($poll_interval * 60);
750                         if ($next > time()) {
751                                 logger('poll interval not reached');
752                                 return;
753                         }
754                 }
755
756                 logger('cron_start');
757
758                 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
759
760                 if ($mentions) {
761                         $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
762                                                 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
763                                                 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
764                                                 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
765                 } else {
766                         $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
767                                                 WHERE `type` = 7 AND `term` > '%s'
768                                                 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
769                 }
770
771                 foreach ($conversations AS $conversation) {
772                         self::completion($conversation['url'], $conversation['uid']);
773                 }
774
775                 logger('cron_end');
776
777                 set_config('system','ostatus_last_poll', time());
778         }
779
780         /**
781          * @brief Updates the gcontact table with actor data from the conversation
782          *
783          * @param object $actor The actor object that contains the contact data
784          */
785         private function conv_fetch_actor($actor) {
786
787                 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
788                 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
789
790                 if (isset($actor->url))
791                         $contact["url"] = $actor->url;
792
793                 if (isset($actor->displayName))
794                         $contact["name"] = $actor->displayName;
795
796                 if (isset($actor->portablecontacts_net->displayName))
797                         $contact["name"] = $actor->portablecontacts_net->displayName;
798
799                 if (isset($actor->portablecontacts_net->preferredUsername))
800                         $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
801
802                 if (isset($actor->id))
803                         $contact["alias"] = $actor->id;
804
805                 if (isset($actor->summary))
806                         $contact["about"] = $actor->summary;
807
808                 if (isset($actor->portablecontacts_net->note))
809                         $contact["about"] = $actor->portablecontacts_net->note;
810
811                 if (isset($actor->portablecontacts_net->addresses->formatted))
812                         $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
813
814
815                 if (isset($actor->image->url))
816                         $contact["photo"] = $actor->image->url;
817
818                 if (isset($actor->image->width))
819                         $avatarwidth = $actor->image->width;
820
821                 if (is_array($actor->status_net->avatarLinks))
822                         foreach ($actor->status_net->avatarLinks AS $avatar) {
823                                 if ($avatarsize < $avatar->width) {
824                                         $contact["photo"] = $avatar->url;
825                                         $avatarsize = $avatar->width;
826                                 }
827                         }
828
829                 $contact["hide"] = false; // OStatus contacts are never hidden
830                 update_gcontact($contact);
831         }
832
833         /**
834          * @brief Fetches the conversation url for a given item link or conversation id
835          *
836          * @param string $self The link to the posting
837          * @param string $conversation_id The conversation id
838          *
839          * @return string The conversation url
840          */
841         private function fetch_conversation($self, $conversation_id = "") {
842
843                 if ($conversation_id != "") {
844                         $elements = explode(":", $conversation_id);
845
846                         if ((count($elements) <= 2) OR ($elements[0] != "tag"))
847                                 return $conversation_id;
848                 }
849
850                 if ($self == "")
851                         return "";
852
853                 $json = str_replace(".atom", ".json", $self);
854
855                 $raw = fetch_url($json);
856                 if ($raw == "")
857                         return "";
858
859                 $data = json_decode($raw);
860                 if (!is_object($data))
861                         return "";
862
863                 $conversation_id = $data->statusnet_conversation_id;
864
865                 $pos = strpos($self, "/api/statuses/show/");
866                 $base_url = substr($self, 0, $pos);
867
868                 return $base_url."/conversation/".$conversation_id;
869         }
870
871         /**
872          * @brief Fetches actor details of a given actor and user id
873          *
874          * @param string $actor The actor url
875          * @param int $uid The user id
876          * @param int $contact_id The default contact-id
877          *
878          * @return array Array with actor details
879          */
880         private function get_actor_details($actor, $uid, $contact_id) {
881
882                 $details = array();
883
884                 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
885                                         $uid, normalise_link($actor), NETWORK_STATUSNET);
886
887                 if (!$contact)
888                         $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
889                                         $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
890
891                 if ($contact) {
892                         logger("Found contact for url ".$actor, LOGGER_DEBUG);
893                         $details["contact_id"] = $contact[0]["id"];
894                         $details["network"] = $contact[0]["network"];
895
896                         $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
897                 } else {
898                         logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
899
900                         // Adding a global contact
901                         /// @TODO Use this data for the post
902                         $details["global_contact_id"] = get_contact($actor, 0);
903
904                         logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
905
906                         $details["contact_id"] = $contact_id;
907                         $details["network"] = NETWORK_OSTATUS;
908
909                         $details["not_following"] = true;
910                 }
911
912                 return $details;
913         }
914
915         /**
916          * @brief Stores an item and completes the thread
917          *
918          * @param string $conversation_url The URI of the conversation
919          * @param integer $uid The user id
920          * @param array $item Data of the item that is to be posted
921          *
922          * @return integer The item id of the posted item array
923          */
924         private function completion($conversation_url, $uid, $item = array(), $self = "") {
925
926                 /// @todo This function is totally ugly and has to be rewritten totally
927
928                 // Import all threads or only threads that were started by our followers?
929                 $all_threads = !get_config('system','ostatus_full_threads');
930
931                 $item_stored = -1;
932
933                 $conversation_url = self::fetch_conversation($self, $conversation_url);
934
935                 // If the thread shouldn't be completed then store the item and go away
936                 // Don't do a completion on liked content
937                 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
938                         ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
939                         $item_stored = item_store($item, $all_threads);
940                         return $item_stored;
941                 } elseif (count($item) > 0) {
942                         $item = store_conversation($item);
943                 }
944
945                 // Get the parent
946                 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
947                                 `item`.`verb`, `item`.`visible` FROM `term`
948                                 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
949                                 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
950                                 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
951                                 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
952
953 /*              2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
954
955                 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
956                                 (SELECT `parent` FROM `item` WHERE `id` IN
957                                         (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
958                                 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
959 */
960                 if ($parents)
961                         $parent = $parents[0];
962                 elseif (count($item) > 0) {
963                         $parent = $item;
964                         $parent["type"] = "remote";
965                         $parent["verb"] = ACTIVITY_POST;
966                         $parent["visible"] = 1;
967                 } else {
968                         // Preset the parent
969                         $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
970                         if (!$r)
971                                 return(-2);
972
973                         $parent = array();
974                         $parent["id"] = 0;
975                         $parent["parent"] = 0;
976                         $parent["uri"] = "";
977                         $parent["contact-id"] = $r[0]["id"];
978                         $parent["type"] = "remote";
979                         $parent["verb"] = ACTIVITY_POST;
980                         $parent["visible"] = 1;
981                 }
982
983                 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
984                 $pageno = 1;
985                 $items = array();
986
987                 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
988
989                 do {
990                         $conv_arr = z_fetch_url($conv."?page=".$pageno);
991
992                         // If it is a non-ssl site and there is an error, then try ssl or vice versa
993                         if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
994                                 $conv = str_replace("http://", "https://", $conv);
995                                 $conv_as = fetch_url($conv."?page=".$pageno);
996                         } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
997                                 $conv = str_replace("https://", "http://", $conv);
998                                 $conv_as = fetch_url($conv."?page=".$pageno);
999                         } else
1000                                 $conv_as = $conv_arr["body"];
1001
1002                         $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
1003                         $conv_as = json_decode($conv_as);
1004
1005                         $no_of_items = sizeof($items);
1006
1007                         if (@is_array($conv_as->items))
1008                                 foreach ($conv_as->items AS $single_item)
1009                                         $items[$single_item->id] = $single_item;
1010
1011                         if ($no_of_items == sizeof($items))
1012                                 break;
1013
1014                         $pageno++;
1015
1016                 } while (true);
1017
1018                 logger('fetching conversation done. Found '.count($items).' items');
1019
1020                 if (!sizeof($items)) {
1021                         if (count($item) > 0) {
1022                                 $item_stored = item_store($item, $all_threads);
1023
1024                                 if ($item_stored) {
1025                                         logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
1026                                         self::store_conversation($item_id, $conversation_url);
1027                                 }
1028
1029                                 return($item_stored);
1030                         } else
1031                                 return(-3);
1032                 }
1033
1034                 $items = array_reverse($items);
1035
1036                 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1037                 $importer = $r[0];
1038
1039                 $new_parent = true;
1040
1041                 foreach ($items as $single_conv) {
1042
1043                         // Update the gcontact table
1044                         self::conv_fetch_actor($single_conv->actor);
1045
1046                         // Test - remove before flight
1047                         //$tempfile = tempnam(get_temppath(), "conversation");
1048                         //file_put_contents($tempfile, json_encode($single_conv));
1049
1050                         $mention = false;
1051
1052                         if (isset($single_conv->object->id))
1053                                 $single_conv->id = $single_conv->object->id;
1054
1055                         $plink = self::convert_href($single_conv->id);
1056                         if (isset($single_conv->object->url))
1057                                 $plink = self::convert_href($single_conv->object->url);
1058
1059                         if (@!$single_conv->id)
1060                                 continue;
1061
1062                         logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1063
1064                         if ($first_id == "") {
1065                                 $first_id = $single_conv->id;
1066
1067                                 // The first post of the conversation isn't our first post. There are three options:
1068                                 // 1. Our conversation hasn't the "real" thread starter
1069                                 // 2. This first post is a post inside our thread
1070                                 // 3. This first post is a post inside another thread
1071                                 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1072
1073                                         $new_parent = true;
1074
1075                                         $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1076                                                                 (SELECT `parent` FROM `item`
1077                                                                         WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1078                                                 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1079                                         if ($new_parents) {
1080                                                 if ($new_parents[0]["parent"] == $parent["parent"]) {
1081                                                         // Option 2: This post is already present inside our thread - but not as thread starter
1082                                                         logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1083                                                         $first_id = $parent["uri"];
1084                                                 } else {
1085                                                         // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1086                                                         // For now just take the new parent.
1087                                                         $parent = $new_parents[0];
1088                                                         $first_id = $parent["uri"];
1089                                                         logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1090                                                 }
1091                                         } else {
1092                                                 // Option 1: We hadn't got the real thread starter
1093                                                 // We have to clean up our existing messages.
1094                                                 $parent["id"] = 0;
1095                                                 $parent["uri"] = $first_id;
1096                                                 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1097                                         }
1098                                 } elseif ($parent["uri"] == "") {
1099                                         $parent["id"] = 0;
1100                                         $parent["uri"] = $first_id;
1101                                 }
1102                         }
1103
1104                         $parent_uri = $parent["uri"];
1105
1106                         // "context" only seems to exist on older servers
1107                         if (isset($single_conv->context->inReplyTo->id)) {
1108                                 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1109                                                         intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1110                                 if ($parent_exists)
1111                                         $parent_uri = $single_conv->context->inReplyTo->id;
1112                         }
1113
1114                         // This is the current way
1115                         if (isset($single_conv->object->inReplyTo->id)) {
1116                                 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1117                                                         intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1118                                 if ($parent_exists)
1119                                         $parent_uri = $single_conv->object->inReplyTo->id;
1120                         }
1121
1122                         $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1123                                                         intval($uid), dbesc($single_conv->id),
1124                                                         dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1125                         if ($message_exists) {
1126                                 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1127
1128                                 if ($parent["id"] != 0) {
1129                                         $existing_message = $message_exists[0];
1130
1131                                         // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1132                                         /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1133                                         if ($existing_message["parent"] != $parent["id"]) {
1134                                                 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1135
1136                                                 // Update the parent id of the selected item
1137                                                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1138                                                         intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1139
1140                                                 // Update the parent uri in the thread - but only if it points to itself
1141                                                 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1142                                                         dbesc($parent_uri), intval($existing_message["id"]));
1143
1144                                                 // try to change all items of the same parent
1145                                                 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1146                                                         intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1147
1148                                                 // Update the parent uri in the thread - but only if it points to itself
1149                                                 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1150                                                         dbesc($parent["uri"]), intval($existing_message["parent"]));
1151
1152                                                 // Now delete the thread
1153                                                 delete_thread($existing_message["parent"]);
1154                                         }
1155                                 }
1156
1157                                 // The item we are having on the system is the one that we wanted to store via the item array
1158                                 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1159                                         $item = array();
1160                                         $item_stored = 0;
1161                                 }
1162
1163                                 continue;
1164                         }
1165
1166                         if (is_array($single_conv->to))
1167                                 foreach($single_conv->to AS $to)
1168                                         if ($importer["nurl"] == normalise_link($to->id))
1169                                                 $mention = true;
1170
1171                         $actor = $single_conv->actor->id;
1172                         if (isset($single_conv->actor->url))
1173                                 $actor = $single_conv->actor->url;
1174
1175                         $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1176
1177                         // Do we only want to import threads that were started by our contacts?
1178                         if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1179                                 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1180                                 continue;
1181                         }
1182
1183                         $arr = array();
1184                         $arr["network"] = $details["network"];
1185                         $arr["uri"] = $single_conv->id;
1186                         $arr["plink"] = $plink;
1187                         $arr["uid"] = $uid;
1188                         $arr["contact-id"] = $details["contact_id"];
1189                         $arr["parent-uri"] = $parent_uri;
1190                         $arr["created"] = $single_conv->published;
1191                         $arr["edited"] = $single_conv->published;
1192                         $arr["owner-name"] = $single_conv->actor->displayName;
1193                         if ($arr["owner-name"] == '')
1194                                 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1195                         if ($arr["owner-name"] == '')
1196                                 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1197
1198                         $arr["owner-link"] = $actor;
1199                         $arr["owner-avatar"] = self::fix_avatar($single_conv->actor->image->url, $arr["owner-link"]);
1200
1201                         $arr["author-name"] = $arr["owner-name"];
1202                         $arr["author-link"] = $arr["owner-link"];
1203                         $arr["author-avatar"] = $arr["owner-avatar"];
1204                         $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1205
1206                         if (isset($single_conv->status_net->conversation)) {
1207                                 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1208                         }
1209
1210                         if (isset($single_conv->status_net->notice_info->source))
1211                                 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1212                         elseif (isset($single_conv->statusnet->notice_info->source))
1213                                 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1214                         elseif (isset($single_conv->statusnet_notice_info->source))
1215                                 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1216                         elseif (isset($single_conv->provider->displayName))
1217                                 $arr["app"] = $single_conv->provider->displayName;
1218                         else
1219                                 $arr["app"] = "OStatus";
1220
1221
1222                         $arr["source"] = json_encode($single_conv);
1223                         $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1224
1225                         $arr["verb"] = $parent["verb"];
1226                         $arr["visible"] = $parent["visible"];
1227                         $arr["location"] = $single_conv->location->displayName;
1228                         $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1229
1230                         // Is it a reshared item?
1231                         if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1232                                 if (is_array($single_conv->object))
1233                                         $single_conv->object = $single_conv->object[0];
1234
1235                                 logger("Found reshared item ".$single_conv->object->id);
1236
1237                                 // $single_conv->object->context->conversation;
1238
1239                                 if (isset($single_conv->object->object->id))
1240                                         $arr["uri"] = $single_conv->object->object->id;
1241                                 else
1242                                         $arr["uri"] = $single_conv->object->id;
1243
1244                                 if (isset($single_conv->object->object->url))
1245                                         $plink = self::convert_href($single_conv->object->object->url);
1246                                 else
1247                                         $plink = self::convert_href($single_conv->object->url);
1248
1249                                 if (isset($single_conv->object->object->content))
1250                                         $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1251                                 else
1252                                         $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1253
1254                                 $arr["plink"] = $plink;
1255
1256                                 $arr["created"] = $single_conv->object->published;
1257                                 $arr["edited"] = $single_conv->object->published;
1258
1259                                 $arr["author-name"] = $single_conv->object->actor->displayName;
1260                                 if ($arr["owner-name"] == '') {
1261                                         $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1262                                 }
1263                                 $arr["author-link"] = $single_conv->object->actor->url;
1264                                 $arr["author-avatar"] = self::fix_avatar($single_conv->object->actor->image->url, $arr["author-link"]);
1265
1266                                 $arr["app"] = $single_conv->object->provider->displayName."#";
1267                                 //$arr["verb"] = $single_conv->object->verb;
1268
1269                                 $arr["location"] = $single_conv->object->location->displayName;
1270                                 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1271                         }
1272
1273                         if ($arr["location"] == "")
1274                                 unset($arr["location"]);
1275
1276                         if ($arr["coord"] == "")
1277                                 unset($arr["coord"]);
1278
1279                         // Copy fields from given item array
1280                         if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] ==  $single_conv->id))) {
1281                                 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1282                                                         "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1283                                                         "title", "attach", "app", "type", "location", "contact-id", "uri");
1284                                 foreach ($copy_fields AS $field)
1285                                         if (isset($item[$field]))
1286                                                 $arr[$field] = $item[$field];
1287
1288                         }
1289
1290                         $newitem = item_store($arr);
1291                         if (!$newitem) {
1292                                 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1293                                 continue;
1294                         }
1295
1296                         if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1297                                 $item = array();
1298                                 $item_stored = $newitem;
1299                         }
1300
1301                         logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1302
1303                         // Add the conversation entry (but don't fetch the whole conversation)
1304                         self::store_conversation($newitem, $conversation_url);
1305
1306                         // If the newly created item is the top item then change the parent settings of the thread
1307                         // This shouldn't happen anymore. This is supposed to be absolote.
1308                         if ($arr["uri"] == $first_id) {
1309                                 logger('setting new parent to id '.$newitem);
1310                                 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1311                                         intval($uid), intval($newitem));
1312                                 if ($new_parents)
1313                                         $parent = $new_parents[0];
1314                         }
1315                 }
1316
1317                 if (($item_stored < 0) AND (count($item) > 0)) {
1318
1319                         if (get_config('system','ostatus_full_threads')) {
1320                                 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1321                                 if ($details["not_following"]) {
1322                                         logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1323                                         return false;
1324                                 }
1325                         }
1326
1327                         $item_stored = item_store($item, $all_threads);
1328                         if ($item_stored) {
1329                                 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1330                                 self::store_conversation($item_stored, $conversation_url);
1331                         }
1332                 }
1333
1334                 return($item_stored);
1335         }
1336
1337         /**
1338          * @brief Stores conversation data into the database
1339          *
1340          * @param integer $itemid The id of the item
1341          * @param string $conversation_url The uri of the conversation
1342          */
1343         private function store_conversation($itemid, $conversation_url) {
1344
1345                 $conversation_url = self::convert_href($conversation_url);
1346
1347                 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1348                 if (!$messages)
1349                         return;
1350                 $message = $messages[0];
1351
1352                 // Store conversation url if not done before
1353                 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1354                         intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1355
1356                 if (!$conversation) {
1357                         $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1358                                 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1359                                 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1360                         logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1361                 }
1362         }
1363
1364         /**
1365          * @brief Checks if the current post is a reshare
1366          *
1367          * @param array $item The item array of thw post
1368          *
1369          * @return string The guid if the post is a reshare
1370          */
1371         private function get_reshared_guid($item) {
1372                 $body = trim($item["body"]);
1373
1374                 // Skip if it isn't a pure repeated messages
1375                 // Does it start with a share?
1376                 if (strpos($body, "[share") > 0)
1377                         return("");
1378
1379                 // Does it end with a share?
1380                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1381                         return("");
1382
1383                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1384                 // Skip if there is no shared message in there
1385                 if ($body == $attributes)
1386                         return(false);
1387
1388                 $guid = "";
1389                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1390                 if ($matches[1] != "")
1391                         $guid = $matches[1];
1392
1393                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1394                 if ($matches[1] != "")
1395                         $guid = $matches[1];
1396
1397                 return $guid;
1398         }
1399
1400         /**
1401          * @brief Cleans the body of a post if it contains picture links
1402          *
1403          * @param string $body The body
1404          *
1405          * @return string The cleaned body
1406          */
1407         private function format_picture_post($body) {
1408                 $siteinfo = get_attached_data($body);
1409
1410                 if (($siteinfo["type"] == "photo")) {
1411                         if (isset($siteinfo["preview"]))
1412                                 $preview = $siteinfo["preview"];
1413                         else
1414                                 $preview = $siteinfo["image"];
1415
1416                         // Is it a remote picture? Then make a smaller preview here
1417                         $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1418
1419                         // Is it a local picture? Then make it smaller here
1420                         $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1421                         $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1422
1423                         if (isset($siteinfo["url"]))
1424                                 $url = $siteinfo["url"];
1425                         else
1426                                 $url = $siteinfo["image"];
1427
1428                         $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1429                 }
1430
1431                 return $body;
1432         }
1433
1434         /**
1435          * @brief Adds the header elements to the XML document
1436          *
1437          * @param object $doc XML document
1438          * @param array $owner Contact data of the poster
1439          *
1440          * @return object header root element
1441          */
1442         private function add_header($doc, $owner) {
1443
1444                 $a = get_app();
1445
1446                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1447                 $doc->appendChild($root);
1448
1449                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1450                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1451                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1452                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1453                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1454                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1455                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1456                 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1457
1458                 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1459                 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1460                 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1461                 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1462                 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1463                 xml::add_element($doc, $root, "logo", $owner["photo"]);
1464                 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1465
1466                 $author = self::add_author($doc, $owner);
1467                 $root->appendChild($author);
1468
1469                 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1470                 xml::add_element($doc, $root, "link", "", $attributes);
1471
1472                 /// @TODO We have to find out what this is
1473                 /// $attributes = array("href" => App::get_baseurl()."/sup",
1474                 ///             "rel" => "http://api.friendfeed.com/2008/03#sup",
1475                 ///             "type" => "application/json");
1476                 /// xml::add_element($doc, $root, "link", "", $attributes);
1477
1478                 self::hublinks($doc, $root);
1479
1480                 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1481                 xml::add_element($doc, $root, "link", "", $attributes);
1482
1483                 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1484                 xml::add_element($doc, $root, "link", "", $attributes);
1485
1486                 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1487                 xml::add_element($doc, $root, "link", "", $attributes);
1488
1489                 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1490                                 "rel" => "self", "type" => "application/atom+xml");
1491                 xml::add_element($doc, $root, "link", "", $attributes);
1492
1493                 return $root;
1494         }
1495
1496         /**
1497          * @brief Add the link to the push hubs to the XML document
1498          *
1499          * @param object $doc XML document
1500          * @param object $root XML root element where the hub links are added
1501          */
1502         public static function hublinks($doc, $root) {
1503                 $hub = get_config('system','huburl');
1504
1505                 $hubxml = '';
1506                 if(strlen($hub)) {
1507                         $hubs = explode(',', $hub);
1508                         if(count($hubs)) {
1509                                 foreach($hubs as $h) {
1510                                         $h = trim($h);
1511                                         if(! strlen($h))
1512                                                 continue;
1513                                         if ($h === '[internal]')
1514                                                 $h = App::get_baseurl() . '/pubsubhubbub';
1515                                         xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1516                                 }
1517                         }
1518                 }
1519         }
1520
1521         /**
1522          * @brief Adds attachement data to the XML document
1523          *
1524          * @param object $doc XML document
1525          * @param object $root XML root element where the hub links are added
1526          * @param array $item Data of the item that is to be posted
1527          */
1528         private function get_attachment($doc, $root, $item) {
1529                 $o = "";
1530                 $siteinfo = get_attached_data($item["body"]);
1531
1532                 switch ($siteinfo["type"]) {
1533                         case 'photo':
1534                                 $imgdata = get_photo_info($siteinfo["image"]);
1535                                 $attributes = array("rel" => "enclosure",
1536                                                 "href" => $siteinfo["image"],
1537                                                 "type" => $imgdata["mime"],
1538                                                 "length" => intval($imgdata["size"]));
1539                                 xml::add_element($doc, $root, "link", "", $attributes);
1540                                 break;
1541                         case 'video':
1542                                 $attributes = array("rel" => "enclosure",
1543                                                 "href" => $siteinfo["url"],
1544                                                 "type" => "text/html; charset=UTF-8",
1545                                                 "length" => "",
1546                                                 "title" => $siteinfo["title"]);
1547                                 xml::add_element($doc, $root, "link", "", $attributes);
1548                                 break;
1549                         default:
1550                                 break;
1551                 }
1552
1553                 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1554                         $imgdata = get_photo_info($siteinfo["image"]);
1555                         $attributes = array("rel" => "enclosure",
1556                                         "href" => $siteinfo["image"],
1557                                         "type" => $imgdata["mime"],
1558                                         "length" => intval($imgdata["size"]));
1559
1560                         xml::add_element($doc, $root, "link", "", $attributes);
1561                 }
1562
1563                 $arr = explode('[/attach],', $item['attach']);
1564                 if (count($arr)) {
1565                         foreach ($arr as $r) {
1566                                 $matches = false;
1567                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1568                                 if ($cnt) {
1569                                         $attributes = array("rel" => "enclosure",
1570                                                         "href" => $matches[1],
1571                                                         "type" => $matches[3]);
1572
1573                                         if (intval($matches[2])) {
1574                                                 $attributes["length"] = intval($matches[2]);
1575                                         }
1576                                         if (trim($matches[4]) != "") {
1577                                                 $attributes["title"] = trim($matches[4]);
1578                                         }
1579                                         xml::add_element($doc, $root, "link", "", $attributes);
1580                                 }
1581                         }
1582                 }
1583         }
1584
1585         /**
1586          * @brief Adds the author element to the XML document
1587          *
1588          * @param object $doc XML document
1589          * @param array $owner Contact data of the poster
1590          *
1591          * @return object author element
1592          */
1593         private function add_author($doc, $owner) {
1594
1595                 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1596                 if ($r)
1597                         $profile = $r[0];
1598
1599                 $author = $doc->createElement("author");
1600                 xml::add_element($doc, $author, "id", $owner["url"]);
1601                 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1602                 xml::add_element($doc, $author, "uri", $owner["url"]);
1603                 xml::add_element($doc, $author, "name", $owner["nick"]);
1604                 xml::add_element($doc, $author, "email", $owner["addr"]);
1605                 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1606
1607                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1608                 xml::add_element($doc, $author, "link", "", $attributes);
1609
1610                 $attributes = array(
1611                                 "rel" => "avatar",
1612                                 "type" => "image/jpeg", // To-Do?
1613                                 "media:width" => 175,
1614                                 "media:height" => 175,
1615                                 "href" => $owner["photo"]);
1616                 xml::add_element($doc, $author, "link", "", $attributes);
1617
1618                 if (isset($owner["thumb"])) {
1619                         $attributes = array(
1620                                         "rel" => "avatar",
1621                                         "type" => "image/jpeg", // To-Do?
1622                                         "media:width" => 80,
1623                                         "media:height" => 80,
1624                                         "href" => $owner["thumb"]);
1625                         xml::add_element($doc, $author, "link", "", $attributes);
1626                 }
1627
1628                 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1629                 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1630                 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1631
1632                 if (trim($owner["location"]) != "") {
1633                         $element = $doc->createElement("poco:address");
1634                         xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1635                         $author->appendChild($element);
1636                 }
1637
1638                 if (trim($profile["homepage"]) != "") {
1639                         $urls = $doc->createElement("poco:urls");
1640                         xml::add_element($doc, $urls, "poco:type", "homepage");
1641                         xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1642                         xml::add_element($doc, $urls, "poco:primary", "true");
1643                         $author->appendChild($urls);
1644                 }
1645
1646                 if (count($profile)) {
1647                         xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1648                         xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1649                 }
1650
1651                 if ($profile["publish"]) {
1652                         xml::add_element($doc, $author, "mastodon:scope", "public");
1653                 }
1654                 return $author;
1655         }
1656
1657         /**
1658          * @TODO Picture attachments should look like this:
1659          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1660          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1661          *
1662         */
1663
1664         /**
1665          * @brief Returns the given activity if present - otherwise returns the "post" activity
1666          *
1667          * @param array $item Data of the item that is to be posted
1668          *
1669          * @return string activity
1670          */
1671         function construct_verb($item) {
1672                 if ($item['verb'])
1673                         return $item['verb'];
1674                 return ACTIVITY_POST;
1675         }
1676
1677         /**
1678          * @brief Returns the given object type if present - otherwise returns the "note" object type
1679          *
1680          * @param array $item Data of the item that is to be posted
1681          *
1682          * @return string Object type
1683          */
1684         function construct_objecttype($item) {
1685                 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1686                         return $item['object-type'];
1687                 return ACTIVITY_OBJ_NOTE;
1688         }
1689
1690         /**
1691          * @brief Adds an entry element to the XML document
1692          *
1693          * @param object $doc XML document
1694          * @param array $item Data of the item that is to be posted
1695          * @param array $owner Contact data of the poster
1696          * @param bool $toplevel
1697          *
1698          * @return object Entry element
1699          */
1700         private function entry($doc, $item, $owner, $toplevel = false) {
1701                 $repeated_guid = self::get_reshared_guid($item);
1702                 if ($repeated_guid != "")
1703                         $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1704
1705                 if ($xml)
1706                         return $xml;
1707
1708                 if ($item["verb"] == ACTIVITY_LIKE) {
1709                         return self::like_entry($doc, $item, $owner, $toplevel);
1710                 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1711                         return self::follow_entry($doc, $item, $owner, $toplevel);
1712                 } else {
1713                         return self::note_entry($doc, $item, $owner, $toplevel);
1714                 }
1715         }
1716
1717         /**
1718          * @brief Adds a source entry to the XML document
1719          *
1720          * @param object $doc XML document
1721          * @param array $contact Array of the contact that is added
1722          *
1723          * @return object Source element
1724          */
1725         private function source_entry($doc, $contact) {
1726                 $source = $doc->createElement("source");
1727                 xml::add_element($doc, $source, "id", $contact["poll"]);
1728                 xml::add_element($doc, $source, "title", $contact["name"]);
1729                 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1730                                                                 "type" => "text/html",
1731                                                                 "href" => $contact["alias"]));
1732                 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1733                                                                 "type" => "application/atom+xml",
1734                                                                 "href" => $contact["poll"]));
1735                 xml::add_element($doc, $source, "icon", $contact["photo"]);
1736                 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1737
1738                 return $source;
1739         }
1740
1741         /**
1742          * @brief Fetches contact data from the contact or the gcontact table
1743          *
1744          * @param string $url URL of the contact
1745          * @param array $owner Contact data of the poster
1746          *
1747          * @return array Contact array
1748          */
1749         private function contact_entry($url, $owner) {
1750
1751                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1752                         dbesc(normalise_link($url)), intval($owner["uid"]));
1753                 if ($r) {
1754                         $contact = $r[0];
1755                         $contact["uid"] = -1;
1756                 }
1757
1758                 if (!$r) {
1759                         $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1760                                 dbesc(normalise_link($url)));
1761                         if ($r) {
1762                                 $contact = $r[0];
1763                                 $contact["uid"] = -1;
1764                                 $contact["success_update"] = $contact["updated"];
1765                         }
1766                 }
1767
1768                 if (!$r)
1769                         $contact = owner;
1770
1771                 if (!isset($contact["poll"])) {
1772                         $data = probe_url($url);
1773                         $contact["poll"] = $data["poll"];
1774
1775                         if (!$contact["alias"])
1776                                 $contact["alias"] = $data["alias"];
1777                 }
1778
1779                 if (!isset($contact["alias"]))
1780                         $contact["alias"] = $contact["url"];
1781
1782                 return $contact;
1783         }
1784
1785         /**
1786          * @brief Adds an entry element with reshared content
1787          *
1788          * @param object $doc XML document
1789          * @param array $item Data of the item that is to be posted
1790          * @param array $owner Contact data of the poster
1791          * @param $repeated_guid
1792          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1793          *
1794          * @return object Entry element
1795          */
1796         private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1797
1798                 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1799                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1800                 }
1801
1802                 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1803
1804                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1805                         intval($owner["uid"]), dbesc($repeated_guid),
1806                         dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1807                 if ($r)
1808                         $repeated_item = $r[0];
1809                 else
1810                         return false;
1811
1812                 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1813
1814                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1815
1816                 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1817
1818                 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1819
1820                 $as_object = $doc->createElement("activity:object");
1821
1822                 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1823
1824                 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1825
1826                 $author = self::add_author($doc, $contact);
1827                 $as_object->appendChild($author);
1828
1829                 $as_object2 = $doc->createElement("activity:object");
1830
1831                 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1832
1833                 $title = sprintf("New comment by %s", $contact["nick"]);
1834
1835                 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1836
1837                 $as_object->appendChild($as_object2);
1838
1839                 self::entry_footer($doc, $as_object, $item, $owner, false);
1840
1841                 $source = self::source_entry($doc, $contact);
1842
1843                 $as_object->appendChild($source);
1844
1845                 $entry->appendChild($as_object);
1846
1847                 self::entry_footer($doc, $entry, $item, $owner);
1848
1849                 return $entry;
1850         }
1851
1852         /**
1853          * @brief Adds an entry element with a "like"
1854          *
1855          * @param object $doc XML document
1856          * @param array $item Data of the item that is to be posted
1857          * @param array $owner Contact data of the poster
1858          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1859          *
1860          * @return object Entry element with "like"
1861          */
1862         private function like_entry($doc, $item, $owner, $toplevel) {
1863
1864                 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1865                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1866                 }
1867
1868                 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1869
1870                 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1871                 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1872
1873                 $as_object = $doc->createElement("activity:object");
1874
1875                 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1876                         dbesc($item["thr-parent"]), intval($item["uid"]));
1877                 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1878
1879                 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1880
1881                 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1882
1883                 $entry->appendChild($as_object);
1884
1885                 self::entry_footer($doc, $entry, $item, $owner);
1886
1887                 return $entry;
1888         }
1889
1890         /**
1891          * @brief Adds the person object element to the XML document
1892          *
1893          * @param object $doc XML document
1894          * @param array $owner Contact data of the poster
1895          * @param array $contact Contact data of the target
1896          *
1897          * @return object author element
1898          */
1899         private function add_person_object($doc, $owner, $contact) {
1900
1901                 $object = $doc->createElement("activity:object");
1902                 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1903
1904                 if ($contact['network'] == NETWORK_PHANTOM) {
1905                         xml::add_element($doc, $object, "id", $contact['url']);
1906                         return $object;
1907                 }
1908
1909                 xml::add_element($doc, $object, "id", $contact["alias"]);
1910                 xml::add_element($doc, $object, "title", $contact["nick"]);
1911
1912                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1913                 xml::add_element($doc, $object, "link", "", $attributes);
1914
1915                 $attributes = array(
1916                                 "rel" => "avatar",
1917                                 "type" => "image/jpeg", // To-Do?
1918                                 "media:width" => 175,
1919                                 "media:height" => 175,
1920                                 "href" => $contact["photo"]);
1921                 xml::add_element($doc, $object, "link", "", $attributes);
1922
1923                 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1924                 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1925
1926                 if (trim($contact["location"]) != "") {
1927                         $element = $doc->createElement("poco:address");
1928                         xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1929                         $object->appendChild($element);
1930                 }
1931
1932                 return $object;
1933         }
1934
1935         /**
1936          * @brief Adds a follow/unfollow entry element
1937          *
1938          * @param object $doc XML document
1939          * @param array $item Data of the follow/unfollow message
1940          * @param array $owner Contact data of the poster
1941          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1942          *
1943          * @return object Entry element
1944          */
1945         private function follow_entry($doc, $item, $owner, $toplevel) {
1946
1947                 $item["id"] = $item["parent"] = 0;
1948                 $item["created"] = $item["edited"] = date("c");
1949                 $item["private"] = true;
1950
1951                 $contact = Probe::uri($item['follow']);
1952
1953                 if ($contact['alias'] == '') {
1954                         $contact['alias'] = $contact["url"];
1955                 } else {
1956                         $item['follow'] = $contact['alias'];
1957                 }
1958
1959                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1960                         intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1961
1962                 if (dbm::is_result($r)) {
1963                         $connect_id = $r[0]['id'];
1964                 } else {
1965                         $connect_id = 0;
1966                 }
1967
1968                 if ($item['verb'] == ACTIVITY_FOLLOW) {
1969                         $message = t('%s is now following %s.');
1970                         $title = t('following');
1971                         $action = "subscription";
1972                 } else {
1973                         $message = t('%s stopped following %s.');
1974                         $title = t('stopped following');
1975                         $action = "unfollow";
1976                 }
1977
1978                 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1979                                 'tag:'.get_app()->get_hostname().
1980                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1981                                 ':person:'.$connect_id.':'.$item['created'];
1982
1983                 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1984
1985                 self::entry_header($doc, $entry, $owner, $toplevel);
1986
1987                 self::entry_content($doc, $entry, $item, $owner, $title);
1988
1989                 $object = self::add_person_object($doc, $owner, $contact);
1990                 $entry->appendChild($object);
1991
1992                 self::entry_footer($doc, $entry, $item, $owner);
1993
1994                 return $entry;
1995         }
1996
1997         /**
1998          * @brief Adds a regular entry element
1999          *
2000          * @param object $doc XML document
2001          * @param array $item Data of the item that is to be posted
2002          * @param array $owner Contact data of the poster
2003          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2004          *
2005          * @return object Entry element
2006          */
2007         private function note_entry($doc, $item, $owner, $toplevel) {
2008
2009                 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
2010                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
2011                 }
2012
2013                 $title = self::entry_header($doc, $entry, $owner, $toplevel);
2014
2015                 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
2016
2017                 self::entry_content($doc, $entry, $item, $owner, $title);
2018
2019                 self::entry_footer($doc, $entry, $item, $owner);
2020
2021                 return $entry;
2022         }
2023
2024         /**
2025          * @brief Adds a header element to the XML document
2026          *
2027          * @param object $doc XML document
2028          * @param object $entry The entry element where the elements are added
2029          * @param array $owner Contact data of the poster
2030          * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2031          *
2032          * @return string The title for the element
2033          */
2034         private function entry_header($doc, &$entry, $owner, $toplevel) {
2035                 /// @todo Check if this title stuff is really needed (I guess not)
2036                 if (!$toplevel) {
2037                         $entry = $doc->createElement("entry");
2038                         $title = sprintf("New note by %s", $owner["nick"]);
2039                 } else {
2040                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2041
2042                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2043                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2044                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2045                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2046                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2047                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2048                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2049                         $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2050
2051                         $author = self::add_author($doc, $owner);
2052                         $entry->appendChild($author);
2053
2054                         $title = sprintf("New comment by %s", $owner["nick"]);
2055                 }
2056                 return $title;
2057         }
2058
2059         /**
2060          * @brief Adds elements to the XML document
2061          *
2062          * @param object $doc XML document
2063          * @param object $entry Entry element where the content is added
2064          * @param array $item Data of the item that is to be posted
2065          * @param array $owner Contact data of the poster
2066          * @param string $title Title for the post
2067          * @param string $verb The activity verb
2068          * @param bool $complete Add the "status_net" element?
2069          */
2070         private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2071
2072                 if ($verb == "")
2073                         $verb = self::construct_verb($item);
2074
2075                 xml::add_element($doc, $entry, "id", $item["uri"]);
2076                 xml::add_element($doc, $entry, "title", $title);
2077
2078                 $body = self::format_picture_post($item['body']);
2079
2080                 if ($item['title'] != "")
2081                         $body = "[b]".$item['title']."[/b]\n\n".$body;
2082
2083                 $body = bbcode($body, false, false, 7);
2084
2085                 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2086
2087                 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2088                                                                 "href" => App::get_baseurl()."/display/".$item["guid"]));
2089
2090                 if ($complete AND ($item["id"] > 0))
2091                         xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2092
2093                 xml::add_element($doc, $entry, "activity:verb", $verb);
2094
2095                 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2096                 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2097         }
2098
2099         /**
2100          * @brief Adds the elements at the foot of an entry to the XML document
2101          *
2102          * @param object $doc XML document
2103          * @param object $entry The entry element where the elements are added
2104          * @param array $item Data of the item that is to be posted
2105          * @param array $owner Contact data of the poster
2106          * @param $complete
2107          */
2108         private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2109
2110                 $mentioned = array();
2111
2112                 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2113                         $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2114                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2115
2116                         $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2117                                         intval($owner["uid"]),
2118                                         dbesc($parent_item));
2119                         if ($thrparent) {
2120                                 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2121                                 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2122                                 $parent_plink = $thrparent[0]["plink"];
2123                         } else {
2124                                 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2125                                 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2126                                 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2127                         }
2128
2129                         $attributes = array(
2130                                         "ref" => $parent_item,
2131                                         "href" => $parent_plink);
2132                         xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2133
2134                         $attributes = array(
2135                                         "rel" => "related",
2136                                         "href" => $parent_plink);
2137                         xml::add_element($doc, $entry, "link", "", $attributes);
2138                 }
2139
2140                 if (intval($item["parent"]) > 0) {
2141                         $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2142                         $conversation_uri = $conversation_href;
2143
2144                         if (isset($parent_item)) {
2145                                 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2146                                 if (dbm::is_result($r)) {
2147                                         if ($r['conversation-uri'] != '') {
2148                                                 $conversation_uri = $r['conversation-uri'];
2149                                         }
2150                                         if ($r['conversation-href'] != '') {
2151                                                 $conversation_href = $r['conversation-href'];
2152                                         }
2153                                 }
2154                         }
2155
2156                         xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2157
2158                         $attributes = array(
2159                                         "href" => $conversation_href,
2160                                         "local_id" => $item["parent"],
2161                                         "ref" => $conversation_uri);
2162
2163                         xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2164                 }
2165
2166                 $tags = item_getfeedtags($item);
2167
2168                 if(count($tags))
2169                         foreach($tags as $t)
2170                                 if ($t[0] == "@")
2171                                         $mentioned[$t[1]] = $t[1];
2172
2173                 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2174                 $newmentions = array();
2175                 foreach ($mentioned AS $mention) {
2176                         $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2177                         $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2178                 }
2179                 $mentioned = $newmentions;
2180
2181                 foreach ($mentioned AS $mention) {
2182                         $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2183                                 intval($owner["uid"]),
2184                                 dbesc(normalise_link($mention)));
2185                         if ($r[0]["forum"] OR $r[0]["prv"])
2186                                 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2187                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2188                                                                                         "href" => $mention));
2189                         else
2190                                 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2191                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2192                                                                                         "href" => $mention));
2193                 }
2194
2195                 if (!$item["private"]) {
2196                         xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2197                                                                         "href" => "http://activityschema.org/collection/public"));
2198                         xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2199                                                                         "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2200                                                                         "href" => "http://activityschema.org/collection/public"));
2201                         xml::add_element($doc, $entry, "mastodon:scope", "public");
2202                 }
2203
2204                 if(count($tags))
2205                         foreach($tags as $t)
2206                                 if ($t[0] != "@")
2207                                         xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2208
2209                 self::get_attachment($doc, $entry, $item);
2210
2211                 if ($complete AND ($item["id"] > 0)) {
2212                         $app = $item["app"];
2213                         if ($app == "")
2214                                 $app = "web";
2215
2216                         $attributes = array("local_id" => $item["id"], "source" => $app);
2217
2218                         if (isset($parent["id"]))
2219                                 $attributes["repeat_of"] = $parent["id"];
2220
2221                         if ($item["coord"] != "")
2222                                 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2223
2224                         xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2225                 }
2226         }
2227
2228         /**
2229          * @brief Creates the XML feed for a given nickname
2230          *
2231          * @param app $a The application class
2232          * @param string $owner_nick Nickname of the feed owner
2233          * @param string $last_update Date of the last update
2234          *
2235          * @return string XML feed
2236          */
2237         public static function feed(App $a, $owner_nick, $last_update) {
2238
2239                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2240                                 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2241                                 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2242                                 dbesc($owner_nick));
2243                 if (!$r)
2244                         return;
2245
2246                 $owner = $r[0];
2247
2248                 if(!strlen($last_update))
2249                         $last_update = 'now -30 days';
2250
2251                 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2252                 $authorid = get_contact($owner["url"], 0);
2253
2254                 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2255                                 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2256                                 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2257                                         `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2258                                         NOT `item`.`deleted` AND NOT `item`.`private` AND
2259                                         `thread`.`network` IN ('%s', '%s')
2260                                 ORDER BY `item`.`created` DESC LIMIT 300",
2261                                 intval($owner["uid"]), intval($owner["id"]),
2262                                 intval($authorid), dbesc($check_date),
2263                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2264
2265 /*              2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2266
2267                 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2268                                 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2269                                 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2270                                 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2271                                         AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
2272                                         AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2273                                                 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2274                                         AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2275                                                 OR (`item`.`author-link` IN ('%s', '%s')))
2276                                 ORDER BY `item`.`id` DESC
2277                                 LIMIT 0, 300",
2278                                 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2279                                 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2280                                 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2281                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2282                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2283                                 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2284                                 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2285                         );
2286 */
2287                 $doc = new DOMDocument('1.0', 'utf-8');
2288                 $doc->formatOutput = true;
2289
2290                 $root = self::add_header($doc, $owner);
2291
2292                 foreach ($items AS $item) {
2293                         if (Config::get('system', 'ostatus_debug')) {
2294                                 $item['body'] .= '🍼';
2295                         }
2296                         $entry = self::entry($doc, $item, $owner);
2297                         $root->appendChild($entry);
2298                 }
2299
2300                 return(trim($doc->saveXML()));
2301         }
2302
2303         /**
2304          * @brief Creates the XML for a salmon message
2305          *
2306          * @param array $item Data of the item that is to be posted
2307          * @param array $owner Contact data of the poster
2308          *
2309          * @return string XML for the salmon
2310          */
2311         public static function salmon($item,$owner) {
2312
2313                 $doc = new DOMDocument('1.0', 'utf-8');
2314                 $doc->formatOutput = true;
2315
2316                 if (Config::get('system', 'ostatus_debug')) {
2317                         $item['body'] .= '🐟';
2318                 }
2319
2320                 $entry = self::entry($doc, $item, $owner, true);
2321
2322                 $doc->appendChild($entry);
2323
2324                 return(trim($doc->saveXML()));
2325         }
2326 }
2327 ?>