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
9 namespace Friendica\Protocol;
12 use Friendica\Core\Config;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
23 require_once "include/Contact.php";
24 require_once "include/enotify.php";
25 require_once "include/threads.php";
26 require_once "include/socgraph.php";
27 require_once "include/items.php";
28 require_once "include/tags.php";
29 require_once "include/files.php";
30 require_once "include/event.php";
31 require_once "include/text.php";
32 require_once "include/oembed.php";
33 require_once "include/html2bbcode.php";
34 require_once "include/bbcode.php";
37 * @brief This class contain functions to create and send DFRN XML files
42 const DFRN_TOP_LEVEL = 0; // Top level posting
43 const DFRN_REPLY = 1; // Regular reply that is stored locally
44 const DFRN_REPLY_RC = 2; // Reply that will be relayed
47 * @brief Generates the atom entries for delivery.php
49 * This function is used whenever content is transmitted via DFRN.
51 * @param array $items Item elements
52 * @param array $owner Owner record
54 * @return string DFRN entries
55 * @todo Add type-hints
57 public static function entries($items, $owner)
59 $doc = new DOMDocument('1.0', 'utf-8');
60 $doc->formatOutput = true;
62 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
64 if (! count($items)) {
65 return trim($doc->saveXML());
68 foreach ($items as $item) {
69 $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
70 $root->appendChild($entry);
73 return(trim($doc->saveXML()));
77 * @brief Generate an atom feed for the given user
79 * This function is called when another server is pulling data from the user feed.
81 * @param string $dfrn_id DFRN ID from the requesting party
82 * @param string $owner_nick Owner nick name
83 * @param string $last_update Date of the last update
84 * @param int $direction Can be -1, 0 or 1.
85 * @param boolean $onlyheader Output only the header without content? (Default is "no")
87 * @return string DFRN feed entries
89 public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
93 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
94 $public_feed = (($dfrn_id) ? false : true);
95 $starred = false; // not yet implemented, possible security issues
98 if ($public_feed && $a->argc > 2) {
99 for ($x = 2; $x < $a->argc; $x++) {
100 if ($a->argv[$x] == 'converse') {
103 if ($a->argv[$x] == 'starred') {
106 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
107 $category = $a->argv[$x+1];
114 // default permissions - anonymous user
116 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
119 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
120 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
121 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
125 if (! DBM::is_result($r)) {
130 $owner_id = $owner['uid'];
131 $owner_nick = $owner['nickname'];
133 $sql_post_table = "";
135 if (! $public_feed) {
137 switch ($direction) {
139 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
143 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
144 $my_id = '1:' . $dfrn_id;
147 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
148 $my_id = '0:' . $dfrn_id;
156 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
160 if (! DBM::is_result($r)) {
165 include_once 'include/security.php';
166 $groups = init_groups_visitor($contact['id']);
168 if (count($groups)) {
169 for ($x = 0; $x < count($groups); $x ++)
170 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
171 $gs = implode('|', $groups);
173 $gs = '<<>>' ; // Impossible to match
176 $sql_extra = sprintf(
178 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
179 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
180 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
181 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
183 intval($contact['id']),
184 intval($contact['id']),
196 if (! strlen($last_update)) {
197 $last_update = 'now -30 days';
200 if (isset($category)) {
201 $sql_post_table = sprintf(
202 "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` ",
203 dbesc(protect_sprintf($category)),
204 intval(TERM_OBJ_POST),
205 intval(TERM_CATEGORY),
208 //$sql_extra .= file_tag_file_query('item',$category,'category');
213 $sql_extra .= " AND `contact`.`self` = 1 ";
217 $check_date = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
220 "SELECT `item`.*, `item`.`id` AS `item_id`,
221 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
222 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
223 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
224 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
225 FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
226 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
227 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
228 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
229 WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
230 AND `item`.`wall` AND `item`.`changed` > '%s'
232 ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
239 * Will check further below if this actually returned results.
240 * We will provide an empty feed if that is the case.
245 $doc = new DOMDocument('1.0', 'utf-8');
246 $doc->formatOutput = true;
248 $alternatelink = $owner['url'];
250 if (isset($category)) {
251 $alternatelink .= "/category/".$category;
255 $author = "dfrn:owner";
260 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
262 /// @TODO This hook can't work anymore
263 // call_hooks('atom_feed', $atom);
265 if (!DBM::is_result($items) || $onlyheader) {
266 $atom = trim($doc->saveXML());
268 call_hooks('atom_feed_end', $atom);
273 foreach ($items as $item) {
274 // prevent private email from leaking.
275 if ($item['network'] == NETWORK_MAIL) {
279 // public feeds get html, our own nodes use bbcode
283 // catch any email that's in a public conversation and make sure it doesn't leak
284 if ($item['private']) {
291 $entry = self::entry($doc, $type, $item, $owner, true);
292 $root->appendChild($entry);
295 $atom = trim($doc->saveXML());
297 call_hooks('atom_feed_end', $atom);
303 * @brief Generate an atom entry for a given item id
305 * @param int $item_id The item id
306 * @param boolean $conversation Show the conversation. If false show the single post.
308 * @return string DFRN feed entry
310 public static function itemFeed($item_id, $conversation = false)
313 $condition = '`item`.`parent`';
315 $condition = '`item`.`id`';
319 "SELECT `item`.*, `item`.`id` AS `item_id`,
320 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
321 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
322 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
323 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
325 STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
326 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
327 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
328 WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
329 AND NOT `item`.`private`",
334 if (!DBM::is_result($r)) {
342 "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
343 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
344 WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
348 if (!DBM::is_result($r)) {
354 $doc = new DOMDocument('1.0', 'utf-8');
355 $doc->formatOutput = true;
359 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
360 $doc->appendChild($root);
362 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
363 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
364 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
365 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
366 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
367 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
368 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
369 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
370 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
372 //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
374 foreach ($items as $item) {
375 $entry = self::entry($doc, $type, $item, $owner, true, 0);
376 $root->appendChild($entry);
379 $root = self::entry($doc, $type, $item, $owner, true, 0, true);
382 $atom = trim($doc->saveXML());
387 * @brief Create XML text for DFRN mails
389 * @param array $item message elements
390 * @param array $owner Owner record
392 * @return string DFRN mail
393 * @todo Add type-hints
395 public static function mail($item, $owner)
397 $doc = new DOMDocument('1.0', 'utf-8');
398 $doc->formatOutput = true;
400 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
402 $mail = $doc->createElement("dfrn:mail");
403 $sender = $doc->createElement("dfrn:sender");
405 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
406 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
407 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
409 $mail->appendChild($sender);
411 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
412 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
413 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
414 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
415 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
417 $root->appendChild($mail);
419 return(trim($doc->saveXML()));
423 * @brief Create XML text for DFRN friend suggestions
425 * @param array $item suggestion elements
426 * @param array $owner Owner record
428 * @return string DFRN suggestions
429 * @todo Add type-hints
431 public static function fsuggest($item, $owner)
433 $doc = new DOMDocument('1.0', 'utf-8');
434 $doc->formatOutput = true;
436 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
438 $suggest = $doc->createElement("dfrn:suggest");
440 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
441 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
442 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
443 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
444 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
446 $root->appendChild($suggest);
448 return(trim($doc->saveXML()));
452 * @brief Create XML text for DFRN relocations
454 * @param array $owner Owner record
455 * @param int $uid User ID
457 * @return string DFRN relocations
458 * @todo Add type-hints
460 public static function relocate($owner, $uid)
463 /* get site pubkey. this could be a new installation with no site keys*/
464 $pubkey = Config::get('system', 'site_pubkey');
466 $res = new_keypair(1024);
467 Config::set('system', 'site_prvkey', $res['prvkey']);
468 Config::set('system', 'site_pubkey', $res['pubkey']);
472 "SELECT `resource-id` , `scale`, type FROM `photo`
473 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
477 $ext = Photo::supportedTypes();
479 foreach ($rp as $p) {
480 $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
485 $doc = new DOMDocument('1.0', 'utf-8');
486 $doc->formatOutput = true;
488 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
490 $relocate = $doc->createElement("dfrn:relocate");
492 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
493 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
494 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
495 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
496 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
497 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
498 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
499 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
500 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
501 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
502 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
503 xml::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey'));
505 $root->appendChild($relocate);
507 return(trim($doc->saveXML()));
511 * @brief Adds the header elements for the DFRN protocol
513 * @param object $doc XML document
514 * @param array $owner Owner record
515 * @param string $authorelement Element name for the author
516 * @param string $alternatelink link to profile or category
517 * @param bool $public Is it a header for public posts?
519 * @return object XML root object
520 * @todo Add type-hints
522 private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false)
525 if ($alternatelink == "") {
526 $alternatelink = $owner['url'];
529 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
530 $doc->appendChild($root);
532 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
533 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
534 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
535 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
536 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
537 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
538 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
539 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
540 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
542 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
543 xml::add_element($doc, $root, "title", $owner["name"]);
545 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
546 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
548 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
549 xml::add_element($doc, $root, "link", "", $attributes);
551 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
552 xml::add_element($doc, $root, "link", "", $attributes);
556 // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
557 ostatus::hublinks($doc, $root, $owner["nick"]);
559 $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
560 xml::add_element($doc, $root, "link", "", $attributes);
562 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
563 xml::add_element($doc, $root, "link", "", $attributes);
565 $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
566 xml::add_element($doc, $root, "link", "", $attributes);
569 // For backward compatibility we keep this element
570 if ($owner['page-flags'] == PAGE_COMMUNITY) {
571 xml::add_element($doc, $root, "dfrn:community", 1);
574 // The former element is replaced by this one
575 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
577 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
579 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
581 $author = self::add_author($doc, $owner, $authorelement, $public);
582 $root->appendChild($author);
588 * @brief Adds the author element in the header for the DFRN protocol
590 * @param object $doc XML document
591 * @param array $owner Owner record
592 * @param string $authorelement Element name for the author
594 * @return object XML author object
595 * @todo Add type-hints
597 private static function add_author($doc, $owner, $authorelement, $public)
599 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
601 "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
602 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
603 intval($owner['uid'])
605 if (DBM::is_result($r)) {
611 $author = $doc->createElement($authorelement);
613 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
614 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
615 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
617 $attributes = array();
619 if (!$public || !$hidewall) {
620 $attributes = array("dfrn:updated" => $namdate);
623 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
624 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
625 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
627 $attributes = array("rel" => "photo", "type" => "image/jpeg",
628 "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
630 if (!$public || !$hidewall) {
631 $attributes["dfrn:updated"] = $picdate;
634 xml::add_element($doc, $author, "link", "", $attributes);
636 $attributes["rel"] = "avatar";
637 xml::add_element($doc, $author, "link", "", $attributes);
640 xml::add_element($doc, $author, "dfrn:hide", "true");
643 // The following fields will only be generated if the data isn't meant for a public feed
648 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
651 xml::add_element($doc, $author, "dfrn:birthday", $birthday);
654 // Only show contact details when we are allowed to
656 "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
657 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
658 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
660 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
661 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
662 intval($owner['uid'])
664 if (DBM::is_result($r)) {
667 xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
668 xml::add_element($doc, $author, "poco:updated", $namdate);
670 if (trim($profile["dob"]) > '0001-01-01') {
671 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
674 xml::add_element($doc, $author, "poco:note", $profile["about"]);
675 xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
677 $savetz = date_default_timezone_get();
678 date_default_timezone_set($profile["timezone"]);
679 xml::add_element($doc, $author, "poco:utcOffset", date("P"));
680 date_default_timezone_set($savetz);
682 if (trim($profile["homepage"]) != "") {
683 $urls = $doc->createElement("poco:urls");
684 xml::add_element($doc, $urls, "poco:type", "homepage");
685 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
686 xml::add_element($doc, $urls, "poco:primary", "true");
687 $author->appendChild($urls);
690 if (trim($profile["pub_keywords"]) != "") {
691 $keywords = explode(",", $profile["pub_keywords"]);
693 foreach ($keywords AS $keyword) {
694 xml::add_element($doc, $author, "poco:tags", trim($keyword));
698 if (trim($profile["xmpp"]) != "") {
699 $ims = $doc->createElement("poco:ims");
700 xml::add_element($doc, $ims, "poco:type", "xmpp");
701 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
702 xml::add_element($doc, $ims, "poco:primary", "true");
703 $author->appendChild($ims);
706 if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
707 $element = $doc->createElement("poco:address");
709 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
711 if (trim($profile["locality"]) != "") {
712 xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
715 if (trim($profile["region"]) != "") {
716 xml::add_element($doc, $element, "poco:region", $profile["region"]);
719 if (trim($profile["country-name"]) != "") {
720 xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
723 $author->appendChild($element);
731 * @brief Adds the author elements in the "entry" elements of the DFRN protocol
733 * @param object $doc XML document
734 * @param string $element Element name for the author
735 * @param string $contact_url Link of the contact
736 * @param array $item Item elements
738 * @return object XML author object
739 * @todo Add type-hints
741 private static function add_entry_author($doc, $element, $contact_url, $item)
744 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
746 $author = $doc->createElement($element);
747 xml::add_element($doc, $author, "name", $contact["name"]);
748 xml::add_element($doc, $author, "uri", $contact["url"]);
749 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
752 /// - Check real image type and image size
753 /// - Check which of these boths elements we should use
756 "type" => "image/jpeg",
758 "media:height" => 80,
759 "href" => $contact["photo"]);
760 xml::add_element($doc, $author, "link", "", $attributes);
764 "type" => "image/jpeg",
766 "media:height" => 80,
767 "href" => $contact["photo"]);
768 xml::add_element($doc, $author, "link", "", $attributes);
774 * @brief Adds the activity elements
776 * @param object $doc XML document
777 * @param string $element Element name for the activity
778 * @param string $activity activity value
780 * @return object XML activity object
781 * @todo Add type-hints
783 private static function create_activity($doc, $element, $activity)
786 $entry = $doc->createElement($element);
788 $r = parse_xml_string($activity, false);
793 xml::add_element($doc, $entry, "activity:object-type", $r->type);
796 xml::add_element($doc, $entry, "id", $r->id);
799 xml::add_element($doc, $entry, "title", $r->title);
803 if (substr($r->link, 0, 1) == '<') {
804 if (strstr($r->link, '&') && (! strstr($r->link, '&'))) {
805 $r->link = str_replace('&', '&', $r->link);
808 $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
810 // XML does need a single element as root element so we add a dummy element here
811 $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
812 if (is_object($data)) {
813 foreach ($data->link AS $link) {
814 $attributes = array();
815 foreach ($link->attributes() AS $parameter => $value) {
816 $attributes[$parameter] = $value;
818 xml::add_element($doc, $entry, "link", "", $attributes);
822 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
823 xml::add_element($doc, $entry, "link", "", $attributes);
827 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
837 * @brief Adds the elements for attachments
839 * @param object $doc XML document
840 * @param object $root XML root
841 * @param array $item Item element
843 * @return object XML attachment object
844 * @todo Add type-hints
846 private static function get_attachment($doc, $root, $item)
848 $arr = explode('[/attach],', $item['attach']);
850 foreach ($arr as $r) {
852 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
854 $attributes = array("rel" => "enclosure",
855 "href" => $matches[1],
856 "type" => $matches[3]);
858 if (intval($matches[2])) {
859 $attributes["length"] = intval($matches[2]);
862 if (trim($matches[4]) != "") {
863 $attributes["title"] = trim($matches[4]);
866 xml::add_element($doc, $root, "link", "", $attributes);
873 * @brief Adds the "entry" elements for the DFRN protocol
875 * @param object $doc XML document
876 * @param string $type "text" or "html"
877 * @param array $item Item element
878 * @param array $owner Owner record
879 * @param bool $comment Trigger the sending of the "comment" element
880 * @param int $cid Contact ID of the recipient
881 * @param bool $single If set, the entry is created as an XML document with a single "entry" element
883 * @return object XML entry object
884 * @todo Add type-hints
886 private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false)
888 $mentioned = array();
890 if (!$item['parent']) {
894 if ($item['deleted']) {
895 $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME));
896 return xml::create_element($doc, "at:deleted-entry", "", $attributes);
900 $entry = $doc->createElement("entry");
902 $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
903 $doc->appendChild($entry);
905 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
906 $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
907 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
908 $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
909 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
910 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
911 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
912 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
913 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
916 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
917 $body = fix_private_photos($item['body'], $owner['uid'], $item, $cid);
919 $body = $item['body'];
922 // Remove the abstract element. It is only locally important.
923 $body = remove_abstract($body);
925 if ($type == 'html') {
928 if ($item['title'] != "") {
929 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
932 $htmlbody = bbcode($htmlbody, false, false, 7);
935 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
936 $entry->appendChild($author);
938 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
939 $entry->appendChild($dfrnowner);
941 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
942 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
943 $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
944 $attributes = array("ref" => $parent_item, "type" => "text/html",
945 "href" => $parent[0]['plink'],
946 "dfrn:diaspora_guid" => $parent[0]['guid']);
947 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
950 // Add conversation data. This is used for OStatus
951 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
952 $conversation_uri = $conversation_href;
954 if (isset($parent_item)) {
955 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
956 if (DBM::is_result($r)) {
957 if ($r['conversation-uri'] != '') {
958 $conversation_uri = $r['conversation-uri'];
960 if ($r['conversation-href'] != '') {
961 $conversation_href = $r['conversation-href'];
967 "href" => $conversation_href,
968 "ref" => $conversation_uri);
970 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
972 xml::add_element($doc, $entry, "id", $item["uri"]);
973 xml::add_element($doc, $entry, "title", $item["title"]);
975 xml::add_element($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
976 xml::add_element($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME));
978 // "dfrn:env" is used to read the content
979 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
981 // The "content" field is not read by the receiver. We could remove it when the type is "text"
982 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
983 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
985 // We save this value in "plink". Maybe we should read it from there as well?
991 array("rel" => "alternate", "type" => "text/html",
992 "href" => System::baseUrl() . "/display/" . $item["guid"])
995 // "comment-allow" is some old fashioned stuff for old Friendica versions.
996 // It is included in the rewritten code for completeness
998 xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
1001 if ($item['location']) {
1002 xml::add_element($doc, $entry, "dfrn:location", $item['location']);
1005 if ($item['coord']) {
1006 xml::add_element($doc, $entry, "georss:point", $item['coord']);
1009 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1010 xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1013 if ($item['extid']) {
1014 xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
1017 if ($item['bookmark']) {
1018 xml::add_element($doc, $entry, "dfrn:bookmark", "true");
1022 xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
1025 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1027 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1028 // It is needed for relayed comments to Diaspora.
1029 if ($item['signed_text']) {
1030 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
1031 xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
1034 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
1036 if ($item['object-type'] != "") {
1037 xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1038 } elseif ($item['id'] == $item['parent']) {
1039 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1041 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1044 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1046 $entry->appendChild($actobj);
1049 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1051 $entry->appendChild($actarg);
1054 $tags = item_getfeedtags($item);
1057 foreach ($tags as $t) {
1058 if (($type != 'html') || ($t[0] != "@")) {
1059 xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1065 foreach ($tags as $t) {
1067 $mentioned[$t[1]] = $t[1];
1072 foreach ($mentioned AS $mention) {
1074 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1075 intval($owner["uid"]),
1076 dbesc(normalise_link($mention))
1079 if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1085 array("rel" => "mentioned",
1086 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1095 array("rel" => "mentioned",
1096 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1102 self::get_attachment($doc, $entry, $item);
1108 * @brief encrypts data via AES
1110 * @param string $data The data that is to be encrypted
1111 * @param string $key The AES key
1113 * @return string encrypted data
1115 private static function aes_encrypt($data, $key)
1117 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1121 * @brief decrypts data via AES
1123 * @param string $encrypted The encrypted data
1124 * @param string $key The AES key
1126 * @return string decrypted data
1128 public static function aes_decrypt($encrypted, $key)
1130 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1134 * @brief Delivers the atom content to the contacts
1136 * @param array $owner Owner record
1137 * @param array $contact Contact record of the receiver
1138 * @param string $atom Content that will be transmitted
1139 * @param bool $dissolve (to be documented)
1141 * @return int Deliver status. -1 means an error.
1142 * @todo Add array type-hint for $owner, $contact
1144 public static function deliver($owner, $contact, $atom, $dissolve = false)
1148 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1150 if ($contact['duplex'] && $contact['dfrn-id']) {
1151 $idtosend = '0:' . $orig_id;
1153 if ($contact['duplex'] && $contact['issued-id']) {
1154 $idtosend = '1:' . $orig_id;
1157 $rino = Config::get('system', 'rino_encrypt');
1158 $rino = intval($rino);
1160 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1162 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1166 case SSL_POLICY_FULL:
1167 $ssl_policy = 'full';
1169 case SSL_POLICY_SELFSIGN:
1170 $ssl_policy = 'self';
1172 case SSL_POLICY_NONE:
1174 $ssl_policy = 'none';
1178 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1180 logger('dfrn_deliver: ' . $url);
1182 $ret = z_fetch_url($url);
1184 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1185 return -2; // timed out
1188 $xml = $ret['body'];
1190 $curl_stat = $a->get_curl_code();
1192 return -3; // timed out
1195 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1201 if (strpos($xml, '<?xml') === false) {
1202 logger('dfrn_deliver: no valid XML returned');
1203 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1207 $res = parse_xml_string($xml);
1209 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1210 return (($res->status) ? $res->status : 3);
1213 $postvars = array();
1214 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1215 $challenge = hex2bin((string) $res->challenge);
1216 $perm = (($res->perm) ? $res->perm : null);
1217 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1218 $rino_remote_version = intval($res->rino);
1219 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1221 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1223 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1227 $final_dfrn_id = '';
1230 if ((($perm == 'rw') && (! intval($contact['writable'])))
1231 || (($perm == 'r') && (intval($contact['writable'])))
1234 "update contact set writable = %d where id = %d",
1235 intval(($perm == 'rw') ? 1 : 0),
1236 intval($contact['id'])
1238 $contact['writable'] = (string) 1 - intval($contact['writable']);
1242 if (($contact['duplex'] && strlen($contact['pubkey']))
1243 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1244 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1246 openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1247 openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1249 openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1250 openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1253 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1255 if (strpos($final_dfrn_id, ':') == 1) {
1256 $final_dfrn_id = substr($final_dfrn_id, 2);
1259 if ($final_dfrn_id != $orig_id) {
1260 logger('dfrn_deliver: wrong dfrn_id.');
1261 // did not decode properly - cannot trust this site
1265 $postvars['dfrn_id'] = $idtosend;
1266 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1268 $postvars['dissolve'] = '1';
1272 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1273 $postvars['data'] = $atom;
1274 $postvars['perm'] = 'rw';
1276 $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1277 $postvars['perm'] = 'r';
1280 $postvars['ssl_policy'] = $ssl_policy;
1283 $postvars['page'] = $page;
1287 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1288 logger('rino version: '. $rino_remote_version);
1290 switch ($rino_remote_version) {
1292 // Deprecated rino version!
1293 $key = openssl_random_pseudo_bytes(16);
1294 $data = self::aes_encrypt($postvars['data'], $key);
1297 // RINO 2 based on php-encryption
1299 $key = \Crypto::createNewRandomKey();
1300 } catch (\CryptoTestFailedException $ex) {
1301 logger('Cannot safely create a key');
1303 } catch (\CannotPerformOperationException $ex) {
1304 logger('Cannot safely create a key');
1308 $data = Crypto::encrypt($postvars['data'], $key);
1309 } catch (\CryptoTestFailedException $ex) {
1310 logger('Cannot safely perform encryption');
1312 } catch (\CannotPerformOperationException $ex) {
1313 logger('Cannot safely perform encryption');
1318 logger("rino: invalid requested version '$rino_remote_version'");
1322 $postvars['rino'] = $rino_remote_version;
1323 $postvars['data'] = bin2hex($data);
1325 //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1328 if ($dfrn_version >= 2.1) {
1329 if (($contact['duplex'] && strlen($contact['pubkey']))
1330 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1331 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1333 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1335 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1338 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1339 openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1341 openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1345 logger('md5 rawkey ' . md5($postvars['key']));
1347 $postvars['key'] = bin2hex($postvars['key']);
1351 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1353 $xml = post_url($contact['notify'], $postvars);
1355 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1357 $curl_stat = $a->get_curl_code();
1358 if ((!$curl_stat) || (!strlen($xml))) {
1359 return -9; // timed out
1362 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1366 if (strpos($xml, '<?xml') === false) {
1367 logger('dfrn_deliver: phase 2: no valid XML returned');
1368 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1372 if ($contact['term-date'] > NULL_DATE) {
1373 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1374 include_once 'include/Contact.php';
1375 unmark_for_death($contact);
1378 $res = parse_xml_string($xml);
1380 if (!isset($res->status)) {
1384 if (!empty($res->message)) {
1385 logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1388 return intval($res->status);
1392 * @brief Add new birthday event for this person
1394 * @param array $contact Contact record
1395 * @param string $birthday Birthday of the contact
1396 * @todo Add array type-hint for $contact
1398 private static function birthday_event($contact, $birthday)
1400 // Check for duplicates
1402 "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1403 intval($contact["uid"]),
1404 intval($contact["id"]),
1405 dbesc(datetime_convert("UTC", "UTC", $birthday)),
1409 if (DBM::is_result($r)) {
1413 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1415 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1416 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1419 "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1420 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1421 intval($contact["uid"]),
1422 intval($contact["id"]),
1423 dbesc(datetime_convert()),
1424 dbesc(datetime_convert()),
1425 dbesc(datetime_convert("UTC", "UTC", $birthday)),
1426 dbesc(datetime_convert("UTC", "UTC", $birthday . " + 1 day ")),
1434 * @brief Fetch the author data from head or entry items
1436 * @param object $xpath XPath object
1437 * @param object $context In which context should the data be searched
1438 * @param array $importer Record of the importer user mixed with contact of the content
1439 * @param string $element Element name from which the data is fetched
1440 * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1442 * @return Returns an array with relevant data of the author
1443 * @todo Find good type-hints for all parameter
1445 private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1448 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1449 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1452 "SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1453 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1454 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1455 intval($importer["uid"]),
1456 dbesc(normalise_link($author["link"])),
1457 dbesc(NETWORK_STATUSNET)
1460 if (DBM::is_result($r)) {
1462 $author["contact-id"] = $r[0]["id"];
1463 $author["network"] = $r[0]["network"];
1466 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1469 $author["contact-id"] = $importer["id"];
1470 $author["network"] = $importer["network"];
1474 // Until now we aren't serving different sizes - but maybe later
1475 $avatarlist = array();
1476 /// @todo check if "avatar" or "photo" would be the best field in the specification
1477 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1478 foreach ($avatars AS $avatar) {
1481 foreach ($avatar->attributes AS $attributes) {
1482 /// @TODO Rewrite these similar if () to one switch
1483 if ($attributes->name == "href") {
1484 $href = $attributes->textContent;
1486 if ($attributes->name == "width") {
1487 $width = $attributes->textContent;
1489 if ($attributes->name == "updated") {
1490 $contact["avatar-date"] = $attributes->textContent;
1493 if (($width > 0) && ($href != "")) {
1494 $avatarlist[$width] = $href;
1497 if (count($avatarlist) > 0) {
1498 krsort($avatarlist);
1499 $author["avatar"] = current($avatarlist);
1502 if (DBM::is_result($r) && !$onlyfetch) {
1503 logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1505 $poco = array("url" => $contact["url"]);
1507 // When was the last change to name or uri?
1508 $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1509 foreach ($name_element->attributes AS $attributes) {
1510 if ($attributes->name == "updated") {
1511 $poco["name-date"] = $attributes->textContent;
1515 $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1516 foreach ($link_element->attributes AS $attributes) {
1517 if ($attributes->name == "updated") {
1518 $poco["uri-date"] = $attributes->textContent;
1522 // Update contact data
1523 $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1525 $poco["addr"] = $value;
1528 $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1530 $poco["name"] = $value;
1533 $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1535 $poco["nick"] = $value;
1538 $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1540 $poco["about"] = $value;
1543 $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1545 $poco["location"] = $value;
1548 /// @todo Only search for elements with "poco:type" = "xmpp"
1549 $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1551 $poco["xmpp"] = $value;
1554 /// @todo Add support for the following fields that we don't support by now in the contact table:
1555 /// - poco:utcOffset
1561 // If the "hide" element is present then the profile isn't searchable.
1562 $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1564 logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1566 // If the contact isn't searchable then set the contact to "hidden".
1567 // Problem: This can be manually overridden by the user.
1569 $contact["hidden"] = true;
1572 // Save the keywords into the contact table
1574 $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1575 foreach ($tagelements AS $tag) {
1576 $tags[$tag->nodeValue] = $tag->nodeValue;
1580 $poco["keywords"] = implode(", ", $tags);
1583 // "dfrn:birthday" contains the birthday converted to UTC
1584 $old_bdyear = $contact["bdyear"];
1586 $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1588 if (strtotime($birthday) > time()) {
1589 $bd_timestamp = strtotime($birthday);
1591 $poco["bdyear"] = date("Y", $bd_timestamp);
1594 // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1595 $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1597 if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1598 $bdyear = date("Y");
1599 $value = str_replace("0000", $bdyear, $value);
1601 if (strtotime($value) < time()) {
1602 $value = str_replace($bdyear, $bdyear + 1, $value);
1603 $bdyear = $bdyear + 1;
1606 $poco["bd"] = $value;
1609 $contact = array_merge($contact, $poco);
1611 if ($old_bdyear != $contact["bdyear"]) {
1612 self::birthday_event($contact, $birthday);
1615 // Get all field names
1617 foreach ($r[0] AS $field => $data) {
1618 $fields[$field] = $data;
1621 unset($fields["id"]);
1622 unset($fields["uid"]);
1623 unset($fields["url"]);
1624 unset($fields["avatar-date"]);
1625 unset($fields["name-date"]);
1626 unset($fields["uri-date"]);
1628 // Update check for this field has to be done differently
1629 $datefields = array("name-date", "uri-date");
1630 foreach ($datefields AS $field) {
1631 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1632 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1637 foreach ($fields AS $field => $data) {
1638 if ($contact[$field] != $r[0][$field]) {
1639 logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1645 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1648 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1649 `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1650 `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
1651 WHERE `id` = %d AND `network` = '%s'",
1652 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1653 dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1654 dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1655 dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1656 intval($contact["id"]), dbesc($contact["network"])
1660 update_contact_avatar(
1664 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"]))
1668 * The generation is a sign for the reliability of the provided data.
1669 * It is used in the socgraph.php to prevent that old contact data
1670 * that was relayed over several servers can overwrite contact
1671 * data that we received directly.
1674 $poco["generation"] = 2;
1675 $poco["photo"] = $author["avatar"];
1676 $poco["hide"] = $hide;
1677 $poco["contact-type"] = $contact["contact-type"];
1678 $gcid = update_gcontact($poco);
1680 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1687 * @brief Transforms activity objects into an XML string
1689 * @param object $xpath XPath object
1690 * @param object $activity Activity object
1691 * @param text $element element name
1693 * @return string XML string
1694 * @todo Find good type-hints for all parameter
1696 private static function transform_activity($xpath, $activity, $element)
1698 if (!is_object($activity)) {
1702 $obj_doc = new DOMDocument("1.0", "utf-8");
1703 $obj_doc->formatOutput = true;
1705 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1707 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1708 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1710 $id = $xpath->query("atom:id", $activity)->item(0);
1711 if (is_object($id)) {
1712 $obj_element->appendChild($obj_doc->importNode($id, true));
1715 $title = $xpath->query("atom:title", $activity)->item(0);
1716 if (is_object($title)) {
1717 $obj_element->appendChild($obj_doc->importNode($title, true));
1720 $links = $xpath->query("atom:link", $activity);
1721 if (is_object($links)) {
1722 foreach ($links AS $link) {
1723 $obj_element->appendChild($obj_doc->importNode($link, true));
1727 $content = $xpath->query("atom:content", $activity)->item(0);
1728 if (is_object($content)) {
1729 $obj_element->appendChild($obj_doc->importNode($content, true));
1732 $obj_doc->appendChild($obj_element);
1734 $objxml = $obj_doc->saveXML($obj_element);
1736 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1737 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1742 * @brief Processes the mail elements
1744 * @param object $xpath XPath object
1745 * @param object $mail mail elements
1746 * @param array $importer Record of the importer user mixed with contact of the content
1747 * @todo Find good type-hints for all parameter
1749 private static function process_mail($xpath, $mail, $importer)
1751 logger("Processing mails");
1753 /// @TODO Rewrite this to one statement
1755 $msg["uid"] = $importer["importer_uid"];
1756 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1757 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1758 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1759 $msg["contact-id"] = $importer["id"];
1760 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1761 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1762 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1763 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1764 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1766 $msg["replied"] = 0;
1768 dba::insert('mail', $msg);
1770 // send notifications.
1771 /// @TODO Arange this mess
1772 $notif_params = array(
1773 "type" => NOTIFY_MAIL,
1774 "notify_flags" => $importer["notify-flags"],
1775 "language" => $importer["language"],
1776 "to_name" => $importer["username"],
1777 "to_email" => $importer["email"],
1778 "uid" => $importer["importer_uid"],
1780 "source_name" => $msg["from-name"],
1781 "source_link" => $importer["url"],
1782 "source_photo" => $importer["thumb"],
1783 "verb" => ACTIVITY_POST,
1787 notification($notif_params);
1789 logger("Mail is processed, notification was sent.");
1793 * @brief Processes the suggestion elements
1795 * @param object $xpath XPath object
1796 * @param object $suggestion suggestion elements
1797 * @param array $importer Record of the importer user mixed with contact of the content
1798 * @todo Find good type-hints for all parameter
1800 private static function process_suggestion($xpath, $suggestion, $importer)
1804 logger("Processing suggestions");
1806 /// @TODO Rewrite this to one statement
1808 $suggest["uid"] = $importer["importer_uid"];
1809 $suggest["cid"] = $importer["id"];
1810 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1811 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1812 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1813 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1814 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1816 // Does our member already have a friend matching this description?
1819 "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1820 dbesc($suggest["name"]),
1821 dbesc(normalise_link($suggest["url"])),
1822 intval($suggest["uid"])
1826 * The valid result means the friend we're about to send a friend
1827 * suggestion already has them in their contact, which means no further
1828 * action is required.
1830 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1832 if (DBM::is_result($r)) {
1836 // Do we already have an fcontact record for this person?
1840 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1841 dbesc($suggest["url"]),
1842 dbesc($suggest["name"]),
1843 dbesc($suggest["request"])
1845 if (DBM::is_result($r)) {
1848 // OK, we do. Do we already have an introduction for this person ?
1850 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1851 intval($suggest["uid"]),
1856 * The valid result means the friend we're about to send a friend
1857 * suggestion already has them in their contact, which means no further
1858 * action is required.
1860 * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1862 if (DBM::is_result($r)) {
1868 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1869 dbesc($suggest["name"]),
1870 dbesc($suggest["url"]),
1871 dbesc($suggest["photo"]),
1872 dbesc($suggest["request"])
1876 "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1877 dbesc($suggest["url"]),
1878 dbesc($suggest["name"]),
1879 dbesc($suggest["request"])
1883 * If no record in fcontact is found, below INSERT statement will not
1884 * link an introduction to it.
1886 if (!DBM::is_result($r)) {
1887 // database record did not get created. Quietly give up.
1893 $hash = random_string();
1896 "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1897 VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1898 intval($suggest["uid"]),
1900 intval($suggest["cid"]),
1901 dbesc($suggest["body"]),
1903 dbesc(datetime_convert()),
1908 "type" => NOTIFY_SUGGEST,
1909 "notify_flags" => $importer["notify-flags"],
1910 "language" => $importer["language"],
1911 "to_name" => $importer["username"],
1912 "to_email" => $importer["email"],
1913 "uid" => $importer["importer_uid"],
1915 "link" => System::baseUrl()."/notifications/intros",
1916 "source_name" => $importer["name"],
1917 "source_link" => $importer["url"],
1918 "source_photo" => $importer["photo"],
1919 "verb" => ACTIVITY_REQ_FRIEND,
1927 * @brief Processes the relocation elements
1929 * @param object $xpath XPath object
1930 * @param object $relocation relocation elements
1931 * @param array $importer Record of the importer user mixed with contact of the content
1932 * @todo Find good type-hints for all parameter
1934 private static function process_relocation($xpath, $relocation, $importer)
1936 logger("Processing relocations");
1938 /// @TODO Rewrite this to one statement
1939 $relocate = array();
1940 $relocate["uid"] = $importer["importer_uid"];
1941 $relocate["cid"] = $importer["id"];
1942 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1943 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1944 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1945 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1946 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1947 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1948 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1949 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1950 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1951 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1952 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1953 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1955 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1956 $relocate["avatar"] = $relocate["photo"];
1959 if ($relocate["addr"] == "") {
1960 $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1965 "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1966 intval($importer["id"]),
1967 intval($importer["importer_uid"])
1970 if (!DBM::is_result($r)) {
1971 logger("Query failed to execute, no result returned in " . __FUNCTION__);
1977 // Update the gcontact entry
1978 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1981 "UPDATE `gcontact` SET
1990 WHERE `nurl` = '%s';",
1991 dbesc($relocate["name"]),
1992 dbesc($relocate["avatar"]),
1993 dbesc($relocate["url"]),
1994 dbesc(normalise_link($relocate["url"])),
1995 dbesc($relocate["addr"]),
1996 dbesc($relocate["addr"]),
1997 dbesc($relocate["notify"]),
1998 dbesc($relocate["server_url"]),
1999 dbesc(normalise_link($old["url"]))
2002 // Update the contact table. We try to find every entry.
2004 "UPDATE `contact` SET
2014 `site-pubkey` = '%s'
2015 WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2016 dbesc($relocate["name"]),
2017 dbesc($relocate["avatar"]),
2018 dbesc($relocate["url"]),
2019 dbesc(normalise_link($relocate["url"])),
2020 dbesc($relocate["addr"]),
2021 dbesc($relocate["request"]),
2022 dbesc($relocate["confirm"]),
2023 dbesc($relocate["notify"]),
2024 dbesc($relocate["poll"]),
2025 dbesc($relocate["sitepubkey"]),
2026 intval($importer["id"]),
2027 intval($importer["importer_uid"]),
2028 dbesc(normalise_link($old["url"]))
2031 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2038 /// @todo This is an extreme performance killer
2040 'owner-link' => array($old["url"], $relocate["url"]),
2041 'author-link' => array($old["url"], $relocate["url"]),
2042 //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2043 //'author-avatar' => array($old["photo"], $relocate["photo"]),
2045 foreach ($fields as $n => $f) {
2047 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2050 intval($importer["importer_uid"])
2053 if (DBM::is_result($r)) {
2055 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2060 intval($importer["importer_uid"])
2070 /// merge with current record, current contents have priority
2071 /// update record, set url-updated
2072 /// update profile photos
2073 /// schedule a scan?
2078 * @brief Updates an item
2080 * @param array $current the current item record
2081 * @param array $item the new item record
2082 * @param array $importer Record of the importer user mixed with contact of the content
2083 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2084 * @todo set proper type-hints (array?)
2086 private static function update_content($current, $item, $importer, $entrytype)
2090 if (edited_timestamp_is_newer($current, $item)) {
2091 // do not accept (ignore) an earlier edit than one we currently have.
2092 if (datetime_convert("UTC", "UTC", $item["edited"]) < $current["edited"]) {
2096 $fields = array('title' => $item["title"], 'body' => $item["body"],
2097 'tag' => $item["tag"], 'changed' => datetime_convert(),
2098 'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2100 $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2101 dba::update('item', $fields, $condition);
2103 create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2104 update_thread_uri($item["uri"], $importer["importer_uid"]);
2108 if ($entrytype == DFRN_REPLY_RC) {
2109 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $current["id"]);
2113 // update last-child if it changes
2114 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2116 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2117 dbesc(datetime_convert()),
2118 dbesc($item["parent-uri"]),
2119 intval($importer["importer_uid"])
2122 "UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2123 intval($item["last-child"]),
2124 dbesc(datetime_convert()),
2125 dbesc($item["uri"]),
2126 intval($importer["importer_uid"])
2133 * @brief Detects the entry type of the item
2135 * @param array $importer Record of the importer user mixed with contact of the content
2136 * @param array $item the new item record
2138 * @return int Is it a toplevel entry, a comment or a relayed comment?
2139 * @todo set proper type-hints (array?)
2141 private static function get_entry_type($importer, $item)
2143 if ($item["parent-uri"] != $item["uri"]) {
2146 if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2149 logger("possible community action");
2151 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2154 // was the top-level post for this action written by somebody on this site?
2155 // Specifically, the recipient?
2157 $is_a_remote_action = false;
2160 "SELECT `item`.`parent-uri` FROM `item`
2161 WHERE `item`.`uri` = '%s'
2163 dbesc($item["parent-uri"])
2165 if (DBM::is_result($r)) {
2167 "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2168 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2169 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2170 AND `item`.`uid` = %d
2173 dbesc($r[0]["parent-uri"]),
2174 dbesc($r[0]["parent-uri"]),
2175 dbesc($r[0]["parent-uri"]),
2176 intval($importer["importer_uid"])
2178 if (DBM::is_result($r)) {
2179 $is_a_remote_action = true;
2184 * Does this have the characteristics of a community or private group action?
2185 * If it's an action to a wall post on a community/prvgroup page it's a
2186 * valid community action. Also forum_mode makes it valid for sure.
2187 * If neither, it's not.
2190 /// @TODO Maybe merge these if() blocks into one?
2191 if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2192 $is_a_remote_action = false;
2193 logger("not a community action");
2196 if ($is_a_remote_action) {
2197 return DFRN_REPLY_RC;
2202 return DFRN_TOP_LEVEL;
2207 * @brief Send a "poke"
2209 * @param array $item the new item record
2210 * @param array $importer Record of the importer user mixed with contact of the content
2211 * @param int $posted_id The record number of item record that was just posted
2212 * @todo set proper type-hints (array?)
2214 private static function do_poke($item, $importer, $posted_id)
2216 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2220 $xo = parse_xml_string($item["object"], false);
2222 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2223 // somebody was poked/prodded. Was it me?
2224 foreach ($xo->link as $l) {
2225 $atts = $l->attributes();
2226 switch ($atts["rel"]) {
2228 $Blink = $atts["href"];
2235 if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2236 // send a notification
2239 "type" => NOTIFY_POKE,
2240 "notify_flags" => $importer["notify-flags"],
2241 "language" => $importer["language"],
2242 "to_name" => $importer["username"],
2243 "to_email" => $importer["email"],
2244 "uid" => $importer["importer_uid"],
2246 "link" => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2247 "source_name" => stripslashes($item["author-name"]),
2248 "source_link" => $item["author-link"],
2249 "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2250 ? $importer["thumb"] : $item["author-avatar"]),
2251 "verb" => $item["verb"],
2252 "otype" => "person",
2253 "activity" => $verb,
2254 "parent" => $item["parent"])
2261 * @brief Processes several actions, depending on the verb
2263 * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2264 * @param array $importer Record of the importer user mixed with contact of the content
2265 * @param array $item the new item record
2266 * @param bool $is_like Is the verb a "like"?
2268 * @return bool Should the processing of the entries be continued?
2269 * @todo set proper type-hints (array?)
2271 private static function process_verbs($entrytype, $importer, &$item, &$is_like)
2273 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2275 if (($entrytype == DFRN_TOP_LEVEL)) {
2276 // The filling of the the "contact" variable is done for legcy reasons
2277 // The functions below are partly used by ostatus.php as well - where we have this variable
2278 $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2280 $nickname = $contact["nick"];
2282 // Big question: Do we need these functions? They were part of the "consume_feed" function.
2283 // This function once was responsible for DFRN and OStatus.
2284 if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2285 logger("New follower");
2286 new_follower($importer, $contact, $item, $nickname);
2289 if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2290 logger("Lost follower");
2291 lose_follower($importer, $contact, $item);
2294 if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2295 logger("New friend request");
2296 new_follower($importer, $contact, $item, $nickname, true);
2299 if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2300 logger("Lost sharer");
2301 lose_sharer($importer, $contact, $item);
2305 if (($item["verb"] == ACTIVITY_LIKE)
2306 || ($item["verb"] == ACTIVITY_DISLIKE)
2307 || ($item["verb"] == ACTIVITY_ATTEND)
2308 || ($item["verb"] == ACTIVITY_ATTENDNO)
2309 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2312 $item["type"] = "activity";
2313 $item["gravity"] = GRAVITY_LIKE;
2314 // only one like or dislike per person
2315 // splitted into two queries for performance issues
2317 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2318 intval($item["uid"]),
2319 dbesc($item["author-link"]),
2320 dbesc($item["verb"]),
2321 dbesc($item["parent-uri"])
2323 if (DBM::is_result($r)) {
2328 "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2329 intval($item["uid"]),
2330 dbesc($item["author-link"]),
2331 dbesc($item["verb"]),
2332 dbesc($item["parent-uri"])
2334 if (DBM::is_result($r)) {
2341 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2343 $xo = parse_xml_string($item["object"], false);
2344 $xt = parse_xml_string($item["target"], false);
2346 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2348 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2350 intval($importer["importer_uid"])
2353 if (!DBM::is_result($r)) {
2354 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2358 // extract tag, if not duplicate, add to parent item
2360 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2361 q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2362 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2365 create_tags_from_item($r[0]["id"]);
2375 * @brief Processes the link elements
2377 * @param object $links link elements
2378 * @param array $item the item record
2379 * @todo set proper type-hints
2381 private static function parse_links($links, &$item)
2388 foreach ($links AS $link) {
2389 foreach ($link->attributes AS $attributes) {
2390 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2391 if ($attributes->name == "href") {
2392 $href = $attributes->textContent;
2394 if ($attributes->name == "rel") {
2395 $rel = $attributes->textContent;
2397 if ($attributes->name == "type") {
2398 $type = $attributes->textContent;
2400 if ($attributes->name == "length") {
2401 $length = $attributes->textContent;
2403 if ($attributes->name == "title") {
2404 $title = $attributes->textContent;
2407 if (($rel != "") && ($href != "")) {
2410 $item["plink"] = $href;
2414 if (strlen($item["attach"])) {
2415 $item["attach"] .= ",";
2418 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2426 * @brief Processes the entry elements which contain the items and comments
2428 * @param array $header Array of the header elements that always stay the same
2429 * @param object $xpath XPath object
2430 * @param object $entry entry elements
2431 * @param array $importer Record of the importer user mixed with contact of the content
2432 * @todo Add type-hints
2434 private static function process_entry($header, $xpath, $entry, $importer, $xml)
2436 logger("Processing entries");
2440 $item["protocol"] = PROTOCOL_DFRN;
2442 $item["source"] = $xml;
2445 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2447 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2450 "SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2451 dbesc($item["uri"]),
2452 intval($importer["importer_uid"])
2455 // Is there an existing item?
2456 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item)
2457 && (datetime_convert("UTC", "UTC", $item["edited"]) < $current[0]["edited"])
2459 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2464 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2466 $item["owner-name"] = $owner["name"];
2467 $item["owner-link"] = $owner["link"];
2468 $item["owner-avatar"] = $owner["avatar"];
2471 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2473 $item["author-name"] = $author["name"];
2474 $item["author-link"] = $author["link"];
2475 $item["author-avatar"] = $author["avatar"];
2477 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2479 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2481 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2482 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''), $item["body"]);
2483 // make sure nobody is trying to sneak some html tags by us
2484 $item["body"] = notags(base64url_decode($item["body"]));
2486 $item["body"] = limit_body_size($item["body"]);
2488 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2489 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2490 $item['body'] = reltoabs($item['body'], $base_url);
2492 $item['body'] = html2bb_video($item['body']);
2494 $item['body'] = oembed_html2bbcode($item['body']);
2496 $config = HTMLPurifier_Config::createDefault();
2497 $config->set('Cache.DefinitionImpl', null);
2499 // we shouldn't need a whitelist, because the bbcode converter
2500 // will strip out any unsupported tags.
2502 $purifier = new HTMLPurifier($config);
2503 $item['body'] = $purifier->purify($item['body']);
2505 $item['body'] = @html2bbcode($item['body']);
2508 /// @todo We should check for a repeated post and if we know the repeated author.
2510 // We don't need the content element since "dfrn:env" is always present
2511 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2513 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2514 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2516 $georsspoint = $xpath->query("georss:point", $entry);
2518 $item["coord"] = $georsspoint->item(0)->nodeValue;
2521 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2523 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2525 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2526 $item["bookmark"] = true;
2529 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2530 if ($notice_info && ($notice_info->length > 0)) {
2531 foreach ($notice_info->item(0)->attributes AS $attributes) {
2532 if ($attributes->name == "source") {
2533 $item["app"] = strip_tags($attributes->textContent);
2538 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2540 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2541 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2542 if ($dsprsig != "") {
2543 $item["dsprsig"] = $dsprsig;
2546 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2548 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2549 $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2552 $object = $xpath->query("activity:object", $entry)->item(0);
2553 $item["object"] = self::transform_activity($xpath, $object, "object");
2555 if (trim($item["object"]) != "") {
2556 $r = parse_xml_string($item["object"], false);
2557 if (isset($r->type)) {
2558 $item["object-type"] = $r->type;
2562 $target = $xpath->query("activity:target", $entry)->item(0);
2563 $item["target"] = self::transform_activity($xpath, $target, "target");
2565 $categories = $xpath->query("atom:category", $entry);
2567 foreach ($categories AS $category) {
2570 foreach ($category->attributes AS $attributes) {
2571 if ($attributes->name == "term") {
2572 $term = $attributes->textContent;
2575 if ($attributes->name == "scheme") {
2576 $scheme = $attributes->textContent;
2580 if (($term != "") && ($scheme != "")) {
2581 $parts = explode(":", $scheme);
2582 if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2583 $termhash = array_shift($parts);
2584 $termurl = implode(":", $parts);
2586 if (strlen($item["tag"])) {
2587 $item["tag"] .= ",";
2590 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2598 $links = $xpath->query("atom:link", $entry);
2600 self::parse_links($links, $item);
2603 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2605 $conv = $xpath->query('ostatus:conversation', $entry);
2606 if (is_object($conv->item(0))) {
2607 foreach ($conv->item(0)->attributes AS $attributes) {
2608 if ($attributes->name == "ref") {
2609 $item['conversation-uri'] = $attributes->textContent;
2611 if ($attributes->name == "href") {
2612 $item['conversation-href'] = $attributes->textContent;
2617 // Is it a reply or a top level posting?
2618 $item["parent-uri"] = $item["uri"];
2620 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2621 if (is_object($inreplyto->item(0))) {
2622 foreach ($inreplyto->item(0)->attributes AS $attributes) {
2623 if ($attributes->name == "ref") {
2624 $item["parent-uri"] = $attributes->textContent;
2629 // Get the type of the item (Top level post, reply or remote reply)
2630 $entrytype = self::get_entry_type($importer, $item);
2632 // Now assign the rest of the values that depend on the type of the message
2633 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2634 if (!isset($item["object-type"])) {
2635 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2638 if ($item["contact-id"] != $owner["contact-id"]) {
2639 $item["contact-id"] = $owner["contact-id"];
2642 if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2643 $item["network"] = $owner["network"];
2646 if ($item["contact-id"] != $author["contact-id"]) {
2647 $item["contact-id"] = $author["contact-id"];
2650 if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2651 $item["network"] = $author["network"];
2654 /// @TODO maybe remove this old-lost code then?
2655 // This code was taken from the old DFRN code
2656 // When activated, forums don't work.
2657 // And: Why should we disallow commenting by followers?
2658 // the behaviour is now similar to the Diaspora part.
2659 //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2660 // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2665 if ($entrytype == DFRN_REPLY_RC) {
2666 $item["type"] = "remote-comment";
2668 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2669 if (!isset($item["object-type"])) {
2670 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2674 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2675 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2676 $ev = bbtoevent($item["body"]);
2677 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2678 logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2679 /// @TODO Mixure of "/' ahead ...
2680 $ev["cid"] = $importer["id"];
2681 $ev["uid"] = $importer["uid"];
2682 $ev["uri"] = $item["uri"];
2683 $ev["edited"] = $item["edited"];
2684 $ev['private'] = $item['private'];
2685 $ev["guid"] = $item["guid"];
2688 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2689 dbesc($item["uri"]),
2690 intval($importer["uid"])
2692 if (DBM::is_result($r)) {
2693 $ev["id"] = $r[0]["id"];
2696 $event_id = event_store($ev);
2697 logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2703 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2704 logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2708 // Update content if 'updated' changes
2709 if (DBM::is_result($current)) {
2710 if (self::update_content($r[0], $item, $importer, $entrytype)) {
2711 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2713 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2718 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2719 $posted_id = item_store($item);
2723 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2725 $item["id"] = $posted_id;
2728 "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2730 intval($importer["importer_uid"])
2732 if (DBM::is_result($r)) {
2733 $parent = $r[0]["parent"];
2734 $parent_uri = $r[0]["parent-uri"];
2739 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2740 dbesc(datetime_convert()),
2741 intval($importer["importer_uid"]),
2742 intval($r[0]["parent"])
2746 "UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2747 dbesc(datetime_convert()),
2748 intval($importer["importer_uid"]),
2753 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2754 logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2755 Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $posted_id);
2760 } else { // $entrytype == DFRN_TOP_LEVEL
2761 if (!link_compare($item["owner-link"], $importer["url"])) {
2763 * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2764 * but otherwise there's a possible data mixup on the sender's system.
2765 * the tgroup delivery code called from item_store will correct it if it's a forum,
2766 * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2768 logger('Correcting item owner.', LOGGER_DEBUG);
2769 $item["owner-name"] = $importer["senderName"];
2770 $item["owner-link"] = $importer["url"];
2771 $item["owner-avatar"] = $importer["thumb"];
2774 if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2775 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2779 // This is my contact on another system, but it's really me.
2780 // Turn this into a wall post.
2781 $notify = item_is_remote_self($importer, $item);
2783 $posted_id = item_store($item, false, $notify);
2785 logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2787 if (stristr($item["verb"],ACTIVITY_POKE))
2788 self::do_poke($item, $importer, $posted_id);
2793 * @brief Deletes items
2795 * @param object $xpath XPath object
2796 * @param object $deletion deletion elements
2797 * @param array $importer Record of the importer user mixed with contact of the content
2798 * @todo set proper type-hints
2800 private static function process_deletion($xpath, $deletion, $importer)
2802 logger("Processing deletions");
2804 foreach ($deletion->attributes AS $attributes) {
2805 if ($attributes->name == "ref") {
2806 $uri = $attributes->textContent;
2808 if ($attributes->name == "when") {
2809 $when = $attributes->textContent;
2813 $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2815 $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2818 if (!$uri || !$importer["id"]) {
2822 /// @todo Only select the used fields
2824 "SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2825 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2827 intval($importer["uid"]),
2828 intval($importer["id"])
2830 if (!DBM::is_result($r)) {
2831 logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2836 $entrytype = self::get_entry_type($importer, $item);
2838 if (!$item["deleted"]) {
2839 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2844 if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2845 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2846 event_delete($item["event-id"]);
2849 if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2851 $xo = parse_xml_string($item["object"], false);
2852 $xt = parse_xml_string($item["target"], false);
2854 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2856 "SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2858 intval($importer["importer_uid"])
2860 if (DBM::is_result($i)) {
2861 // For tags, the owner cannot remove the tag on the author's copy of the post.
2863 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2864 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2865 $author_copy = (($item["origin"]) ? true : false);
2867 if ($owner_remove && $author_copy) {
2870 if ($author_remove || $owner_remove) {
2871 $tags = explode(',', $i[0]["tag"]);
2874 foreach ($tags as $tag) {
2875 if (trim($tag) !== trim($xo->body)) {
2876 $newtags[] = trim($tag);
2881 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2882 dbesc(implode(',', $newtags)),
2885 create_tags_from_item($i[0]["id"]);
2891 if ($entrytype == DFRN_TOP_LEVEL) {
2893 "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2894 `body` = '', `title` = ''
2895 WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2897 dbesc(datetime_convert()),
2899 intval($importer["uid"])
2901 create_tags_from_itemuri($uri, $importer["uid"]);
2902 create_files_from_itemuri($uri, $importer["uid"]);
2903 update_thread_uri($uri, $importer["uid"]);
2906 "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2907 `body` = '', `title` = ''
2908 WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2910 dbesc(datetime_convert()),
2912 intval($importer["uid"])
2914 create_tags_from_itemuri($uri, $importer["uid"]);
2915 create_files_from_itemuri($uri, $importer["uid"]);
2916 update_thread_uri($uri, $importer["importer_uid"]);
2917 if ($item["last-child"]) {
2918 // ensure that last-child is set in case the comment that had it just got wiped.
2920 "UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2921 dbesc(datetime_convert()),
2922 dbesc($item["parent-uri"]),
2923 intval($item["uid"])
2925 // who is the last child now?
2927 "SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2928 ORDER BY `created` DESC LIMIT 1",
2929 dbesc($item["parent-uri"]),
2930 intval($importer["uid"])
2932 if (DBM::is_result($r)) {
2934 "UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2939 // if this is a relayed delete, propagate it to other recipients
2941 if ($entrytype == DFRN_REPLY_RC) {
2942 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2943 Worker::add(PRIORITY_HIGH, "notifier", "drop", $item["id"]);
2950 * @brief Imports a DFRN message
2952 * @param text $xml The DFRN message
2953 * @param array $importer Record of the importer user mixed with contact of the content
2954 * @param bool $sort_by_date Is used when feeds are polled
2955 * @return integer Import status
2956 * @todo set proper type-hints
2958 public static function import($xml, $importer, $sort_by_date = false)
2964 $doc = new DOMDocument();
2965 @$doc->loadXML($xml);
2967 $xpath = new DomXPath($doc);
2968 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2969 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2970 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2971 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2972 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2973 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2974 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2975 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2976 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2977 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2980 $header["uid"] = $importer["uid"];
2981 $header["network"] = NETWORK_DFRN;
2982 $header["type"] = "remote";
2983 $header["wall"] = 0;
2984 $header["origin"] = 0;
2985 $header["contact-id"] = $importer["id"];
2987 // Update the contact table if the data has changed
2989 // The "atom:author" is only present in feeds
2990 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2991 self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2994 // Only the "dfrn:owner" in the head section contains all data
2995 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2996 self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2999 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
3001 // The account type is new since 3.5.1
3002 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
3003 $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
3005 if ($accounttype != $importer["contact-type"]) {
3006 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
3010 // is it a public forum? Private forums aren't supported with this method
3011 // This is deprecated since 3.5.1
3012 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
3014 if ($forum != $importer["forum"]) {
3015 $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
3016 dba::update('contact', array('forum' => $forum), $condition);
3019 // We are processing relocations even if we are ignoring a contact
3020 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
3021 foreach ($relocations AS $relocation) {
3022 self::process_relocation($xpath, $relocation, $importer);
3025 if ($importer["readonly"]) {
3026 // We aren't receiving stuff from this person. But we will quietly ignore them
3027 // rather than a blatant "go away" message.
3028 logger('ignoring contact '.$importer["id"]);
3032 $mails = $xpath->query("/atom:feed/dfrn:mail");
3033 foreach ($mails AS $mail) {
3034 self::process_mail($xpath, $mail, $importer);
3037 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
3038 foreach ($suggestions AS $suggestion) {
3039 self::process_suggestion($xpath, $suggestion, $importer);
3042 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
3043 foreach ($deletions AS $deletion) {
3044 self::process_deletion($xpath, $deletion, $importer);
3047 if (!$sort_by_date) {
3048 $entries = $xpath->query("/atom:feed/atom:entry");
3049 foreach ($entries AS $entry) {
3050 self::process_entry($header, $xpath, $entry, $importer, $xml);
3053 $newentries = array();
3054 $entries = $xpath->query("/atom:feed/atom:entry");
3055 foreach ($entries AS $entry) {
3056 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
3057 $newentries[strtotime($created)] = $entry;
3060 // Now sort after the publishing date
3063 foreach ($newentries AS $entry) {
3064 self::process_entry($header, $xpath, $entry, $importer, $xml);
3067 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);