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