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