]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
Add Contact Object
[friendica.git] / src / Protocol / DFRN.php
1 <?php
2 /**
3  * @file include/dfrn.php
4  * @brief The implementation of the dfrn protocol
5  *
6  * @see https://github.com/friendica/friendica/wiki/Protocol and
7  * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
8  */
9 namespace Friendica\Protocol;
10
11 use Friendica\App;
12 use Friendica\Core\Config;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16 use Friendica\Model\GlobalContact;
17 use Friendica\Object\Contact;
18 use Friendica\Object\Profile;
19 use Friendica\Protocol\OStatus;
20 use Friendica\Util\XML;
21
22 use dba;
23 use DOMDocument;
24 use DomXPath;
25
26 require_once "include/Contact.php";
27 require_once "include/enotify.php";
28 require_once "include/threads.php";
29 require_once "include/items.php";
30 require_once "include/tags.php";
31 require_once "include/files.php";
32 require_once "include/event.php";
33 require_once "include/text.php";
34 require_once "include/oembed.php";
35 require_once "include/html2bbcode.php";
36 require_once "include/bbcode.php";
37
38 /**
39  * @brief This class contain functions to create and send DFRN XML files
40  */
41 class DFRN
42 {
43
44         const DFRN_TOP_LEVEL = 0;       // Top level posting
45         const DFRN_REPLY = 1;           // Regular reply that is stored locally
46         const DFRN_REPLY_RC = 2;        // Reply that will be relayed
47
48         /**
49          * @brief Generates the atom entries for delivery.php
50          *
51          * This function is used whenever content is transmitted via DFRN.
52          *
53          * @param array $items Item elements
54          * @param array $owner Owner record
55          *
56          * @return string DFRN entries
57          * @todo Add type-hints
58          */
59         public static function entries($items, $owner)
60         {
61                 $doc = new DOMDocument('1.0', 'utf-8');
62                 $doc->formatOutput = true;
63
64                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
65
66                 if (! count($items)) {
67                         return trim($doc->saveXML());
68                 }
69
70                 foreach ($items as $item) {
71                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
72                         $root->appendChild($entry);
73                 }
74
75                 return(trim($doc->saveXML()));
76         }
77
78         /**
79          * @brief Generate an atom feed for the given user
80          *
81          * This function is called when another server is pulling data from the user feed.
82          *
83          * @param string  $dfrn_id     DFRN ID from the requesting party
84          * @param string  $owner_nick  Owner nick name
85          * @param string  $last_update Date of the last update
86          * @param int     $direction   Can be -1, 0 or 1.
87          * @param boolean $onlyheader  Output only the header without content? (Default is "no")
88          *
89          * @return string DFRN feed entries
90          */
91         public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
92         {
93                 $a = get_app();
94
95                 $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
96                 $public_feed = (($dfrn_id) ? false : true);
97                 $starred     = false;   // not yet implemented, possible security issues
98                 $converse    = false;
99
100                 if ($public_feed && $a->argc > 2) {
101                         for ($x = 2; $x < $a->argc; $x++) {
102                                 if ($a->argv[$x] == 'converse') {
103                                         $converse = true;
104                                 }
105                                 if ($a->argv[$x] == 'starred') {
106                                         $starred = true;
107                                 }
108                                 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
109                                         $category = $a->argv[$x+1];
110                                 }
111                         }
112                 }
113
114
115
116                 // default permissions - anonymous user
117
118                 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' ";
119
120                 $r = q(
121                         "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
122                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
123                         WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
124                         dbesc($owner_nick)
125                 );
126
127                 if (! DBM::is_result($r)) {
128                         killme();
129                 }
130
131                 $owner = $r[0];
132                 $owner_id = $owner['uid'];
133                 $owner_nick = $owner['nickname'];
134
135                 $sql_post_table = "";
136
137                 if (! $public_feed) {
138                         $sql_extra = '';
139                         switch ($direction) {
140                                 case (-1):
141                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
142                                         $my_id = $dfrn_id;
143                                         break;
144                                 case 0:
145                                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
146                                         $my_id = '1:' . $dfrn_id;
147                                         break;
148                                 case 1:
149                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
150                                         $my_id = '0:' . $dfrn_id;
151                                         break;
152                                 default:
153                                         return false;
154                                         break; // NOTREACHED
155                         }
156
157                         $r = q(
158                                 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
159                                 intval($owner_id)
160                         );
161
162                         if (! DBM::is_result($r)) {
163                                 killme();
164                         }
165
166                         $contact = $r[0];
167                         include_once 'include/security.php';
168                         $groups = init_groups_visitor($contact['id']);
169
170                         if (count($groups)) {
171                                 for ($x = 0; $x < count($groups); $x ++)
172                                         $groups[$x] = '<' . intval($groups[$x]) . '>' ;
173                                 $gs = implode('|', $groups);
174                         } else {
175                                 $gs = '<<>>' ; // Impossible to match
176                         }
177
178                         $sql_extra = sprintf(
179                                 "
180                                 AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' )
181                                 AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' )
182                                 AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
183                                 AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s')
184                         ",
185                                 intval($contact['id']),
186                                 intval($contact['id']),
187                                 dbesc($gs),
188                                 dbesc($gs)
189                         );
190                 }
191
192                 if ($public_feed) {
193                         $sort = 'DESC';
194                 } else {
195                         $sort = 'ASC';
196                 }
197
198                 if (! strlen($last_update)) {
199                         $last_update = 'now -30 days';
200                 }
201
202                 if (isset($category)) {
203                         $sql_post_table = sprintf(
204                                 "INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
205                                 dbesc(protect_sprintf($category)),
206                                 intval(TERM_OBJ_POST),
207                                 intval(TERM_CATEGORY),
208                                 intval($owner_id)
209                         );
210                         //$sql_extra .= file_tag_file_query('item',$category,'category');
211                 }
212
213                 if ($public_feed) {
214                         if (! $converse) {
215                                 $sql_extra .= " AND `contact`.`self` = 1 ";
216                         }
217                 }
218
219                 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
220
221                 $r = q(
222                         "SELECT `item`.*, `item`.`id` AS `item_id`,
223                         `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
224                         `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
225                         `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
226                         `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
227                         FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
228                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
229                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
230                         LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
231                         WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
232                         AND `item`.`wall` AND `item`.`changed` > '%s'
233                         $sql_extra
234                         ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
235                         intval($owner_id),
236                         dbesc($check_date),
237                         dbesc($sort)
238                 );
239
240                 /*
241                  * Will check further below if this actually returned results.
242                  * We will provide an empty feed if that is the case.
243                  */
244
245                 $items = $r;
246
247                 $doc = new DOMDocument('1.0', 'utf-8');
248                 $doc->formatOutput = true;
249
250                 $alternatelink = $owner['url'];
251
252                 if (isset($category)) {
253                         $alternatelink .= "/category/".$category;
254                 }
255
256                 if ($public_feed) {
257                         $author = "dfrn:owner";
258                 } else {
259                         $author = "author";
260                 }
261
262                 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
263
264                 /// @TODO This hook can't work anymore
265                 //      call_hooks('atom_feed', $atom);
266
267                 if (!DBM::is_result($items) || $onlyheader) {
268                         $atom = trim($doc->saveXML());
269
270                         call_hooks('atom_feed_end', $atom);
271
272                         return $atom;
273                 }
274
275                 foreach ($items as $item) {
276                         // prevent private email from leaking.
277                         if ($item['network'] == NETWORK_MAIL) {
278                                 continue;
279                         }
280
281                         // public feeds get html, our own nodes use bbcode
282
283                         if ($public_feed) {
284                                 $type = 'html';
285                                 // catch any email that's in a public conversation and make sure it doesn't leak
286                                 if ($item['private']) {
287                                         continue;
288                                 }
289                         } else {
290                                 $type = 'text';
291                         }
292
293                         $entry = self::entry($doc, $type, $item, $owner, true);
294                         $root->appendChild($entry);
295                 }
296
297                 $atom = trim($doc->saveXML());
298
299                 call_hooks('atom_feed_end', $atom);
300
301                 return $atom;
302         }
303
304         /**
305          * @brief Generate an atom entry for a given item id
306          *
307          * @param int     $item_id      The item id
308          * @param boolean $conversation Show the conversation. If false show the single post.
309          *
310          * @return string DFRN feed entry
311          */
312         public static function itemFeed($item_id, $conversation = false)
313         {
314                 if ($conversation) {
315                         $condition = '`item`.`parent`';
316                 } else {
317                         $condition = '`item`.`id`';
318                 }
319
320                 $r = q(
321                         "SELECT `item`.*, `item`.`id` AS `item_id`,
322                         `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
323                         `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
324                         `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
325                         `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
326                         FROM `item`
327                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
328                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
329                         LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
330                         WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
331                         AND NOT `item`.`private`",
332                         $condition,
333                         intval($item_id)
334                 );
335
336                 if (!DBM::is_result($r)) {
337                         killme();
338                 }
339
340                 $items = $r;
341                 $item = $r[0];
342
343                 $r = q(
344                         "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
345                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
346                         WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
347                         intval($item['uid'])
348                 );
349
350                 if (!DBM::is_result($r)) {
351                         killme();
352                 }
353
354                 $owner = $r[0];
355
356                 $doc = new DOMDocument('1.0', 'utf-8');
357                 $doc->formatOutput = true;
358                 $type = 'html';
359
360                 if ($conversation) {
361                         $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
362                         $doc->appendChild($root);
363
364                         $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
365                         $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
366                         $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
367                         $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
368                         $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
369                         $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
370                         $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
371                         $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
372                         $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
373
374                         //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
375
376                         foreach ($items as $item) {
377                                 $entry = self::entry($doc, $type, $item, $owner, true, 0);
378                                 $root->appendChild($entry);
379                         }
380                 } else {
381                         $root = self::entry($doc, $type, $item, $owner, true, 0, true);
382                 }
383
384                 $atom = trim($doc->saveXML());
385                 return $atom;
386         }
387
388         /**
389          * @brief Create XML text for DFRN mails
390          *
391          * @param array $item  message elements
392          * @param array $owner Owner record
393          *
394          * @return string DFRN mail
395          * @todo Add type-hints
396          */
397         public static function mail($item, $owner)
398         {
399                 $doc = new DOMDocument('1.0', 'utf-8');
400                 $doc->formatOutput = true;
401
402                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
403
404                 $mail = $doc->createElement("dfrn:mail");
405                 $sender = $doc->createElement("dfrn:sender");
406
407                 XML::add_element($doc, $sender, "dfrn:name", $owner['name']);
408                 XML::add_element($doc, $sender, "dfrn:uri", $owner['url']);
409                 XML::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
410
411                 $mail->appendChild($sender);
412
413                 XML::add_element($doc, $mail, "dfrn:id", $item['uri']);
414                 XML::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
415                 XML::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
416                 XML::add_element($doc, $mail, "dfrn:subject", $item['title']);
417                 XML::add_element($doc, $mail, "dfrn:content", $item['body']);
418
419                 $root->appendChild($mail);
420
421                 return(trim($doc->saveXML()));
422         }
423
424         /**
425          * @brief Create XML text for DFRN friend suggestions
426          *
427          * @param array $item  suggestion elements
428          * @param array $owner Owner record
429          *
430          * @return string DFRN suggestions
431          * @todo Add type-hints
432          */
433         public static function fsuggest($item, $owner)
434         {
435                 $doc = new DOMDocument('1.0', 'utf-8');
436                 $doc->formatOutput = true;
437
438                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
439
440                 $suggest = $doc->createElement("dfrn:suggest");
441
442                 XML::add_element($doc, $suggest, "dfrn:url", $item['url']);
443                 XML::add_element($doc, $suggest, "dfrn:name", $item['name']);
444                 XML::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
445                 XML::add_element($doc, $suggest, "dfrn:request", $item['request']);
446                 XML::add_element($doc, $suggest, "dfrn:note", $item['note']);
447
448                 $root->appendChild($suggest);
449
450                 return(trim($doc->saveXML()));
451         }
452
453         /**
454          * @brief Create XML text for DFRN relocations
455          *
456          * @param array $owner Owner record
457          * @param int   $uid   User ID
458          *
459          * @return string DFRN relocations
460          * @todo Add type-hints
461          */
462         public static function relocate($owner, $uid)
463         {
464
465                 /* get site pubkey. this could be a new installation with no site keys*/
466                 $pubkey = Config::get('system', 'site_pubkey');
467                 if (! $pubkey) {
468                         $res = new_keypair(1024);
469                         Config::set('system', 'site_prvkey', $res['prvkey']);
470                         Config::set('system', 'site_pubkey', $res['pubkey']);
471                 }
472
473                 $rp = q(
474                         "SELECT `resource-id` , `scale`, type FROM `photo`
475                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
476                         $uid
477                 );
478                 $photos = array();
479                 $ext = Photo::supportedTypes();
480
481                 foreach ($rp as $p) {
482                         $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
483                 }
484
485                 unset($rp, $ext);
486
487                 $doc = new DOMDocument('1.0', 'utf-8');
488                 $doc->formatOutput = true;
489
490                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
491
492                 $relocate = $doc->createElement("dfrn:relocate");
493
494                 XML::add_element($doc, $relocate, "dfrn:url", $owner['url']);
495                 XML::add_element($doc, $relocate, "dfrn:name", $owner['name']);
496                 XML::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
497                 XML::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
498                 XML::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
499                 XML::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
500                 XML::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
501                 XML::add_element($doc, $relocate, "dfrn:request", $owner['request']);
502                 XML::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
503                 XML::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
504                 XML::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
505                 XML::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey'));
506
507                 $root->appendChild($relocate);
508
509                 return(trim($doc->saveXML()));
510         }
511
512         /**
513          * @brief Adds the header elements for the DFRN protocol
514          *
515          * @param object $doc           XML document
516          * @param array  $owner         Owner record
517          * @param string $authorelement Element name for the author
518          * @param string $alternatelink link to profile or category
519          * @param bool   $public        Is it a header for public posts?
520          *
521          * @return object XML root object
522          * @todo Add type-hints
523          */
524         private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false)
525         {
526
527                 if ($alternatelink == "") {
528                         $alternatelink = $owner['url'];
529                 }
530
531                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
532                 $doc->appendChild($root);
533
534                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
535                 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
536                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
537                 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
538                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
539                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
540                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
541                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
542                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
543
544                 XML::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
545                 XML::add_element($doc, $root, "title", $owner["name"]);
546
547                 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
548                 XML::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
549
550                 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
551                 XML::add_element($doc, $root, "link", "", $attributes);
552
553                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
554                 XML::add_element($doc, $root, "link", "", $attributes);
555
556
557                 if ($public) {
558                         // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
559                         OStatus::hublinks($doc, $root, $owner["nick"]);
560
561                         $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
562                         XML::add_element($doc, $root, "link", "", $attributes);
563
564                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
565                         XML::add_element($doc, $root, "link", "", $attributes);
566
567                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
568                         XML::add_element($doc, $root, "link", "", $attributes);
569                 }
570
571                 // For backward compatibility we keep this element
572                 if ($owner['page-flags'] == PAGE_COMMUNITY) {
573                         XML::add_element($doc, $root, "dfrn:community", 1);
574                 }
575
576                 // The former element is replaced by this one
577                 XML::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
578
579                 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
580
581                 XML::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
582
583                 $author = self::add_author($doc, $owner, $authorelement, $public);
584                 $root->appendChild($author);
585
586                 return $root;
587         }
588
589         /**
590          * @brief Adds the author element in the header for the DFRN protocol
591          *
592          * @param object $doc           XML document
593          * @param array  $owner         Owner record
594          * @param string $authorelement Element name for the author
595          *
596          * @return object XML author object
597          * @todo Add type-hints
598          */
599         private static function add_author($doc, $owner, $authorelement, $public)
600         {
601                 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
602                 $r = q(
603                         "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
604                                 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
605                         intval($owner['uid'])
606                 );
607                 if (DBM::is_result($r)) {
608                         $hidewall = true;
609                 } else {
610                         $hidewall = false;
611                 }
612
613                 $author = $doc->createElement($authorelement);
614
615                 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
616                 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
617                 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
618
619                 $attributes = array();
620
621                 if (!$public || !$hidewall) {
622                         $attributes = array("dfrn:updated" => $namdate);
623                 }
624
625                 XML::add_element($doc, $author, "name", $owner["name"], $attributes);
626                 XML::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
627                 XML::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
628
629                 $attributes = array("rel" => "photo", "type" => "image/jpeg",
630                                         "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
631
632                 if (!$public || !$hidewall) {
633                         $attributes["dfrn:updated"] = $picdate;
634                 }
635
636                 XML::add_element($doc, $author, "link", "", $attributes);
637
638                 $attributes["rel"] = "avatar";
639                 XML::add_element($doc, $author, "link", "", $attributes);
640
641                 if ($hidewall) {
642                         XML::add_element($doc, $author, "dfrn:hide", "true");
643                 }
644
645                 // The following fields will only be generated if the data isn't meant for a public feed
646                 if ($public) {
647                         return $author;
648                 }
649
650                 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
651
652                 if ($birthday) {
653                         XML::add_element($doc, $author, "dfrn:birthday", $birthday);
654                 }
655
656                 // Only show contact details when we are allowed to
657                 $r = q(
658                         "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
659                                 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
660                                 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
661                         FROM `profile`
662                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
663                                 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
664                         intval($owner['uid'])
665                 );
666                 if (DBM::is_result($r)) {
667                         $profile = $r[0];
668
669                         XML::add_element($doc, $author, "poco:displayName", $profile["name"]);
670                         XML::add_element($doc, $author, "poco:updated", $namdate);
671
672                         if (trim($profile["dob"]) > '0001-01-01') {
673                                 XML::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
674                         }
675
676                         XML::add_element($doc, $author, "poco:note", $profile["about"]);
677                         XML::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
678
679                         $savetz = date_default_timezone_get();
680                         date_default_timezone_set($profile["timezone"]);
681                         XML::add_element($doc, $author, "poco:utcOffset", date("P"));
682                         date_default_timezone_set($savetz);
683
684                         if (trim($profile["homepage"]) != "") {
685                                 $urls = $doc->createElement("poco:urls");
686                                 XML::add_element($doc, $urls, "poco:type", "homepage");
687                                 XML::add_element($doc, $urls, "poco:value", $profile["homepage"]);
688                                 XML::add_element($doc, $urls, "poco:primary", "true");
689                                 $author->appendChild($urls);
690                         }
691
692                         if (trim($profile["pub_keywords"]) != "") {
693                                 $keywords = explode(",", $profile["pub_keywords"]);
694
695                                 foreach ($keywords as $keyword) {
696                                         XML::add_element($doc, $author, "poco:tags", trim($keyword));
697                                 }
698                         }
699
700                         if (trim($profile["xmpp"]) != "") {
701                                 $ims = $doc->createElement("poco:ims");
702                                 XML::add_element($doc, $ims, "poco:type", "xmpp");
703                                 XML::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
704                                 XML::add_element($doc, $ims, "poco:primary", "true");
705                                 $author->appendChild($ims);
706                         }
707
708                         if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
709                                 $element = $doc->createElement("poco:address");
710
711                                 XML::add_element($doc, $element, "poco:formatted", formatted_location($profile));
712
713                                 if (trim($profile["locality"]) != "") {
714                                         XML::add_element($doc, $element, "poco:locality", $profile["locality"]);
715                                 }
716
717                                 if (trim($profile["region"]) != "") {
718                                         XML::add_element($doc, $element, "poco:region", $profile["region"]);
719                                 }
720
721                                 if (trim($profile["country-name"]) != "") {
722                                         XML::add_element($doc, $element, "poco:country", $profile["country-name"]);
723                                 }
724
725                                 $author->appendChild($element);
726                         }
727                 }
728
729                 return $author;
730         }
731
732         /**
733          * @brief Adds the author elements in the "entry" elements of the DFRN protocol
734          *
735          * @param object $doc         XML document
736          * @param string $element     Element name for the author
737          * @param string $contact_url Link of the contact
738          * @param array  $item        Item elements
739          *
740          * @return object XML author object
741          * @todo Add type-hints
742          */
743         private static function add_entry_author($doc, $element, $contact_url, $item)
744         {
745
746                 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
747
748                 $author = $doc->createElement($element);
749                 XML::add_element($doc, $author, "name", $contact["name"]);
750                 XML::add_element($doc, $author, "uri", $contact["url"]);
751                 XML::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
752
753                 /// @Todo
754                 /// - Check real image type and image size
755                 /// - Check which of these boths elements we should use
756                 $attributes = array(
757                                 "rel" => "photo",
758                                 "type" => "image/jpeg",
759                                 "media:width" => 80,
760                                 "media:height" => 80,
761                                 "href" => $contact["photo"]);
762                 XML::add_element($doc, $author, "link", "", $attributes);
763
764                 $attributes = array(
765                                 "rel" => "avatar",
766                                 "type" => "image/jpeg",
767                                 "media:width" => 80,
768                                 "media:height" => 80,
769                                 "href" => $contact["photo"]);
770                 XML::add_element($doc, $author, "link", "", $attributes);
771
772                 return $author;
773         }
774
775         /**
776          * @brief Adds the activity elements
777          *
778          * @param object $doc      XML document
779          * @param string $element  Element name for the activity
780          * @param string $activity activity value
781          *
782          * @return object XML activity object
783          * @todo Add type-hints
784          */
785         private static function create_activity($doc, $element, $activity)
786         {
787                 if ($activity) {
788                         $entry = $doc->createElement($element);
789
790                         $r = parse_xml_string($activity, false);
791                         if (!$r) {
792                                 return false;
793                         }
794                         if ($r->type) {
795                                 XML::add_element($doc, $entry, "activity:object-type", $r->type);
796                         }
797                         if ($r->id) {
798                                 XML::add_element($doc, $entry, "id", $r->id);
799                         }
800                         if ($r->title) {
801                                 XML::add_element($doc, $entry, "title", $r->title);
802                         }
803
804                         if ($r->link) {
805                                 if (substr($r->link, 0, 1) == '<') {
806                                         if (strstr($r->link, '&') && (! strstr($r->link, '&amp;'))) {
807                                                 $r->link = str_replace('&', '&amp;', $r->link);
808                                         }
809
810                                         $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
811
812                                         // XML does need a single element as root element so we add a dummy element here
813                                         $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
814                                         if (is_object($data)) {
815                                                 foreach ($data->link AS $link) {
816                                                         $attributes = array();
817                                                         foreach ($link->attributes() as $parameter => $value) {
818                                                                 $attributes[$parameter] = $value;
819                                                         }
820                                                         XML::add_element($doc, $entry, "link", "", $attributes);
821                                                 }
822                                         }
823                                 } else {
824                                         $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
825                                         XML::add_element($doc, $entry, "link", "", $attributes);
826                                 }
827                         }
828                         if ($r->content) {
829                                 XML::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
830                         }
831
832                         return $entry;
833                 }
834
835                 return false;
836         }
837
838         /**
839          * @brief Adds the elements for attachments
840          *
841          * @param object $doc  XML document
842          * @param object $root XML root
843          * @param array  $item Item element
844          *
845          * @return object XML attachment object
846          * @todo Add type-hints
847          */
848         private static function get_attachment($doc, $root, $item)
849         {
850                 $arr = explode('[/attach],', $item['attach']);
851                 if (count($arr)) {
852                         foreach ($arr as $r) {
853                                 $matches = false;
854                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
855                                 if ($cnt) {
856                                         $attributes = array("rel" => "enclosure",
857                                                         "href" => $matches[1],
858                                                         "type" => $matches[3]);
859
860                                         if (intval($matches[2])) {
861                                                 $attributes["length"] = intval($matches[2]);
862                                         }
863
864                                         if (trim($matches[4]) != "") {
865                                                 $attributes["title"] = trim($matches[4]);
866                                         }
867
868                                         XML::add_element($doc, $root, "link", "", $attributes);
869                                 }
870                         }
871                 }
872         }
873
874         /**
875          * @brief Adds the "entry" elements for the DFRN protocol
876          *
877          * @param object $doc     XML document
878          * @param string $type    "text" or "html"
879          * @param array  $item    Item element
880          * @param array  $owner   Owner record
881          * @param bool   $comment Trigger the sending of the "comment" element
882          * @param int    $cid     Contact ID of the recipient
883          * @param bool   $single  If set, the entry is created as an XML document with a single "entry" element
884          *
885          * @return object XML entry object
886          * @todo Add type-hints
887          */
888         private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
889         {
890                 $mentioned = array();
891
892                 if (!$item['parent']) {
893                         return;
894                 }
895
896                 if ($item['deleted']) {
897                         $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME));
898                         return XML::create_element($doc, "at:deleted-entry", "", $attributes);
899                 }
900
901                 if (!$single) {
902                         $entry = $doc->createElement("entry");
903                 } else {
904                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
905                         $doc->appendChild($entry);
906
907                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
908                         $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
909                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
910                         $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
911                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
912                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
913                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
914                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
915                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
916                 }
917
918                 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
919                         $body = fix_private_photos($item['body'], $owner['uid'], $item, $cid);
920                 } else {
921                         $body = $item['body'];
922                 }
923
924                 // Remove the abstract element. It is only locally important.
925                 $body = remove_abstract($body);
926
927                 if ($type == 'html') {
928                         $htmlbody = $body;
929
930                         if ($item['title'] != "") {
931                                 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
932                         }
933
934                         $htmlbody = bbcode($htmlbody, false, false, 7);
935                 }
936
937                 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
938                 $entry->appendChild($author);
939
940                 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
941                 $entry->appendChild($dfrnowner);
942
943                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
944                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
945                         $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
946                         $attributes = array("ref" => $parent_item, "type" => "text/html",
947                                                 "href" => $parent[0]['plink'],
948                                                 "dfrn:diaspora_guid" => $parent[0]['guid']);
949                         XML::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
950                 }
951
952                 // Add conversation data. This is used for OStatus
953                 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
954                 $conversation_uri = $conversation_href;
955
956                 if (isset($parent_item)) {
957                         $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
958                         if (DBM::is_result($r)) {
959                                 if ($r['conversation-uri'] != '') {
960                                         $conversation_uri = $r['conversation-uri'];
961                                 }
962                                 if ($r['conversation-href'] != '') {
963                                         $conversation_href = $r['conversation-href'];
964                                 }
965                         }
966                 }
967
968                 $attributes = array(
969                                 "href" => $conversation_href,
970                                 "ref" => $conversation_uri);
971
972                 XML::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
973
974                 XML::add_element($doc, $entry, "id", $item["uri"]);
975                 XML::add_element($doc, $entry, "title", $item["title"]);
976
977                 XML::add_element($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
978                 XML::add_element($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME));
979
980                 // "dfrn:env" is used to read the content
981                 XML::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
982
983                 // The "content" field is not read by the receiver. We could remove it when the type is "text"
984                 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
985                 XML::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
986
987                 // We save this value in "plink". Maybe we should read it from there as well?
988                 XML::add_element(
989                         $doc,
990                         $entry,
991                         "link",
992                         "",
993                         array("rel" => "alternate", "type" => "text/html",
994                                  "href" => System::baseUrl() . "/display/" . $item["guid"])
995                 );
996
997                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
998                 // It is included in the rewritten code for completeness
999                 if ($comment) {
1000                         XML::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
1001                 }
1002
1003                 if ($item['location']) {
1004                         XML::add_element($doc, $entry, "dfrn:location", $item['location']);
1005                 }
1006
1007                 if ($item['coord']) {
1008                         XML::add_element($doc, $entry, "georss:point", $item['coord']);
1009                 }
1010
1011                 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1012                         XML::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1013                 }
1014
1015                 if ($item['extid']) {
1016                         XML::add_element($doc, $entry, "dfrn:extid", $item['extid']);
1017                 }
1018
1019                 if ($item['bookmark']) {
1020                         XML::add_element($doc, $entry, "dfrn:bookmark", "true");
1021                 }
1022
1023                 if ($item['app']) {
1024                         XML::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
1025                 }
1026
1027                 XML::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1028
1029                 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1030                 // It is needed for relayed comments to Diaspora.
1031                 if ($item['signed_text']) {
1032                         $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
1033                         XML::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
1034                 }
1035
1036                 XML::add_element($doc, $entry, "activity:verb", construct_verb($item));
1037
1038                 if ($item['object-type'] != "") {
1039                         XML::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1040                 } elseif ($item['id'] == $item['parent']) {
1041                         XML::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1042                 } else {
1043                         XML::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1044                 }
1045
1046                 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1047                 if ($actobj) {
1048                         $entry->appendChild($actobj);
1049                 }
1050
1051                 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1052                 if ($actarg) {
1053                         $entry->appendChild($actarg);
1054                 }
1055
1056                 $tags = item_getfeedtags($item);
1057
1058                 if (count($tags)) {
1059                         foreach ($tags as $t) {
1060                                 if (($type != 'html') || ($t[0] != "@")) {
1061                                         XML::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1062                                 }
1063                         }
1064                 }
1065
1066                 if (count($tags)) {
1067                         foreach ($tags as $t) {
1068                                 if ($t[0] == "@") {
1069                                         $mentioned[$t[1]] = $t[1];
1070                                 }
1071                         }
1072                 }
1073
1074                 foreach ($mentioned as $mention) {
1075                         $r = q(
1076                                 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1077                                 intval($owner["uid"]),
1078                                 dbesc(normalise_link($mention))
1079                         );
1080
1081                         if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1082                                 XML::add_element(
1083                                         $doc,
1084                                         $entry,
1085                                         "link",
1086                                         "",
1087                                         array("rel" => "mentioned",
1088                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1089                                                         "href" => $mention)
1090                                 );
1091                         } else {
1092                                 XML::add_element(
1093                                         $doc,
1094                                         $entry,
1095                                         "link",
1096                                         "",
1097                                         array("rel" => "mentioned",
1098                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1099                                                         "href" => $mention)
1100                                 );
1101                         }
1102                 }
1103
1104                 self::get_attachment($doc, $entry, $item);
1105
1106                 return $entry;
1107         }
1108
1109         /**
1110          * @brief encrypts data via AES
1111          *
1112          * @param string $data The data that is to be encrypted
1113          * @param string $key  The AES key
1114          *
1115          * @return string encrypted data
1116          */
1117         private static function aes_encrypt($data, $key)
1118         {
1119                 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1120         }
1121
1122         /**
1123          * @brief decrypts data via AES
1124          *
1125          * @param string $encrypted The encrypted data
1126          * @param string $key       The AES key
1127          *
1128          * @return string decrypted data
1129          */
1130         public static function aes_decrypt($encrypted, $key)
1131         {
1132                 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1133         }
1134
1135         /**
1136          * @brief Delivers the atom content to the contacts
1137          *
1138          * @param array  $owner    Owner record
1139          * @param array  $contact  Contact record of the receiver
1140          * @param string $atom     Content that will be transmitted
1141          * @param bool   $dissolve (to be documented)
1142          *
1143          * @return int Deliver status. -1 means an error.
1144          * @todo Add array type-hint for $owner, $contact
1145          */
1146         public static function deliver($owner, $contact, $atom, $dissolve = false)
1147         {
1148                 $a = get_app();
1149
1150                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1151
1152                 if ($contact['duplex'] && $contact['dfrn-id']) {
1153                         $idtosend = '0:' . $orig_id;
1154                 }
1155                 if ($contact['duplex'] && $contact['issued-id']) {
1156                         $idtosend = '1:' . $orig_id;
1157                 }
1158
1159                 $rino = Config::get('system', 'rino_encrypt');
1160                 $rino = intval($rino);
1161
1162                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1163
1164                 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1165                 $ssl_policy = '';
1166
1167                 switch ($ssl_val) {
1168                         case SSL_POLICY_FULL:
1169                                 $ssl_policy = 'full';
1170                                 break;
1171                         case SSL_POLICY_SELFSIGN:
1172                                 $ssl_policy = 'self';
1173                                 break;
1174                         case SSL_POLICY_NONE:
1175                         default:
1176                                 $ssl_policy = 'none';
1177                                 break;
1178                 }
1179
1180                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1181
1182                 logger('dfrn_deliver: ' . $url);
1183
1184                 $ret = z_fetch_url($url);
1185
1186                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1187                         return -2; // timed out
1188                 }
1189
1190                 $xml = $ret['body'];
1191
1192                 $curl_stat = $a->get_curl_code();
1193                 if (!$curl_stat) {
1194                         return -3; // timed out
1195                 }
1196
1197                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1198
1199                 if (! $xml) {
1200                         return 3;
1201                 }
1202
1203                 if (strpos($xml, '<?xml') === false) {
1204                         logger('dfrn_deliver: no valid XML returned');
1205                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1206                         return 3;
1207                 }
1208
1209                 $res = parse_xml_string($xml);
1210
1211                 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1212                         return (($res->status) ? $res->status : 3);
1213                 }
1214
1215                 $postvars     = array();
1216                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1217                 $challenge    = hex2bin((string) $res->challenge);
1218                 $perm         = (($res->perm) ? $res->perm : null);
1219                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1220                 $rino_remote_version = intval($res->rino);
1221                 $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1222
1223                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1224
1225                 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1226                         $page = 2;
1227                 }
1228
1229                 $final_dfrn_id = '';
1230
1231                 if ($perm) {
1232                         if ((($perm == 'rw') && (! intval($contact['writable'])))
1233                                 || (($perm == 'r') && (intval($contact['writable'])))
1234                         ) {
1235                                 q(
1236                                         "update contact set writable = %d where id = %d",
1237                                         intval(($perm == 'rw') ? 1 : 0),
1238                                         intval($contact['id'])
1239                                 );
1240                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
1241                         }
1242                 }
1243
1244                 if (($contact['duplex'] && strlen($contact['pubkey']))
1245                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1246                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1247                 ) {
1248                         openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1249                         openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1250                 } else {
1251                         openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1252                         openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1253                 }
1254
1255                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1256
1257                 if (strpos($final_dfrn_id, ':') == 1) {
1258                         $final_dfrn_id = substr($final_dfrn_id, 2);
1259                 }
1260
1261                 if ($final_dfrn_id != $orig_id) {
1262                         logger('dfrn_deliver: wrong dfrn_id.');
1263                         // did not decode properly - cannot trust this site
1264                         return 3;
1265                 }
1266
1267                 $postvars['dfrn_id']      = $idtosend;
1268                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1269                 if ($dissolve) {
1270                         $postvars['dissolve'] = '1';
1271                 }
1272
1273
1274                 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1275                         $postvars['data'] = $atom;
1276                         $postvars['perm'] = 'rw';
1277                 } else {
1278                         $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1279                         $postvars['perm'] = 'r';
1280                 }
1281
1282                 $postvars['ssl_policy'] = $ssl_policy;
1283
1284                 if ($page) {
1285                         $postvars['page'] = $page;
1286                 }
1287
1288
1289                 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1290                         logger('rino version: '. $rino_remote_version);
1291
1292                         switch ($rino_remote_version) {
1293                                 case 1:
1294                                         // Deprecated rino version!
1295                                         $key = openssl_random_pseudo_bytes(16);
1296                                         $data = self::aes_encrypt($postvars['data'], $key);
1297                                         break;
1298                                 case 2:
1299                                         // RINO 2 based on php-encryption
1300                                         try {
1301                                                 $key = \Crypto::createNewRandomKey();
1302                                         } catch (\CryptoTestFailedException $ex) {
1303                                                 logger('Cannot safely create a key');
1304                                                 return -4;
1305                                         } catch (\CannotPerformOperationException $ex) {
1306                                                 logger('Cannot safely create a key');
1307                                                 return -5;
1308                                         }
1309                                         try {
1310                                                 $data = \Crypto::encrypt($postvars['data'], $key);
1311                                         } catch (\CryptoTestFailedException $ex) {
1312                                                 logger('Cannot safely perform encryption');
1313                                                 return -6;
1314                                         } catch (\CannotPerformOperationException $ex) {
1315                                                 logger('Cannot safely perform encryption');
1316                                                 return -7;
1317                                         }
1318                                         break;
1319                                 default:
1320                                         logger("rino: invalid requested version '$rino_remote_version'");
1321                                         return -8;
1322                         }
1323
1324                         $postvars['rino'] = $rino_remote_version;
1325                         $postvars['data'] = bin2hex($data);
1326
1327                         //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1328
1329
1330                         if ($dfrn_version >= 2.1) {
1331                                 if (($contact['duplex'] && strlen($contact['pubkey']))
1332                                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1333                                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1334                                 ) {
1335                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1336                                 } else {
1337                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1338                                 }
1339                         } else {
1340                                 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1341                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1342                                 } else {
1343                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1344                                 }
1345                         }
1346
1347                         logger('md5 rawkey ' . md5($postvars['key']));
1348
1349                         $postvars['key'] = bin2hex($postvars['key']);
1350                 }
1351
1352
1353                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1354
1355                 $xml = post_url($contact['notify'], $postvars);
1356
1357                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1358
1359                 $curl_stat = $a->get_curl_code();
1360                 if ((!$curl_stat) || (!strlen($xml))) {
1361                         return -9; // timed out
1362                 }
1363
1364                 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1365                         return -10;
1366                 }
1367
1368                 if (strpos($xml, '<?xml') === false) {
1369                         logger('dfrn_deliver: phase 2: no valid XML returned');
1370                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1371                         return 3;
1372                 }
1373
1374                 if ($contact['term-date'] > NULL_DATE) {
1375                         logger("dfrn_deliver: $url back from the dead - removing mark for death");
1376                         include_once 'include/Contact.php';
1377                         unmark_for_death($contact);
1378                 }
1379
1380                 $res = parse_xml_string($xml);
1381
1382                 if (!isset($res->status)) {
1383                         return -11;
1384                 }
1385
1386                 if (!empty($res->message)) {
1387                         logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1388                 }
1389
1390                 return intval($res->status);
1391         }
1392
1393         /**
1394          * @brief Add new birthday event for this person
1395          *
1396          * @param array  $contact  Contact record
1397          * @param string $birthday Birthday of the contact
1398          * @todo Add array type-hint for $contact
1399          */
1400         private static function birthday_event($contact, $birthday)
1401         {
1402                 // Check for duplicates
1403                 $r = q(
1404                         "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1405                         intval($contact["uid"]),
1406                         intval($contact["id"]),
1407                         dbesc(datetime_convert("UTC", "UTC", $birthday)),
1408                         dbesc("birthday")
1409                 );
1410
1411                 if (DBM::is_result($r)) {
1412                         return;
1413                 }
1414
1415                 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1416
1417                 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1418                 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1419
1420                 $r = q(
1421                         "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1422                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1423                         intval($contact["uid"]),
1424                         intval($contact["id"]),
1425                         dbesc(datetime_convert()),
1426                         dbesc(datetime_convert()),
1427                         dbesc(datetime_convert("UTC", "UTC", $birthday)),
1428                         dbesc(datetime_convert("UTC", "UTC", $birthday . " + 1 day ")),
1429                         dbesc($bdtext),
1430                         dbesc($bdtext2),
1431                         dbesc("birthday")
1432                 );
1433         }
1434
1435         /**
1436          * @brief Fetch the author data from head or entry items
1437          *
1438          * @param object $xpath     XPath object
1439          * @param object $context   In which context should the data be searched
1440          * @param array  $importer  Record of the importer user mixed with contact of the content
1441          * @param string $element   Element name from which the data is fetched
1442          * @param bool   $onlyfetch Should the data only be fetched or should it update the contact record as well
1443          *
1444          * @return Returns an array with relevant data of the author
1445          * @todo Find good type-hints for all parameter
1446          */
1447         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1448         {
1449                 $author = array();
1450                 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1451                 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1452
1453                 $r = q(
1454                         "SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1455                                 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1456                                 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1457                         intval($importer["uid"]),
1458                         dbesc(normalise_link($author["link"])),
1459                         dbesc(NETWORK_STATUSNET)
1460                 );
1461
1462                 if (DBM::is_result($r)) {
1463                         $contact = $r[0];
1464                         $author["contact-id"] = $r[0]["id"];
1465                         $author["network"] = $r[0]["network"];
1466                 } else {
1467                         if (!$onlyfetch) {
1468                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1469                         }
1470
1471                         $author["contact-id"] = $importer["id"];
1472                         $author["network"] = $importer["network"];
1473                         $onlyfetch = true;
1474                 }
1475
1476                 // Until now we aren't serving different sizes - but maybe later
1477                 $avatarlist = array();
1478                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1479                 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1480                 foreach ($avatars AS $avatar) {
1481                         $href = "";
1482                         $width = 0;
1483                         foreach ($avatar->attributes AS $attributes) {
1484                                 /// @TODO Rewrite these similar if () to one switch
1485                                 if ($attributes->name == "href") {
1486                                         $href = $attributes->textContent;
1487                                 }
1488                                 if ($attributes->name == "width") {
1489                                         $width = $attributes->textContent;
1490                                 }
1491                                 if ($attributes->name == "updated") {
1492                                         $contact["avatar-date"] = $attributes->textContent;
1493                                 }
1494                         }
1495                         if (($width > 0) && ($href != "")) {
1496                                 $avatarlist[$width] = $href;
1497                         }
1498                 }
1499                 if (count($avatarlist) > 0) {
1500                         krsort($avatarlist);
1501                         $author["avatar"] = current($avatarlist);
1502                 }
1503
1504                 if (DBM::is_result($r) && !$onlyfetch) {
1505                         logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1506
1507                         $poco = array("url" => $contact["url"]);
1508
1509                         // When was the last change to name or uri?
1510                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1511                         foreach ($name_element->attributes AS $attributes) {
1512                                 if ($attributes->name == "updated") {
1513                                         $poco["name-date"] = $attributes->textContent;
1514                                 }
1515                         }
1516
1517                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1518                         foreach ($link_element->attributes AS $attributes) {
1519                                 if ($attributes->name == "updated") {
1520                                         $poco["uri-date"] = $attributes->textContent;
1521                                 }
1522                         }
1523
1524                         // Update contact data
1525                         $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1526                         if ($value != "") {
1527                                 $poco["addr"] = $value;
1528                         }
1529
1530                         $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1531                         if ($value != "") {
1532                                 $poco["name"] = $value;
1533                         }
1534
1535                         $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1536                         if ($value != "") {
1537                                 $poco["nick"] = $value;
1538                         }
1539
1540                         $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1541                         if ($value != "") {
1542                                 $poco["about"] = $value;
1543                         }
1544
1545                         $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1546                         if ($value != "") {
1547                                 $poco["location"] = $value;
1548                         }
1549
1550                         /// @todo Only search for elements with "poco:type" = "xmpp"
1551                         $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1552                         if ($value != "") {
1553                                 $poco["xmpp"] = $value;
1554                         }
1555
1556                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1557                         /// - poco:utcOffset
1558                         /// - poco:urls
1559                         /// - poco:locality
1560                         /// - poco:region
1561                         /// - poco:country
1562
1563                         // If the "hide" element is present then the profile isn't searchable.
1564                         $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1565
1566                         logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1567
1568                         // If the contact isn't searchable then set the contact to "hidden".
1569                         // Problem: This can be manually overridden by the user.
1570                         if ($hide) {
1571                                 $contact["hidden"] = true;
1572                         }
1573
1574                         // Save the keywords into the contact table
1575                         $tags = array();
1576                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1577                         foreach ($tagelements AS $tag) {
1578                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1579                         }
1580
1581                         if (count($tags)) {
1582                                 $poco["keywords"] = implode(", ", $tags);
1583                         }
1584
1585                         // "dfrn:birthday" contains the birthday converted to UTC
1586                         $old_bdyear = $contact["bdyear"];
1587
1588                         $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1589
1590                         if (strtotime($birthday) > time()) {
1591                                 $bd_timestamp = strtotime($birthday);
1592
1593                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1594                         }
1595
1596                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1597                         $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1598
1599                         if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1600                                 $bdyear = date("Y");
1601                                 $value = str_replace("0000", $bdyear, $value);
1602
1603                                 if (strtotime($value) < time()) {
1604                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1605                                         $bdyear = $bdyear + 1;
1606                                 }
1607
1608                                 $poco["bd"] = $value;
1609                         }
1610
1611                         $contact = array_merge($contact, $poco);
1612
1613                         if ($old_bdyear != $contact["bdyear"]) {
1614                                 self::birthday_event($contact, $birthday);
1615                         }
1616
1617                         // Get all field names
1618                         $fields = array();
1619                         foreach ($r[0] AS $field => $data) {
1620                                 $fields[$field] = $data;
1621                         }
1622
1623                         unset($fields["id"]);
1624                         unset($fields["uid"]);
1625                         unset($fields["url"]);
1626                         unset($fields["avatar-date"]);
1627                         unset($fields["name-date"]);
1628                         unset($fields["uri-date"]);
1629
1630                         // Update check for this field has to be done differently
1631                         $datefields = array("name-date", "uri-date");
1632                         foreach ($datefields AS $field) {
1633                                 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1634                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1635                                         $update = true;
1636                                 }
1637                         }
1638
1639                         foreach ($fields AS $field => $data) {
1640                                 if ($contact[$field] != $r[0][$field]) {
1641                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1642                                         $update = true;
1643                                 }
1644                         }
1645
1646                         if ($update) {
1647                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1648
1649                                 q(
1650                                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1651                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1652                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1653                                         WHERE `id` = %d AND `network` = '%s'",
1654                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]),     dbesc($contact["location"]),
1655                                         dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1656                                         dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1657                                         dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1658                                         intval($contact["id"]), dbesc($contact["network"])
1659                                 );
1660                         }
1661
1662                         update_contact_avatar(
1663                                 $author["avatar"],
1664                                 $importer["uid"],
1665                                 $contact["id"],
1666                                 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"]))
1667                         );
1668
1669                         /*
1670                          * The generation is a sign for the reliability of the provided data.
1671                          * It is used in the socgraph.php to prevent that old contact data
1672                          * that was relayed over several servers can overwrite contact
1673                          * data that we received directly.
1674                          */
1675
1676                         $poco["generation"] = 2;
1677                         $poco["photo"] = $author["avatar"];
1678                         $poco["hide"] = $hide;
1679                         $poco["contact-type"] = $contact["contact-type"];
1680                         $gcid = GlobalContact::update($poco);
1681
1682                         GlobalContact::link($gcid, $importer["uid"], $contact["id"]);
1683                 }
1684
1685                 return($author);
1686         }
1687
1688         /**
1689          * @brief Transforms activity objects into an XML string
1690          *
1691          * @param object $xpath    XPath object
1692          * @param object $activity Activity object
1693          * @param text   $element  element name
1694          *
1695          * @return string XML string
1696          * @todo Find good type-hints for all parameter
1697          */
1698         private static function transform_activity($xpath, $activity, $element)
1699         {
1700                 if (!is_object($activity)) {
1701                         return "";
1702                 }
1703
1704                 $obj_doc = new DOMDocument("1.0", "utf-8");
1705                 $obj_doc->formatOutput = true;
1706
1707                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1708
1709                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1710                 XML::add_element($obj_doc, $obj_element, "type", $activity_type);
1711
1712                 $id = $xpath->query("atom:id", $activity)->item(0);
1713                 if (is_object($id)) {
1714                         $obj_element->appendChild($obj_doc->importNode($id, true));
1715                 }
1716
1717                 $title = $xpath->query("atom:title", $activity)->item(0);
1718                 if (is_object($title)) {
1719                         $obj_element->appendChild($obj_doc->importNode($title, true));
1720                 }
1721
1722                 $links = $xpath->query("atom:link", $activity);
1723                 if (is_object($links)) {
1724                         foreach ($links as $link) {
1725                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1726                         }
1727                 }
1728
1729                 $content = $xpath->query("atom:content", $activity)->item(0);
1730                 if (is_object($content)) {
1731                         $obj_element->appendChild($obj_doc->importNode($content, true));
1732                 }
1733
1734                 $obj_doc->appendChild($obj_element);
1735
1736                 $objxml = $obj_doc->saveXML($obj_element);
1737
1738                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1739                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1740                 return($objxml);
1741         }
1742
1743         /**
1744          * @brief Processes the mail elements
1745          *
1746          * @param object $xpath    XPath object
1747          * @param object $mail     mail elements
1748          * @param array  $importer Record of the importer user mixed with contact of the content
1749          * @todo Find good type-hints for all parameter
1750          */
1751         private static function process_mail($xpath, $mail, $importer)
1752         {
1753                 logger("Processing mails");
1754
1755                 /// @TODO Rewrite this to one statement
1756                 $msg = array();
1757                 $msg["uid"] = $importer["importer_uid"];
1758                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1759                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1760                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1761                 $msg["contact-id"] = $importer["id"];
1762                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1763                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1764                 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1765                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1766                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1767                 $msg["seen"] = 0;
1768                 $msg["replied"] = 0;
1769
1770                 dba::insert('mail', $msg);
1771
1772                 // send notifications.
1773                 /// @TODO Arange this mess
1774                 $notif_params = array(
1775                         "type" => NOTIFY_MAIL,
1776                         "notify_flags" => $importer["notify-flags"],
1777                         "language" => $importer["language"],
1778                         "to_name" => $importer["username"],
1779                         "to_email" => $importer["email"],
1780                         "uid" => $importer["importer_uid"],
1781                         "item" => $msg,
1782                         "source_name" => $msg["from-name"],
1783                         "source_link" => $importer["url"],
1784                         "source_photo" => $importer["thumb"],
1785                         "verb" => ACTIVITY_POST,
1786                         "otype" => "mail"
1787                 );
1788
1789                 notification($notif_params);
1790
1791                 logger("Mail is processed, notification was sent.");
1792         }
1793
1794         /**
1795          * @brief Processes the suggestion elements
1796          *
1797          * @param object $xpath      XPath object
1798          * @param object $suggestion suggestion elements
1799          * @param array  $importer   Record of the importer user mixed with contact of the content
1800          * @todo Find good type-hints for all parameter
1801          */
1802         private static function process_suggestion($xpath, $suggestion, $importer)
1803         {
1804                 $a = get_app();
1805
1806                 logger("Processing suggestions");
1807
1808                 /// @TODO Rewrite this to one statement
1809                 $suggest = array();
1810                 $suggest["uid"] = $importer["importer_uid"];
1811                 $suggest["cid"] = $importer["id"];
1812                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1813                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1814                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1815                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1816                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1817
1818                 // Does our member already have a friend matching this description?
1819
1820                 $r = q(
1821                         "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1822                         dbesc($suggest["name"]),
1823                         dbesc(normalise_link($suggest["url"])),
1824                         intval($suggest["uid"])
1825                 );
1826
1827                 /*
1828                  * The valid result means the friend we're about to send a friend
1829                  * suggestion already has them in their contact, which means no further
1830                  * action is required.
1831                  *
1832                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1833                  */
1834                 if (DBM::is_result($r)) {
1835                         return false;
1836                 }
1837
1838                 // Do we already have an fcontact record for this person?
1839
1840                 $fid = 0;
1841                 $r = q(
1842                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1843                         dbesc($suggest["url"]),
1844                         dbesc($suggest["name"]),
1845                         dbesc($suggest["request"])
1846                 );
1847                 if (DBM::is_result($r)) {
1848                         $fid = $r[0]["id"];
1849
1850                         // OK, we do. Do we already have an introduction for this person ?
1851                         $r = q(
1852                                 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1853                                 intval($suggest["uid"]),
1854                                 intval($fid)
1855                         );
1856
1857                         /*
1858                          * The valid result means the friend we're about to send a friend
1859                          * suggestion already has them in their contact, which means no further
1860                          * action is required.
1861                          *
1862                          * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1863                          */
1864                         if (DBM::is_result($r)) {
1865                                 return false;
1866                         }
1867                 }
1868                 if (!$fid) {
1869                         $r = q(
1870                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1871                                 dbesc($suggest["name"]),
1872                                 dbesc($suggest["url"]),
1873                                 dbesc($suggest["photo"]),
1874                                 dbesc($suggest["request"])
1875                         );
1876                 }
1877                 $r = q(
1878                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1879                         dbesc($suggest["url"]),
1880                         dbesc($suggest["name"]),
1881                         dbesc($suggest["request"])
1882                 );
1883
1884                 /*
1885                  * If no record in fcontact is found, below INSERT statement will not
1886                  * link an introduction to it.
1887                  */
1888                 if (!DBM::is_result($r)) {
1889                         // database record did not get created. Quietly give up.
1890                         killme();
1891                 }
1892
1893                 $fid = $r[0]["id"];
1894
1895                 $hash = random_string();
1896
1897                 $r = q(
1898                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1899                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1900                         intval($suggest["uid"]),
1901                         intval($fid),
1902                         intval($suggest["cid"]),
1903                         dbesc($suggest["body"]),
1904                         dbesc($hash),
1905                         dbesc(datetime_convert()),
1906                         intval(0)
1907                 );
1908
1909                 notification(array(
1910                         "type"         => NOTIFY_SUGGEST,
1911                         "notify_flags" => $importer["notify-flags"],
1912                         "language"     => $importer["language"],
1913                         "to_name"      => $importer["username"],
1914                         "to_email"     => $importer["email"],
1915                         "uid"          => $importer["importer_uid"],
1916                         "item"         => $suggest,
1917                         "link"         => System::baseUrl()."/notifications/intros",
1918                         "source_name"  => $importer["name"],
1919                         "source_link"  => $importer["url"],
1920                         "source_photo" => $importer["photo"],
1921                         "verb"         => ACTIVITY_REQ_FRIEND,
1922                         "otype"        => "intro")
1923                 );
1924
1925                 return true;
1926         }
1927
1928         /**
1929          * @brief Processes the relocation elements
1930          *
1931          * @param object $xpath      XPath object
1932          * @param object $relocation relocation elements
1933          * @param array  $importer   Record of the importer user mixed with contact of the content
1934          * @todo Find good type-hints for all parameter
1935          */
1936         private static function process_relocation($xpath, $relocation, $importer)
1937         {
1938                 logger("Processing relocations");
1939
1940                 /// @TODO Rewrite this to one statement
1941                 $relocate = array();
1942                 $relocate["uid"] = $importer["importer_uid"];
1943                 $relocate["cid"] = $importer["id"];
1944                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1945                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1946                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1947                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1948                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1949                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1950                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1951                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1952                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1953                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1954                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1955                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1956
1957                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1958                         $relocate["avatar"] = $relocate["photo"];
1959                 }
1960
1961                 if ($relocate["addr"] == "") {
1962                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1963                 }
1964
1965                 // update contact
1966                 $r = q(
1967                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1968                         intval($importer["id"]),
1969                         intval($importer["importer_uid"])
1970                 );
1971
1972                 if (!DBM::is_result($r)) {
1973                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
1974                         return false;
1975                 }
1976
1977                 $old = $r[0];
1978
1979                 // Update the gcontact entry
1980                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1981
1982                 $x = q(
1983                         "UPDATE `gcontact` SET
1984                                         `name` = '%s',
1985                                         `photo` = '%s',
1986                                         `url` = '%s',
1987                                         `nurl` = '%s',
1988                                         `addr` = '%s',
1989                                         `connect` = '%s',
1990                                         `notify` = '%s',
1991                                         `server_url` = '%s'
1992                         WHERE `nurl` = '%s';",
1993                         dbesc($relocate["name"]),
1994                         dbesc($relocate["avatar"]),
1995                         dbesc($relocate["url"]),
1996                         dbesc(normalise_link($relocate["url"])),
1997                         dbesc($relocate["addr"]),
1998                         dbesc($relocate["addr"]),
1999                         dbesc($relocate["notify"]),
2000                         dbesc($relocate["server_url"]),
2001                         dbesc(normalise_link($old["url"]))
2002                 );
2003
2004                 // Update the contact table. We try to find every entry.
2005                 $x = q(
2006                         "UPDATE `contact` SET
2007                                         `name` = '%s',
2008                                         `avatar` = '%s',
2009                                         `url` = '%s',
2010                                         `nurl` = '%s',
2011                                         `addr` = '%s',
2012                                         `request` = '%s',
2013                                         `confirm` = '%s',
2014                                         `notify` = '%s',
2015                                         `poll` = '%s',
2016                                         `site-pubkey` = '%s'
2017                         WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2018                         dbesc($relocate["name"]),
2019                         dbesc($relocate["avatar"]),
2020                         dbesc($relocate["url"]),
2021                         dbesc(normalise_link($relocate["url"])),
2022                         dbesc($relocate["addr"]),
2023                         dbesc($relocate["request"]),
2024                         dbesc($relocate["confirm"]),
2025                         dbesc($relocate["notify"]),
2026                         dbesc($relocate["poll"]),
2027                         dbesc($relocate["sitepubkey"]),
2028                         intval($importer["id"]),
2029                         intval($importer["importer_uid"]),
2030                         dbesc(normalise_link($old["url"]))
2031                 );
2032
2033                 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2034
2035                 if ($x === false) {
2036                         return false;
2037                 }
2038
2039                 // update items
2040                 /// @todo This is an extreme performance killer
2041                 $fields = array(
2042                         'owner-link' => array($old["url"], $relocate["url"]),
2043                         'author-link' => array($old["url"], $relocate["url"]),
2044                         //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2045                         //'author-avatar' => array($old["photo"], $relocate["photo"]),
2046                 );
2047                 foreach ($fields as $n => $f) {
2048                         $r = q(
2049                                 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2050                                 $n,
2051                                 dbesc($f[0]),
2052                                 intval($importer["importer_uid"])
2053                         );
2054
2055                         if (DBM::is_result($r)) {
2056                                 $x = q(
2057                                         "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2058                                         $n,
2059                                         dbesc($f[1]),
2060                                         $n,
2061                                         dbesc($f[0]),
2062                                         intval($importer["importer_uid"])
2063                                 );
2064
2065                                 if ($x === false) {
2066                                         return false;
2067                                 }
2068                         }
2069                 }
2070
2071                 /// @TODO
2072                 /// merge with current record, current contents have priority
2073                 /// update record, set url-updated
2074                 /// update profile photos
2075                 /// schedule a scan?
2076                 return true;
2077         }
2078
2079         /**
2080          * @brief Updates an item
2081          *
2082          * @param array $current   the current item record
2083          * @param array $item      the new item record
2084          * @param array $importer  Record of the importer user mixed with contact of the content
2085          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2086          * @todo set proper type-hints (array?)
2087          */
2088         private static function update_content($current, $item, $importer, $entrytype)
2089         {
2090                 $changed = false;
2091
2092                 if (edited_timestamp_is_newer($current, $item)) {
2093                         // do not accept (ignore) an earlier edit than one we currently have.
2094                         if (datetime_convert("UTC", "UTC", $item["edited"]) < $current["edited"]) {
2095                                 return false;
2096                         }
2097
2098                         $fields = array('title' => $item["title"], 'body' => $item["body"],
2099                                         'tag' => $item["tag"], 'changed' => datetime_convert(),
2100                                         'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2101
2102                         $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2103                         dba::update('item', $fields, $condition);
2104
2105                         create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2106                         update_thread_uri($item["uri"], $importer["importer_uid"]);
2107
2108                         $changed = true;
2109
2110                         if ($entrytype == DFRN_REPLY_RC) {
2111                                 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2112                         }
2113                 }
2114
2115                 // update last-child if it changes
2116                 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2117                         $r = q(
2118                                 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2119                                 dbesc(datetime_convert()),
2120                                 dbesc($item["parent-uri"]),
2121                                 intval($importer["importer_uid"])
2122                         );
2123                         $r = q(
2124                                 "UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2125                                 intval($item["last-child"]),
2126                                 dbesc(datetime_convert()),
2127                                 dbesc($item["uri"]),
2128                                 intval($importer["importer_uid"])
2129                         );
2130                 }
2131                 return $changed;
2132         }
2133
2134         /**
2135          * @brief Detects the entry type of the item
2136          *
2137          * @param array $importer Record of the importer user mixed with contact of the content
2138          * @param array $item     the new item record
2139          *
2140          * @return int Is it a toplevel entry, a comment or a relayed comment?
2141          * @todo set proper type-hints (array?)
2142          */
2143         private static function get_entry_type($importer, $item)
2144         {
2145                 if ($item["parent-uri"] != $item["uri"]) {
2146                         $community = false;
2147
2148                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2149                                 $sql_extra = "";
2150                                 $community = true;
2151                                 logger("possible community action");
2152                         } else {
2153                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2154                         }
2155
2156                         // was the top-level post for this action written by somebody on this site?
2157                         // Specifically, the recipient?
2158
2159                         $is_a_remote_action = false;
2160
2161                         $r = q(
2162                                 "SELECT `item`.`parent-uri` FROM `item`
2163                                 WHERE `item`.`uri` = '%s'
2164                                 LIMIT 1",
2165                                 dbesc($item["parent-uri"])
2166                         );
2167                         if (DBM::is_result($r)) {
2168                                 $r = q(
2169                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2170                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2171                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2172                                         AND `item`.`uid` = %d
2173                                         $sql_extra
2174                                         LIMIT 1",
2175                                         dbesc($r[0]["parent-uri"]),
2176                                         dbesc($r[0]["parent-uri"]),
2177                                         dbesc($r[0]["parent-uri"]),
2178                                         intval($importer["importer_uid"])
2179                                 );
2180                                 if (DBM::is_result($r)) {
2181                                         $is_a_remote_action = true;
2182                                 }
2183                         }
2184
2185                         /*
2186                          * Does this have the characteristics of a community or private group action?
2187                          * If it's an action to a wall post on a community/prvgroup page it's a
2188                          * valid community action. Also forum_mode makes it valid for sure.
2189                          * If neither, it's not.
2190                          */
2191
2192                         /// @TODO Maybe merge these if() blocks into one?
2193                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2194                                 $is_a_remote_action = false;
2195                                 logger("not a community action");
2196                         }
2197
2198                         if ($is_a_remote_action) {
2199                                 return DFRN_REPLY_RC;
2200                         } else {
2201                                 return DFRN_REPLY;
2202                         }
2203                 } else {
2204                         return DFRN_TOP_LEVEL;
2205                 }
2206         }
2207
2208         /**
2209          * @brief Send a "poke"
2210          *
2211          * @param array $item      the new item record
2212          * @param array $importer  Record of the importer user mixed with contact of the content
2213          * @param int   $posted_id The record number of item record that was just posted
2214          * @todo set proper type-hints (array?)
2215          */
2216         private static function do_poke($item, $importer, $posted_id)
2217         {
2218                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2219                 if (!$verb) {
2220                         return;
2221                 }
2222                 $xo = parse_xml_string($item["object"], false);
2223
2224                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2225                         // somebody was poked/prodded. Was it me?
2226                         foreach ($xo->link as $l) {
2227                                 $atts = $l->attributes();
2228                                 switch ($atts["rel"]) {
2229                                         case "alternate":
2230                                                 $Blink = $atts["href"];
2231                                                 break;
2232                                         default:
2233                                                 break;
2234                                 }
2235                         }
2236
2237                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2238                                 // send a notification
2239                                 notification(
2240                                         array(
2241                                         "type"         => NOTIFY_POKE,
2242                                         "notify_flags" => $importer["notify-flags"],
2243                                         "language"     => $importer["language"],
2244                                         "to_name"      => $importer["username"],
2245                                         "to_email"     => $importer["email"],
2246                                         "uid"          => $importer["importer_uid"],
2247                                         "item"         => $item,
2248                                         "link"         => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2249                                         "source_name"  => stripslashes($item["author-name"]),
2250                                         "source_link"  => $item["author-link"],
2251                                         "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2252                                                 ? $importer["thumb"] : $item["author-avatar"]),
2253                                         "verb"         => $item["verb"],
2254                                         "otype"        => "person",
2255                                         "activity"     => $verb,
2256                                         "parent"       => $item["parent"])
2257                                 );
2258                         }
2259                 }
2260         }
2261
2262         /**
2263          * @brief Processes several actions, depending on the verb
2264          *
2265          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2266          * @param array $importer  Record of the importer user mixed with contact of the content
2267          * @param array $item      the new item record
2268          * @param bool  $is_like   Is the verb a "like"?
2269          *
2270          * @return bool Should the processing of the entries be continued?
2271          * @todo set proper type-hints (array?)
2272          */
2273         private static function process_verbs($entrytype, $importer, &$item, &$is_like)
2274         {
2275                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2276
2277                 if (($entrytype == DFRN_TOP_LEVEL)) {
2278                         // The filling of the the "contact" variable is done for legcy reasons
2279                         // The functions below are partly used by ostatus.php as well - where we have this variable
2280                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2281                         $contact = $r[0];
2282                         $nickname = $contact["nick"];
2283
2284                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2285                         // This function once was responsible for DFRN and OStatus.
2286                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2287                                 logger("New follower");
2288                                 new_follower($importer, $contact, $item, $nickname);
2289                                 return false;
2290                         }
2291                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2292                                 logger("Lost follower");
2293                                 lose_follower($importer, $contact, $item);
2294                                 return false;
2295                         }
2296                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2297                                 logger("New friend request");
2298                                 new_follower($importer, $contact, $item, $nickname, true);
2299                                 return false;
2300                         }
2301                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2302                                 logger("Lost sharer");
2303                                 lose_sharer($importer, $contact, $item);
2304                                 return false;
2305                         }
2306                 } else {
2307                         if (($item["verb"] == ACTIVITY_LIKE)
2308                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2309                                 || ($item["verb"] == ACTIVITY_ATTEND)
2310                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2311                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2312                         ) {
2313                                 $is_like = true;
2314                                 $item["type"] = "activity";
2315                                 $item["gravity"] = GRAVITY_LIKE;
2316                                 // only one like or dislike per person
2317                                 // splitted into two queries for performance issues
2318                                 $r = q(
2319                                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2320                                         intval($item["uid"]),
2321                                         dbesc($item["author-link"]),
2322                                         dbesc($item["verb"]),
2323                                         dbesc($item["parent-uri"])
2324                                 );
2325                                 if (DBM::is_result($r)) {
2326                                         return false;
2327                                 }
2328
2329                                 $r = q(
2330                                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2331                                         intval($item["uid"]),
2332                                         dbesc($item["author-link"]),
2333                                         dbesc($item["verb"]),
2334                                         dbesc($item["parent-uri"])
2335                                 );
2336                                 if (DBM::is_result($r)) {
2337                                         return false;
2338                                 }
2339                         } else {
2340                                 $is_like = false;
2341                         }
2342
2343                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2344
2345                                 $xo = parse_xml_string($item["object"], false);
2346                                 $xt = parse_xml_string($item["target"], false);
2347
2348                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2349                                         $r = q(
2350                                                 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2351                                                 dbesc($xt->id),
2352                                                 intval($importer["importer_uid"])
2353                                         );
2354
2355                                         if (!DBM::is_result($r)) {
2356                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2357                                                 return false;
2358                                         }
2359
2360                                         // extract tag, if not duplicate, add to parent item
2361                                         if ($xo->content) {
2362                                                 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2363                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2364                                                                 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2365                                                                 intval($r[0]["id"])
2366                                                         );
2367                                                         create_tags_from_item($r[0]["id"]);
2368                                                 }
2369                                         }
2370                                 }
2371                         }
2372                 }
2373                 return true;
2374         }
2375
2376         /**
2377          * @brief Processes the link elements
2378          *
2379          * @param object $links link elements
2380          * @param array  $item  the item record
2381          * @todo set proper type-hints
2382          */
2383         private static function parse_links($links, &$item)
2384         {
2385                 $rel = "";
2386                 $href = "";
2387                 $type = "";
2388                 $length = "0";
2389                 $title = "";
2390                 foreach ($links AS $link) {
2391                         foreach ($link->attributes AS $attributes) {
2392                                 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2393                                 if ($attributes->name == "href") {
2394                                         $href = $attributes->textContent;
2395                                 }
2396                                 if ($attributes->name == "rel") {
2397                                         $rel = $attributes->textContent;
2398                                 }
2399                                 if ($attributes->name == "type") {
2400                                         $type = $attributes->textContent;
2401                                 }
2402                                 if ($attributes->name == "length") {
2403                                         $length = $attributes->textContent;
2404                                 }
2405                                 if ($attributes->name == "title") {
2406                                         $title = $attributes->textContent;
2407                                 }
2408                         }
2409                         if (($rel != "") && ($href != "")) {
2410                                 switch ($rel) {
2411                                         case "alternate":
2412                                                 $item["plink"] = $href;
2413                                                 break;
2414                                         case "enclosure":
2415                                                 $enclosure = $href;
2416                                                 if (strlen($item["attach"])) {
2417                                                         $item["attach"] .= ",";
2418                                                 }
2419
2420                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2421                                                 break;
2422                                 }
2423                         }
2424                 }
2425         }
2426
2427         /**
2428          * @brief Processes the entry elements which contain the items and comments
2429          *
2430          * @param array $header Array of the header elements that always stay the same
2431          * @param object $xpath XPath object
2432          * @param object $entry entry elements
2433          * @param array $importer Record of the importer user mixed with contact of the content
2434          * @todo Add type-hints
2435          */
2436         private static function process_entry($header, $xpath, $entry, $importer, $xml)
2437         {
2438                 logger("Processing entries");
2439
2440                 $item = $header;
2441
2442                 $item["protocol"] = PROTOCOL_DFRN;
2443
2444                 $item["source"] = $xml;
2445
2446                 // Get the uri
2447                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2448
2449                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2450
2451                 $current = q(
2452                         "SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2453                         dbesc($item["uri"]),
2454                         intval($importer["importer_uid"])
2455                 );
2456
2457                 // Is there an existing item?
2458                 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item)
2459                         && (datetime_convert("UTC", "UTC", $item["edited"]) < $current[0]["edited"])
2460                 ) {
2461                         logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2462                         return;
2463                 }
2464
2465                 // Fetch the owner
2466                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2467
2468                 $item["owner-name"] = $owner["name"];
2469                 $item["owner-link"] = $owner["link"];
2470                 $item["owner-avatar"] = $owner["avatar"];
2471
2472                 // fetch the author
2473                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2474
2475                 $item["author-name"] = $author["name"];
2476                 $item["author-link"] = $author["link"];
2477                 $item["author-avatar"] = $author["avatar"];
2478
2479                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2480
2481                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2482
2483                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2484                 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''), $item["body"]);
2485                 // make sure nobody is trying to sneak some html tags by us
2486                 $item["body"] = notags(base64url_decode($item["body"]));
2487
2488                 $item["body"] = limit_body_size($item["body"]);
2489
2490                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2491                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2492                         $item['body'] = reltoabs($item['body'], $base_url);
2493
2494                         $item['body'] = html2bb_video($item['body']);
2495
2496                         $item['body'] = oembed_html2bbcode($item['body']);
2497
2498                         $config = HTMLPurifier_Config::createDefault();
2499                         $config->set('Cache.DefinitionImpl', null);
2500
2501                         // we shouldn't need a whitelist, because the bbcode converter
2502                         // will strip out any unsupported tags.
2503
2504                         $purifier = new HTMLPurifier($config);
2505                         $item['body'] = $purifier->purify($item['body']);
2506
2507                         $item['body'] = @html2bbcode($item['body']);
2508                 }
2509
2510                 /// @todo We should check for a repeated post and if we know the repeated author.
2511
2512                 // We don't need the content element since "dfrn:env" is always present
2513                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2514
2515                 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2516                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2517
2518                 $georsspoint = $xpath->query("georss:point", $entry);
2519                 if ($georsspoint) {
2520                         $item["coord"] = $georsspoint->item(0)->nodeValue;
2521                 }
2522
2523                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2524
2525                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2526
2527                 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2528                         $item["bookmark"] = true;
2529                 }
2530
2531                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2532                 if ($notice_info && ($notice_info->length > 0)) {
2533                         foreach ($notice_info->item(0)->attributes AS $attributes) {
2534                                 if ($attributes->name == "source") {
2535                                         $item["app"] = strip_tags($attributes->textContent);
2536                                 }
2537                         }
2538                 }
2539
2540                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2541
2542                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2543                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2544                 if ($dsprsig != "") {
2545                         $item["dsprsig"] = $dsprsig;
2546                 }
2547
2548                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2549
2550                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2551                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2552                 }
2553
2554                 $object = $xpath->query("activity:object", $entry)->item(0);
2555                 $item["object"] = self::transform_activity($xpath, $object, "object");
2556
2557                 if (trim($item["object"]) != "") {
2558                         $r = parse_xml_string($item["object"], false);
2559                         if (isset($r->type)) {
2560                                 $item["object-type"] = $r->type;
2561                         }
2562                 }
2563
2564                 $target = $xpath->query("activity:target", $entry)->item(0);
2565                 $item["target"] = self::transform_activity($xpath, $target, "target");
2566
2567                 $categories = $xpath->query("atom:category", $entry);
2568                 if ($categories) {
2569                         foreach ($categories AS $category) {
2570                                 $term = "";
2571                                 $scheme = "";
2572                                 foreach ($category->attributes AS $attributes) {
2573                                         if ($attributes->name == "term") {
2574                                                 $term = $attributes->textContent;
2575                                         }
2576
2577                                         if ($attributes->name == "scheme") {
2578                                                 $scheme = $attributes->textContent;
2579                                         }
2580                                 }
2581
2582                                 if (($term != "") && ($scheme != "")) {
2583                                         $parts = explode(":", $scheme);
2584                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2585                                                 $termhash = array_shift($parts);
2586                                                 $termurl = implode(":", $parts);
2587
2588                                                 if (strlen($item["tag"])) {
2589                                                         $item["tag"] .= ",";
2590                                                 }
2591
2592                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2593                                         }
2594                                 }
2595                         }
2596                 }
2597
2598                 $enclosure = "";
2599
2600                 $links = $xpath->query("atom:link", $entry);
2601                 if ($links) {
2602                         self::parse_links($links, $item);
2603                 }
2604
2605                 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2606
2607                 $conv = $xpath->query('ostatus:conversation', $entry);
2608                 if (is_object($conv->item(0))) {
2609                         foreach ($conv->item(0)->attributes AS $attributes) {
2610                                 if ($attributes->name == "ref") {
2611                                         $item['conversation-uri'] = $attributes->textContent;
2612                                 }
2613                                 if ($attributes->name == "href") {
2614                                         $item['conversation-href'] = $attributes->textContent;
2615                                 }
2616                         }
2617                 }
2618
2619                 // Is it a reply or a top level posting?
2620                 $item["parent-uri"] = $item["uri"];
2621
2622                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2623                 if (is_object($inreplyto->item(0))) {
2624                         foreach ($inreplyto->item(0)->attributes AS $attributes) {
2625                                 if ($attributes->name == "ref") {
2626                                         $item["parent-uri"] = $attributes->textContent;
2627                                 }
2628                         }
2629                 }
2630
2631                 // Get the type of the item (Top level post, reply or remote reply)
2632                 $entrytype = self::get_entry_type($importer, $item);
2633
2634                 // Now assign the rest of the values that depend on the type of the message
2635                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2636                         if (!isset($item["object-type"])) {
2637                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2638                         }
2639
2640                         if ($item["contact-id"] != $owner["contact-id"]) {
2641                                 $item["contact-id"] = $owner["contact-id"];
2642                         }
2643
2644                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2645                                 $item["network"] = $owner["network"];
2646                         }
2647
2648                         if ($item["contact-id"] != $author["contact-id"]) {
2649                                 $item["contact-id"] = $author["contact-id"];
2650                         }
2651
2652                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2653                                 $item["network"] = $author["network"];
2654                         }
2655
2656                         /// @TODO maybe remove this old-lost code then?
2657                         // This code was taken from the old DFRN code
2658                         // When activated, forums don't work.
2659                         // And: Why should we disallow commenting by followers?
2660                         // the behaviour is now similar to the Diaspora part.
2661                         //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2662                         //      logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2663                         //      return;
2664                         //}
2665                 }
2666
2667                 if ($entrytype == DFRN_REPLY_RC) {
2668                         $item["type"] = "remote-comment";
2669                         $item["wall"] = 1;
2670                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2671                         if (!isset($item["object-type"])) {
2672                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2673                         }
2674
2675                         // Is it an event?
2676                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2677                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2678                                 $ev = bbtoevent($item["body"]);
2679                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2680                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2681                                         /// @TODO Mixure of "/' ahead ...
2682                                         $ev["cid"] = $importer["id"];
2683                                         $ev["uid"] = $importer["uid"];
2684                                         $ev["uri"] = $item["uri"];
2685                                         $ev["edited"] = $item["edited"];
2686                                         $ev['private'] = $item['private'];
2687                                         $ev["guid"] = $item["guid"];
2688
2689                                         $r = q(
2690                                                 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2691                                                 dbesc($item["uri"]),
2692                                                 intval($importer["uid"])
2693                                         );
2694                                         if (DBM::is_result($r)) {
2695                                                 $ev["id"] = $r[0]["id"];
2696                                         }
2697
2698                                         $event_id = event_store($ev);
2699                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2700                                         return;
2701                                 }
2702                         }
2703                 }
2704
2705                 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2706                         logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2707                         return;
2708                 }
2709
2710                 // Update content if 'updated' changes
2711                 if (DBM::is_result($current)) {
2712                         if (self::update_content($r[0], $item, $importer, $entrytype)) {
2713                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2714                         } else {
2715                                 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2716                         }
2717                         return;
2718                 }
2719
2720                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2721                         $posted_id = item_store($item);
2722                         $parent = 0;
2723
2724                         if ($posted_id) {
2725                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2726
2727                                 $item["id"] = $posted_id;
2728
2729                                 $r = q(
2730                                         "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2731                                         intval($posted_id),
2732                                         intval($importer["importer_uid"])
2733                                 );
2734                                 if (DBM::is_result($r)) {
2735                                         $parent = $r[0]["parent"];
2736                                         $parent_uri = $r[0]["parent-uri"];
2737                                 }
2738
2739                                 if (!$is_like) {
2740                                         $r1 = q(
2741                                                 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2742                                                 dbesc(datetime_convert()),
2743                                                 intval($importer["importer_uid"]),
2744                                                 intval($r[0]["parent"])
2745                                         );
2746
2747                                         $r2 = q(
2748                                                 "UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2749                                                 dbesc(datetime_convert()),
2750                                                 intval($importer["importer_uid"]),
2751                                                 intval($posted_id)
2752                                         );
2753                                 }
2754
2755                                 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2756                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2757                                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2758                                 }
2759
2760                                 return true;
2761                         }
2762                 } else { // $entrytype == DFRN_TOP_LEVEL
2763                         if (!link_compare($item["owner-link"], $importer["url"])) {
2764                                 /*
2765                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2766                                  * but otherwise there's a possible data mixup on the sender's system.
2767                                  * the tgroup delivery code called from item_store will correct it if it's a forum,
2768                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2769                                  */
2770                                 logger('Correcting item owner.', LOGGER_DEBUG);
2771                                 $item["owner-name"]   = $importer["senderName"];
2772                                 $item["owner-link"]   = $importer["url"];
2773                                 $item["owner-avatar"] = $importer["thumb"];
2774                         }
2775
2776                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2777                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2778                                 return;
2779                         }
2780
2781                         // This is my contact on another system, but it's really me.
2782                         // Turn this into a wall post.
2783                         $notify = item_is_remote_self($importer, $item);
2784
2785                         $posted_id = item_store($item, false, $notify);
2786
2787                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2788
2789                         if (stristr($item["verb"],ACTIVITY_POKE))
2790                                 self::do_poke($item, $importer, $posted_id);
2791                 }
2792         }
2793
2794         /**
2795          * @brief Deletes items
2796          *
2797          * @param object $xpath    XPath object
2798          * @param object $deletion deletion elements
2799          * @param array  $importer Record of the importer user mixed with contact of the content
2800          * @todo set proper type-hints
2801          */
2802         private static function process_deletion($xpath, $deletion, $importer)
2803         {
2804                 logger("Processing deletions");
2805
2806                 foreach ($deletion->attributes AS $attributes) {
2807                         if ($attributes->name == "ref") {
2808                                 $uri = $attributes->textContent;
2809                         }
2810                         if ($attributes->name == "when") {
2811                                 $when = $attributes->textContent;
2812                         }
2813                 }
2814                 if ($when) {
2815                         $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2816                 } else {
2817                         $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2818                 }
2819
2820                 if (!$uri || !$importer["id"]) {
2821                         return false;
2822                 }
2823
2824                 /// @todo Only select the used fields
2825                 $r = q(
2826                         "SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2827                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2828                         dbesc($uri),
2829                         intval($importer["uid"]),
2830                         intval($importer["id"])
2831                 );
2832                 if (!DBM::is_result($r)) {
2833                         logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2834                         return;
2835                 } else {
2836                         $item = $r[0];
2837
2838                         $entrytype = self::get_entry_type($importer, $item);
2839
2840                         if (!$item["deleted"]) {
2841                                 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2842                         } else {
2843                                 return;
2844                         }
2845
2846                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2847                                 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2848                                 event_delete($item["event-id"]);
2849                         }
2850
2851                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2852
2853                                 $xo = parse_xml_string($item["object"], false);
2854                                 $xt = parse_xml_string($item["target"], false);
2855
2856                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2857                                         $i = q(
2858                                                 "SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2859                                                 dbesc($xt->id),
2860                                                 intval($importer["importer_uid"])
2861                                         );
2862                                         if (DBM::is_result($i)) {
2863                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2864
2865                                                 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2866                                                 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2867                                                 $author_copy = (($item["origin"]) ? true : false);
2868
2869                                                 if ($owner_remove && $author_copy) {
2870                                                         return;
2871                                                 }
2872                                                 if ($author_remove || $owner_remove) {
2873                                                         $tags = explode(',', $i[0]["tag"]);
2874                                                         $newtags = array();
2875                                                         if (count($tags)) {
2876                                                                 foreach ($tags as $tag) {
2877                                                                         if (trim($tag) !== trim($xo->body)) {
2878                                                                                 $newtags[] = trim($tag);
2879                                                                         }
2880                                                                 }
2881                                                         }
2882                                                         q(
2883                                                                 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2884                                                                 dbesc(implode(',', $newtags)),
2885                                                                 intval($i[0]["id"])
2886                                                         );
2887                                                         create_tags_from_item($i[0]["id"]);
2888                                                 }
2889                                         }
2890                                 }
2891                         }
2892
2893                         if ($entrytype == DFRN_TOP_LEVEL) {
2894                                 $r = q(
2895                                         "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2896                                                 `body` = '', `title` = ''
2897                                         WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2898                                         dbesc($when),
2899                                         dbesc(datetime_convert()),
2900                                         dbesc($uri),
2901                                         intval($importer["uid"])
2902                                 );
2903                                 create_tags_from_itemuri($uri, $importer["uid"]);
2904                                 create_files_from_itemuri($uri, $importer["uid"]);
2905                                 update_thread_uri($uri, $importer["uid"]);
2906                         } else {
2907                                 $r = q(
2908                                         "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2909                                                 `body` = '', `title` = ''
2910                                         WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2911                                         dbesc($when),
2912                                         dbesc(datetime_convert()),
2913                                         dbesc($uri),
2914                                         intval($importer["uid"])
2915                                 );
2916                                 create_tags_from_itemuri($uri, $importer["uid"]);
2917                                 create_files_from_itemuri($uri, $importer["uid"]);
2918                                 update_thread_uri($uri, $importer["importer_uid"]);
2919                                 if ($item["last-child"]) {
2920                                         // ensure that last-child is set in case the comment that had it just got wiped.
2921                                         q(
2922                                                 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2923                                                 dbesc(datetime_convert()),
2924                                                 dbesc($item["parent-uri"]),
2925                                                 intval($item["uid"])
2926                                         );
2927                                         // who is the last child now?
2928                                         $r = q(
2929                                                 "SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2930                                                 ORDER BY `created` DESC LIMIT 1",
2931                                                 dbesc($item["parent-uri"]),
2932                                                 intval($importer["uid"])
2933                                         );
2934                                         if (DBM::is_result($r)) {
2935                                                 q(
2936                                                         "UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2937                                                         intval($r[0]["id"])
2938                                                 );
2939                                         }
2940                                 }
2941                                 // if this is a relayed delete, propagate it to other recipients
2942
2943                                 if ($entrytype == DFRN_REPLY_RC) {
2944                                         logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2945                                         Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2946                                 }
2947                         }
2948                 }
2949         }
2950
2951         /**
2952          * @brief Imports a DFRN message
2953          *
2954          * @param text  $xml          The DFRN message
2955          * @param array $importer     Record of the importer user mixed with contact of the content
2956          * @param bool  $sort_by_date Is used when feeds are polled
2957          * @return integer Import status
2958          * @todo set proper type-hints
2959          */
2960         public static function import($xml, $importer, $sort_by_date = false)
2961         {
2962                 if ($xml == "") {
2963                         return 400;
2964                 }
2965
2966                 $doc = new DOMDocument();
2967                 @$doc->loadXML($xml);
2968
2969                 $xpath = new DomXPath($doc);
2970                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2971                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2972                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2973                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2974                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2975                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2976                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2977                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2978                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2979                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2980
2981                 $header = array();
2982                 $header["uid"] = $importer["uid"];
2983                 $header["network"] = NETWORK_DFRN;
2984                 $header["type"] = "remote";
2985                 $header["wall"] = 0;
2986                 $header["origin"] = 0;
2987                 $header["contact-id"] = $importer["id"];
2988
2989                 // Update the contact table if the data has changed
2990
2991                 // The "atom:author" is only present in feeds
2992                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2993                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2994                 }
2995
2996                 // Only the "dfrn:owner" in the head section contains all data
2997                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2998                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2999                 }
3000
3001                 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
3002
3003                 // The account type is new since 3.5.1
3004                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
3005                         $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
3006
3007                         if ($accounttype != $importer["contact-type"]) {
3008                                 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
3009                         }
3010                 }
3011
3012                 // is it a public forum? Private forums aren't supported with this method
3013                 // This is deprecated since 3.5.1
3014                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
3015
3016                 if ($forum != $importer["forum"]) {
3017                         $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
3018                         dba::update('contact', array('forum' => $forum), $condition);
3019                 }
3020
3021                 // We are processing relocations even if we are ignoring a contact
3022                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
3023                 foreach ($relocations AS $relocation) {
3024                         self::process_relocation($xpath, $relocation, $importer);
3025                 }
3026
3027                 if ($importer["readonly"]) {
3028                         // We aren't receiving stuff from this person. But we will quietly ignore them
3029                         // rather than a blatant "go away" message.
3030                         logger('ignoring contact '.$importer["id"]);
3031                         return 403;
3032                 }
3033
3034                 $mails = $xpath->query("/atom:feed/dfrn:mail");
3035                 foreach ($mails AS $mail) {
3036                         self::process_mail($xpath, $mail, $importer);
3037                 }
3038
3039                 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
3040                 foreach ($suggestions AS $suggestion) {
3041                         self::process_suggestion($xpath, $suggestion, $importer);
3042                 }
3043
3044                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
3045                 foreach ($deletions AS $deletion) {
3046                         self::process_deletion($xpath, $deletion, $importer);
3047                 }
3048
3049                 if (!$sort_by_date) {
3050                         $entries = $xpath->query("/atom:feed/atom:entry");
3051                         foreach ($entries AS $entry) {
3052                                 self::process_entry($header, $xpath, $entry, $importer, $xml);
3053                         }
3054                 } else {
3055                         $newentries = array();
3056                         $entries = $xpath->query("/atom:feed/atom:entry");
3057                         foreach ($entries AS $entry) {
3058                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
3059                                 $newentries[strtotime($created)] = $entry;
3060                         }
3061
3062                         // Now sort after the publishing date
3063                         ksort($newentries);
3064
3065                         foreach ($newentries AS $entry) {
3066                                 self::process_entry($header, $xpath, $entry, $importer, $xml);
3067                         }
3068                 }
3069                 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
3070                 return 200;
3071         }
3072 }