3 * @file include/dfrn.php
4 * @brief The implementation of the dfrn protocol
6 * @see https://github.com/friendica/friendica/wiki/Protocol and
7 * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
11 use Friendica\Core\System;
12 use Friendica\Core\Worker;
14 require_once("include/Contact.php");
15 require_once("include/ostatus.php");
16 require_once("include/enotify.php");
17 require_once("include/threads.php");
18 require_once("include/socgraph.php");
19 require_once("include/items.php");
20 require_once("include/tags.php");
21 require_once("include/files.php");
22 require_once("include/event.php");
23 require_once("include/text.php");
24 require_once("include/oembed.php");
25 require_once("include/html2bbcode.php");
26 require_once("include/bbcode.php");
27 require_once("include/xml.php");
30 * @brief This class contain functions to create and send DFRN XML files
35 const DFRN_TOP_LEVEL = 0; // Top level posting
36 const DFRN_REPLY = 1; // Regular reply that is stored locally
37 const DFRN_REPLY_RC = 2; // Reply that will be relayed
40 * @brief Generates the atom entries for delivery.php
42 * This function is used whenever content is transmitted via DFRN.
44 * @param array $items Item elements
45 * @param array $owner Owner record
47 * @return string DFRN entries
48 * @todo Add type-hints
50 public static function entries($items,$owner) {
52 $doc = new DOMDocument('1.0', 'utf-8');
53 $doc->formatOutput = true;
55 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
57 if (! count($items)) {
58 return trim($doc->saveXML());
61 foreach ($items as $item) {
62 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
63 $root->appendChild($entry);
66 return(trim($doc->saveXML()));
70 * @brief Generate an atom feed for the given user
72 * This function is called when another server is pulling data from the user feed.
74 * @param string $dfrn_id DFRN ID from the requesting party
75 * @param string $owner_nick Owner nick name
76 * @param string $last_update Date of the last update
77 * @param int $direction Can be -1, 0 or 1.
78 * @param boolean $onlyheader Output only the header without content? (Default is "no")
80 * @return string DFRN feed entries
82 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
86 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
87 $public_feed = (($dfrn_id) ? false : true);
88 $starred = false; // not yet implemented, possible security issues
91 if ($public_feed && $a->argc > 2) {
92 for ($x = 2; $x < $a->argc; $x++) {
93 if ($a->argv[$x] == 'converse') {
96 if ($a->argv[$x] == 'starred') {
99 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
100 $category = $a->argv[$x+1];
107 // default permissions - anonymous user
109 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
111 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
112 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
113 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
117 if (! dbm::is_result($r)) {
122 $owner_id = $owner['uid'];
123 $owner_nick = $owner['nickname'];
125 $sql_post_table = "";
127 if (! $public_feed) {
132 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
136 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
137 $my_id = '1:' . $dfrn_id;
140 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
141 $my_id = '0:' . $dfrn_id;
148 $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
152 if (! dbm::is_result($r)) {
157 require_once('include/security.php');
158 $groups = init_groups_visitor($contact['id']);
160 if (count($groups)) {
161 for ($x = 0; $x < count($groups); $x ++)
162 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
163 $gs = implode('|', $groups);
165 $gs = '<<>>' ; // Impossible to match
168 $sql_extra = sprintf("
169 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
170 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
171 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
172 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
174 intval($contact['id']),
175 intval($contact['id']),
187 if (! strlen($last_update)) {
188 $last_update = 'now -30 days';
191 if (isset($category)) {
192 $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` ",
193 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
194 //$sql_extra .= file_tag_file_query('item',$category,'category');
199 $sql_extra .= " AND `contact`.`self` = 1 ";
203 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
205 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
206 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
207 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
208 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
209 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
210 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
211 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
212 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
213 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
214 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
215 AND `item`.`wall` AND `item`.`changed` > '%s'
217 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
224 * Will check further below if this actually returned results.
225 * We will provide an empty feed if that is the case.
230 $doc = new DOMDocument('1.0', 'utf-8');
231 $doc->formatOutput = true;
233 $alternatelink = $owner['url'];
235 if (isset($category)) {
236 $alternatelink .= "/category/".$category;
240 $author = "dfrn:owner";
245 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
247 /// @TODO This hook can't work anymore
248 // call_hooks('atom_feed', $atom);
250 if (!dbm::is_result($items) || $onlyheader) {
251 $atom = trim($doc->saveXML());
253 call_hooks('atom_feed_end', $atom);
258 foreach ($items as $item) {
260 // prevent private email from leaking.
261 if ($item['network'] == NETWORK_MAIL) {
265 // public feeds get html, our own nodes use bbcode
269 // catch any email that's in a public conversation and make sure it doesn't leak
270 if ($item['private']) {
277 $entry = self::entry($doc, $type, $item, $owner, true);
278 $root->appendChild($entry);
282 $atom = trim($doc->saveXML());
284 call_hooks('atom_feed_end', $atom);
290 * @brief Generate an atom entry for a given item id
292 * @param int $item_id The item id
293 * @param boolean $conversation Show the conversation. If false show the single post.
295 * @return string DFRN feed entry
297 public static function itemFeed($item_id, $conversation = false) {
299 $condition = '`item`.`parent`';
301 $condition = '`item`.`id`';
304 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
305 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
306 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
307 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
308 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
310 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
311 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
312 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
313 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
314 AND NOT `item`.`private`",
319 if (!dbm::is_result($r)) {
326 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
327 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
328 WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
332 if (!dbm::is_result($r)) {
338 $doc = new DOMDocument('1.0', 'utf-8');
339 $doc->formatOutput = true;
343 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
344 $doc->appendChild($root);
346 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
347 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
348 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
349 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
350 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
351 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
352 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
353 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
354 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
356 //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
358 foreach ($items as $item) {
359 $entry = self::entry($doc, $type, $item, $owner, true, 0);
360 $root->appendChild($entry);
363 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
366 $atom = trim($doc->saveXML());
371 * @brief Create XML text for DFRN mails
373 * @param array $item message elements
374 * @param array $owner Owner record
376 * @return string DFRN mail
377 * @todo Add type-hints
379 public static function mail($item, $owner) {
380 $doc = new DOMDocument('1.0', 'utf-8');
381 $doc->formatOutput = true;
383 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
385 $mail = $doc->createElement("dfrn:mail");
386 $sender = $doc->createElement("dfrn:sender");
388 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
389 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
390 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
392 $mail->appendChild($sender);
394 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
395 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
396 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
397 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
398 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
400 $root->appendChild($mail);
402 return(trim($doc->saveXML()));
406 * @brief Create XML text for DFRN friend suggestions
408 * @param array $item suggestion elements
409 * @param array $owner Owner record
411 * @return string DFRN suggestions
412 * @todo Add type-hints
414 public static function fsuggest($item, $owner) {
415 $doc = new DOMDocument('1.0', 'utf-8');
416 $doc->formatOutput = true;
418 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
420 $suggest = $doc->createElement("dfrn:suggest");
422 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
423 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
424 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
425 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
426 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
428 $root->appendChild($suggest);
430 return(trim($doc->saveXML()));
434 * @brief Create XML text for DFRN relocations
436 * @param array $owner Owner record
437 * @param int $uid User ID
439 * @return string DFRN relocations
440 * @todo Add type-hints
442 public static function relocate($owner, $uid) {
444 /* get site pubkey. this could be a new installation with no site keys*/
445 $pubkey = get_config('system','site_pubkey');
447 $res = new_keypair(1024);
448 set_config('system','site_prvkey', $res['prvkey']);
449 set_config('system','site_pubkey', $res['pubkey']);
452 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
453 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
455 $ext = Photo::supportedTypes();
457 foreach ($rp as $p) {
458 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
463 $doc = new DOMDocument('1.0', 'utf-8');
464 $doc->formatOutput = true;
466 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
468 $relocate = $doc->createElement("dfrn:relocate");
470 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
471 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
472 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
473 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
474 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
475 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
476 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
477 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
478 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
479 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
480 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
481 xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
483 $root->appendChild($relocate);
485 return(trim($doc->saveXML()));
489 * @brief Adds the header elements for the DFRN protocol
491 * @param object $doc XML document
492 * @param array $owner Owner record
493 * @param string $authorelement Element name for the author
494 * @param string $alternatelink link to profile or category
495 * @param bool $public Is it a header for public posts?
497 * @return object XML root object
498 * @todo Add type-hints
500 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
502 if ($alternatelink == "") {
503 $alternatelink = $owner['url'];
506 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
507 $doc->appendChild($root);
509 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
510 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
511 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
512 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
513 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
514 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
515 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
516 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
517 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
519 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
520 xml::add_element($doc, $root, "title", $owner["name"]);
522 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
523 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
525 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
526 xml::add_element($doc, $root, "link", "", $attributes);
528 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
529 xml::add_element($doc, $root, "link", "", $attributes);
533 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
534 ostatus::hublinks($doc, $root, $owner["nick"]);
536 $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
537 xml::add_element($doc, $root, "link", "", $attributes);
539 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
540 xml::add_element($doc, $root, "link", "", $attributes);
542 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
543 xml::add_element($doc, $root, "link", "", $attributes);
546 // For backward compatibility we keep this element
547 if ($owner['page-flags'] == PAGE_COMMUNITY) {
548 xml::add_element($doc, $root, "dfrn:community", 1);
551 // The former element is replaced by this one
552 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
554 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
556 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
558 $author = self::add_author($doc, $owner, $authorelement, $public);
559 $root->appendChild($author);
565 * @brief Adds the author element in the header for the DFRN protocol
567 * @param object $doc XML document
568 * @param array $owner Owner record
569 * @param string $authorelement Element name for the author
571 * @return object XML author object
572 * @todo Add type-hints
574 private static function add_author($doc, $owner, $authorelement, $public) {
576 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
577 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
578 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
579 intval($owner['uid']));
580 if (dbm::is_result($r)) {
586 $author = $doc->createElement($authorelement);
588 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
589 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
590 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
592 $attributes = array();
594 if (!$public || !$hidewall) {
595 $attributes = array("dfrn:updated" => $namdate);
598 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
599 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
600 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
602 $attributes = array("rel" => "photo", "type" => "image/jpeg",
603 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
605 if (!$public || !$hidewall) {
606 $attributes["dfrn:updated"] = $picdate;
609 xml::add_element($doc, $author, "link", "", $attributes);
611 $attributes["rel"] = "avatar";
612 xml::add_element($doc, $author, "link", "", $attributes);
615 xml::add_element($doc, $author, "dfrn:hide", "true");
618 // The following fields will only be generated if the data isn't meant for a public feed
623 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
626 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
628 // Only show contact details when we are allowed to
629 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
630 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
631 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
633 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
634 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
635 intval($owner['uid']));
636 if (dbm::is_result($r)) {
639 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
640 xml::add_element($doc, $author, "poco:updated", $namdate);
642 if (trim($profile["dob"]) > '0001-01-01') {
643 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
646 xml::add_element($doc, $author, "poco:note", $profile["about"]);
647 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
649 $savetz = date_default_timezone_get();
650 date_default_timezone_set($profile["timezone"]);
651 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
652 date_default_timezone_set($savetz);
654 if (trim($profile["homepage"]) != "") {
655 $urls = $doc->createElement("poco:urls");
656 xml::add_element($doc, $urls, "poco:type", "homepage");
657 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
658 xml::add_element($doc, $urls, "poco:primary", "true");
659 $author->appendChild($urls);
662 if (trim($profile["pub_keywords"]) != "") {
663 $keywords = explode(",", $profile["pub_keywords"]);
665 foreach ($keywords AS $keyword) {
666 xml::add_element($doc, $author, "poco:tags", trim($keyword));
671 if (trim($profile["xmpp"]) != "") {
672 $ims = $doc->createElement("poco:ims");
673 xml::add_element($doc, $ims, "poco:type", "xmpp");
674 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
675 xml::add_element($doc, $ims, "poco:primary", "true");
676 $author->appendChild($ims);
679 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
680 $element = $doc->createElement("poco:address");
682 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
684 if (trim($profile["locality"]) != "") {
685 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
688 if (trim($profile["region"]) != "") {
689 xml::add_element($doc, $element, "poco:region", $profile["region"]);
692 if (trim($profile["country-name"]) != "") {
693 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
696 $author->appendChild($element);
704 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
706 * @param object $doc XML document
707 * @param string $element Element name for the author
708 * @param string $contact_url Link of the contact
709 * @param array $items Item elements
711 * @return object XML author object
712 * @todo Add type-hints
714 private static function add_entry_author($doc, $element, $contact_url, $item) {
716 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
718 $author = $doc->createElement($element);
719 xml::add_element($doc, $author, "name", $contact["name"]);
720 xml::add_element($doc, $author, "uri", $contact["url"]);
721 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
724 /// - Check real image type and image size
725 /// - Check which of these boths elements we should use
728 "type" => "image/jpeg",
730 "media:height" => 80,
731 "href" => $contact["photo"]);
732 xml::add_element($doc, $author, "link", "", $attributes);
736 "type" => "image/jpeg",
738 "media:height" => 80,
739 "href" => $contact["photo"]);
740 xml::add_element($doc, $author, "link", "", $attributes);
746 * @brief Adds the activity elements
748 * @param object $doc XML document
749 * @param string $element Element name for the activity
750 * @param string $activity activity value
752 * @return object XML activity object
753 * @todo Add type-hints
755 private static function create_activity($doc, $element, $activity) {
758 $entry = $doc->createElement($element);
760 $r = parse_xml_string($activity, false);
765 xml::add_element($doc, $entry, "activity:object-type", $r->type);
768 xml::add_element($doc, $entry, "id", $r->id);
771 xml::add_element($doc, $entry, "title", $r->title);
775 if (substr($r->link, 0, 1) == '<') {
776 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
777 $r->link = str_replace('&', '&', $r->link);
780 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
782 // XML does need a single element as root element so we add a dummy element here
783 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
784 if (is_object($data)) {
785 foreach ($data->link AS $link) {
786 $attributes = array();
787 foreach ($link->attributes() AS $parameter => $value) {
788 $attributes[$parameter] = $value;
790 xml::add_element($doc, $entry, "link", "", $attributes);
794 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
795 xml::add_element($doc, $entry, "link", "", $attributes);
799 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
809 * @brief Adds the elements for attachments
811 * @param object $doc XML document
812 * @param object $root XML root
813 * @param array $item Item element
815 * @return object XML attachment object
816 * @todo Add type-hints
818 private static function get_attachment($doc, $root, $item) {
819 $arr = explode('[/attach],',$item['attach']);
821 foreach ($arr as $r) {
823 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
825 $attributes = array("rel" => "enclosure",
826 "href" => $matches[1],
827 "type" => $matches[3]);
829 if (intval($matches[2])) {
830 $attributes["length"] = intval($matches[2]);
833 if (trim($matches[4]) != "") {
834 $attributes["title"] = trim($matches[4]);
837 xml::add_element($doc, $root, "link", "", $attributes);
844 * @brief Adds the "entry" elements for the DFRN protocol
846 * @param object $doc XML document
847 * @param string $type "text" or "html"
848 * @param array $item Item element
849 * @param array $owner Owner record
850 * @param bool $comment Trigger the sending of the "comment" element
851 * @param int $cid Contact ID of the recipient
852 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
854 * @return object XML entry object
855 * @todo Add type-hints
857 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) {
859 $mentioned = array();
861 if (!$item['parent']) {
865 if ($item['deleted']) {
866 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
867 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
871 $entry = $doc->createElement("entry");
873 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
874 $doc->appendChild($entry);
876 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
877 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
878 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
879 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
880 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
881 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
882 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
883 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
884 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
887 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
888 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
890 $body = $item['body'];
893 // Remove the abstract element. It is only locally important.
894 $body = remove_abstract($body);
896 if ($type == 'html') {
899 if ($item['title'] != "") {
900 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
903 $htmlbody = bbcode($htmlbody, false, false, 7);
906 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
907 $entry->appendChild($author);
909 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
910 $entry->appendChild($dfrnowner);
912 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
913 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
914 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
915 $attributes = array("ref" => $parent_item, "type" => "text/html",
916 "href" => $parent[0]['plink'],
917 "dfrn:diaspora_guid" => $parent[0]['guid']);
918 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
921 // Add conversation data. This is used for OStatus
922 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
923 $conversation_uri = $conversation_href;
925 if (isset($parent_item)) {
926 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
927 if (dbm::is_result($r)) {
928 if ($r['conversation-uri'] != '') {
929 $conversation_uri = $r['conversation-uri'];
931 if ($r['conversation-href'] != '') {
932 $conversation_href = $r['conversation-href'];
938 "href" => $conversation_href,
939 "ref" => $conversation_uri);
941 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
943 xml::add_element($doc, $entry, "id", $item["uri"]);
944 xml::add_element($doc, $entry, "title", $item["title"]);
946 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
947 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
949 // "dfrn:env" is used to read the content
950 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
952 // The "content" field is not read by the receiver. We could remove it when the type is "text"
953 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
954 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
956 // We save this value in "plink". Maybe we should read it from there as well?
957 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
958 "href" => System::baseUrl()."/display/".$item["guid"]));
960 // "comment-allow" is some old fashioned stuff for old Friendica versions.
961 // It is included in the rewritten code for completeness
963 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
966 if ($item['location']) {
967 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
970 if ($item['coord']) {
971 xml::add_element($doc, $entry, "georss:point", $item['coord']);
974 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
975 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
978 if ($item['extid']) {
979 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
982 if ($item['bookmark']) {
983 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
987 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
990 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
992 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
993 // It is needed for relayed comments to Diaspora.
994 if ($item['signed_text']) {
995 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
996 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
999 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
1001 if ($item['object-type'] != "") {
1002 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1003 } elseif ($item['id'] == $item['parent']) {
1004 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1006 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1009 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1011 $entry->appendChild($actobj);
1014 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1016 $entry->appendChild($actarg);
1019 $tags = item_getfeedtags($item);
1022 foreach ($tags as $t) {
1023 if (($type != 'html') || ($t[0] != "@")) {
1024 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1030 foreach ($tags as $t) {
1032 $mentioned[$t[1]] = $t[1];
1037 foreach ($mentioned AS $mention) {
1038 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1039 intval($owner["uid"]),
1040 dbesc(normalise_link($mention)));
1042 if (dbm::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1043 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1044 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1045 "href" => $mention));
1047 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1048 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1049 "href" => $mention));
1053 self::get_attachment($doc, $entry, $item);
1059 * @brief encrypts data via AES
1061 * @param string $data The data that is to be encrypted
1062 * @param string $key The AES key
1064 * @return string encrypted data
1066 private static function aes_encrypt($data, $key) {
1067 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1071 * @brief decrypts data via AES
1073 * @param string $encrypted The encrypted data
1074 * @param string $key The AES key
1076 * @return string decrypted data
1078 public static function aes_decrypt($encrypted, $key) {
1079 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1083 * @brief Delivers the atom content to the contacts
1085 * @param array $owner Owner record
1086 * @param array $contactr Contact record of the receiver
1087 * @param string $atom Content that will be transmitted
1088 * @param bool $dissolve (to be documented)
1090 * @return int Deliver status. -1 means an error.
1091 * @todo Add array type-hint for $owner, $contact
1093 public static function deliver($owner,$contact,$atom, $dissolve = false) {
1097 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1099 if ($contact['duplex'] && $contact['dfrn-id']) {
1100 $idtosend = '0:' . $orig_id;
1102 if ($contact['duplex'] && $contact['issued-id']) {
1103 $idtosend = '1:' . $orig_id;
1106 $rino = get_config('system', 'rino_encrypt');
1107 $rino = intval($rino);
1109 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1111 $ssl_val = intval(get_config('system','ssl_policy'));
1115 case SSL_POLICY_FULL:
1116 $ssl_policy = 'full';
1118 case SSL_POLICY_SELFSIGN:
1119 $ssl_policy = 'self';
1121 case SSL_POLICY_NONE:
1123 $ssl_policy = 'none';
1127 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1129 logger('dfrn_deliver: ' . $url);
1131 $ret = z_fetch_url($url);
1133 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1134 return -2; // timed out
1137 $xml = $ret['body'];
1139 $curl_stat = $a->get_curl_code();
1141 return -3; // timed out
1144 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1150 if (strpos($xml,'<?xml') === false) {
1151 logger('dfrn_deliver: no valid XML returned');
1152 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1156 $res = parse_xml_string($xml);
1158 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1159 return (($res->status) ? $res->status : 3);
1162 $postvars = array();
1163 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1164 $challenge = hex2bin((string) $res->challenge);
1165 $perm = (($res->perm) ? $res->perm : null);
1166 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1167 $rino_remote_version = intval($res->rino);
1168 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1170 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1172 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1176 $final_dfrn_id = '';
1179 if ((($perm == 'rw') && (! intval($contact['writable'])))
1180 || (($perm == 'r') && (intval($contact['writable'])))) {
1181 q("update contact set writable = %d where id = %d",
1182 intval(($perm == 'rw') ? 1 : 0),
1183 intval($contact['id'])
1185 $contact['writable'] = (string) 1 - intval($contact['writable']);
1189 if (($contact['duplex'] && strlen($contact['pubkey']))
1190 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1191 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1192 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1193 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1195 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1196 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1199 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1201 if (strpos($final_dfrn_id,':') == 1) {
1202 $final_dfrn_id = substr($final_dfrn_id,2);
1205 if ($final_dfrn_id != $orig_id) {
1206 logger('dfrn_deliver: wrong dfrn_id.');
1207 // did not decode properly - cannot trust this site
1211 $postvars['dfrn_id'] = $idtosend;
1212 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1214 $postvars['dissolve'] = '1';
1218 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1219 $postvars['data'] = $atom;
1220 $postvars['perm'] = 'rw';
1222 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1223 $postvars['perm'] = 'r';
1226 $postvars['ssl_policy'] = $ssl_policy;
1229 $postvars['page'] = $page;
1233 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1234 logger('rino version: '. $rino_remote_version);
1236 switch ($rino_remote_version) {
1238 // Deprecated rino version!
1239 $key = openssl_random_pseudo_bytes(16);
1240 $data = self::aes_encrypt($postvars['data'], $key);
1243 // RINO 2 based on php-encryption
1245 $key = Crypto::createNewRandomKey();
1246 } catch (CryptoTestFailed $ex) {
1247 logger('Cannot safely create a key');
1249 } catch (CannotPerformOperation $ex) {
1250 logger('Cannot safely create a key');
1254 $data = Crypto::encrypt($postvars['data'], $key);
1255 } catch (CryptoTestFailed $ex) {
1256 logger('Cannot safely perform encryption');
1258 } catch (CannotPerformOperation $ex) {
1259 logger('Cannot safely perform encryption');
1264 logger("rino: invalid requested verision '$rino_remote_version'");
1268 $postvars['rino'] = $rino_remote_version;
1269 $postvars['data'] = bin2hex($data);
1271 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1274 if ($dfrn_version >= 2.1) {
1275 if (($contact['duplex'] && strlen($contact['pubkey']))
1276 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1277 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1278 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1280 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1284 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1285 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1287 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1292 logger('md5 rawkey ' . md5($postvars['key']));
1294 $postvars['key'] = bin2hex($postvars['key']);
1298 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1300 $xml = post_url($contact['notify'], $postvars);
1302 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1304 $curl_stat = $a->get_curl_code();
1305 if ((!$curl_stat) || (!strlen($xml))) {
1306 return -9; // timed out
1309 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1313 if (strpos($xml,'<?xml') === false) {
1314 logger('dfrn_deliver: phase 2: no valid XML returned');
1315 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1319 if ($contact['term-date'] > NULL_DATE) {
1320 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1321 require_once('include/Contact.php');
1322 unmark_for_death($contact);
1325 $res = parse_xml_string($xml);
1327 if (!isset($res->status)) {
1331 if (!empty($res->message)) {
1332 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1335 return intval($res->status);
1339 * @brief Add new birthday event for this person
1341 * @param array $contact Contact record
1342 * @param string $birthday Birthday of the contact
1343 * @todo Add array type-hint for $contact
1345 private static function birthday_event($contact, $birthday) {
1347 // Check for duplicates
1348 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1349 intval($contact["uid"]),
1350 intval($contact["id"]),
1351 dbesc(datetime_convert("UTC","UTC", $birthday)),
1354 if (dbm::is_result($r)) {
1358 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1360 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1361 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1363 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1364 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1365 intval($contact["uid"]),
1366 intval($contact["id"]),
1367 dbesc(datetime_convert()),
1368 dbesc(datetime_convert()),
1369 dbesc(datetime_convert("UTC","UTC", $birthday)),
1370 dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1378 * @brief Fetch the author data from head or entry items
1380 * @param object $xpath XPath object
1381 * @param object $context In which context should the data be searched
1382 * @param array $importer Record of the importer user mixed with contact of the content
1383 * @param string $element Element name from which the data is fetched
1384 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1386 * @return Returns an array with relevant data of the author
1387 * @todo Find good type-hints for all parameter
1389 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1392 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1393 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1395 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1396 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1397 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1398 intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1400 if (dbm::is_result($r)) {
1402 $author["contact-id"] = $r[0]["id"];
1403 $author["network"] = $r[0]["network"];
1406 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1409 $author["contact-id"] = $importer["id"];
1410 $author["network"] = $importer["network"];
1414 // Until now we aren't serving different sizes - but maybe later
1415 $avatarlist = array();
1416 /// @todo check if "avatar" or "photo" would be the best field in the specification
1417 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1418 foreach ($avatars AS $avatar) {
1421 foreach ($avatar->attributes AS $attributes) {
1422 /// @TODO Rewrite these similar if () to one switch
1423 if ($attributes->name == "href") {
1424 $href = $attributes->textContent;
1426 if ($attributes->name == "width") {
1427 $width = $attributes->textContent;
1429 if ($attributes->name == "updated") {
1430 $contact["avatar-date"] = $attributes->textContent;
1433 if (($width > 0) && ($href != "")) {
1434 $avatarlist[$width] = $href;
1437 if (count($avatarlist) > 0) {
1438 krsort($avatarlist);
1439 $author["avatar"] = current($avatarlist);
1442 if (dbm::is_result($r) && !$onlyfetch) {
1443 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1445 $poco = array("url" => $contact["url"]);
1447 // When was the last change to name or uri?
1448 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1449 foreach ($name_element->attributes AS $attributes) {
1450 if ($attributes->name == "updated") {
1451 $poco["name-date"] = $attributes->textContent;
1455 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1456 foreach ($link_element->attributes AS $attributes) {
1457 if ($attributes->name == "updated") {
1458 $poco["uri-date"] = $attributes->textContent;
1462 // Update contact data
1463 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1465 $poco["addr"] = $value;
1468 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1470 $poco["name"] = $value;
1473 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1475 $poco["nick"] = $value;
1478 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1480 $poco["about"] = $value;
1483 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1485 $poco["location"] = $value;
1488 /// @todo Only search for elements with "poco:type" = "xmpp"
1489 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1491 $poco["xmpp"] = $value;
1494 /// @todo Add support for the following fields that we don't support by now in the contact table:
1495 /// - poco:utcOffset
1501 // If the "hide" element is present then the profile isn't searchable.
1502 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1504 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1506 // If the contact isn't searchable then set the contact to "hidden".
1507 // Problem: This can be manually overridden by the user.
1509 $contact["hidden"] = true;
1512 // Save the keywords into the contact table
1514 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1515 foreach ($tagelements AS $tag) {
1516 $tags[$tag->nodeValue] = $tag->nodeValue;
1520 $poco["keywords"] = implode(", ", $tags);
1523 // "dfrn:birthday" contains the birthday converted to UTC
1524 $old_bdyear = $contact["bdyear"];
1526 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1528 if (strtotime($birthday) > time()) {
1529 $bd_timestamp = strtotime($birthday);
1531 $poco["bdyear"] = date("Y", $bd_timestamp);
1534 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1535 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1537 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1538 $bdyear = date("Y");
1539 $value = str_replace("0000", $bdyear, $value);
1541 if (strtotime($value) < time()) {
1542 $value = str_replace($bdyear, $bdyear + 1, $value);
1543 $bdyear = $bdyear + 1;
1546 $poco["bd"] = $value;
1549 $contact = array_merge($contact, $poco);
1551 if ($old_bdyear != $contact["bdyear"]) {
1552 self::birthday_event($contact, $birthday);
1555 // Get all field names
1557 foreach ($r[0] AS $field => $data) {
1558 $fields[$field] = $data;
1561 unset($fields["id"]);
1562 unset($fields["uid"]);
1563 unset($fields["url"]);
1564 unset($fields["avatar-date"]);
1565 unset($fields["name-date"]);
1566 unset($fields["uri-date"]);
1568 // Update check for this field has to be done differently
1569 $datefields = array("name-date", "uri-date");
1570 foreach ($datefields AS $field) {
1571 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1572 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1577 foreach ($fields AS $field => $data) {
1578 if ($contact[$field] != $r[0][$field]) {
1579 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1585 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1587 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1588 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1589 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1590 WHERE `id` = %d AND `network` = '%s'",
1591 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1592 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1593 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1594 dbesc(dbm::date($contact["name-date"])), dbesc(dbm::date($contact["uri-date"])),
1595 intval($contact["id"]), dbesc($contact["network"]));
1598 update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1599 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1602 * The generation is a sign for the reliability of the provided data.
1603 * It is used in the socgraph.php to prevent that old contact data
1604 * that was relayed over several servers can overwrite contact
1605 * data that we received directly.
1608 $poco["generation"] = 2;
1609 $poco["photo"] = $author["avatar"];
1610 $poco["hide"] = $hide;
1611 $poco["contact-type"] = $contact["contact-type"];
1612 $gcid = update_gcontact($poco);
1614 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1621 * @brief Transforms activity objects into an XML string
1623 * @param object $xpath XPath object
1624 * @param object $activity Activity object
1625 * @param text $element element name
1627 * @return string XML string
1628 * @todo Find good type-hints for all parameter
1630 private static function transform_activity($xpath, $activity, $element) {
1631 if (!is_object($activity)) {
1635 $obj_doc = new DOMDocument("1.0", "utf-8");
1636 $obj_doc->formatOutput = true;
1638 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1640 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1641 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1643 $id = $xpath->query("atom:id", $activity)->item(0);
1644 if (is_object($id)) {
1645 $obj_element->appendChild($obj_doc->importNode($id, true));
1648 $title = $xpath->query("atom:title", $activity)->item(0);
1649 if (is_object($title)) {
1650 $obj_element->appendChild($obj_doc->importNode($title, true));
1653 $links = $xpath->query("atom:link", $activity);
1654 if (is_object($links)) {
1655 foreach ($links AS $link) {
1656 $obj_element->appendChild($obj_doc->importNode($link, true));
1660 $content = $xpath->query("atom:content", $activity)->item(0);
1661 if (is_object($content)) {
1662 $obj_element->appendChild($obj_doc->importNode($content, true));
1665 $obj_doc->appendChild($obj_element);
1667 $objxml = $obj_doc->saveXML($obj_element);
1669 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1670 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1675 * @brief Processes the mail elements
1677 * @param object $xpath XPath object
1678 * @param object $mail mail elements
1679 * @param array $importer Record of the importer user mixed with contact of the content
1680 * @todo Find good type-hints for all parameter
1682 private static function process_mail($xpath, $mail, $importer) {
1684 logger("Processing mails");
1686 /// @TODO Rewrite this to one statement
1688 $msg["uid"] = $importer["importer_uid"];
1689 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1690 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1691 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1692 $msg["contact-id"] = $importer["id"];
1693 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1694 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1695 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1696 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1697 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1699 $msg["replied"] = 0;
1701 dba::insert('mail', $msg);
1703 // send notifications.
1704 /// @TODO Arange this mess
1705 $notif_params = array(
1706 "type" => NOTIFY_MAIL,
1707 "notify_flags" => $importer["notify-flags"],
1708 "language" => $importer["language"],
1709 "to_name" => $importer["username"],
1710 "to_email" => $importer["email"],
1711 "uid" => $importer["importer_uid"],
1713 "source_name" => $msg["from-name"],
1714 "source_link" => $importer["url"],
1715 "source_photo" => $importer["thumb"],
1716 "verb" => ACTIVITY_POST,
1720 notification($notif_params);
1722 logger("Mail is processed, notification was sent.");
1726 * @brief Processes the suggestion elements
1728 * @param object $xpath XPath object
1729 * @param object $suggestion suggestion elements
1730 * @param array $importer Record of the importer user mixed with contact of the content
1731 * @todo Find good type-hints for all parameter
1733 private static function process_suggestion($xpath, $suggestion, $importer) {
1736 logger("Processing suggestions");
1738 /// @TODO Rewrite this to one statement
1740 $suggest["uid"] = $importer["importer_uid"];
1741 $suggest["cid"] = $importer["id"];
1742 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1743 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1744 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1745 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1746 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1748 // Does our member already have a friend matching this description?
1750 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1751 dbesc($suggest["name"]),
1752 dbesc(normalise_link($suggest["url"])),
1753 intval($suggest["uid"])
1757 * The valid result means the friend we're about to send a friend
1758 * suggestion already has them in their contact, which means no further
1759 * action is required.
1761 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1763 if (dbm::is_result($r)) {
1767 // Do we already have an fcontact record for this person?
1770 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1771 dbesc($suggest["url"]),
1772 dbesc($suggest["name"]),
1773 dbesc($suggest["request"])
1775 if (dbm::is_result($r)) {
1778 // OK, we do. Do we already have an introduction for this person ?
1779 $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1780 intval($suggest["uid"]),
1785 * The valid result means the friend we're about to send a friend
1786 * suggestion already has them in their contact, which means no further
1787 * action is required.
1789 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1791 if (dbm::is_result($r)) {
1796 $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1797 dbesc($suggest["name"]),
1798 dbesc($suggest["url"]),
1799 dbesc($suggest["photo"]),
1800 dbesc($suggest["request"])
1803 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1804 dbesc($suggest["url"]),
1805 dbesc($suggest["name"]),
1806 dbesc($suggest["request"])
1810 * If no record in fcontact is found, below INSERT statement will not
1811 * link an introduction to it.
1813 if (!dbm::is_result($r)) {
1814 // database record did not get created. Quietly give up.
1820 $hash = random_string();
1822 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1823 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1824 intval($suggest["uid"]),
1826 intval($suggest["cid"]),
1827 dbesc($suggest["body"]),
1829 dbesc(datetime_convert()),
1834 "type" => NOTIFY_SUGGEST,
1835 "notify_flags" => $importer["notify-flags"],
1836 "language" => $importer["language"],
1837 "to_name" => $importer["username"],
1838 "to_email" => $importer["email"],
1839 "uid" => $importer["importer_uid"],
1841 "link" => System::baseUrl()."/notifications/intros",
1842 "source_name" => $importer["name"],
1843 "source_link" => $importer["url"],
1844 "source_photo" => $importer["photo"],
1845 "verb" => ACTIVITY_REQ_FRIEND,
1854 * @brief Processes the relocation elements
1856 * @param object $xpath XPath object
1857 * @param object $relocation relocation elements
1858 * @param array $importer Record of the importer user mixed with contact of the content
1859 * @todo Find good type-hints for all parameter
1861 private static function process_relocation($xpath, $relocation, $importer) {
1863 logger("Processing relocations");
1865 /// @TODO Rewrite this to one statement
1866 $relocate = array();
1867 $relocate["uid"] = $importer["importer_uid"];
1868 $relocate["cid"] = $importer["id"];
1869 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1870 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1871 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1872 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1873 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1874 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1875 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1876 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1877 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1878 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1879 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1880 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1882 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1883 $relocate["avatar"] = $relocate["photo"];
1886 if ($relocate["addr"] == "") {
1887 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1891 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1892 intval($importer["id"]),
1893 intval($importer["importer_uid"]));
1895 if (!dbm::is_result($r)) {
1896 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1902 // Update the gcontact entry
1903 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1905 $x = q("UPDATE `gcontact` SET
1914 WHERE `nurl` = '%s';",
1915 dbesc($relocate["name"]),
1916 dbesc($relocate["avatar"]),
1917 dbesc($relocate["url"]),
1918 dbesc(normalise_link($relocate["url"])),
1919 dbesc($relocate["addr"]),
1920 dbesc($relocate["addr"]),
1921 dbesc($relocate["notify"]),
1922 dbesc($relocate["server_url"]),
1923 dbesc(normalise_link($old["url"])));
1925 // Update the contact table. We try to find every entry.
1926 $x = q("UPDATE `contact` SET
1936 `site-pubkey` = '%s'
1937 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1938 dbesc($relocate["name"]),
1939 dbesc($relocate["avatar"]),
1940 dbesc($relocate["url"]),
1941 dbesc(normalise_link($relocate["url"])),
1942 dbesc($relocate["addr"]),
1943 dbesc($relocate["request"]),
1944 dbesc($relocate["confirm"]),
1945 dbesc($relocate["notify"]),
1946 dbesc($relocate["poll"]),
1947 dbesc($relocate["sitepubkey"]),
1948 intval($importer["id"]),
1949 intval($importer["importer_uid"]),
1950 dbesc(normalise_link($old["url"])));
1952 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1959 /// @todo This is an extreme performance killer
1961 'owner-link' => array($old["url"], $relocate["url"]),
1962 'author-link' => array($old["url"], $relocate["url"]),
1963 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1964 //'author-avatar' => array($old["photo"], $relocate["photo"]),
1966 foreach ($fields as $n=>$f) {
1967 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1969 intval($importer["importer_uid"]));
1971 if (dbm::is_result($r)) {
1972 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1975 intval($importer["importer_uid"]));
1984 /// merge with current record, current contents have priority
1985 /// update record, set url-updated
1986 /// update profile photos
1987 /// schedule a scan?
1992 * @brief Updates an item
1994 * @param array $current the current item record
1995 * @param array $item the new item record
1996 * @param array $importer Record of the importer user mixed with contact of the content
1997 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
1998 * @todo set proper type-hints (array?)
2000 private static function update_content($current, $item, $importer, $entrytype) {
2003 if (edited_timestamp_is_newer($current, $item)) {
2005 // do not accept (ignore) an earlier edit than one we currently have.
2006 if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2010 $fields = array('title' => $item["title"], 'body' => $item["body"],
2011 'tag' => $item["tag"], 'changed' => datetime_convert(),
2012 'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2014 $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2015 dba::update('item', $fields, $condition);
2017 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2018 update_thread_uri($item["uri"], $importer["importer_uid"]);
2022 if ($entrytype == DFRN_REPLY_RC) {
2023 Worker::add(PRIORITY_HIGH, "notifier","comment-import", $current["id"]);
2027 // update last-child if it changes
2028 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2029 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2030 dbesc(datetime_convert()),
2031 dbesc($item["parent-uri"]),
2032 intval($importer["importer_uid"])
2034 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2035 intval($item["last-child"]),
2036 dbesc(datetime_convert()),
2037 dbesc($item["uri"]),
2038 intval($importer["importer_uid"])
2045 * @brief Detects the entry type of the item
2047 * @param array $importer Record of the importer user mixed with contact of the content
2048 * @param array $item the new item record
2050 * @return int Is it a toplevel entry, a comment or a relayed comment?
2051 * @todo set proper type-hints (array?)
2053 private static function get_entry_type($importer, $item) {
2054 if ($item["parent-uri"] != $item["uri"]) {
2057 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2060 logger("possible community action");
2062 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2065 // was the top-level post for this action written by somebody on this site?
2066 // Specifically, the recipient?
2068 $is_a_remote_action = false;
2070 $r = q("SELECT `item`.`parent-uri` FROM `item`
2071 WHERE `item`.`uri` = '%s'
2073 dbesc($item["parent-uri"])
2075 if (dbm::is_result($r)) {
2076 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2077 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2078 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2079 AND `item`.`uid` = %d
2082 dbesc($r[0]["parent-uri"]),
2083 dbesc($r[0]["parent-uri"]),
2084 dbesc($r[0]["parent-uri"]),
2085 intval($importer["importer_uid"])
2087 if (dbm::is_result($r)) {
2088 $is_a_remote_action = true;
2093 * Does this have the characteristics of a community or private group action?
2094 * If it's an action to a wall post on a community/prvgroup page it's a
2095 * valid community action. Also forum_mode makes it valid for sure.
2096 * If neither, it's not.
2099 /// @TODO Maybe merge these if() blocks into one?
2100 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2101 $is_a_remote_action = false;
2102 logger("not a community action");
2105 if ($is_a_remote_action) {
2106 return DFRN_REPLY_RC;
2111 return DFRN_TOP_LEVEL;
2117 * @brief Send a "poke"
2119 * @param array $item the new item record
2120 * @param array $importer Record of the importer user mixed with contact of the content
2121 * @param int $posted_id The record number of item record that was just posted
2122 * @todo set proper type-hints (array?)
2124 private static function do_poke($item, $importer, $posted_id) {
2125 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2129 $xo = parse_xml_string($item["object"],false);
2131 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2133 // somebody was poked/prodded. Was it me?
2134 foreach ($xo->link as $l) {
2135 $atts = $l->attributes();
2136 switch ($atts["rel"]) {
2138 $Blink = $atts["href"];
2145 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2147 // send a notification
2149 "type" => NOTIFY_POKE,
2150 "notify_flags" => $importer["notify-flags"],
2151 "language" => $importer["language"],
2152 "to_name" => $importer["username"],
2153 "to_email" => $importer["email"],
2154 "uid" => $importer["importer_uid"],
2156 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2157 "source_name" => stripslashes($item["author-name"]),
2158 "source_link" => $item["author-link"],
2159 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2160 ? $importer["thumb"] : $item["author-avatar"]),
2161 "verb" => $item["verb"],
2162 "otype" => "person",
2163 "activity" => $verb,
2164 "parent" => $item["parent"]
2171 * @brief Processes several actions, depending on the verb
2173 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2174 * @param array $importer Record of the importer user mixed with contact of the content
2175 * @param array $item the new item record
2176 * @param bool $is_like Is the verb a "like"?
2178 * @return bool Should the processing of the entries be continued?
2179 * @todo set proper type-hints (array?)
2181 private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2183 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2185 if (($entrytype == DFRN_TOP_LEVEL)) {
2186 // The filling of the the "contact" variable is done for legcy reasons
2187 // The functions below are partly used by ostatus.php as well - where we have this variable
2188 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2190 $nickname = $contact["nick"];
2192 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2193 // This function once was responsible for DFRN and OStatus.
2194 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2195 logger("New follower");
2196 new_follower($importer, $contact, $item, $nickname);
2199 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2200 logger("Lost follower");
2201 lose_follower($importer, $contact, $item);
2204 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2205 logger("New friend request");
2206 new_follower($importer, $contact, $item, $nickname, true);
2209 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2210 logger("Lost sharer");
2211 lose_sharer($importer, $contact, $item);
2215 if (($item["verb"] == ACTIVITY_LIKE)
2216 || ($item["verb"] == ACTIVITY_DISLIKE)
2217 || ($item["verb"] == ACTIVITY_ATTEND)
2218 || ($item["verb"] == ACTIVITY_ATTENDNO)
2219 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2221 $item["type"] = "activity";
2222 $item["gravity"] = GRAVITY_LIKE;
2223 // only one like or dislike per person
2224 // splitted into two queries for performance issues
2225 $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",
2226 intval($item["uid"]),
2227 dbesc($item["author-link"]),
2228 dbesc($item["verb"]),
2229 dbesc($item["parent-uri"])
2231 if (dbm::is_result($r)) {
2235 $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",
2236 intval($item["uid"]),
2237 dbesc($item["author-link"]),
2238 dbesc($item["verb"]),
2239 dbesc($item["parent-uri"])
2241 if (dbm::is_result($r)) {
2248 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2250 $xo = parse_xml_string($item["object"],false);
2251 $xt = parse_xml_string($item["target"],false);
2253 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2254 $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2256 intval($importer["importer_uid"])
2259 if (!dbm::is_result($r)) {
2260 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2264 // extract tag, if not duplicate, add to parent item
2266 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2267 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2268 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2271 create_tags_from_item($r[0]["id"]);
2281 * @brief Processes the link elements
2283 * @param object $links link elements
2284 * @param array $item the item record
2285 * @todo set proper type-hints
2287 private static function parse_links($links, &$item) {
2293 foreach ($links AS $link) {
2294 foreach ($link->attributes AS $attributes) {
2295 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2296 if ($attributes->name == "href") {
2297 $href = $attributes->textContent;
2299 if ($attributes->name == "rel") {
2300 $rel = $attributes->textContent;
2302 if ($attributes->name == "type") {
2303 $type = $attributes->textContent;
2305 if ($attributes->name == "length") {
2306 $length = $attributes->textContent;
2308 if ($attributes->name == "title") {
2309 $title = $attributes->textContent;
2312 if (($rel != "") && ($href != "")) {
2315 $item["plink"] = $href;
2319 if (strlen($item["attach"])) {
2320 $item["attach"] .= ",";
2323 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2331 * @brief Processes the entry elements which contain the items and comments
2333 * @param array $header Array of the header elements that always stay the same
2334 * @param object $xpath XPath object
2335 * @param object $entry entry elements
2336 * @param array $importer Record of the importer user mixed with contact of the content
2337 * @todo Add type-hints
2339 private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2341 logger("Processing entries");
2345 $item["protocol"] = PROTOCOL_DFRN;
2347 $item["source"] = $xml;
2350 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2352 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2354 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2355 dbesc($item["uri"]),
2356 intval($importer["importer_uid"])
2359 // Is there an existing item?
2360 if (dbm::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2361 (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2362 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2367 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2369 $item["owner-name"] = $owner["name"];
2370 $item["owner-link"] = $owner["link"];
2371 $item["owner-avatar"] = $owner["avatar"];
2374 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2376 $item["author-name"] = $author["name"];
2377 $item["author-link"] = $author["link"];
2378 $item["author-avatar"] = $author["avatar"];
2380 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2382 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2384 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2385 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2386 // make sure nobody is trying to sneak some html tags by us
2387 $item["body"] = notags(base64url_decode($item["body"]));
2389 $item["body"] = limit_body_size($item["body"]);
2391 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2392 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2394 $item['body'] = reltoabs($item['body'],$base_url);
2396 $item['body'] = html2bb_video($item['body']);
2398 $item['body'] = oembed_html2bbcode($item['body']);
2400 $config = HTMLPurifier_Config::createDefault();
2401 $config->set('Cache.DefinitionImpl', null);
2403 // we shouldn't need a whitelist, because the bbcode converter
2404 // will strip out any unsupported tags.
2406 $purifier = new HTMLPurifier($config);
2407 $item['body'] = $purifier->purify($item['body']);
2409 $item['body'] = @html2bbcode($item['body']);
2412 /// @todo We should check for a repeated post and if we know the repeated author.
2414 // We don't need the content element since "dfrn:env" is always present
2415 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2417 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2418 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2420 $georsspoint = $xpath->query("georss:point", $entry);
2422 $item["coord"] = $georsspoint->item(0)->nodeValue;
2425 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2427 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2429 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2430 $item["bookmark"] = true;
2433 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2434 if ($notice_info && ($notice_info->length > 0)) {
2435 foreach ($notice_info->item(0)->attributes AS $attributes) {
2436 if ($attributes->name == "source") {
2437 $item["app"] = strip_tags($attributes->textContent);
2442 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2444 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2445 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2446 if ($dsprsig != "") {
2447 $item["dsprsig"] = $dsprsig;
2450 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2452 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2453 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2456 $object = $xpath->query("activity:object", $entry)->item(0);
2457 $item["object"] = self::transform_activity($xpath, $object, "object");
2459 if (trim($item["object"]) != "") {
2460 $r = parse_xml_string($item["object"], false);
2461 if (isset($r->type)) {
2462 $item["object-type"] = $r->type;
2466 $target = $xpath->query("activity:target", $entry)->item(0);
2467 $item["target"] = self::transform_activity($xpath, $target, "target");
2469 $categories = $xpath->query("atom:category", $entry);
2471 foreach ($categories AS $category) {
2474 foreach ($category->attributes AS $attributes) {
2475 if ($attributes->name == "term") {
2476 $term = $attributes->textContent;
2479 if ($attributes->name == "scheme") {
2480 $scheme = $attributes->textContent;
2484 if (($term != "") && ($scheme != "")) {
2485 $parts = explode(":", $scheme);
2486 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2487 $termhash = array_shift($parts);
2488 $termurl = implode(":", $parts);
2490 if (strlen($item["tag"])) {
2491 $item["tag"] .= ",";
2494 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2502 $links = $xpath->query("atom:link", $entry);
2504 self::parse_links($links, $item);
2507 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2509 $conv = $xpath->query('ostatus:conversation', $entry);
2510 if (is_object($conv->item(0))) {
2511 foreach ($conv->item(0)->attributes AS $attributes) {
2512 if ($attributes->name == "ref") {
2513 $item['conversation-uri'] = $attributes->textContent;
2515 if ($attributes->name == "href") {
2516 $item['conversation-href'] = $attributes->textContent;
2521 // Is it a reply or a top level posting?
2522 $item["parent-uri"] = $item["uri"];
2524 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2525 if (is_object($inreplyto->item(0))) {
2526 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2527 if ($attributes->name == "ref") {
2528 $item["parent-uri"] = $attributes->textContent;
2533 // Get the type of the item (Top level post, reply or remote reply)
2534 $entrytype = self::get_entry_type($importer, $item);
2536 // Now assign the rest of the values that depend on the type of the message
2537 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2538 if (!isset($item["object-type"])) {
2539 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2542 if ($item["contact-id"] != $owner["contact-id"]) {
2543 $item["contact-id"] = $owner["contact-id"];
2546 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2547 $item["network"] = $owner["network"];
2550 if ($item["contact-id"] != $author["contact-id"]) {
2551 $item["contact-id"] = $author["contact-id"];
2554 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2555 $item["network"] = $author["network"];
2558 /// @TODO maybe remove this old-lost code then?
2559 // This code was taken from the old DFRN code
2560 // When activated, forums don't work.
2561 // And: Why should we disallow commenting by followers?
2562 // the behaviour is now similar to the Diaspora part.
2563 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2564 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2569 if ($entrytype == DFRN_REPLY_RC) {
2570 $item["type"] = "remote-comment";
2572 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2573 if (!isset($item["object-type"])) {
2574 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2578 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2579 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2580 $ev = bbtoevent($item["body"]);
2581 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2582 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2583 /// @TODO Mixure of "/' ahead ...
2584 $ev["cid"] = $importer["id"];
2585 $ev["uid"] = $importer["uid"];
2586 $ev["uri"] = $item["uri"];
2587 $ev["edited"] = $item["edited"];
2588 $ev['private'] = $item['private'];
2589 $ev["guid"] = $item["guid"];
2591 $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2592 dbesc($item["uri"]),
2593 intval($importer["uid"])
2595 if (dbm::is_result($r)) {
2596 $ev["id"] = $r[0]["id"];
2599 $event_id = event_store($ev);
2600 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2606 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2607 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2611 // Update content if 'updated' changes
2612 if (dbm::is_result($current)) {
2613 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2614 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2616 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2621 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2622 $posted_id = item_store($item);
2627 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2629 $item["id"] = $posted_id;
2631 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2633 intval($importer["importer_uid"])
2635 if (dbm::is_result($r)) {
2636 $parent = $r[0]["parent"];
2637 $parent_uri = $r[0]["parent-uri"];
2641 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2642 dbesc(datetime_convert()),
2643 intval($importer["importer_uid"]),
2644 intval($r[0]["parent"])
2647 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2648 dbesc(datetime_convert()),
2649 intval($importer["importer_uid"]),
2654 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2655 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2656 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $posted_id);
2661 } else { // $entrytype == DFRN_TOP_LEVEL
2662 if (!link_compare($item["owner-link"],$importer["url"])) {
2664 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2665 * but otherwise there's a possible data mixup on the sender's system.
2666 * the tgroup delivery code called from item_store will correct it if it's a forum,
2667 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2669 logger('Correcting item owner.', LOGGER_DEBUG);
2670 $item["owner-name"] = $importer["senderName"];
2671 $item["owner-link"] = $importer["url"];
2672 $item["owner-avatar"] = $importer["thumb"];
2675 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2676 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2680 // This is my contact on another system, but it's really me.
2681 // Turn this into a wall post.
2682 $notify = item_is_remote_self($importer, $item);
2684 $posted_id = item_store($item, false, $notify);
2686 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2688 if (stristr($item["verb"],ACTIVITY_POKE))
2689 self::do_poke($item, $importer, $posted_id);
2694 * @brief Deletes items
2696 * @param object $xpath XPath object
2697 * @param object $deletion deletion elements
2698 * @param array $importer Record of the importer user mixed with contact of the content
2699 * @todo set proper type-hints
2701 private static function process_deletion($xpath, $deletion, $importer) {
2703 logger("Processing deletions");
2705 foreach ($deletion->attributes AS $attributes) {
2706 if ($attributes->name == "ref") {
2707 $uri = $attributes->textContent;
2709 if ($attributes->name == "when") {
2710 $when = $attributes->textContent;
2714 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2716 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2719 if (!$uri || !$importer["id"]) {
2723 /// @todo Only select the used fields
2724 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2725 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2727 intval($importer["uid"]),
2728 intval($importer["id"])
2730 if (!dbm::is_result($r)) {
2731 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2737 $entrytype = self::get_entry_type($importer, $item);
2739 if (!$item["deleted"]) {
2740 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2745 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2746 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2747 event_delete($item["event-id"]);
2750 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2752 $xo = parse_xml_string($item["object"],false);
2753 $xt = parse_xml_string($item["target"],false);
2755 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2756 $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2758 intval($importer["importer_uid"])
2760 if (dbm::is_result($i)) {
2762 // For tags, the owner cannot remove the tag on the author's copy of the post.
2764 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2765 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2766 $author_copy = (($item["origin"]) ? true : false);
2768 if ($owner_remove && $author_copy) {
2771 if ($author_remove || $owner_remove) {
2772 $tags = explode(',',$i[0]["tag"]);
2775 foreach ($tags as $tag) {
2776 if (trim($tag) !== trim($xo->body)) {
2777 $newtags[] = trim($tag);
2781 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2782 dbesc(implode(',', $newtags)),
2785 create_tags_from_item($i[0]["id"]);
2791 if ($entrytype == DFRN_TOP_LEVEL) {
2792 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2793 `body` = '', `title` = ''
2794 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2796 dbesc(datetime_convert()),
2798 intval($importer["uid"])
2800 create_tags_from_itemuri($uri, $importer["uid"]);
2801 create_files_from_itemuri($uri, $importer["uid"]);
2802 update_thread_uri($uri, $importer["uid"]);
2804 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2805 `body` = '', `title` = ''
2806 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2808 dbesc(datetime_convert()),
2810 intval($importer["uid"])
2812 create_tags_from_itemuri($uri, $importer["uid"]);
2813 create_files_from_itemuri($uri, $importer["uid"]);
2814 update_thread_uri($uri, $importer["importer_uid"]);
2815 if ($item["last-child"]) {
2816 // ensure that last-child is set in case the comment that had it just got wiped.
2817 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2818 dbesc(datetime_convert()),
2819 dbesc($item["parent-uri"]),
2820 intval($item["uid"])
2822 // who is the last child now?
2823 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2824 ORDER BY `created` DESC LIMIT 1",
2825 dbesc($item["parent-uri"]),
2826 intval($importer["uid"])
2828 if (dbm::is_result($r)) {
2829 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2834 // if this is a relayed delete, propagate it to other recipients
2836 if ($entrytype == DFRN_REPLY_RC) {
2837 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2838 Worker::add(PRIORITY_HIGH, "notifier","drop", $item["id"]);
2845 * @brief Imports a DFRN message
2847 * @param text $xml The DFRN message
2848 * @param array $importer Record of the importer user mixed with contact of the content
2849 * @param bool $sort_by_date Is used when feeds are polled
2850 * @return integer Import status
2851 * @todo set proper type-hints
2853 public static function import($xml, $importer, $sort_by_date = false) {
2859 $doc = new DOMDocument();
2860 @$doc->loadXML($xml);
2862 $xpath = new DomXPath($doc);
2863 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2864 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2865 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2866 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2867 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2868 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2869 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2870 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2871 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2872 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2875 $header["uid"] = $importer["uid"];
2876 $header["network"] = NETWORK_DFRN;
2877 $header["type"] = "remote";
2878 $header["wall"] = 0;
2879 $header["origin"] = 0;
2880 $header["contact-id"] = $importer["id"];
2882 // Update the contact table if the data has changed
2884 // The "atom:author" is only present in feeds
2885 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2886 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2889 // Only the "dfrn:owner" in the head section contains all data
2890 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2891 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2894 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2896 // The account type is new since 3.5.1
2897 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2898 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2900 if ($accounttype != $importer["contact-type"]) {
2901 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2905 // is it a public forum? Private forums aren't supported with this method
2906 // This is deprecated since 3.5.1
2907 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2909 if ($forum != $importer["forum"]) {
2910 $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2911 dba::update('contact', array('forum' => $forum), $condition);
2914 // We are processing relocations even if we are ignoring a contact
2915 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2916 foreach ($relocations AS $relocation) {
2917 self::process_relocation($xpath, $relocation, $importer);
2920 if ($importer["readonly"]) {
2921 // We aren't receiving stuff from this person. But we will quietly ignore them
2922 // rather than a blatant "go away" message.
2923 logger('ignoring contact '.$importer["id"]);
2927 $mails = $xpath->query("/atom:feed/dfrn:mail");
2928 foreach ($mails AS $mail) {
2929 self::process_mail($xpath, $mail, $importer);
2932 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2933 foreach ($suggestions AS $suggestion) {
2934 self::process_suggestion($xpath, $suggestion, $importer);
2937 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2938 foreach ($deletions AS $deletion) {
2939 self::process_deletion($xpath, $deletion, $importer);
2942 if (!$sort_by_date) {
2943 $entries = $xpath->query("/atom:feed/atom:entry");
2944 foreach ($entries AS $entry) {
2945 self::process_entry($header, $xpath, $entry, $importer, $xml);
2948 $newentries = array();
2949 $entries = $xpath->query("/atom:feed/atom:entry");
2950 foreach ($entries AS $entry) {
2951 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2952 $newentries[strtotime($created)] = $entry;
2955 // Now sort after the publishing date
2958 foreach ($newentries AS $entry) {
2959 self::process_entry($header, $xpath, $entry, $importer, $xml);
2962 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);