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