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