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