]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
Move Object\Contact to Model\Contact
[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\Contact;
17 use Friendica\Model\GlobalContact;
18 use Friendica\Model\Profile;
19 use Friendica\Object\Image;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Util\XML;
22
23 use dba;
24 use DOMDocument;
25 use DomXPath;
26
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::addHeader($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::addHeader($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::addHeader($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::addHeader($doc, $owner, "dfrn:owner", "", false);
403
404                 $mail = $doc->createElement("dfrn:mail");
405                 $sender = $doc->createElement("dfrn:sender");
406
407                 XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
408                 XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
409                 XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
410
411                 $mail->appendChild($sender);
412
413                 XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
414                 XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
415                 XML::addElement($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME));
416                 XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
417                 XML::addElement($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::addHeader($doc, $owner, "dfrn:owner", "", false);
439
440                 $suggest = $doc->createElement("dfrn:suggest");
441
442                 XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
443                 XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
444                 XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
445                 XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
446                 XML::addElement($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 = Image::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::addHeader($doc, $owner, "dfrn:owner", "", false);
491
492                 $relocate = $doc->createElement("dfrn:relocate");
493
494                 XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
495                 XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
496                 XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
497                 XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
498                 XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
499                 XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
500                 XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
501                 XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
502                 XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
503                 XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
504                 XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
505                 XML::addElement($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 addHeader($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::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
545                 XML::addElement($doc, $root, "title", $owner["name"]);
546
547                 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
548                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
549
550                 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
551                 XML::addElement($doc, $root, "link", "", $attributes);
552
553                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
554                 XML::addElement($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::addElement($doc, $root, "link", "", $attributes);
563
564                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
565                         XML::addElement($doc, $root, "link", "", $attributes);
566
567                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
568                         XML::addElement($doc, $root, "link", "", $attributes);
569                 }
570
571                 // For backward compatibility we keep this element
572                 if ($owner['page-flags'] == PAGE_COMMUNITY) {
573                         XML::addElement($doc, $root, "dfrn:community", 1);
574                 }
575
576                 // The former element is replaced by this one
577                 XML::addElement($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::addElement($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
582
583                 $author = self::addAuthor($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          * @param boolean $public        boolean
596          *
597          * @return object XML author object
598          * @todo Add type-hints
599          */
600         private static function addAuthor($doc, $owner, $authorelement, $public)
601         {
602                 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
603                 $r = q(
604                         "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
605                                 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
606                         intval($owner['uid'])
607                 );
608                 if (DBM::is_result($r)) {
609                         $hidewall = true;
610                 } else {
611                         $hidewall = false;
612                 }
613
614                 $author = $doc->createElement($authorelement);
615
616                 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
617                 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
618                 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
619
620                 $attributes = array();
621
622                 if (!$public || !$hidewall) {
623                         $attributes = array("dfrn:updated" => $namdate);
624                 }
625
626                 XML::addElement($doc, $author, "name", $owner["name"], $attributes);
627                 XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
628                 XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
629
630                 $attributes = array("rel" => "photo", "type" => "image/jpeg",
631                                         "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
632
633                 if (!$public || !$hidewall) {
634                         $attributes["dfrn:updated"] = $picdate;
635                 }
636
637                 XML::addElement($doc, $author, "link", "", $attributes);
638
639                 $attributes["rel"] = "avatar";
640                 XML::addElement($doc, $author, "link", "", $attributes);
641
642                 if ($hidewall) {
643                         XML::addElement($doc, $author, "dfrn:hide", "true");
644                 }
645
646                 // The following fields will only be generated if the data isn't meant for a public feed
647                 if ($public) {
648                         return $author;
649                 }
650
651                 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
652
653                 if ($birthday) {
654                         XML::addElement($doc, $author, "dfrn:birthday", $birthday);
655                 }
656
657                 // Only show contact details when we are allowed to
658                 $r = q(
659                         "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
660                                 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
661                                 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
662                         FROM `profile`
663                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
664                                 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
665                         intval($owner['uid'])
666                 );
667                 if (DBM::is_result($r)) {
668                         $profile = $r[0];
669
670                         XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
671                         XML::addElement($doc, $author, "poco:updated", $namdate);
672
673                         if (trim($profile["dob"]) > '0001-01-01') {
674                                 XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
675                         }
676
677                         XML::addElement($doc, $author, "poco:note", $profile["about"]);
678                         XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
679
680                         $savetz = date_default_timezone_get();
681                         date_default_timezone_set($profile["timezone"]);
682                         XML::addElement($doc, $author, "poco:utcOffset", date("P"));
683                         date_default_timezone_set($savetz);
684
685                         if (trim($profile["homepage"]) != "") {
686                                 $urls = $doc->createElement("poco:urls");
687                                 XML::addElement($doc, $urls, "poco:type", "homepage");
688                                 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
689                                 XML::addElement($doc, $urls, "poco:primary", "true");
690                                 $author->appendChild($urls);
691                         }
692
693                         if (trim($profile["pub_keywords"]) != "") {
694                                 $keywords = explode(",", $profile["pub_keywords"]);
695
696                                 foreach ($keywords as $keyword) {
697                                         XML::addElement($doc, $author, "poco:tags", trim($keyword));
698                                 }
699                         }
700
701                         if (trim($profile["xmpp"]) != "") {
702                                 $ims = $doc->createElement("poco:ims");
703                                 XML::addElement($doc, $ims, "poco:type", "xmpp");
704                                 XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
705                                 XML::addElement($doc, $ims, "poco:primary", "true");
706                                 $author->appendChild($ims);
707                         }
708
709                         if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
710                                 $element = $doc->createElement("poco:address");
711
712                                 XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
713
714                                 if (trim($profile["locality"]) != "") {
715                                         XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
716                                 }
717
718                                 if (trim($profile["region"]) != "") {
719                                         XML::addElement($doc, $element, "poco:region", $profile["region"]);
720                                 }
721
722                                 if (trim($profile["country-name"]) != "") {
723                                         XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
724                                 }
725
726                                 $author->appendChild($element);
727                         }
728                 }
729
730                 return $author;
731         }
732
733         /**
734          * @brief Adds the author elements in the "entry" elements of the DFRN protocol
735          *
736          * @param object $doc         XML document
737          * @param string $element     Element name for the author
738          * @param string $contact_url Link of the contact
739          * @param array  $item        Item elements
740          *
741          * @return object XML author object
742          * @todo Add type-hints
743          */
744         private static function addEntryAuthor($doc, $element, $contact_url, $item)
745         {
746                 $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
747
748                 $author = $doc->createElement($element);
749                 XML::addElement($doc, $author, "name", $contact["name"]);
750                 XML::addElement($doc, $author, "uri", $contact["url"]);
751                 XML::addElement($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::addElement($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::addElement($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 createActivity($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::addElement($doc, $entry, "activity:object-type", $r->type);
796                         }
797                         if ($r->id) {
798                                 XML::addElement($doc, $entry, "id", $r->id);
799                         }
800                         if ($r->title) {
801                                 XML::addElement($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::addElement($doc, $entry, "link", "", $attributes);
821                                                 }
822                                         }
823                                 } else {
824                                         $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
825                                         XML::addElement($doc, $entry, "link", "", $attributes);
826                                 }
827                         }
828                         if ($r->content) {
829                                 XML::addElement($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 getAttachment($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::addElement($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::createElement($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::addEntryAuthor($doc, "author", $item["author-link"], $item);
938                 $entry->appendChild($author);
939
940                 $dfrnowner = self::addEntryAuthor($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::addElement($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::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
973
974                 XML::addElement($doc, $entry, "id", $item["uri"]);
975                 XML::addElement($doc, $entry, "title", $item["title"]);
976
977                 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
978                 XML::addElement($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::addElement($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::addElement($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::addElement(
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::addElement($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
1001                 }
1002
1003                 if ($item['location']) {
1004                         XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1005                 }
1006
1007                 if ($item['coord']) {
1008                         XML::addElement($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::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1013                 }
1014
1015                 if ($item['extid']) {
1016                         XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1017                 }
1018
1019                 if ($item['bookmark']) {
1020                         XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1021                 }
1022
1023                 if ($item['app']) {
1024                         XML::addElement($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
1025                 }
1026
1027                 XML::addElement($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::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1034                 }
1035
1036                 XML::addElement($doc, $entry, "activity:verb", construct_verb($item));
1037
1038                 if ($item['object-type'] != "") {
1039                         XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1040                 } elseif ($item['id'] == $item['parent']) {
1041                         XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1042                 } else {
1043                         XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1044                 }
1045
1046                 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1047                 if ($actobj) {
1048                         $entry->appendChild($actobj);
1049                 }
1050
1051                 $actarg = self::createActivity($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::addElement($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::addElement(
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::addElement(
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::getAttachment($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 aesEncrypt($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 aesDecrypt($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::aesEncrypt($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                         Contact::unmarkForArchival($contact);
1377                 }
1378
1379                 $res = parse_xml_string($xml);
1380
1381                 if (!isset($res->status)) {
1382                         return -11;
1383                 }
1384
1385                 if (!empty($res->message)) {
1386                         logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1387                 }
1388
1389                 return intval($res->status);
1390         }
1391
1392         /**
1393          * @brief Add new birthday event for this person
1394          *
1395          * @param array  $contact  Contact record
1396          * @param string $birthday Birthday of the contact
1397          * @return void
1398          * @todo Add array type-hint for $contact
1399          */
1400         private static function birthdayEvent($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          * @param string $xml       optional, default empty
1444          *
1445          * @return Returns an array with relevant data of the author
1446          * @todo Find good type-hints for all parameter
1447          */
1448         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1449         {
1450                 $author = array();
1451                 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1452                 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1453
1454                 $r = q(
1455                         "SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1456                                 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1457                                 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1458                         intval($importer["uid"]),
1459                         dbesc(normalise_link($author["link"])),
1460                         dbesc(NETWORK_STATUSNET)
1461                 );
1462
1463                 if (DBM::is_result($r)) {
1464                         $contact = $r[0];
1465                         $author["contact-id"] = $r[0]["id"];
1466                         $author["network"] = $r[0]["network"];
1467                 } else {
1468                         if (!$onlyfetch) {
1469                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1470                         }
1471
1472                         $author["contact-id"] = $importer["id"];
1473                         $author["network"] = $importer["network"];
1474                         $onlyfetch = true;
1475                 }
1476
1477                 // Until now we aren't serving different sizes - but maybe later
1478                 $avatarlist = array();
1479                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1480                 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1481                 foreach ($avatars as $avatar) {
1482                         $href = "";
1483                         $width = 0;
1484                         foreach ($avatar->attributes as $attributes) {
1485                                 /// @TODO Rewrite these similar if () to one switch
1486                                 if ($attributes->name == "href") {
1487                                         $href = $attributes->textContent;
1488                                 }
1489                                 if ($attributes->name == "width") {
1490                                         $width = $attributes->textContent;
1491                                 }
1492                                 if ($attributes->name == "updated") {
1493                                         $contact["avatar-date"] = $attributes->textContent;
1494                                 }
1495                         }
1496                         if (($width > 0) && ($href != "")) {
1497                                 $avatarlist[$width] = $href;
1498                         }
1499                 }
1500                 if (count($avatarlist) > 0) {
1501                         krsort($avatarlist);
1502                         $author["avatar"] = current($avatarlist);
1503                 }
1504
1505                 if (DBM::is_result($r) && !$onlyfetch) {
1506                         logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1507
1508                         $poco = array("url" => $contact["url"]);
1509
1510                         // When was the last change to name or uri?
1511                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1512                         foreach ($name_element->attributes as $attributes) {
1513                                 if ($attributes->name == "updated") {
1514                                         $poco["name-date"] = $attributes->textContent;
1515                                 }
1516                         }
1517
1518                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1519                         foreach ($link_element->attributes as $attributes) {
1520                                 if ($attributes->name == "updated") {
1521                                         $poco["uri-date"] = $attributes->textContent;
1522                                 }
1523                         }
1524
1525                         // Update contact data
1526                         $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1527                         if ($value != "") {
1528                                 $poco["addr"] = $value;
1529                         }
1530
1531                         $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1532                         if ($value != "") {
1533                                 $poco["name"] = $value;
1534                         }
1535
1536                         $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1537                         if ($value != "") {
1538                                 $poco["nick"] = $value;
1539                         }
1540
1541                         $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1542                         if ($value != "") {
1543                                 $poco["about"] = $value;
1544                         }
1545
1546                         $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1547                         if ($value != "") {
1548                                 $poco["location"] = $value;
1549                         }
1550
1551                         /// @todo Only search for elements with "poco:type" = "xmpp"
1552                         $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1553                         if ($value != "") {
1554                                 $poco["xmpp"] = $value;
1555                         }
1556
1557                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1558                         /// - poco:utcOffset
1559                         /// - poco:urls
1560                         /// - poco:locality
1561                         /// - poco:region
1562                         /// - poco:country
1563
1564                         // If the "hide" element is present then the profile isn't searchable.
1565                         $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1566
1567                         logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1568
1569                         // If the contact isn't searchable then set the contact to "hidden".
1570                         // Problem: This can be manually overridden by the user.
1571                         if ($hide) {
1572                                 $contact["hidden"] = true;
1573                         }
1574
1575                         // Save the keywords into the contact table
1576                         $tags = array();
1577                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1578                         foreach ($tagelements as $tag) {
1579                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1580                         }
1581
1582                         if (count($tags)) {
1583                                 $poco["keywords"] = implode(", ", $tags);
1584                         }
1585
1586                         // "dfrn:birthday" contains the birthday converted to UTC
1587                         $old_bdyear = $contact["bdyear"];
1588
1589                         $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1590
1591                         if (strtotime($birthday) > time()) {
1592                                 $bd_timestamp = strtotime($birthday);
1593
1594                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1595                         }
1596
1597                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1598                         $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1599
1600                         if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1601                                 $bdyear = date("Y");
1602                                 $value = str_replace("0000", $bdyear, $value);
1603
1604                                 if (strtotime($value) < time()) {
1605                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1606                                         $bdyear = $bdyear + 1;
1607                                 }
1608
1609                                 $poco["bd"] = $value;
1610                         }
1611
1612                         $contact = array_merge($contact, $poco);
1613
1614                         if ($old_bdyear != $contact["bdyear"]) {
1615                                 self::birthdayEvent($contact, $birthday);
1616                         }
1617
1618                         // Get all field names
1619                         $fields = array();
1620                         foreach ($r[0] as $field => $data) {
1621                                 $fields[$field] = $data;
1622                         }
1623
1624                         unset($fields["id"]);
1625                         unset($fields["uid"]);
1626                         unset($fields["url"]);
1627                         unset($fields["avatar-date"]);
1628                         unset($fields["name-date"]);
1629                         unset($fields["uri-date"]);
1630
1631                         // Update check for this field has to be done differently
1632                         $datefields = array("name-date", "uri-date");
1633                         foreach ($datefields as $field) {
1634                                 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1635                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1636                                         $update = true;
1637                                 }
1638                         }
1639
1640                         foreach ($fields as $field => $data) {
1641                                 if ($contact[$field] != $r[0][$field]) {
1642                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1643                                         $update = true;
1644                                 }
1645                         }
1646
1647                         if ($update) {
1648                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1649
1650                                 q(
1651                                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1652                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1653                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1654                                         WHERE `id` = %d AND `network` = '%s'",
1655                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]),     dbesc($contact["location"]),
1656                                         dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1657                                         dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1658                                         dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1659                                         intval($contact["id"]), dbesc($contact["network"])
1660                                 );
1661                         }
1662
1663                         Contact::updateAvatar(
1664                                 $author["avatar"],
1665                                 $importer["uid"],
1666                                 $contact["id"],
1667                                 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"]))
1668                         );
1669
1670                         /*
1671                          * The generation is a sign for the reliability of the provided data.
1672                          * It is used in the socgraph.php to prevent that old contact data
1673                          * that was relayed over several servers can overwrite contact
1674                          * data that we received directly.
1675                          */
1676
1677                         $poco["generation"] = 2;
1678                         $poco["photo"] = $author["avatar"];
1679                         $poco["hide"] = $hide;
1680                         $poco["contact-type"] = $contact["contact-type"];
1681                         $gcid = GlobalContact::update($poco);
1682
1683                         GlobalContact::link($gcid, $importer["uid"], $contact["id"]);
1684                 }
1685
1686                 return($author);
1687         }
1688
1689         /**
1690          * @brief Transforms activity objects into an XML string
1691          *
1692          * @param object $xpath    XPath object
1693          * @param object $activity Activity object
1694          * @param text   $element  element name
1695          *
1696          * @return string XML string
1697          * @todo Find good type-hints for all parameter
1698          */
1699         private static function transformActivity($xpath, $activity, $element)
1700         {
1701                 if (!is_object($activity)) {
1702                         return "";
1703                 }
1704
1705                 $obj_doc = new DOMDocument("1.0", "utf-8");
1706                 $obj_doc->formatOutput = true;
1707
1708                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1709
1710                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1711                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1712
1713                 $id = $xpath->query("atom:id", $activity)->item(0);
1714                 if (is_object($id)) {
1715                         $obj_element->appendChild($obj_doc->importNode($id, true));
1716                 }
1717
1718                 $title = $xpath->query("atom:title", $activity)->item(0);
1719                 if (is_object($title)) {
1720                         $obj_element->appendChild($obj_doc->importNode($title, true));
1721                 }
1722
1723                 $links = $xpath->query("atom:link", $activity);
1724                 if (is_object($links)) {
1725                         foreach ($links as $link) {
1726                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1727                         }
1728                 }
1729
1730                 $content = $xpath->query("atom:content", $activity)->item(0);
1731                 if (is_object($content)) {
1732                         $obj_element->appendChild($obj_doc->importNode($content, true));
1733                 }
1734
1735                 $obj_doc->appendChild($obj_element);
1736
1737                 $objxml = $obj_doc->saveXML($obj_element);
1738
1739                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1740                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1741                 return($objxml);
1742         }
1743
1744         /**
1745          * @brief Processes the mail elements
1746          *
1747          * @param object $xpath    XPath object
1748          * @param object $mail     mail elements
1749          * @param array  $importer Record of the importer user mixed with contact of the content
1750          * @return void
1751          * @todo Find good type-hints for all parameter
1752          */
1753         private static function processMail($xpath, $mail, $importer)
1754         {
1755                 logger("Processing mails");
1756
1757                 /// @TODO Rewrite this to one statement
1758                 $msg = array();
1759                 $msg["uid"] = $importer["importer_uid"];
1760                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1761                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1762                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1763                 $msg["contact-id"] = $importer["id"];
1764                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1765                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1766                 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1767                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1768                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1769                 $msg["seen"] = 0;
1770                 $msg["replied"] = 0;
1771
1772                 dba::insert('mail', $msg);
1773
1774                 // send notifications.
1775                 /// @TODO Arange this mess
1776                 $notif_params = array(
1777                         "type" => NOTIFY_MAIL,
1778                         "notify_flags" => $importer["notify-flags"],
1779                         "language" => $importer["language"],
1780                         "to_name" => $importer["username"],
1781                         "to_email" => $importer["email"],
1782                         "uid" => $importer["importer_uid"],
1783                         "item" => $msg,
1784                         "source_name" => $msg["from-name"],
1785                         "source_link" => $importer["url"],
1786                         "source_photo" => $importer["thumb"],
1787                         "verb" => ACTIVITY_POST,
1788                         "otype" => "mail"
1789                 );
1790
1791                 notification($notif_params);
1792
1793                 logger("Mail is processed, notification was sent.");
1794         }
1795
1796         /**
1797          * @brief Processes the suggestion elements
1798          *
1799          * @param object $xpath      XPath object
1800          * @param object $suggestion suggestion elements
1801          * @param array  $importer   Record of the importer user mixed with contact of the content
1802          * @return boolean
1803          * @todo Find good type-hints for all parameter
1804          */
1805         private static function processSuggestion($xpath, $suggestion, $importer)
1806         {
1807                 $a = get_app();
1808
1809                 logger("Processing suggestions");
1810
1811                 /// @TODO Rewrite this to one statement
1812                 $suggest = array();
1813                 $suggest["uid"] = $importer["importer_uid"];
1814                 $suggest["cid"] = $importer["id"];
1815                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1816                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1817                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1818                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1819                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1820
1821                 // Does our member already have a friend matching this description?
1822
1823                 $r = q(
1824                         "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1825                         dbesc($suggest["name"]),
1826                         dbesc(normalise_link($suggest["url"])),
1827                         intval($suggest["uid"])
1828                 );
1829
1830                 /*
1831                  * The valid result means the friend we're about to send a friend
1832                  * suggestion already has them in their contact, which means no further
1833                  * action is required.
1834                  *
1835                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1836                  */
1837                 if (DBM::is_result($r)) {
1838                         return false;
1839                 }
1840
1841                 // Do we already have an fcontact record for this person?
1842
1843                 $fid = 0;
1844                 $r = q(
1845                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1846                         dbesc($suggest["url"]),
1847                         dbesc($suggest["name"]),
1848                         dbesc($suggest["request"])
1849                 );
1850                 if (DBM::is_result($r)) {
1851                         $fid = $r[0]["id"];
1852
1853                         // OK, we do. Do we already have an introduction for this person ?
1854                         $r = q(
1855                                 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1856                                 intval($suggest["uid"]),
1857                                 intval($fid)
1858                         );
1859
1860                         /*
1861                          * The valid result means the friend we're about to send a friend
1862                          * suggestion already has them in their contact, which means no further
1863                          * action is required.
1864                          *
1865                          * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1866                          */
1867                         if (DBM::is_result($r)) {
1868                                 return false;
1869                         }
1870                 }
1871                 if (!$fid) {
1872                         $r = q(
1873                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1874                                 dbesc($suggest["name"]),
1875                                 dbesc($suggest["url"]),
1876                                 dbesc($suggest["photo"]),
1877                                 dbesc($suggest["request"])
1878                         );
1879                 }
1880                 $r = q(
1881                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1882                         dbesc($suggest["url"]),
1883                         dbesc($suggest["name"]),
1884                         dbesc($suggest["request"])
1885                 );
1886
1887                 /*
1888                  * If no record in fcontact is found, below INSERT statement will not
1889                  * link an introduction to it.
1890                  */
1891                 if (!DBM::is_result($r)) {
1892                         // database record did not get created. Quietly give up.
1893                         killme();
1894                 }
1895
1896                 $fid = $r[0]["id"];
1897
1898                 $hash = random_string();
1899
1900                 $r = q(
1901                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1902                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1903                         intval($suggest["uid"]),
1904                         intval($fid),
1905                         intval($suggest["cid"]),
1906                         dbesc($suggest["body"]),
1907                         dbesc($hash),
1908                         dbesc(datetime_convert()),
1909                         intval(0)
1910                 );
1911
1912                 notification(
1913                         array(
1914                                 "type"         => NOTIFY_SUGGEST,
1915                                 "notify_flags" => $importer["notify-flags"],
1916                                 "language"     => $importer["language"],
1917                                 "to_name"      => $importer["username"],
1918                                 "to_email"     => $importer["email"],
1919                                 "uid"          => $importer["importer_uid"],
1920                                 "item"         => $suggest,
1921                                 "link"         => System::baseUrl()."/notifications/intros",
1922                                 "source_name"  => $importer["name"],
1923                                 "source_link"  => $importer["url"],
1924                                 "source_photo" => $importer["photo"],
1925                                 "verb"         => ACTIVITY_REQ_FRIEND,
1926                                 "otype"        => "intro")
1927                 );
1928
1929                 return true;
1930         }
1931
1932         /**
1933          * @brief Processes the relocation elements
1934          *
1935          * @param object $xpath      XPath object
1936          * @param object $relocation relocation elements
1937          * @param array  $importer   Record of the importer user mixed with contact of the content
1938          * @return boolean
1939          * @todo Find good type-hints for all parameter
1940          */
1941         private static function processRelocation($xpath, $relocation, $importer)
1942         {
1943                 logger("Processing relocations");
1944
1945                 /// @TODO Rewrite this to one statement
1946                 $relocate = array();
1947                 $relocate["uid"] = $importer["importer_uid"];
1948                 $relocate["cid"] = $importer["id"];
1949                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1950                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1951                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1952                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1953                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1954                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1955                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1956                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1957                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1958                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1959                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1960                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1961
1962                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1963                         $relocate["avatar"] = $relocate["photo"];
1964                 }
1965
1966                 if ($relocate["addr"] == "") {
1967                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1968                 }
1969
1970                 // update contact
1971                 $r = q(
1972                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1973                         intval($importer["id"]),
1974                         intval($importer["importer_uid"])
1975                 );
1976
1977                 if (!DBM::is_result($r)) {
1978                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
1979                         return false;
1980                 }
1981
1982                 $old = $r[0];
1983
1984                 // Update the gcontact entry
1985                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1986
1987                 $x = q(
1988                         "UPDATE `gcontact` SET
1989                                         `name` = '%s',
1990                                         `photo` = '%s',
1991                                         `url` = '%s',
1992                                         `nurl` = '%s',
1993                                         `addr` = '%s',
1994                                         `connect` = '%s',
1995                                         `notify` = '%s',
1996                                         `server_url` = '%s'
1997                         WHERE `nurl` = '%s';",
1998                         dbesc($relocate["name"]),
1999                         dbesc($relocate["avatar"]),
2000                         dbesc($relocate["url"]),
2001                         dbesc(normalise_link($relocate["url"])),
2002                         dbesc($relocate["addr"]),
2003                         dbesc($relocate["addr"]),
2004                         dbesc($relocate["notify"]),
2005                         dbesc($relocate["server_url"]),
2006                         dbesc(normalise_link($old["url"]))
2007                 );
2008
2009                 // Update the contact table. We try to find every entry.
2010                 $x = q(
2011                         "UPDATE `contact` SET
2012                                         `name` = '%s',
2013                                         `avatar` = '%s',
2014                                         `url` = '%s',
2015                                         `nurl` = '%s',
2016                                         `addr` = '%s',
2017                                         `request` = '%s',
2018                                         `confirm` = '%s',
2019                                         `notify` = '%s',
2020                                         `poll` = '%s',
2021                                         `site-pubkey` = '%s'
2022                         WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2023                         dbesc($relocate["name"]),
2024                         dbesc($relocate["avatar"]),
2025                         dbesc($relocate["url"]),
2026                         dbesc(normalise_link($relocate["url"])),
2027                         dbesc($relocate["addr"]),
2028                         dbesc($relocate["request"]),
2029                         dbesc($relocate["confirm"]),
2030                         dbesc($relocate["notify"]),
2031                         dbesc($relocate["poll"]),
2032                         dbesc($relocate["sitepubkey"]),
2033                         intval($importer["id"]),
2034                         intval($importer["importer_uid"]),
2035                         dbesc(normalise_link($old["url"]))
2036                 );
2037
2038                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2039
2040                 if ($x === false) {
2041                         return false;
2042                 }
2043
2044                 // update items
2045                 /// @todo This is an extreme performance killer
2046                 $fields = array(
2047                         'owner-link' => array($old["url"], $relocate["url"]),
2048                         'author-link' => array($old["url"], $relocate["url"]),
2049                         //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2050                         //'author-avatar' => array($old["photo"], $relocate["photo"]),
2051                 );
2052                 foreach ($fields as $n => $f) {
2053                         $r = q(
2054                                 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2055                                 $n,
2056                                 dbesc($f[0]),
2057                                 intval($importer["importer_uid"])
2058                         );
2059
2060                         if (DBM::is_result($r)) {
2061                                 $x = q(
2062                                         "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2063                                         $n,
2064                                         dbesc($f[1]),
2065                                         $n,
2066                                         dbesc($f[0]),
2067                                         intval($importer["importer_uid"])
2068                                 );
2069
2070                                 if ($x === false) {
2071                                         return false;
2072                                 }
2073                         }
2074                 }
2075
2076                 /// @TODO
2077                 /// merge with current record, current contents have priority
2078                 /// update record, set url-updated
2079                 /// update profile photos
2080                 /// schedule a scan?
2081                 return true;
2082         }
2083
2084         /**
2085          * @brief Updates an item
2086          *
2087          * @param array $current   the current item record
2088          * @param array $item      the new item record
2089          * @param array $importer  Record of the importer user mixed with contact of the content
2090          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2091          * @return mixed
2092          * @todo set proper type-hints (array?)
2093          */
2094         private static function updateContent($current, $item, $importer, $entrytype)
2095         {
2096                 $changed = false;
2097
2098                 if (edited_timestamp_is_newer($current, $item)) {
2099                         // do not accept (ignore) an earlier edit than one we currently have.
2100                         if (datetime_convert("UTC", "UTC", $item["edited"]) < $current["edited"]) {
2101                                 return false;
2102                         }
2103
2104                         $fields = array('title' => $item["title"], 'body' => $item["body"],
2105                                         'tag' => $item["tag"], 'changed' => datetime_convert(),
2106                                         'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2107
2108                         $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2109                         dba::update('item', $fields, $condition);
2110
2111                         create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2112                         update_thread_uri($item["uri"], $importer["importer_uid"]);
2113
2114                         $changed = true;
2115
2116                         if ($entrytype == DFRN_REPLY_RC) {
2117                                 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2118                         }
2119                 }
2120
2121                 // update last-child if it changes
2122                 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2123                         $r = q(
2124                                 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2125                                 dbesc(datetime_convert()),
2126                                 dbesc($item["parent-uri"]),
2127                                 intval($importer["importer_uid"])
2128                         );
2129                         $r = q(
2130                                 "UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2131                                 intval($item["last-child"]),
2132                                 dbesc(datetime_convert()),
2133                                 dbesc($item["uri"]),
2134                                 intval($importer["importer_uid"])
2135                         );
2136                 }
2137                 return $changed;
2138         }
2139
2140         /**
2141          * @brief Detects the entry type of the item
2142          *
2143          * @param array $importer Record of the importer user mixed with contact of the content
2144          * @param array $item     the new item record
2145          *
2146          * @return int Is it a toplevel entry, a comment or a relayed comment?
2147          * @todo set proper type-hints (array?)
2148          */
2149         private static function getEntryType($importer, $item)
2150         {
2151                 if ($item["parent-uri"] != $item["uri"]) {
2152                         $community = false;
2153
2154                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2155                                 $sql_extra = "";
2156                                 $community = true;
2157                                 logger("possible community action");
2158                         } else {
2159                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2160                         }
2161
2162                         // was the top-level post for this action written by somebody on this site?
2163                         // Specifically, the recipient?
2164
2165                         $is_a_remote_action = false;
2166
2167                         $r = q(
2168                                 "SELECT `item`.`parent-uri` FROM `item`
2169                                 WHERE `item`.`uri` = '%s'
2170                                 LIMIT 1",
2171                                 dbesc($item["parent-uri"])
2172                         );
2173                         if (DBM::is_result($r)) {
2174                                 $r = q(
2175                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2176                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2177                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2178                                         AND `item`.`uid` = %d
2179                                         $sql_extra
2180                                         LIMIT 1",
2181                                         dbesc($r[0]["parent-uri"]),
2182                                         dbesc($r[0]["parent-uri"]),
2183                                         dbesc($r[0]["parent-uri"]),
2184                                         intval($importer["importer_uid"])
2185                                 );
2186                                 if (DBM::is_result($r)) {
2187                                         $is_a_remote_action = true;
2188                                 }
2189                         }
2190
2191                         /*
2192                          * Does this have the characteristics of a community or private group action?
2193                          * If it's an action to a wall post on a community/prvgroup page it's a
2194                          * valid community action. Also forum_mode makes it valid for sure.
2195                          * If neither, it's not.
2196                          */
2197
2198                         /// @TODO Maybe merge these if() blocks into one?
2199                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2200                                 $is_a_remote_action = false;
2201                                 logger("not a community action");
2202                         }
2203
2204                         if ($is_a_remote_action) {
2205                                 return DFRN_REPLY_RC;
2206                         } else {
2207                                 return DFRN_REPLY;
2208                         }
2209                 } else {
2210                         return DFRN_TOP_LEVEL;
2211                 }
2212         }
2213
2214         /**
2215          * @brief Send a "poke"
2216          *
2217          * @param array $item      the new item record
2218          * @param array $importer  Record of the importer user mixed with contact of the content
2219          * @param int   $posted_id The record number of item record that was just posted
2220          * @return void
2221          * @todo set proper type-hints (array?)
2222          */
2223         private static function doPoke($item, $importer, $posted_id)
2224         {
2225                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2226                 if (!$verb) {
2227                         return;
2228                 }
2229                 $xo = parse_xml_string($item["object"], false);
2230
2231                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2232                         // somebody was poked/prodded. Was it me?
2233                         foreach ($xo->link as $l) {
2234                                 $atts = $l->attributes();
2235                                 switch ($atts["rel"]) {
2236                                         case "alternate":
2237                                                 $Blink = $atts["href"];
2238                                                 break;
2239                                         default:
2240                                                 break;
2241                                 }
2242                         }
2243
2244                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2245                                 // send a notification
2246                                 notification(
2247                                         array(
2248                                         "type"         => NOTIFY_POKE,
2249                                         "notify_flags" => $importer["notify-flags"],
2250                                         "language"     => $importer["language"],
2251                                         "to_name"      => $importer["username"],
2252                                         "to_email"     => $importer["email"],
2253                                         "uid"          => $importer["importer_uid"],
2254                                         "item"         => $item,
2255                                         "link"         => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2256                                         "source_name"  => stripslashes($item["author-name"]),
2257                                         "source_link"  => $item["author-link"],
2258                                         "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2259                                                 ? $importer["thumb"] : $item["author-avatar"]),
2260                                         "verb"         => $item["verb"],
2261                                         "otype"        => "person",
2262                                         "activity"     => $verb,
2263                                         "parent"       => $item["parent"])
2264                                 );
2265                         }
2266                 }
2267         }
2268
2269         /**
2270          * @brief Processes several actions, depending on the verb
2271          *
2272          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2273          * @param array $importer  Record of the importer user mixed with contact of the content
2274          * @param array $item      the new item record
2275          * @param bool  $is_like   Is the verb a "like"?
2276          *
2277          * @return bool Should the processing of the entries be continued?
2278          * @todo set proper type-hints (array?)
2279          */
2280         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2281         {
2282                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2283
2284                 if (($entrytype == DFRN_TOP_LEVEL)) {
2285                         // The filling of the the "contact" variable is done for legcy reasons
2286                         // The functions below are partly used by ostatus.php as well - where we have this variable
2287                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2288                         $contact = $r[0];
2289                         $nickname = $contact["nick"];
2290
2291                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2292                         // This function once was responsible for DFRN and OStatus.
2293                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2294                                 logger("New follower");
2295                                 new_follower($importer, $contact, $item, $nickname);
2296                                 return false;
2297                         }
2298                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2299                                 logger("Lost follower");
2300                                 lose_follower($importer, $contact, $item);
2301                                 return false;
2302                         }
2303                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2304                                 logger("New friend request");
2305                                 new_follower($importer, $contact, $item, $nickname, true);
2306                                 return false;
2307                         }
2308                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2309                                 logger("Lost sharer");
2310                                 lose_sharer($importer, $contact, $item);
2311                                 return false;
2312                         }
2313                 } else {
2314                         if (($item["verb"] == ACTIVITY_LIKE)
2315                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2316                                 || ($item["verb"] == ACTIVITY_ATTEND)
2317                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2318                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2319                         ) {
2320                                 $is_like = true;
2321                                 $item["type"] = "activity";
2322                                 $item["gravity"] = GRAVITY_LIKE;
2323                                 // only one like or dislike per person
2324                                 // splitted into two queries for performance issues
2325                                 $r = q(
2326                                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2327                                         intval($item["uid"]),
2328                                         dbesc($item["author-link"]),
2329                                         dbesc($item["verb"]),
2330                                         dbesc($item["parent-uri"])
2331                                 );
2332                                 if (DBM::is_result($r)) {
2333                                         return false;
2334                                 }
2335
2336                                 $r = q(
2337                                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2338                                         intval($item["uid"]),
2339                                         dbesc($item["author-link"]),
2340                                         dbesc($item["verb"]),
2341                                         dbesc($item["parent-uri"])
2342                                 );
2343                                 if (DBM::is_result($r)) {
2344                                         return false;
2345                                 }
2346                         } else {
2347                                 $is_like = false;
2348                         }
2349
2350                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2351                                 $xo = parse_xml_string($item["object"], false);
2352                                 $xt = parse_xml_string($item["target"], false);
2353
2354                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2355                                         $r = q(
2356                                                 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2357                                                 dbesc($xt->id),
2358                                                 intval($importer["importer_uid"])
2359                                         );
2360
2361                                         if (!DBM::is_result($r)) {
2362                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2363                                                 return false;
2364                                         }
2365
2366                                         // extract tag, if not duplicate, add to parent item
2367                                         if ($xo->content) {
2368                                                 if (!(stristr($r[0]["tag"], trim($xo->content)))) {
2369                                                         q(
2370                                                                 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2371                                                                 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2372                                                                 intval($r[0]["id"])
2373                                                         );
2374                                                         create_tags_from_item($r[0]["id"]);
2375                                                 }
2376                                         }
2377                                 }
2378                         }
2379                 }
2380                 return true;
2381         }
2382
2383         /**
2384          * @brief Processes the link elements
2385          *
2386          * @param object $links link elements
2387          * @param array  $item  the item record
2388          * @return void
2389          * @todo set proper type-hints
2390          */
2391         private static function parseLinks($links, &$item)
2392         {
2393                 $rel = "";
2394                 $href = "";
2395                 $type = "";
2396                 $length = "0";
2397                 $title = "";
2398                 foreach ($links as $link) {
2399                         foreach ($link->attributes as $attributes) {
2400                                 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2401                                 if ($attributes->name == "href") {
2402                                         $href = $attributes->textContent;
2403                                 }
2404                                 if ($attributes->name == "rel") {
2405                                         $rel = $attributes->textContent;
2406                                 }
2407                                 if ($attributes->name == "type") {
2408                                         $type = $attributes->textContent;
2409                                 }
2410                                 if ($attributes->name == "length") {
2411                                         $length = $attributes->textContent;
2412                                 }
2413                                 if ($attributes->name == "title") {
2414                                         $title = $attributes->textContent;
2415                                 }
2416                         }
2417                         if (($rel != "") && ($href != "")) {
2418                                 switch ($rel) {
2419                                         case "alternate":
2420                                                 $item["plink"] = $href;
2421                                                 break;
2422                                         case "enclosure":
2423                                                 $enclosure = $href;
2424                                                 if (strlen($item["attach"])) {
2425                                                         $item["attach"] .= ",";
2426                                                 }
2427
2428                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2429                                                 break;
2430                                 }
2431                         }
2432                 }
2433         }
2434
2435         /**
2436          * @brief Processes the entry elements which contain the items and comments
2437          *
2438          * @param array  $header   Array of the header elements that always stay the same
2439          * @param object $xpath    XPath object
2440          * @param object $entry    entry elements
2441          * @param array  $importer Record of the importer user mixed with contact of the content
2442          * @param object $xml      xml
2443          * @return void
2444          * @todo Add type-hints
2445          */
2446         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2447         {
2448                 logger("Processing entries");
2449
2450                 $item = $header;
2451
2452                 $item["protocol"] = PROTOCOL_DFRN;
2453
2454                 $item["source"] = $xml;
2455
2456                 // Get the uri
2457                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2458
2459                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2460
2461                 $current = q(
2462                         "SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2463                         dbesc($item["uri"]),
2464                         intval($importer["importer_uid"])
2465                 );
2466
2467                 // Is there an existing item?
2468                 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item)
2469                         && (datetime_convert("UTC", "UTC", $item["edited"]) < $current[0]["edited"])
2470                 ) {
2471                         logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2472                         return;
2473                 }
2474
2475                 // Fetch the owner
2476                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2477
2478                 $item["owner-name"] = $owner["name"];
2479                 $item["owner-link"] = $owner["link"];
2480                 $item["owner-avatar"] = $owner["avatar"];
2481
2482                 // fetch the author
2483                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2484
2485                 $item["author-name"] = $author["name"];
2486                 $item["author-link"] = $author["link"];
2487                 $item["author-avatar"] = $author["avatar"];
2488
2489                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2490
2491                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2492
2493                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2494                 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''), $item["body"]);
2495                 // make sure nobody is trying to sneak some html tags by us
2496                 $item["body"] = notags(base64url_decode($item["body"]));
2497
2498                 $item["body"] = limit_body_size($item["body"]);
2499
2500                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2501                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2502                         $item['body'] = reltoabs($item['body'], $base_url);
2503
2504                         $item['body'] = html2bb_video($item['body']);
2505
2506                         $item['body'] = oembed_html2bbcode($item['body']);
2507
2508                         $config = HTMLPurifier_Config::createDefault();
2509                         $config->set('Cache.DefinitionImpl', null);
2510
2511                         // we shouldn't need a whitelist, because the bbcode converter
2512                         // will strip out any unsupported tags.
2513
2514                         $purifier = new HTMLPurifier($config);
2515                         $item['body'] = $purifier->purify($item['body']);
2516
2517                         $item['body'] = @html2bbcode($item['body']);
2518                 }
2519
2520                 /// @todo We should check for a repeated post and if we know the repeated author.
2521
2522                 // We don't need the content element since "dfrn:env" is always present
2523                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2524
2525                 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2526                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2527
2528                 $georsspoint = $xpath->query("georss:point", $entry);
2529                 if ($georsspoint) {
2530                         $item["coord"] = $georsspoint->item(0)->nodeValue;
2531                 }
2532
2533                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2534
2535                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2536
2537                 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2538                         $item["bookmark"] = true;
2539                 }
2540
2541                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2542                 if ($notice_info && ($notice_info->length > 0)) {
2543                         foreach ($notice_info->item(0)->attributes as $attributes) {
2544                                 if ($attributes->name == "source") {
2545                                         $item["app"] = strip_tags($attributes->textContent);
2546                                 }
2547                         }
2548                 }
2549
2550                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2551
2552                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2553                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2554                 if ($dsprsig != "") {
2555                         $item["dsprsig"] = $dsprsig;
2556                 }
2557
2558                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2559
2560                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2561                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2562                 }
2563
2564                 $object = $xpath->query("activity:object", $entry)->item(0);
2565                 $item["object"] = self::transformActivity($xpath, $object, "object");
2566
2567                 if (trim($item["object"]) != "") {
2568                         $r = parse_xml_string($item["object"], false);
2569                         if (isset($r->type)) {
2570                                 $item["object-type"] = $r->type;
2571                         }
2572                 }
2573
2574                 $target = $xpath->query("activity:target", $entry)->item(0);
2575                 $item["target"] = self::transformActivity($xpath, $target, "target");
2576
2577                 $categories = $xpath->query("atom:category", $entry);
2578                 if ($categories) {
2579                         foreach ($categories as $category) {
2580                                 $term = "";
2581                                 $scheme = "";
2582                                 foreach ($category->attributes as $attributes) {
2583                                         if ($attributes->name == "term") {
2584                                                 $term = $attributes->textContent;
2585                                         }
2586
2587                                         if ($attributes->name == "scheme") {
2588                                                 $scheme = $attributes->textContent;
2589                                         }
2590                                 }
2591
2592                                 if (($term != "") && ($scheme != "")) {
2593                                         $parts = explode(":", $scheme);
2594                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2595                                                 $termhash = array_shift($parts);
2596                                                 $termurl = implode(":", $parts);
2597
2598                                                 if (strlen($item["tag"])) {
2599                                                         $item["tag"] .= ",";
2600                                                 }
2601
2602                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2603                                         }
2604                                 }
2605                         }
2606                 }
2607
2608                 $enclosure = "";
2609
2610                 $links = $xpath->query("atom:link", $entry);
2611                 if ($links) {
2612                         self::parseLinks($links, $item);
2613                 }
2614
2615                 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2616
2617                 $conv = $xpath->query('ostatus:conversation', $entry);
2618                 if (is_object($conv->item(0))) {
2619                         foreach ($conv->item(0)->attributes as $attributes) {
2620                                 if ($attributes->name == "ref") {
2621                                         $item['conversation-uri'] = $attributes->textContent;
2622                                 }
2623                                 if ($attributes->name == "href") {
2624                                         $item['conversation-href'] = $attributes->textContent;
2625                                 }
2626                         }
2627                 }
2628
2629                 // Is it a reply or a top level posting?
2630                 $item["parent-uri"] = $item["uri"];
2631
2632                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2633                 if (is_object($inreplyto->item(0))) {
2634                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2635                                 if ($attributes->name == "ref") {
2636                                         $item["parent-uri"] = $attributes->textContent;
2637                                 }
2638                         }
2639                 }
2640
2641                 // Get the type of the item (Top level post, reply or remote reply)
2642                 $entrytype = self::getEntryType($importer, $item);
2643
2644                 // Now assign the rest of the values that depend on the type of the message
2645                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2646                         if (!isset($item["object-type"])) {
2647                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2648                         }
2649
2650                         if ($item["contact-id"] != $owner["contact-id"]) {
2651                                 $item["contact-id"] = $owner["contact-id"];
2652                         }
2653
2654                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2655                                 $item["network"] = $owner["network"];
2656                         }
2657
2658                         if ($item["contact-id"] != $author["contact-id"]) {
2659                                 $item["contact-id"] = $author["contact-id"];
2660                         }
2661
2662                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2663                                 $item["network"] = $author["network"];
2664                         }
2665
2666                         /// @TODO maybe remove this old-lost code then?
2667                         // This code was taken from the old DFRN code
2668                         // When activated, forums don't work.
2669                         // And: Why should we disallow commenting by followers?
2670                         // the behaviour is now similar to the Diaspora part.
2671                         //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2672                         //      logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2673                         //      return;
2674                         //}
2675                 }
2676
2677                 if ($entrytype == DFRN_REPLY_RC) {
2678                         $item["type"] = "remote-comment";
2679                         $item["wall"] = 1;
2680                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2681                         if (!isset($item["object-type"])) {
2682                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2683                         }
2684
2685                         // Is it an event?
2686                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2687                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2688                                 $ev = bbtoevent($item["body"]);
2689                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2690                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2691                                         /// @TODO Mixure of "/' ahead ...
2692                                         $ev["cid"] = $importer["id"];
2693                                         $ev["uid"] = $importer["uid"];
2694                                         $ev["uri"] = $item["uri"];
2695                                         $ev["edited"] = $item["edited"];
2696                                         $ev['private'] = $item['private'];
2697                                         $ev["guid"] = $item["guid"];
2698
2699                                         $r = q(
2700                                                 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2701                                                 dbesc($item["uri"]),
2702                                                 intval($importer["uid"])
2703                                         );
2704                                         if (DBM::is_result($r)) {
2705                                                 $ev["id"] = $r[0]["id"];
2706                                         }
2707
2708                                         $event_id = event_store($ev);
2709                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2710                                         return;
2711                                 }
2712                         }
2713                 }
2714
2715                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2716                         logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2717                         return;
2718                 }
2719
2720                 // Update content if 'updated' changes
2721                 if (DBM::is_result($current)) {
2722                         if (self::updateContent($r[0], $item, $importer, $entrytype)) {
2723                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2724                         } else {
2725                                 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2726                         }
2727                         return;
2728                 }
2729
2730                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2731                         $posted_id = item_store($item);
2732                         $parent = 0;
2733
2734                         if ($posted_id) {
2735                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2736
2737                                 $item["id"] = $posted_id;
2738
2739                                 $r = q(
2740                                         "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2741                                         intval($posted_id),
2742                                         intval($importer["importer_uid"])
2743                                 );
2744                                 if (DBM::is_result($r)) {
2745                                         $parent = $r[0]["parent"];
2746                                         $parent_uri = $r[0]["parent-uri"];
2747                                 }
2748
2749                                 if (!$is_like) {
2750                                         $r1 = q(
2751                                                 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2752                                                 dbesc(datetime_convert()),
2753                                                 intval($importer["importer_uid"]),
2754                                                 intval($r[0]["parent"])
2755                                         );
2756
2757                                         $r2 = q(
2758                                                 "UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2759                                                 dbesc(datetime_convert()),
2760                                                 intval($importer["importer_uid"]),
2761                                                 intval($posted_id)
2762                                         );
2763                                 }
2764
2765                                 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2766                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2767                                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2768                                 }
2769
2770                                 return true;
2771                         }
2772                 } else { // $entrytype == DFRN_TOP_LEVEL
2773                         if (!link_compare($item["owner-link"], $importer["url"])) {
2774                                 /*
2775                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2776                                  * but otherwise there's a possible data mixup on the sender's system.
2777                                  * the tgroup delivery code called from item_store will correct it if it's a forum,
2778                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2779                                  */
2780                                 logger('Correcting item owner.', LOGGER_DEBUG);
2781                                 $item["owner-name"]   = $importer["senderName"];
2782                                 $item["owner-link"]   = $importer["url"];
2783                                 $item["owner-avatar"] = $importer["thumb"];
2784                         }
2785
2786                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2787                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2788                                 return;
2789                         }
2790
2791                         // This is my contact on another system, but it's really me.
2792                         // Turn this into a wall post.
2793                         $notify = item_is_remote_self($importer, $item);
2794
2795                         $posted_id = item_store($item, false, $notify);
2796
2797                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2798
2799                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2800                                 self::doPoke($item, $importer, $posted_id);
2801                         }
2802                 }
2803         }
2804
2805         /**
2806          * @brief Deletes items
2807          *
2808          * @param object $xpath    XPath object
2809          * @param object $deletion deletion elements
2810          * @param array  $importer Record of the importer user mixed with contact of the content
2811          * @return void
2812          * @todo set proper type-hints
2813          */
2814         private static function processDeletion($xpath, $deletion, $importer)
2815         {
2816                 logger("Processing deletions");
2817
2818                 foreach ($deletion->attributes as $attributes) {
2819                         if ($attributes->name == "ref") {
2820                                 $uri = $attributes->textContent;
2821                         }
2822                         if ($attributes->name == "when") {
2823                                 $when = $attributes->textContent;
2824                         }
2825                 }
2826                 if ($when) {
2827                         $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2828                 } else {
2829                         $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2830                 }
2831
2832                 if (!$uri || !$importer["id"]) {
2833                         return false;
2834                 }
2835
2836                 /// @todo Only select the used fields
2837                 $r = q(
2838                         "SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2839                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2840                         dbesc($uri),
2841                         intval($importer["uid"]),
2842                         intval($importer["id"])
2843                 );
2844                 if (!DBM::is_result($r)) {
2845                         logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2846                         return;
2847                 } else {
2848                         $item = $r[0];
2849
2850                         $entrytype = self::getEntryType($importer, $item);
2851
2852                         if (!$item["deleted"]) {
2853                                 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2854                         } else {
2855                                 return;
2856                         }
2857
2858                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2859                                 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2860                                 event_delete($item["event-id"]);
2861                         }
2862
2863                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2864                                 $xo = parse_xml_string($item["object"], false);
2865                                 $xt = parse_xml_string($item["target"], false);
2866
2867                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2868                                         $i = q(
2869                                                 "SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2870                                                 dbesc($xt->id),
2871                                                 intval($importer["importer_uid"])
2872                                         );
2873                                         if (DBM::is_result($i)) {
2874                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2875
2876                                                 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2877                                                 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2878                                                 $author_copy = (($item["origin"]) ? true : false);
2879
2880                                                 if ($owner_remove && $author_copy) {
2881                                                         return;
2882                                                 }
2883                                                 if ($author_remove || $owner_remove) {
2884                                                         $tags = explode(',', $i[0]["tag"]);
2885                                                         $newtags = array();
2886                                                         if (count($tags)) {
2887                                                                 foreach ($tags as $tag) {
2888                                                                         if (trim($tag) !== trim($xo->body)) {
2889                                                                                 $newtags[] = trim($tag);
2890                                                                         }
2891                                                                 }
2892                                                         }
2893                                                         q(
2894                                                                 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2895                                                                 dbesc(implode(',', $newtags)),
2896                                                                 intval($i[0]["id"])
2897                                                         );
2898                                                         create_tags_from_item($i[0]["id"]);
2899                                                 }
2900                                         }
2901                                 }
2902                         }
2903
2904                         if ($entrytype == DFRN_TOP_LEVEL) {
2905                                 $r = q(
2906                                         "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2907                                                 `body` = '', `title` = ''
2908                                         WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2909                                         dbesc($when),
2910                                         dbesc(datetime_convert()),
2911                                         dbesc($uri),
2912                                         intval($importer["uid"])
2913                                 );
2914                                 create_tags_from_itemuri($uri, $importer["uid"]);
2915                                 create_files_from_itemuri($uri, $importer["uid"]);
2916                                 update_thread_uri($uri, $importer["uid"]);
2917                         } else {
2918                                 $r = q(
2919                                         "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2920                                                 `body` = '', `title` = ''
2921                                         WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2922                                         dbesc($when),
2923                                         dbesc(datetime_convert()),
2924                                         dbesc($uri),
2925                                         intval($importer["uid"])
2926                                 );
2927                                 create_tags_from_itemuri($uri, $importer["uid"]);
2928                                 create_files_from_itemuri($uri, $importer["uid"]);
2929                                 update_thread_uri($uri, $importer["importer_uid"]);
2930                                 if ($item["last-child"]) {
2931                                         // ensure that last-child is set in case the comment that had it just got wiped.
2932                                         q(
2933                                                 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2934                                                 dbesc(datetime_convert()),
2935                                                 dbesc($item["parent-uri"]),
2936                                                 intval($item["uid"])
2937                                         );
2938                                         // who is the last child now?
2939                                         $r = q(
2940                                                 "SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2941                                                 ORDER BY `created` DESC LIMIT 1",
2942                                                 dbesc($item["parent-uri"]),
2943                                                 intval($importer["uid"])
2944                                         );
2945                                         if (DBM::is_result($r)) {
2946                                                 q(
2947                                                         "UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2948                                                         intval($r[0]["id"])
2949                                                 );
2950                                         }
2951                                 }
2952                                 // if this is a relayed delete, propagate it to other recipients
2953
2954                                 if ($entrytype == DFRN_REPLY_RC) {
2955                                         logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2956                                         Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2957                                 }
2958                         }
2959                 }
2960         }
2961
2962         /**
2963          * @brief Imports a DFRN message
2964          *
2965          * @param text  $xml          The DFRN message
2966          * @param array $importer     Record of the importer user mixed with contact of the content
2967          * @param bool  $sort_by_date Is used when feeds are polled
2968          * @return integer Import status
2969          * @todo set proper type-hints
2970          */
2971         public static function import($xml, $importer, $sort_by_date = false)
2972         {
2973                 if ($xml == "") {
2974                         return 400;
2975                 }
2976
2977                 $doc = new DOMDocument();
2978                 @$doc->loadXML($xml);
2979
2980                 $xpath = new DomXPath($doc);
2981                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2982                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2983                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2984                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2985                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2986                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2987                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2988                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2989                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2990                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2991
2992                 $header = array();
2993                 $header["uid"] = $importer["uid"];
2994                 $header["network"] = NETWORK_DFRN;
2995                 $header["type"] = "remote";
2996                 $header["wall"] = 0;
2997                 $header["origin"] = 0;
2998                 $header["contact-id"] = $importer["id"];
2999
3000                 // Update the contact table if the data has changed
3001
3002                 // The "atom:author" is only present in feeds
3003                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
3004                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
3005                 }
3006
3007                 // Only the "dfrn:owner" in the head section contains all data
3008                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
3009                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
3010                 }
3011
3012                 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
3013
3014                 // The account type is new since 3.5.1
3015                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
3016                         $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
3017
3018                         if ($accounttype != $importer["contact-type"]) {
3019                                 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
3020                         }
3021                 }
3022
3023                 // is it a public forum? Private forums aren't supported with this method
3024                 // This is deprecated since 3.5.1
3025                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
3026
3027                 if ($forum != $importer["forum"]) {
3028                         $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
3029                         dba::update('contact', array('forum' => $forum), $condition);
3030                 }
3031
3032                 // We are processing relocations even if we are ignoring a contact
3033                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
3034                 foreach ($relocations as $relocation) {
3035                         self::processRelocation($xpath, $relocation, $importer);
3036                 }
3037
3038                 if ($importer["readonly"]) {
3039                         // We aren't receiving stuff from this person. But we will quietly ignore them
3040                         // rather than a blatant "go away" message.
3041                         logger('ignoring contact '.$importer["id"]);
3042                         return 403;
3043                 }
3044
3045                 $mails = $xpath->query("/atom:feed/dfrn:mail");
3046                 foreach ($mails as $mail) {
3047                         self::processMail($xpath, $mail, $importer);
3048                 }
3049
3050                 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
3051                 foreach ($suggestions as $suggestion) {
3052                         self::processSuggestion($xpath, $suggestion, $importer);
3053                 }
3054
3055                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
3056                 foreach ($deletions as $deletion) {
3057                         self::processDeletion($xpath, $deletion, $importer);
3058                 }
3059
3060                 if (!$sort_by_date) {
3061                         $entries = $xpath->query("/atom:feed/atom:entry");
3062                         foreach ($entries as $entry) {
3063                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
3064                         }
3065                 } else {
3066                         $newentries = array();
3067                         $entries = $xpath->query("/atom:feed/atom:entry");
3068                         foreach ($entries as $entry) {
3069                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
3070                                 $newentries[strtotime($created)] = $entry;
3071                         }
3072
3073                         // Now sort after the publishing date
3074                         ksort($newentries);
3075
3076                         foreach ($newentries as $entry) {
3077                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
3078                         }
3079                 }
3080                 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
3081                 return 200;
3082         }
3083 }