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