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