2 namespace Friendica\Protocol;
4 * @file include/dfrn.php
5 * @brief The implementation of the dfrn protocol
7 * @see https://github.com/friendica/friendica/wiki/Protocol and
8 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
12 use Friendica\Core\Config;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
20 require_once("include/Contact.php");
21 require_once("include/ostatus.php");
22 require_once("include/enotify.php");
23 require_once("include/threads.php");
24 require_once("include/socgraph.php");
25 require_once("include/items.php");
26 require_once("include/tags.php");
27 require_once("include/files.php");
28 require_once("include/event.php");
29 require_once("include/text.php");
30 require_once("include/oembed.php");
31 require_once("include/html2bbcode.php");
32 require_once("include/bbcode.php");
33 require_once("include/xml.php");
36 * @brief This class contain functions to create and send DFRN XML files
41 const DFRN_TOP_LEVEL = 0; // Top level posting
42 const DFRN_REPLY = 1; // Regular reply that is stored locally
43 const DFRN_REPLY_RC = 2; // Reply that will be relayed
46 * @brief Generates the atom entries for delivery.php
48 * This function is used whenever content is transmitted via DFRN.
50 * @param array $items Item elements
51 * @param array $owner Owner record
53 * @return string DFRN entries
54 * @todo Add type-hints
56 public static function entries($items,$owner) {
58 $doc = new DOMDocument('1.0', 'utf-8');
59 $doc->formatOutput = true;
61 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
63 if (! count($items)) {
64 return trim($doc->saveXML());
67 foreach ($items as $item) {
68 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
69 $root->appendChild($entry);
72 return(trim($doc->saveXML()));
76 * @brief Generate an atom feed for the given user
78 * This function is called when another server is pulling data from the user feed.
80 * @param string $dfrn_id DFRN ID from the requesting party
81 * @param string $owner_nick Owner nick name
82 * @param string $last_update Date of the last update
83 * @param int $direction Can be -1, 0 or 1.
84 * @param boolean $onlyheader Output only the header without content? (Default is "no")
86 * @return string DFRN feed entries
88 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
92 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
93 $public_feed = (($dfrn_id) ? false : true);
94 $starred = false; // not yet implemented, possible security issues
97 if ($public_feed && $a->argc > 2) {
98 for ($x = 2; $x < $a->argc; $x++) {
99 if ($a->argv[$x] == 'converse') {
102 if ($a->argv[$x] == 'starred') {
105 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
106 $category = $a->argv[$x+1];
113 // default permissions - anonymous user
115 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
117 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
118 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
119 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
123 if (! DBM::is_result($r)) {
128 $owner_id = $owner['uid'];
129 $owner_nick = $owner['nickname'];
131 $sql_post_table = "";
133 if (! $public_feed) {
138 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
142 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
143 $my_id = '1:' . $dfrn_id;
146 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
147 $my_id = '0:' . $dfrn_id;
154 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
158 if (! DBM::is_result($r)) {
163 require_once('include/security.php');
164 $groups = init_groups_visitor($contact['id']);
166 if (count($groups)) {
167 for ($x = 0; $x < count($groups); $x ++)
168 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
169 $gs = implode('|', $groups);
171 $gs = '<<>>' ; // Impossible to match
174 $sql_extra = sprintf("
175 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
176 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
177 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
178 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
180 intval($contact['id']),
181 intval($contact['id']),
193 if (! strlen($last_update)) {
194 $last_update = 'now -30 days';
197 if (isset($category)) {
198 $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` ",
199 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
200 //$sql_extra .= file_tag_file_query('item',$category,'category');
205 $sql_extra .= " AND `contact`.`self` = 1 ";
209 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
211 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
212 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
213 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
214 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
215 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
216 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
217 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
218 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
219 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
220 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
221 AND `item`.`wall` AND `item`.`changed` > '%s'
223 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
230 * Will check further below if this actually returned results.
231 * We will provide an empty feed if that is the case.
236 $doc = new DOMDocument('1.0', 'utf-8');
237 $doc->formatOutput = true;
239 $alternatelink = $owner['url'];
241 if (isset($category)) {
242 $alternatelink .= "/category/".$category;
246 $author = "dfrn:owner";
251 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
253 /// @TODO This hook can't work anymore
254 // call_hooks('atom_feed', $atom);
256 if (!DBM::is_result($items) || $onlyheader) {
257 $atom = trim($doc->saveXML());
259 call_hooks('atom_feed_end', $atom);
264 foreach ($items as $item) {
266 // prevent private email from leaking.
267 if ($item['network'] == NETWORK_MAIL) {
271 // public feeds get html, our own nodes use bbcode
275 // catch any email that's in a public conversation and make sure it doesn't leak
276 if ($item['private']) {
283 $entry = self::entry($doc, $type, $item, $owner, true);
284 $root->appendChild($entry);
288 $atom = trim($doc->saveXML());
290 call_hooks('atom_feed_end', $atom);
296 * @brief Generate an atom entry for a given item id
298 * @param int $item_id The item id
299 * @param boolean $conversation Show the conversation. If false show the single post.
301 * @return string DFRN feed entry
303 public static function itemFeed($item_id, $conversation = false) {
305 $condition = '`item`.`parent`';
307 $condition = '`item`.`id`';
310 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
311 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
312 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
313 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
314 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
316 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
317 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
318 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
319 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
320 AND NOT `item`.`private`",
325 if (!DBM::is_result($r)) {
332 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
333 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
334 WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
338 if (!DBM::is_result($r)) {
344 $doc = new DOMDocument('1.0', 'utf-8');
345 $doc->formatOutput = true;
349 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
350 $doc->appendChild($root);
352 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
353 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
354 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
355 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
356 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
357 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
358 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
359 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
360 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
362 //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
364 foreach ($items as $item) {
365 $entry = self::entry($doc, $type, $item, $owner, true, 0);
366 $root->appendChild($entry);
369 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
372 $atom = trim($doc->saveXML());
377 * @brief Create XML text for DFRN mails
379 * @param array $item message elements
380 * @param array $owner Owner record
382 * @return string DFRN mail
383 * @todo Add type-hints
385 public static function mail($item, $owner) {
386 $doc = new DOMDocument('1.0', 'utf-8');
387 $doc->formatOutput = true;
389 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
391 $mail = $doc->createElement("dfrn:mail");
392 $sender = $doc->createElement("dfrn:sender");
394 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
395 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
396 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
398 $mail->appendChild($sender);
400 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
401 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
402 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
403 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
404 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
406 $root->appendChild($mail);
408 return(trim($doc->saveXML()));
412 * @brief Create XML text for DFRN friend suggestions
414 * @param array $item suggestion elements
415 * @param array $owner Owner record
417 * @return string DFRN suggestions
418 * @todo Add type-hints
420 public static function fsuggest($item, $owner) {
421 $doc = new DOMDocument('1.0', 'utf-8');
422 $doc->formatOutput = true;
424 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
426 $suggest = $doc->createElement("dfrn:suggest");
428 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
429 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
430 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
431 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
432 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
434 $root->appendChild($suggest);
436 return(trim($doc->saveXML()));
440 * @brief Create XML text for DFRN relocations
442 * @param array $owner Owner record
443 * @param int $uid User ID
445 * @return string DFRN relocations
446 * @todo Add type-hints
448 public static function relocate($owner, $uid) {
450 /* get site pubkey. this could be a new installation with no site keys*/
451 $pubkey = Config::get('system','site_pubkey');
453 $res = new_keypair(1024);
454 Config::set('system','site_prvkey', $res['prvkey']);
455 Config::set('system','site_pubkey', $res['pubkey']);
458 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
459 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
461 $ext = Photo::supportedTypes();
463 foreach ($rp as $p) {
464 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
469 $doc = new DOMDocument('1.0', 'utf-8');
470 $doc->formatOutput = true;
472 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
474 $relocate = $doc->createElement("dfrn:relocate");
476 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
477 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
478 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
479 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
480 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
481 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
482 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
483 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
484 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
485 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
486 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
487 xml::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey'));
489 $root->appendChild($relocate);
491 return(trim($doc->saveXML()));
495 * @brief Adds the header elements for the DFRN protocol
497 * @param object $doc XML document
498 * @param array $owner Owner record
499 * @param string $authorelement Element name for the author
500 * @param string $alternatelink link to profile or category
501 * @param bool $public Is it a header for public posts?
503 * @return object XML root object
504 * @todo Add type-hints
506 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
508 if ($alternatelink == "") {
509 $alternatelink = $owner['url'];
512 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
513 $doc->appendChild($root);
515 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
516 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
517 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
518 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
519 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
520 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
521 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
522 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
523 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
525 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
526 xml::add_element($doc, $root, "title", $owner["name"]);
528 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
529 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
531 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
532 xml::add_element($doc, $root, "link", "", $attributes);
534 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
535 xml::add_element($doc, $root, "link", "", $attributes);
539 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
540 ostatus::hublinks($doc, $root, $owner["nick"]);
542 $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
543 xml::add_element($doc, $root, "link", "", $attributes);
545 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
546 xml::add_element($doc, $root, "link", "", $attributes);
548 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
549 xml::add_element($doc, $root, "link", "", $attributes);
552 // For backward compatibility we keep this element
553 if ($owner['page-flags'] == PAGE_COMMUNITY) {
554 xml::add_element($doc, $root, "dfrn:community", 1);
557 // The former element is replaced by this one
558 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
560 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
562 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
564 $author = self::add_author($doc, $owner, $authorelement, $public);
565 $root->appendChild($author);
571 * @brief Adds the author element in the header for the DFRN protocol
573 * @param object $doc XML document
574 * @param array $owner Owner record
575 * @param string $authorelement Element name for the author
577 * @return object XML author object
578 * @todo Add type-hints
580 private static function add_author($doc, $owner, $authorelement, $public) {
582 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
583 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
584 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
585 intval($owner['uid']));
586 if (DBM::is_result($r)) {
592 $author = $doc->createElement($authorelement);
594 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
595 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
596 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
598 $attributes = array();
600 if (!$public || !$hidewall) {
601 $attributes = array("dfrn:updated" => $namdate);
604 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
605 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
606 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
608 $attributes = array("rel" => "photo", "type" => "image/jpeg",
609 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
611 if (!$public || !$hidewall) {
612 $attributes["dfrn:updated"] = $picdate;
615 xml::add_element($doc, $author, "link", "", $attributes);
617 $attributes["rel"] = "avatar";
618 xml::add_element($doc, $author, "link", "", $attributes);
621 xml::add_element($doc, $author, "dfrn:hide", "true");
624 // The following fields will only be generated if the data isn't meant for a public feed
629 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
632 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
634 // Only show contact details when we are allowed to
635 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
636 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
637 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
639 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
640 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
641 intval($owner['uid']));
642 if (DBM::is_result($r)) {
645 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
646 xml::add_element($doc, $author, "poco:updated", $namdate);
648 if (trim($profile["dob"]) > '0001-01-01') {
649 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
652 xml::add_element($doc, $author, "poco:note", $profile["about"]);
653 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
655 $savetz = date_default_timezone_get();
656 date_default_timezone_set($profile["timezone"]);
657 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
658 date_default_timezone_set($savetz);
660 if (trim($profile["homepage"]) != "") {
661 $urls = $doc->createElement("poco:urls");
662 xml::add_element($doc, $urls, "poco:type", "homepage");
663 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
664 xml::add_element($doc, $urls, "poco:primary", "true");
665 $author->appendChild($urls);
668 if (trim($profile["pub_keywords"]) != "") {
669 $keywords = explode(",", $profile["pub_keywords"]);
671 foreach ($keywords AS $keyword) {
672 xml::add_element($doc, $author, "poco:tags", trim($keyword));
677 if (trim($profile["xmpp"]) != "") {
678 $ims = $doc->createElement("poco:ims");
679 xml::add_element($doc, $ims, "poco:type", "xmpp");
680 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
681 xml::add_element($doc, $ims, "poco:primary", "true");
682 $author->appendChild($ims);
685 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
686 $element = $doc->createElement("poco:address");
688 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
690 if (trim($profile["locality"]) != "") {
691 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
694 if (trim($profile["region"]) != "") {
695 xml::add_element($doc, $element, "poco:region", $profile["region"]);
698 if (trim($profile["country-name"]) != "") {
699 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
702 $author->appendChild($element);
710 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
712 * @param object $doc XML document
713 * @param string $element Element name for the author
714 * @param string $contact_url Link of the contact
715 * @param array $items Item elements
717 * @return object XML author object
718 * @todo Add type-hints
720 private static function add_entry_author($doc, $element, $contact_url, $item) {
722 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
724 $author = $doc->createElement($element);
725 xml::add_element($doc, $author, "name", $contact["name"]);
726 xml::add_element($doc, $author, "uri", $contact["url"]);
727 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
730 /// - Check real image type and image size
731 /// - Check which of these boths elements we should use
734 "type" => "image/jpeg",
736 "media:height" => 80,
737 "href" => $contact["photo"]);
738 xml::add_element($doc, $author, "link", "", $attributes);
742 "type" => "image/jpeg",
744 "media:height" => 80,
745 "href" => $contact["photo"]);
746 xml::add_element($doc, $author, "link", "", $attributes);
752 * @brief Adds the activity elements
754 * @param object $doc XML document
755 * @param string $element Element name for the activity
756 * @param string $activity activity value
758 * @return object XML activity object
759 * @todo Add type-hints
761 private static function create_activity($doc, $element, $activity) {
764 $entry = $doc->createElement($element);
766 $r = parse_xml_string($activity, false);
771 xml::add_element($doc, $entry, "activity:object-type", $r->type);
774 xml::add_element($doc, $entry, "id", $r->id);
777 xml::add_element($doc, $entry, "title", $r->title);
781 if (substr($r->link, 0, 1) == '<') {
782 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
783 $r->link = str_replace('&', '&', $r->link);
786 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
788 // XML does need a single element as root element so we add a dummy element here
789 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
790 if (is_object($data)) {
791 foreach ($data->link AS $link) {
792 $attributes = array();
793 foreach ($link->attributes() AS $parameter => $value) {
794 $attributes[$parameter] = $value;
796 xml::add_element($doc, $entry, "link", "", $attributes);
800 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
801 xml::add_element($doc, $entry, "link", "", $attributes);
805 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
815 * @brief Adds the elements for attachments
817 * @param object $doc XML document
818 * @param object $root XML root
819 * @param array $item Item element
821 * @return object XML attachment object
822 * @todo Add type-hints
824 private static function get_attachment($doc, $root, $item) {
825 $arr = explode('[/attach],',$item['attach']);
827 foreach ($arr as $r) {
829 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
831 $attributes = array("rel" => "enclosure",
832 "href" => $matches[1],
833 "type" => $matches[3]);
835 if (intval($matches[2])) {
836 $attributes["length"] = intval($matches[2]);
839 if (trim($matches[4]) != "") {
840 $attributes["title"] = trim($matches[4]);
843 xml::add_element($doc, $root, "link", "", $attributes);
850 * @brief Adds the "entry" elements for the DFRN protocol
852 * @param object $doc XML document
853 * @param string $type "text" or "html"
854 * @param array $item Item element
855 * @param array $owner Owner record
856 * @param bool $comment Trigger the sending of the "comment" element
857 * @param int $cid Contact ID of the recipient
858 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
860 * @return object XML entry object
861 * @todo Add type-hints
863 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) {
865 $mentioned = array();
867 if (!$item['parent']) {
871 if ($item['deleted']) {
872 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
873 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
877 $entry = $doc->createElement("entry");
879 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
880 $doc->appendChild($entry);
882 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
883 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
884 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
885 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
886 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
887 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
888 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
889 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
890 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
893 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
894 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
896 $body = $item['body'];
899 // Remove the abstract element. It is only locally important.
900 $body = remove_abstract($body);
902 if ($type == 'html') {
905 if ($item['title'] != "") {
906 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
909 $htmlbody = bbcode($htmlbody, false, false, 7);
912 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
913 $entry->appendChild($author);
915 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
916 $entry->appendChild($dfrnowner);
918 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
919 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
920 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
921 $attributes = array("ref" => $parent_item, "type" => "text/html",
922 "href" => $parent[0]['plink'],
923 "dfrn:diaspora_guid" => $parent[0]['guid']);
924 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
927 // Add conversation data. This is used for OStatus
928 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
929 $conversation_uri = $conversation_href;
931 if (isset($parent_item)) {
932 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
933 if (DBM::is_result($r)) {
934 if ($r['conversation-uri'] != '') {
935 $conversation_uri = $r['conversation-uri'];
937 if ($r['conversation-href'] != '') {
938 $conversation_href = $r['conversation-href'];
944 "href" => $conversation_href,
945 "ref" => $conversation_uri);
947 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
949 xml::add_element($doc, $entry, "id", $item["uri"]);
950 xml::add_element($doc, $entry, "title", $item["title"]);
952 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
953 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
955 // "dfrn:env" is used to read the content
956 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
958 // The "content" field is not read by the receiver. We could remove it when the type is "text"
959 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
960 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
962 // We save this value in "plink". Maybe we should read it from there as well?
963 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
964 "href" => System::baseUrl()."/display/".$item["guid"]));
966 // "comment-allow" is some old fashioned stuff for old Friendica versions.
967 // It is included in the rewritten code for completeness
969 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
972 if ($item['location']) {
973 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
976 if ($item['coord']) {
977 xml::add_element($doc, $entry, "georss:point", $item['coord']);
980 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
981 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
984 if ($item['extid']) {
985 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
988 if ($item['bookmark']) {
989 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
993 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
996 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
998 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
999 // It is needed for relayed comments to Diaspora.
1000 if ($item['signed_text']) {
1001 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
1002 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
1005 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
1007 if ($item['object-type'] != "") {
1008 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1009 } elseif ($item['id'] == $item['parent']) {
1010 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1012 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1015 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1017 $entry->appendChild($actobj);
1020 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1022 $entry->appendChild($actarg);
1025 $tags = item_getfeedtags($item);
1028 foreach ($tags as $t) {
1029 if (($type != 'html') || ($t[0] != "@")) {
1030 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1036 foreach ($tags as $t) {
1038 $mentioned[$t[1]] = $t[1];
1043 foreach ($mentioned AS $mention) {
1044 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1045 intval($owner["uid"]),
1046 dbesc(normalise_link($mention)));
1048 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1049 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1050 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1051 "href" => $mention));
1053 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1054 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1055 "href" => $mention));
1059 self::get_attachment($doc, $entry, $item);
1065 * @brief encrypts data via AES
1067 * @param string $data The data that is to be encrypted
1068 * @param string $key The AES key
1070 * @return string encrypted data
1072 private static function aes_encrypt($data, $key) {
1073 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1077 * @brief decrypts data via AES
1079 * @param string $encrypted The encrypted data
1080 * @param string $key The AES key
1082 * @return string decrypted data
1084 public static function aes_decrypt($encrypted, $key) {
1085 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1089 * @brief Delivers the atom content to the contacts
1091 * @param array $owner Owner record
1092 * @param array $contactr Contact record of the receiver
1093 * @param string $atom Content that will be transmitted
1094 * @param bool $dissolve (to be documented)
1096 * @return int Deliver status. -1 means an error.
1097 * @todo Add array type-hint for $owner, $contact
1099 public static function deliver($owner,$contact,$atom, $dissolve = false) {
1103 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1105 if ($contact['duplex'] && $contact['dfrn-id']) {
1106 $idtosend = '0:' . $orig_id;
1108 if ($contact['duplex'] && $contact['issued-id']) {
1109 $idtosend = '1:' . $orig_id;
1112 $rino = Config::get('system', 'rino_encrypt');
1113 $rino = intval($rino);
1115 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1117 $ssl_val = intval(Config::get('system','ssl_policy'));
1121 case SSL_POLICY_FULL:
1122 $ssl_policy = 'full';
1124 case SSL_POLICY_SELFSIGN:
1125 $ssl_policy = 'self';
1127 case SSL_POLICY_NONE:
1129 $ssl_policy = 'none';
1133 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1135 logger('dfrn_deliver: ' . $url);
1137 $ret = z_fetch_url($url);
1139 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1140 return -2; // timed out
1143 $xml = $ret['body'];
1145 $curl_stat = $a->get_curl_code();
1147 return -3; // timed out
1150 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1156 if (strpos($xml,'<?xml') === false) {
1157 logger('dfrn_deliver: no valid XML returned');
1158 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1162 $res = parse_xml_string($xml);
1164 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1165 return (($res->status) ? $res->status : 3);
1168 $postvars = array();
1169 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1170 $challenge = hex2bin((string) $res->challenge);
1171 $perm = (($res->perm) ? $res->perm : null);
1172 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1173 $rino_remote_version = intval($res->rino);
1174 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1176 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1178 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1182 $final_dfrn_id = '';
1185 if ((($perm == 'rw') && (! intval($contact['writable'])))
1186 || (($perm == 'r') && (intval($contact['writable'])))) {
1187 q("update contact set writable = %d where id = %d",
1188 intval(($perm == 'rw') ? 1 : 0),
1189 intval($contact['id'])
1191 $contact['writable'] = (string) 1 - intval($contact['writable']);
1195 if (($contact['duplex'] && strlen($contact['pubkey']))
1196 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1197 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1198 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1199 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1201 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1202 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1205 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1207 if (strpos($final_dfrn_id,':') == 1) {
1208 $final_dfrn_id = substr($final_dfrn_id,2);
1211 if ($final_dfrn_id != $orig_id) {
1212 logger('dfrn_deliver: wrong dfrn_id.');
1213 // did not decode properly - cannot trust this site
1217 $postvars['dfrn_id'] = $idtosend;
1218 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1220 $postvars['dissolve'] = '1';
1224 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1225 $postvars['data'] = $atom;
1226 $postvars['perm'] = 'rw';
1228 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1229 $postvars['perm'] = 'r';
1232 $postvars['ssl_policy'] = $ssl_policy;
1235 $postvars['page'] = $page;
1239 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1240 logger('rino version: '. $rino_remote_version);
1242 switch ($rino_remote_version) {
1244 // Deprecated rino version!
1245 $key = openssl_random_pseudo_bytes(16);
1246 $data = self::aes_encrypt($postvars['data'], $key);
1249 // RINO 2 based on php-encryption
1251 $key = Crypto::createNewRandomKey();
1252 } catch (CryptoTestFailed $ex) {
1253 logger('Cannot safely create a key');
1255 } catch (CannotPerformOperation $ex) {
1256 logger('Cannot safely create a key');
1260 $data = Crypto::encrypt($postvars['data'], $key);
1261 } catch (CryptoTestFailed $ex) {
1262 logger('Cannot safely perform encryption');
1264 } catch (CannotPerformOperation $ex) {
1265 logger('Cannot safely perform encryption');
1270 logger("rino: invalid requested verision '$rino_remote_version'");
1274 $postvars['rino'] = $rino_remote_version;
1275 $postvars['data'] = bin2hex($data);
1277 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1280 if ($dfrn_version >= 2.1) {
1281 if (($contact['duplex'] && strlen($contact['pubkey']))
1282 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1283 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1284 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1286 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1290 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1291 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1293 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1298 logger('md5 rawkey ' . md5($postvars['key']));
1300 $postvars['key'] = bin2hex($postvars['key']);
1304 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1306 $xml = post_url($contact['notify'], $postvars);
1308 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1310 $curl_stat = $a->get_curl_code();
1311 if ((!$curl_stat) || (!strlen($xml))) {
1312 return -9; // timed out
1315 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1319 if (strpos($xml,'<?xml') === false) {
1320 logger('dfrn_deliver: phase 2: no valid XML returned');
1321 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1325 if ($contact['term-date'] > NULL_DATE) {
1326 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1327 require_once('include/Contact.php');
1328 unmark_for_death($contact);
1331 $res = parse_xml_string($xml);
1333 if (!isset($res->status)) {
1337 if (!empty($res->message)) {
1338 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1341 return intval($res->status);
1345 * @brief Add new birthday event for this person
1347 * @param array $contact Contact record
1348 * @param string $birthday Birthday of the contact
1349 * @todo Add array type-hint for $contact
1351 private static function birthday_event($contact, $birthday) {
1353 // Check for duplicates
1354 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1355 intval($contact["uid"]),
1356 intval($contact["id"]),
1357 dbesc(datetime_convert("UTC","UTC", $birthday)),
1360 if (DBM::is_result($r)) {
1364 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1366 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1367 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1369 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1370 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1371 intval($contact["uid"]),
1372 intval($contact["id"]),
1373 dbesc(datetime_convert()),
1374 dbesc(datetime_convert()),
1375 dbesc(datetime_convert("UTC","UTC", $birthday)),
1376 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1384 * @brief Fetch the author data from head or entry items
1386 * @param object $xpath XPath object
1387 * @param object $context In which context should the data be searched
1388 * @param array $importer Record of the importer user mixed with contact of the content
1389 * @param string $element Element name from which the data is fetched
1390 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1392 * @return Returns an array with relevant data of the author
1393 * @todo Find good type-hints for all parameter
1395 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1398 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1399 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1401 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1402 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1403 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1404 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1406 if (DBM::is_result($r)) {
1408 $author["contact-id"] = $r[0]["id"];
1409 $author["network"] = $r[0]["network"];
1412 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1415 $author["contact-id"] = $importer["id"];
1416 $author["network"] = $importer["network"];
1420 // Until now we aren't serving different sizes - but maybe later
1421 $avatarlist = array();
1422 /// @todo check if "avatar" or "photo" would be the best field in the specification
1423 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1424 foreach ($avatars AS $avatar) {
1427 foreach ($avatar->attributes AS $attributes) {
1428 /// @TODO Rewrite these similar if () to one switch
1429 if ($attributes->name == "href") {
1430 $href = $attributes->textContent;
1432 if ($attributes->name == "width") {
1433 $width = $attributes->textContent;
1435 if ($attributes->name == "updated") {
1436 $contact["avatar-date"] = $attributes->textContent;
1439 if (($width > 0) && ($href != "")) {
1440 $avatarlist[$width] = $href;
1443 if (count($avatarlist) > 0) {
1444 krsort($avatarlist);
1445 $author["avatar"] = current($avatarlist);
1448 if (DBM::is_result($r) && !$onlyfetch) {
1449 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1451 $poco = array("url" => $contact["url"]);
1453 // When was the last change to name or uri?
1454 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1455 foreach ($name_element->attributes AS $attributes) {
1456 if ($attributes->name == "updated") {
1457 $poco["name-date"] = $attributes->textContent;
1461 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1462 foreach ($link_element->attributes AS $attributes) {
1463 if ($attributes->name == "updated") {
1464 $poco["uri-date"] = $attributes->textContent;
1468 // Update contact data
1469 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1471 $poco["addr"] = $value;
1474 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1476 $poco["name"] = $value;
1479 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1481 $poco["nick"] = $value;
1484 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1486 $poco["about"] = $value;
1489 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1491 $poco["location"] = $value;
1494 /// @todo Only search for elements with "poco:type" = "xmpp"
1495 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1497 $poco["xmpp"] = $value;
1500 /// @todo Add support for the following fields that we don't support by now in the contact table:
1501 /// - poco:utcOffset
1507 // If the "hide" element is present then the profile isn't searchable.
1508 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1510 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1512 // If the contact isn't searchable then set the contact to "hidden".
1513 // Problem: This can be manually overridden by the user.
1515 $contact["hidden"] = true;
1518 // Save the keywords into the contact table
1520 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1521 foreach ($tagelements AS $tag) {
1522 $tags[$tag->nodeValue] = $tag->nodeValue;
1526 $poco["keywords"] = implode(", ", $tags);
1529 // "dfrn:birthday" contains the birthday converted to UTC
1530 $old_bdyear = $contact["bdyear"];
1532 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1534 if (strtotime($birthday) > time()) {
1535 $bd_timestamp = strtotime($birthday);
1537 $poco["bdyear"] = date("Y", $bd_timestamp);
1540 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1541 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1543 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1544 $bdyear = date("Y");
1545 $value = str_replace("0000", $bdyear, $value);
1547 if (strtotime($value) < time()) {
1548 $value = str_replace($bdyear, $bdyear + 1, $value);
1549 $bdyear = $bdyear + 1;
1552 $poco["bd"] = $value;
1555 $contact = array_merge($contact, $poco);
1557 if ($old_bdyear != $contact["bdyear"]) {
1558 self::birthday_event($contact, $birthday);
1561 // Get all field names
1563 foreach ($r[0] AS $field => $data) {
1564 $fields[$field] = $data;
1567 unset($fields["id"]);
1568 unset($fields["uid"]);
1569 unset($fields["url"]);
1570 unset($fields["avatar-date"]);
1571 unset($fields["name-date"]);
1572 unset($fields["uri-date"]);
1574 // Update check for this field has to be done differently
1575 $datefields = array("name-date", "uri-date");
1576 foreach ($datefields AS $field) {
1577 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1578 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1583 foreach ($fields AS $field => $data) {
1584 if ($contact[$field] != $r[0][$field]) {
1585 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1591 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1593 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1594 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1595 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1596 WHERE `id` = %d AND `network` = '%s'",
1597 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1598 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1599 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1600 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1601 intval($contact["id"]), dbesc($contact["network"]));
1604 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1605 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1608 * The generation is a sign for the reliability of the provided data.
1609 * It is used in the socgraph.php to prevent that old contact data
1610 * that was relayed over several servers can overwrite contact
1611 * data that we received directly.
1614 $poco["generation"] = 2;
1615 $poco["photo"] = $author["avatar"];
1616 $poco["hide"] = $hide;
1617 $poco["contact-type"] = $contact["contact-type"];
1618 $gcid = update_gcontact($poco);
1620 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1627 * @brief Transforms activity objects into an XML string
1629 * @param object $xpath XPath object
1630 * @param object $activity Activity object
1631 * @param text $element element name
1633 * @return string XML string
1634 * @todo Find good type-hints for all parameter
1636 private static function transform_activity($xpath, $activity, $element) {
1637 if (!is_object($activity)) {
1641 $obj_doc = new DOMDocument("1.0", "utf-8");
1642 $obj_doc->formatOutput = true;
1644 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1646 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1647 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1649 $id = $xpath->query("atom:id", $activity)->item(0);
1650 if (is_object($id)) {
1651 $obj_element->appendChild($obj_doc->importNode($id, true));
1654 $title = $xpath->query("atom:title", $activity)->item(0);
1655 if (is_object($title)) {
1656 $obj_element->appendChild($obj_doc->importNode($title, true));
1659 $links = $xpath->query("atom:link", $activity);
1660 if (is_object($links)) {
1661 foreach ($links AS $link) {
1662 $obj_element->appendChild($obj_doc->importNode($link, true));
1666 $content = $xpath->query("atom:content", $activity)->item(0);
1667 if (is_object($content)) {
1668 $obj_element->appendChild($obj_doc->importNode($content, true));
1671 $obj_doc->appendChild($obj_element);
1673 $objxml = $obj_doc->saveXML($obj_element);
1675 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1676 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1681 * @brief Processes the mail elements
1683 * @param object $xpath XPath object
1684 * @param object $mail mail elements
1685 * @param array $importer Record of the importer user mixed with contact of the content
1686 * @todo Find good type-hints for all parameter
1688 private static function process_mail($xpath, $mail, $importer) {
1690 logger("Processing mails");
1692 /// @TODO Rewrite this to one statement
1694 $msg["uid"] = $importer["importer_uid"];
1695 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1696 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1697 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1698 $msg["contact-id"] = $importer["id"];
1699 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1700 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1701 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1702 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1703 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1705 $msg["replied"] = 0;
1707 dba::insert('mail', $msg);
1709 // send notifications.
1710 /// @TODO Arange this mess
1711 $notif_params = array(
1712 "type" => NOTIFY_MAIL,
1713 "notify_flags" => $importer["notify-flags"],
1714 "language" => $importer["language"],
1715 "to_name" => $importer["username"],
1716 "to_email" => $importer["email"],
1717 "uid" => $importer["importer_uid"],
1719 "source_name" => $msg["from-name"],
1720 "source_link" => $importer["url"],
1721 "source_photo" => $importer["thumb"],
1722 "verb" => ACTIVITY_POST,
1726 notification($notif_params);
1728 logger("Mail is processed, notification was sent.");
1732 * @brief Processes the suggestion elements
1734 * @param object $xpath XPath object
1735 * @param object $suggestion suggestion elements
1736 * @param array $importer Record of the importer user mixed with contact of the content
1737 * @todo Find good type-hints for all parameter
1739 private static function process_suggestion($xpath, $suggestion, $importer) {
1742 logger("Processing suggestions");
1744 /// @TODO Rewrite this to one statement
1746 $suggest["uid"] = $importer["importer_uid"];
1747 $suggest["cid"] = $importer["id"];
1748 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1749 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1750 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1751 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1752 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1754 // Does our member already have a friend matching this description?
1756 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1757 dbesc($suggest["name"]),
1758 dbesc(normalise_link($suggest["url"])),
1759 intval($suggest["uid"])
1763 * The valid result means the friend we're about to send a friend
1764 * suggestion already has them in their contact, which means no further
1765 * action is required.
1767 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1769 if (DBM::is_result($r)) {
1773 // Do we already have an fcontact record for this person?
1776 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1777 dbesc($suggest["url"]),
1778 dbesc($suggest["name"]),
1779 dbesc($suggest["request"])
1781 if (DBM::is_result($r)) {
1784 // OK, we do. Do we already have an introduction for this person ?
1785 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1786 intval($suggest["uid"]),
1791 * The valid result means the friend we're about to send a friend
1792 * suggestion already has them in their contact, which means no further
1793 * action is required.
1795 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1797 if (DBM::is_result($r)) {
1802 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1803 dbesc($suggest["name"]),
1804 dbesc($suggest["url"]),
1805 dbesc($suggest["photo"]),
1806 dbesc($suggest["request"])
1809 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1810 dbesc($suggest["url"]),
1811 dbesc($suggest["name"]),
1812 dbesc($suggest["request"])
1816 * If no record in fcontact is found, below INSERT statement will not
1817 * link an introduction to it.
1819 if (!DBM::is_result($r)) {
1820 // database record did not get created. Quietly give up.
1826 $hash = random_string();
1828 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1829 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1830 intval($suggest["uid"]),
1832 intval($suggest["cid"]),
1833 dbesc($suggest["body"]),
1835 dbesc(datetime_convert()),
1840 "type" => NOTIFY_SUGGEST,
1841 "notify_flags" => $importer["notify-flags"],
1842 "language" => $importer["language"],
1843 "to_name" => $importer["username"],
1844 "to_email" => $importer["email"],
1845 "uid" => $importer["importer_uid"],
1847 "link" => System::baseUrl()."/notifications/intros",
1848 "source_name" => $importer["name"],
1849 "source_link" => $importer["url"],
1850 "source_photo" => $importer["photo"],
1851 "verb" => ACTIVITY_REQ_FRIEND,
1860 * @brief Processes the relocation elements
1862 * @param object $xpath XPath object
1863 * @param object $relocation relocation elements
1864 * @param array $importer Record of the importer user mixed with contact of the content
1865 * @todo Find good type-hints for all parameter
1867 private static function process_relocation($xpath, $relocation, $importer) {
1869 logger("Processing relocations");
1871 /// @TODO Rewrite this to one statement
1872 $relocate = array();
1873 $relocate["uid"] = $importer["importer_uid"];
1874 $relocate["cid"] = $importer["id"];
1875 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1876 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1877 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1878 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1879 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1880 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1881 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1882 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1883 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1884 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1885 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1886 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1888 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1889 $relocate["avatar"] = $relocate["photo"];
1892 if ($relocate["addr"] == "") {
1893 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1897 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1898 intval($importer["id"]),
1899 intval($importer["importer_uid"]));
1901 if (!DBM::is_result($r)) {
1902 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1908 // Update the gcontact entry
1909 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1911 $x = q("UPDATE `gcontact` SET
1920 WHERE `nurl` = '%s';",
1921 dbesc($relocate["name"]),
1922 dbesc($relocate["avatar"]),
1923 dbesc($relocate["url"]),
1924 dbesc(normalise_link($relocate["url"])),
1925 dbesc($relocate["addr"]),
1926 dbesc($relocate["addr"]),
1927 dbesc($relocate["notify"]),
1928 dbesc($relocate["server_url"]),
1929 dbesc(normalise_link($old["url"])));
1931 // Update the contact table. We try to find every entry.
1932 $x = q("UPDATE `contact` SET
1942 `site-pubkey` = '%s'
1943 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1944 dbesc($relocate["name"]),
1945 dbesc($relocate["avatar"]),
1946 dbesc($relocate["url"]),
1947 dbesc(normalise_link($relocate["url"])),
1948 dbesc($relocate["addr"]),
1949 dbesc($relocate["request"]),
1950 dbesc($relocate["confirm"]),
1951 dbesc($relocate["notify"]),
1952 dbesc($relocate["poll"]),
1953 dbesc($relocate["sitepubkey"]),
1954 intval($importer["id"]),
1955 intval($importer["importer_uid"]),
1956 dbesc(normalise_link($old["url"])));
1958 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1965 /// @todo This is an extreme performance killer
1967 'owner-link' => array($old["url"], $relocate["url"]),
1968 'author-link' => array($old["url"], $relocate["url"]),
1969 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1970 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1972 foreach ($fields as $n=>$f) {
1973 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1975 intval($importer["importer_uid"]));
1977 if (DBM::is_result($r)) {
1978 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1981 intval($importer["importer_uid"]));
1990 /// merge with current record, current contents have priority
1991 /// update record, set url-updated
1992 /// update profile photos
1993 /// schedule a scan?
1998 * @brief Updates an item
2000 * @param array $current the current item record
2001 * @param array $item the new item record
2002 * @param array $importer Record of the importer user mixed with contact of the content
2003 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2004 * @todo set proper type-hints (array?)
2006 private static function update_content($current, $item, $importer, $entrytype) {
2009 if (edited_timestamp_is_newer($current, $item)) {
2011 // do not accept (ignore) an earlier edit than one we currently have.
2012 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2016 $fields = array('title' => $item["title"], 'body' => $item["body"],
2017 'tag' => $item["tag"], 'changed' => datetime_convert(),
2018 'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2020 $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2021 dba::update('item', $fields, $condition);
2023 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2024 update_thread_uri($item["uri"], $importer["importer_uid"]);
2028 if ($entrytype == DFRN_REPLY_RC) {
2029 Worker::add(PRIORITY_HIGH, "notifier","comment-import", $current["id"]);
2033 // update last-child if it changes
2034 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2035 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2036 dbesc(datetime_convert()),
2037 dbesc($item["parent-uri"]),
2038 intval($importer["importer_uid"])
2040 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2041 intval($item["last-child"]),
2042 dbesc(datetime_convert()),
2043 dbesc($item["uri"]),
2044 intval($importer["importer_uid"])
2051 * @brief Detects the entry type of the item
2053 * @param array $importer Record of the importer user mixed with contact of the content
2054 * @param array $item the new item record
2056 * @return int Is it a toplevel entry, a comment or a relayed comment?
2057 * @todo set proper type-hints (array?)
2059 private static function get_entry_type($importer, $item) {
2060 if ($item["parent-uri"] != $item["uri"]) {
2063 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2066 logger("possible community action");
2068 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2071 // was the top-level post for this action written by somebody on this site?
2072 // Specifically, the recipient?
2074 $is_a_remote_action = false;
2076 $r = q("SELECT `item`.`parent-uri` FROM `item`
2077 WHERE `item`.`uri` = '%s'
2079 dbesc($item["parent-uri"])
2081 if (DBM::is_result($r)) {
2082 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2083 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2084 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2085 AND `item`.`uid` = %d
2088 dbesc($r[0]["parent-uri"]),
2089 dbesc($r[0]["parent-uri"]),
2090 dbesc($r[0]["parent-uri"]),
2091 intval($importer["importer_uid"])
2093 if (DBM::is_result($r)) {
2094 $is_a_remote_action = true;
2099 * Does this have the characteristics of a community or private group action?
2100 * If it's an action to a wall post on a community/prvgroup page it's a
2101 * valid community action. Also forum_mode makes it valid for sure.
2102 * If neither, it's not.
2105 /// @TODO Maybe merge these if() blocks into one?
2106 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2107 $is_a_remote_action = false;
2108 logger("not a community action");
2111 if ($is_a_remote_action) {
2112 return DFRN_REPLY_RC;
2117 return DFRN_TOP_LEVEL;
2123 * @brief Send a "poke"
2125 * @param array $item the new item record
2126 * @param array $importer Record of the importer user mixed with contact of the content
2127 * @param int $posted_id The record number of item record that was just posted
2128 * @todo set proper type-hints (array?)
2130 private static function do_poke($item, $importer, $posted_id) {
2131 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2135 $xo = parse_xml_string($item["object"],false);
2137 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2139 // somebody was poked/prodded. Was it me?
2140 foreach ($xo->link as $l) {
2141 $atts = $l->attributes();
2142 switch ($atts["rel"]) {
2144 $Blink = $atts["href"];
2151 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2153 // send a notification
2155 "type" => NOTIFY_POKE,
2156 "notify_flags" => $importer["notify-flags"],
2157 "language" => $importer["language"],
2158 "to_name" => $importer["username"],
2159 "to_email" => $importer["email"],
2160 "uid" => $importer["importer_uid"],
2162 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2163 "source_name" => stripslashes($item["author-name"]),
2164 "source_link" => $item["author-link"],
2165 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2166 ? $importer["thumb"] : $item["author-avatar"]),
2167 "verb" => $item["verb"],
2168 "otype" => "person",
2169 "activity" => $verb,
2170 "parent" => $item["parent"]
2177 * @brief Processes several actions, depending on the verb
2179 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2180 * @param array $importer Record of the importer user mixed with contact of the content
2181 * @param array $item the new item record
2182 * @param bool $is_like Is the verb a "like"?
2184 * @return bool Should the processing of the entries be continued?
2185 * @todo set proper type-hints (array?)
2187 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2189 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2191 if (($entrytype == DFRN_TOP_LEVEL)) {
2192 // The filling of the the "contact" variable is done for legcy reasons
2193 // The functions below are partly used by ostatus.php as well - where we have this variable
2194 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2196 $nickname = $contact["nick"];
2198 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2199 // This function once was responsible for DFRN and OStatus.
2200 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2201 logger("New follower");
2202 new_follower($importer, $contact, $item, $nickname);
2205 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2206 logger("Lost follower");
2207 lose_follower($importer, $contact, $item);
2210 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2211 logger("New friend request");
2212 new_follower($importer, $contact, $item, $nickname, true);
2215 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2216 logger("Lost sharer");
2217 lose_sharer($importer, $contact, $item);
2221 if (($item["verb"] == ACTIVITY_LIKE)
2222 || ($item["verb"] == ACTIVITY_DISLIKE)
2223 || ($item["verb"] == ACTIVITY_ATTEND)
2224 || ($item["verb"] == ACTIVITY_ATTENDNO)
2225 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2227 $item["type"] = "activity";
2228 $item["gravity"] = GRAVITY_LIKE;
2229 // only one like or dislike per person
2230 // splitted into two queries for performance issues
2231 $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",
2232 intval($item["uid"]),
2233 dbesc($item["author-link"]),
2234 dbesc($item["verb"]),
2235 dbesc($item["parent-uri"])
2237 if (DBM::is_result($r)) {
2241 $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",
2242 intval($item["uid"]),
2243 dbesc($item["author-link"]),
2244 dbesc($item["verb"]),
2245 dbesc($item["parent-uri"])
2247 if (DBM::is_result($r)) {
2254 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2256 $xo = parse_xml_string($item["object"],false);
2257 $xt = parse_xml_string($item["target"],false);
2259 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2260 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2262 intval($importer["importer_uid"])
2265 if (!DBM::is_result($r)) {
2266 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2270 // extract tag, if not duplicate, add to parent item
2272 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2273 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2274 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2277 create_tags_from_item($r[0]["id"]);
2287 * @brief Processes the link elements
2289 * @param object $links link elements
2290 * @param array $item the item record
2291 * @todo set proper type-hints
2293 private static function parse_links($links, &$item) {
2299 foreach ($links AS $link) {
2300 foreach ($link->attributes AS $attributes) {
2301 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2302 if ($attributes->name == "href") {
2303 $href = $attributes->textContent;
2305 if ($attributes->name == "rel") {
2306 $rel = $attributes->textContent;
2308 if ($attributes->name == "type") {
2309 $type = $attributes->textContent;
2311 if ($attributes->name == "length") {
2312 $length = $attributes->textContent;
2314 if ($attributes->name == "title") {
2315 $title = $attributes->textContent;
2318 if (($rel != "") && ($href != "")) {
2321 $item["plink"] = $href;
2325 if (strlen($item["attach"])) {
2326 $item["attach"] .= ",";
2329 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2337 * @brief Processes the entry elements which contain the items and comments
2339 * @param array $header Array of the header elements that always stay the same
2340 * @param object $xpath XPath object
2341 * @param object $entry entry elements
2342 * @param array $importer Record of the importer user mixed with contact of the content
2343 * @todo Add type-hints
2345 private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2347 logger("Processing entries");
2351 $item["protocol"] = PROTOCOL_DFRN;
2353 $item["source"] = $xml;
2356 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2358 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2360 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2361 dbesc($item["uri"]),
2362 intval($importer["importer_uid"])
2365 // Is there an existing item?
2366 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2367 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2368 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2373 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2375 $item["owner-name"] = $owner["name"];
2376 $item["owner-link"] = $owner["link"];
2377 $item["owner-avatar"] = $owner["avatar"];
2380 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2382 $item["author-name"] = $author["name"];
2383 $item["author-link"] = $author["link"];
2384 $item["author-avatar"] = $author["avatar"];
2386 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2388 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2390 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2391 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2392 // make sure nobody is trying to sneak some html tags by us
2393 $item["body"] = notags(base64url_decode($item["body"]));
2395 $item["body"] = limit_body_size($item["body"]);
2397 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2398 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2400 $item['body'] = reltoabs($item['body'],$base_url);
2402 $item['body'] = html2bb_video($item['body']);
2404 $item['body'] = oembed_html2bbcode($item['body']);
2406 $config = HTMLPurifier_Config::createDefault();
2407 $config->set('Cache.DefinitionImpl', null);
2409 // we shouldn't need a whitelist, because the bbcode converter
2410 // will strip out any unsupported tags.
2412 $purifier = new HTMLPurifier($config);
2413 $item['body'] = $purifier->purify($item['body']);
2415 $item['body'] = @html2bbcode($item['body']);
2418 /// @todo We should check for a repeated post and if we know the repeated author.
2420 // We don't need the content element since "dfrn:env" is always present
2421 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2423 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2424 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2426 $georsspoint = $xpath->query("georss:point", $entry);
2428 $item["coord"] = $georsspoint->item(0)->nodeValue;
2431 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2433 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2435 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2436 $item["bookmark"] = true;
2439 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2440 if ($notice_info && ($notice_info->length > 0)) {
2441 foreach ($notice_info->item(0)->attributes AS $attributes) {
2442 if ($attributes->name == "source") {
2443 $item["app"] = strip_tags($attributes->textContent);
2448 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2450 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2451 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2452 if ($dsprsig != "") {
2453 $item["dsprsig"] = $dsprsig;
2456 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2458 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2459 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2462 $object = $xpath->query("activity:object", $entry)->item(0);
2463 $item["object"] = self::transform_activity($xpath, $object, "object");
2465 if (trim($item["object"]) != "") {
2466 $r = parse_xml_string($item["object"], false);
2467 if (isset($r->type)) {
2468 $item["object-type"] = $r->type;
2472 $target = $xpath->query("activity:target", $entry)->item(0);
2473 $item["target"] = self::transform_activity($xpath, $target, "target");
2475 $categories = $xpath->query("atom:category", $entry);
2477 foreach ($categories AS $category) {
2480 foreach ($category->attributes AS $attributes) {
2481 if ($attributes->name == "term") {
2482 $term = $attributes->textContent;
2485 if ($attributes->name == "scheme") {
2486 $scheme = $attributes->textContent;
2490 if (($term != "") && ($scheme != "")) {
2491 $parts = explode(":", $scheme);
2492 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2493 $termhash = array_shift($parts);
2494 $termurl = implode(":", $parts);
2496 if (strlen($item["tag"])) {
2497 $item["tag"] .= ",";
2500 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2508 $links = $xpath->query("atom:link", $entry);
2510 self::parse_links($links, $item);
2513 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2515 $conv = $xpath->query('ostatus:conversation', $entry);
2516 if (is_object($conv->item(0))) {
2517 foreach ($conv->item(0)->attributes AS $attributes) {
2518 if ($attributes->name == "ref") {
2519 $item['conversation-uri'] = $attributes->textContent;
2521 if ($attributes->name == "href") {
2522 $item['conversation-href'] = $attributes->textContent;
2527 // Is it a reply or a top level posting?
2528 $item["parent-uri"] = $item["uri"];
2530 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2531 if (is_object($inreplyto->item(0))) {
2532 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2533 if ($attributes->name == "ref") {
2534 $item["parent-uri"] = $attributes->textContent;
2539 // Get the type of the item (Top level post, reply or remote reply)
2540 $entrytype = self::get_entry_type($importer, $item);
2542 // Now assign the rest of the values that depend on the type of the message
2543 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2544 if (!isset($item["object-type"])) {
2545 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2548 if ($item["contact-id"] != $owner["contact-id"]) {
2549 $item["contact-id"] = $owner["contact-id"];
2552 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2553 $item["network"] = $owner["network"];
2556 if ($item["contact-id"] != $author["contact-id"]) {
2557 $item["contact-id"] = $author["contact-id"];
2560 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2561 $item["network"] = $author["network"];
2564 /// @TODO maybe remove this old-lost code then?
2565 // This code was taken from the old DFRN code
2566 // When activated, forums don't work.
2567 // And: Why should we disallow commenting by followers?
2568 // the behaviour is now similar to the Diaspora part.
2569 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2570 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2575 if ($entrytype == DFRN_REPLY_RC) {
2576 $item["type"] = "remote-comment";
2578 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2579 if (!isset($item["object-type"])) {
2580 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2584 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2585 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2586 $ev = bbtoevent($item["body"]);
2587 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2588 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2589 /// @TODO Mixure of "/' ahead ...
2590 $ev["cid"] = $importer["id"];
2591 $ev["uid"] = $importer["uid"];
2592 $ev["uri"] = $item["uri"];
2593 $ev["edited"] = $item["edited"];
2594 $ev['private'] = $item['private'];
2595 $ev["guid"] = $item["guid"];
2597 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2598 dbesc($item["uri"]),
2599 intval($importer["uid"])
2601 if (DBM::is_result($r)) {
2602 $ev["id"] = $r[0]["id"];
2605 $event_id = event_store($ev);
2606 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2612 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2613 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2617 // Update content if 'updated' changes
2618 if (DBM::is_result($current)) {
2619 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2620 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2622 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2627 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2628 $posted_id = item_store($item);
2633 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2635 $item["id"] = $posted_id;
2637 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2639 intval($importer["importer_uid"])
2641 if (DBM::is_result($r)) {
2642 $parent = $r[0]["parent"];
2643 $parent_uri = $r[0]["parent-uri"];
2647 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2648 dbesc(datetime_convert()),
2649 intval($importer["importer_uid"]),
2650 intval($r[0]["parent"])
2653 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2654 dbesc(datetime_convert()),
2655 intval($importer["importer_uid"]),
2660 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2661 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2662 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $posted_id);
2667 } else { // $entrytype == DFRN_TOP_LEVEL
2668 if (!link_compare($item["owner-link"],$importer["url"])) {
2670 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2671 * but otherwise there's a possible data mixup on the sender's system.
2672 * the tgroup delivery code called from item_store will correct it if it's a forum,
2673 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2675 logger('Correcting item owner.', LOGGER_DEBUG);
2676 $item["owner-name"] = $importer["senderName"];
2677 $item["owner-link"] = $importer["url"];
2678 $item["owner-avatar"] = $importer["thumb"];
2681 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2682 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2686 // This is my contact on another system, but it's really me.
2687 // Turn this into a wall post.
2688 $notify = item_is_remote_self($importer, $item);
2690 $posted_id = item_store($item, false, $notify);
2692 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2694 if (stristr($item["verb"],ACTIVITY_POKE))
2695 self::do_poke($item, $importer, $posted_id);
2700 * @brief Deletes items
2702 * @param object $xpath XPath object
2703 * @param object $deletion deletion elements
2704 * @param array $importer Record of the importer user mixed with contact of the content
2705 * @todo set proper type-hints
2707 private static function process_deletion($xpath, $deletion, $importer) {
2709 logger("Processing deletions");
2711 foreach ($deletion->attributes AS $attributes) {
2712 if ($attributes->name == "ref") {
2713 $uri = $attributes->textContent;
2715 if ($attributes->name == "when") {
2716 $when = $attributes->textContent;
2720 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2722 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2725 if (!$uri || !$importer["id"]) {
2729 /// @todo Only select the used fields
2730 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2731 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2733 intval($importer["uid"]),
2734 intval($importer["id"])
2736 if (!DBM::is_result($r)) {
2737 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2743 $entrytype = self::get_entry_type($importer, $item);
2745 if (!$item["deleted"]) {
2746 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2751 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2752 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2753 event_delete($item["event-id"]);
2756 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2758 $xo = parse_xml_string($item["object"],false);
2759 $xt = parse_xml_string($item["target"],false);
2761 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2762 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2764 intval($importer["importer_uid"])
2766 if (DBM::is_result($i)) {
2768 // For tags, the owner cannot remove the tag on the author's copy of the post.
2770 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2771 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2772 $author_copy = (($item["origin"]) ? true : false);
2774 if ($owner_remove && $author_copy) {
2777 if ($author_remove || $owner_remove) {
2778 $tags = explode(',',$i[0]["tag"]);
2781 foreach ($tags as $tag) {
2782 if (trim($tag) !== trim($xo->body)) {
2783 $newtags[] = trim($tag);
2787 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2788 dbesc(implode(',', $newtags)),
2791 create_tags_from_item($i[0]["id"]);
2797 if ($entrytype == DFRN_TOP_LEVEL) {
2798 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2799 `body` = '', `title` = ''
2800 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2802 dbesc(datetime_convert()),
2804 intval($importer["uid"])
2806 create_tags_from_itemuri($uri, $importer["uid"]);
2807 create_files_from_itemuri($uri, $importer["uid"]);
2808 update_thread_uri($uri, $importer["uid"]);
2810 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2811 `body` = '', `title` = ''
2812 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2814 dbesc(datetime_convert()),
2816 intval($importer["uid"])
2818 create_tags_from_itemuri($uri, $importer["uid"]);
2819 create_files_from_itemuri($uri, $importer["uid"]);
2820 update_thread_uri($uri, $importer["importer_uid"]);
2821 if ($item["last-child"]) {
2822 // ensure that last-child is set in case the comment that had it just got wiped.
2823 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2824 dbesc(datetime_convert()),
2825 dbesc($item["parent-uri"]),
2826 intval($item["uid"])
2828 // who is the last child now?
2829 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2830 ORDER BY `created` DESC LIMIT 1",
2831 dbesc($item["parent-uri"]),
2832 intval($importer["uid"])
2834 if (DBM::is_result($r)) {
2835 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2840 // if this is a relayed delete, propagate it to other recipients
2842 if ($entrytype == DFRN_REPLY_RC) {
2843 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2844 Worker::add(PRIORITY_HIGH, "notifier","drop", $item["id"]);
2851 * @brief Imports a DFRN message
2853 * @param text $xml The DFRN message
2854 * @param array $importer Record of the importer user mixed with contact of the content
2855 * @param bool $sort_by_date Is used when feeds are polled
2856 * @return integer Import status
2857 * @todo set proper type-hints
2859 public static function import($xml, $importer, $sort_by_date = false) {
2865 $doc = new DOMDocument();
2866 @$doc->loadXML($xml);
2868 $xpath = new DomXPath($doc);
2869 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2870 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2871 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2872 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2873 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2874 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2875 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2876 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2877 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2878 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2881 $header["uid"] = $importer["uid"];
2882 $header["network"] = NETWORK_DFRN;
2883 $header["type"] = "remote";
2884 $header["wall"] = 0;
2885 $header["origin"] = 0;
2886 $header["contact-id"] = $importer["id"];
2888 // Update the contact table if the data has changed
2890 // The "atom:author" is only present in feeds
2891 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2892 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2895 // Only the "dfrn:owner" in the head section contains all data
2896 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2897 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2900 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2902 // The account type is new since 3.5.1
2903 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2904 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2906 if ($accounttype != $importer["contact-type"]) {
2907 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2911 // is it a public forum? Private forums aren't supported with this method
2912 // This is deprecated since 3.5.1
2913 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2915 if ($forum != $importer["forum"]) {
2916 $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2917 dba::update('contact', array('forum' => $forum), $condition);
2920 // We are processing relocations even if we are ignoring a contact
2921 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2922 foreach ($relocations AS $relocation) {
2923 self::process_relocation($xpath, $relocation, $importer);
2926 if ($importer["readonly"]) {
2927 // We aren't receiving stuff from this person. But we will quietly ignore them
2928 // rather than a blatant "go away" message.
2929 logger('ignoring contact '.$importer["id"]);
2933 $mails = $xpath->query("/atom:feed/dfrn:mail");
2934 foreach ($mails AS $mail) {
2935 self::process_mail($xpath, $mail, $importer);
2938 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2939 foreach ($suggestions AS $suggestion) {
2940 self::process_suggestion($xpath, $suggestion, $importer);
2943 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2944 foreach ($deletions AS $deletion) {
2945 self::process_deletion($xpath, $deletion, $importer);
2948 if (!$sort_by_date) {
2949 $entries = $xpath->query("/atom:feed/atom:entry");
2950 foreach ($entries AS $entry) {
2951 self::process_entry($header, $xpath, $entry, $importer, $xml);
2954 $newentries = array();
2955 $entries = $xpath->query("/atom:feed/atom:entry");
2956 foreach ($entries AS $entry) {
2957 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2958 $newentries[strtotime($created)] = $entry;
2961 // Now sort after the publishing date
2964 foreach ($newentries AS $entry) {
2965 self::process_entry($header, $xpath, $entry, $importer, $xml);
2968 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);