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