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