Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2552 lines
85KB

  1. <?php
  2. /**
  3. * @file include/dfrn.php
  4. * @brief The implementation of the dfrn protocol
  5. *
  6. * @see https://github.com/friendica/friendica/wiki/Protocol and
  7. * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
  8. */
  9. require_once("include/Contact.php");
  10. require_once("include/ostatus.php");
  11. require_once("include/enotify.php");
  12. require_once("include/threads.php");
  13. require_once("include/socgraph.php");
  14. require_once("include/items.php");
  15. require_once("include/tags.php");
  16. require_once("include/files.php");
  17. require_once("include/event.php");
  18. require_once("include/text.php");
  19. require_once("include/oembed.php");
  20. require_once("include/html2bbcode.php");
  21. require_once("include/bbcode.php");
  22. require_once("include/xml.php");
  23. /**
  24. * @brief This class contain functions to create and send DFRN XML files
  25. *
  26. */
  27. class dfrn {
  28. const DFRN_TOP_LEVEL = 0; // Top level posting
  29. const DFRN_REPLY = 1; // Regular reply that is stored locally
  30. const DFRN_REPLY_RC = 2; // Reply that will be relayed
  31. /**
  32. * @brief Generates the atom entries for delivery.php
  33. *
  34. * This function is used whenever content is transmitted via DFRN.
  35. *
  36. * @param array $items Item elements
  37. * @param array $owner Owner record
  38. *
  39. * @return string DFRN entries
  40. */
  41. public static function entries($items,$owner) {
  42. $doc = new DOMDocument('1.0', 'utf-8');
  43. $doc->formatOutput = true;
  44. $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
  45. if(! count($items))
  46. return trim($doc->saveXML());
  47. foreach($items as $item) {
  48. $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
  49. $root->appendChild($entry);
  50. }
  51. return(trim($doc->saveXML()));
  52. }
  53. /**
  54. * @brief Generate an atom feed for the given user
  55. *
  56. * This function is called when another server is pulling data from the user feed.
  57. *
  58. * @param string $dfrn_id DFRN ID from the requesting party
  59. * @param string $owner_nick Owner nick name
  60. * @param string $last_update Date of the last update
  61. * @param int $direction Can be -1, 0 or 1.
  62. * @param boolean $onlyheader Output only the header without content? (Default is "no")
  63. *
  64. * @return string DFRN feed entries
  65. */
  66. public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
  67. $a = get_app();
  68. $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
  69. $public_feed = (($dfrn_id) ? false : true);
  70. $starred = false; // not yet implemented, possible security issues
  71. $converse = false;
  72. if($public_feed && $a->argc > 2) {
  73. for($x = 2; $x < $a->argc; $x++) {
  74. if($a->argv[$x] == 'converse')
  75. $converse = true;
  76. if($a->argv[$x] == 'starred')
  77. $starred = true;
  78. if($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
  79. $category = $a->argv[$x+1];
  80. }
  81. }
  82. // default permissions - anonymous user
  83. $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
  84. $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
  85. FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
  86. WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
  87. dbesc($owner_nick)
  88. );
  89. if(! count($r))
  90. killme();
  91. $owner = $r[0];
  92. $owner_id = $owner['uid'];
  93. $owner_nick = $owner['nickname'];
  94. $sql_post_table = "";
  95. if(! $public_feed) {
  96. $sql_extra = '';
  97. switch($direction) {
  98. case (-1):
  99. $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
  100. $my_id = $dfrn_id;
  101. break;
  102. case 0:
  103. $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
  104. $my_id = '1:' . $dfrn_id;
  105. break;
  106. case 1:
  107. $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
  108. $my_id = '0:' . $dfrn_id;
  109. break;
  110. default:
  111. return false;
  112. break; // NOTREACHED
  113. }
  114. $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
  115. intval($owner_id)
  116. );
  117. if(! count($r))
  118. killme();
  119. $contact = $r[0];
  120. require_once('include/security.php');
  121. $groups = init_groups_visitor($contact['id']);
  122. if(count($groups)) {
  123. for($x = 0; $x < count($groups); $x ++)
  124. $groups[$x] = '<' . intval($groups[$x]) . '>' ;
  125. $gs = implode('|', $groups);
  126. } else
  127. $gs = '<<>>' ; // Impossible to match
  128. $sql_extra = sprintf("
  129. AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
  130. AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
  131. AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
  132. AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
  133. ",
  134. intval($contact['id']),
  135. intval($contact['id']),
  136. dbesc($gs),
  137. dbesc($gs)
  138. );
  139. }
  140. if($public_feed)
  141. $sort = 'DESC';
  142. else
  143. $sort = 'ASC';
  144. if(! strlen($last_update))
  145. $last_update = 'now -30 days';
  146. if(isset($category)) {
  147. $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` ",
  148. dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
  149. //$sql_extra .= file_tag_file_query('item',$category,'category');
  150. }
  151. if($public_feed) {
  152. if(! $converse)
  153. $sql_extra .= " AND `contact`.`self` = 1 ";
  154. }
  155. $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
  156. $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
  157. `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
  158. `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
  159. `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
  160. `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
  161. FROM `item` USE INDEX (`uid_wall_changed`, `uid_type_changed`) $sql_post_table
  162. STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  163. AND (NOT `contact`.`blocked` OR `contact`.`pending`)
  164. LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
  165. WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
  166. AND `item`.`wall` AND `item`.`changed` > '%s'
  167. $sql_extra
  168. ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
  169. intval($owner_id),
  170. dbesc($check_date),
  171. dbesc($sort)
  172. );
  173. // Will check further below if this actually returned results.
  174. // We will provide an empty feed if that is the case.
  175. $items = $r;
  176. $doc = new DOMDocument('1.0', 'utf-8');
  177. $doc->formatOutput = true;
  178. $alternatelink = $owner['url'];
  179. if(isset($category))
  180. $alternatelink .= "/category/".$category;
  181. if ($public_feed)
  182. $author = "dfrn:owner";
  183. else
  184. $author = "author";
  185. $root = self::add_header($doc, $owner, $author, $alternatelink, true);
  186. // This hook can't work anymore
  187. // call_hooks('atom_feed', $atom);
  188. if (!count($items) OR $onlyheader) {
  189. $atom = trim($doc->saveXML());
  190. call_hooks('atom_feed_end', $atom);
  191. return $atom;
  192. }
  193. foreach($items as $item) {
  194. // prevent private email from leaking.
  195. if($item['network'] == NETWORK_MAIL)
  196. continue;
  197. // public feeds get html, our own nodes use bbcode
  198. if($public_feed) {
  199. $type = 'html';
  200. // catch any email that's in a public conversation and make sure it doesn't leak
  201. if($item['private'])
  202. continue;
  203. } else
  204. $type = 'text';
  205. $entry = self::entry($doc, $type, $item, $owner, true);
  206. $root->appendChild($entry);
  207. }
  208. $atom = trim($doc->saveXML());
  209. call_hooks('atom_feed_end', $atom);
  210. return $atom;
  211. }
  212. /**
  213. * @brief Create XML text for DFRN mails
  214. *
  215. * @param array $item message elements
  216. * @param array $owner Owner record
  217. *
  218. * @return string DFRN mail
  219. */
  220. public static function mail($item, $owner) {
  221. $doc = new DOMDocument('1.0', 'utf-8');
  222. $doc->formatOutput = true;
  223. $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
  224. $mail = $doc->createElement("dfrn:mail");
  225. $sender = $doc->createElement("dfrn:sender");
  226. xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
  227. xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
  228. xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
  229. $mail->appendChild($sender);
  230. xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
  231. xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
  232. xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
  233. xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
  234. xml::add_element($doc, $mail, "dfrn:content", $item['body']);
  235. $root->appendChild($mail);
  236. return(trim($doc->saveXML()));
  237. }
  238. /**
  239. * @brief Create XML text for DFRN friend suggestions
  240. *
  241. * @param array $item suggestion elements
  242. * @param array $owner Owner record
  243. *
  244. * @return string DFRN suggestions
  245. */
  246. public static function fsuggest($item, $owner) {
  247. $doc = new DOMDocument('1.0', 'utf-8');
  248. $doc->formatOutput = true;
  249. $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
  250. $suggest = $doc->createElement("dfrn:suggest");
  251. xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
  252. xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
  253. xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
  254. xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
  255. xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
  256. $root->appendChild($suggest);
  257. return(trim($doc->saveXML()));
  258. }
  259. /**
  260. * @brief Create XML text for DFRN relocations
  261. *
  262. * @param array $owner Owner record
  263. * @param int $uid User ID
  264. *
  265. * @return string DFRN relocations
  266. */
  267. public static function relocate($owner, $uid) {
  268. /* get site pubkey. this could be a new installation with no site keys*/
  269. $pubkey = get_config('system','site_pubkey');
  270. if(! $pubkey) {
  271. $res = new_keypair(1024);
  272. set_config('system','site_prvkey', $res['prvkey']);
  273. set_config('system','site_pubkey', $res['pubkey']);
  274. }
  275. $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
  276. WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
  277. $photos = array();
  278. $ext = Photo::supportedTypes();
  279. foreach($rp as $p)
  280. $photos[$p['scale']] = app::get_baseurl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
  281. unset($rp, $ext);
  282. $doc = new DOMDocument('1.0', 'utf-8');
  283. $doc->formatOutput = true;
  284. $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
  285. $relocate = $doc->createElement("dfrn:relocate");
  286. xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
  287. xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
  288. xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
  289. xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
  290. xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
  291. xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
  292. xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
  293. xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
  294. xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
  295. xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
  296. xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
  297. xml::add_element($doc, $relocate, "dfrn:sitepubkey", get_config('system','site_pubkey'));
  298. $root->appendChild($relocate);
  299. return(trim($doc->saveXML()));
  300. }
  301. /**
  302. * @brief Adds the header elements for the DFRN protocol
  303. *
  304. * @param object $doc XML document
  305. * @param array $owner Owner record
  306. * @param string $authorelement Element name for the author
  307. * @param string $alternatelink link to profile or category
  308. * @param bool $public Is it a header for public posts?
  309. *
  310. * @return object XML root object
  311. */
  312. private function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
  313. if ($alternatelink == "")
  314. $alternatelink = $owner['url'];
  315. $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
  316. $doc->appendChild($root);
  317. $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
  318. $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
  319. $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
  320. $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
  321. $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
  322. $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
  323. $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
  324. $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
  325. $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
  326. xml::add_element($doc, $root, "id", app::get_baseurl()."/profile/".$owner["nick"]);
  327. xml::add_element($doc, $root, "title", $owner["name"]);
  328. $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
  329. xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
  330. $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
  331. xml::add_element($doc, $root, "link", "", $attributes);
  332. $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
  333. xml::add_element($doc, $root, "link", "", $attributes);
  334. if ($public) {
  335. // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
  336. ostatus::hublinks($doc, $root);
  337. $attributes = array("rel" => "salmon", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
  338. xml::add_element($doc, $root, "link", "", $attributes);
  339. $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
  340. xml::add_element($doc, $root, "link", "", $attributes);
  341. $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => app::get_baseurl()."/salmon/".$owner["nick"]);
  342. xml::add_element($doc, $root, "link", "", $attributes);
  343. }
  344. // For backward compatibility we keep this element
  345. if ($owner['page-flags'] == PAGE_COMMUNITY)
  346. xml::add_element($doc, $root, "dfrn:community", 1);
  347. // The former element is replaced by this one
  348. xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
  349. /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
  350. xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
  351. $author = self::add_author($doc, $owner, $authorelement, $public);
  352. $root->appendChild($author);
  353. return $root;
  354. }
  355. /**
  356. * @brief Adds the author element in the header for the DFRN protocol
  357. *
  358. * @param object $doc XML document
  359. * @param array $owner Owner record
  360. * @param string $authorelement Element name for the author
  361. *
  362. * @return object XML author object
  363. */
  364. private function add_author($doc, $owner, $authorelement, $public) {
  365. // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
  366. $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
  367. WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
  368. intval($owner['uid']));
  369. if ($r)
  370. $hidewall = true;
  371. else
  372. $hidewall = false;
  373. $author = $doc->createElement($authorelement);
  374. $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
  375. $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
  376. $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
  377. if (!$public OR !$hidewall)
  378. $attributes = array("dfrn:updated" => $namdate);
  379. else
  380. $attributes = array();
  381. xml::add_element($doc, $author, "name", $owner["name"], $attributes);
  382. xml::add_element($doc, $author, "uri", app::get_baseurl().'/profile/'.$owner["nickname"], $attributes);
  383. xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
  384. $attributes = array("rel" => "photo", "type" => "image/jpeg",
  385. "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
  386. if (!$public OR !$hidewall)
  387. $attributes["dfrn:updated"] = $picdate;
  388. xml::add_element($doc, $author, "link", "", $attributes);
  389. $attributes["rel"] = "avatar";
  390. xml::add_element($doc, $author, "link", "", $attributes);
  391. if ($hidewall)
  392. xml::add_element($doc, $author, "dfrn:hide", "true");
  393. // The following fields will only be generated if the data isn't meant for a public feed
  394. if ($public)
  395. return $author;
  396. $birthday = feed_birthday($owner['uid'], $owner['timezone']);
  397. if ($birthday)
  398. xml::add_element($doc, $author, "dfrn:birthday", $birthday);
  399. // Only show contact details when we are allowed to
  400. $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
  401. `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
  402. `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
  403. FROM `profile`
  404. INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
  405. WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
  406. intval($owner['uid']));
  407. if ($r) {
  408. $profile = $r[0];
  409. xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
  410. xml::add_element($doc, $author, "poco:updated", $namdate);
  411. if (trim($profile["dob"]) != "0000-00-00")
  412. xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
  413. xml::add_element($doc, $author, "poco:note", $profile["about"]);
  414. xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
  415. $savetz = date_default_timezone_get();
  416. date_default_timezone_set($profile["timezone"]);
  417. xml::add_element($doc, $author, "poco:utcOffset", date("P"));
  418. date_default_timezone_set($savetz);
  419. if (trim($profile["homepage"]) != "") {
  420. $urls = $doc->createElement("poco:urls");
  421. xml::add_element($doc, $urls, "poco:type", "homepage");
  422. xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
  423. xml::add_element($doc, $urls, "poco:primary", "true");
  424. $author->appendChild($urls);
  425. }
  426. if (trim($profile["pub_keywords"]) != "") {
  427. $keywords = explode(",", $profile["pub_keywords"]);
  428. foreach ($keywords AS $keyword)
  429. xml::add_element($doc, $author, "poco:tags", trim($keyword));
  430. }
  431. if (trim($profile["xmpp"]) != "") {
  432. $ims = $doc->createElement("poco:ims");
  433. xml::add_element($doc, $ims, "poco:type", "xmpp");
  434. xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
  435. xml::add_element($doc, $ims, "poco:primary", "true");
  436. $author->appendChild($ims);
  437. }
  438. if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
  439. $element = $doc->createElement("poco:address");
  440. xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
  441. if (trim($profile["locality"]) != "")
  442. xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
  443. if (trim($profile["region"]) != "")
  444. xml::add_element($doc, $element, "poco:region", $profile["region"]);
  445. if (trim($profile["country-name"]) != "")
  446. xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
  447. $author->appendChild($element);
  448. }
  449. }
  450. return $author;
  451. }
  452. /**
  453. * @brief Adds the author elements in the "entry" elements of the DFRN protocol
  454. *
  455. * @param object $doc XML document
  456. * @param string $element Element name for the author
  457. * @param string $contact_url Link of the contact
  458. * @param array $items Item elements
  459. *
  460. * @return object XML author object
  461. */
  462. private function add_entry_author($doc, $element, $contact_url, $item) {
  463. $contact = get_contact_details_by_url($contact_url, $item["uid"]);
  464. $author = $doc->createElement($element);
  465. xml::add_element($doc, $author, "name", $contact["name"]);
  466. xml::add_element($doc, $author, "uri", $contact["url"]);
  467. xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
  468. /// @Todo
  469. /// - Check real image type and image size
  470. /// - Check which of these boths elements we should use
  471. $attributes = array(
  472. "rel" => "photo",
  473. "type" => "image/jpeg",
  474. "media:width" => 80,
  475. "media:height" => 80,
  476. "href" => $contact["photo"]);
  477. xml::add_element($doc, $author, "link", "", $attributes);
  478. $attributes = array(
  479. "rel" => "avatar",
  480. "type" => "image/jpeg",
  481. "media:width" => 80,
  482. "media:height" => 80,
  483. "href" => $contact["photo"]);
  484. xml::add_element($doc, $author, "link", "", $attributes);
  485. return $author;
  486. }
  487. /**
  488. * @brief Adds the activity elements
  489. *
  490. * @param object $doc XML document
  491. * @param string $element Element name for the activity
  492. * @param string $activity activity value
  493. *
  494. * @return object XML activity object
  495. */
  496. private function create_activity($doc, $element, $activity) {
  497. if($activity) {
  498. $entry = $doc->createElement($element);
  499. $r = parse_xml_string($activity, false);
  500. if(!$r)
  501. return false;
  502. if($r->type)
  503. xml::add_element($doc, $entry, "activity:object-type", $r->type);
  504. if($r->id)
  505. xml::add_element($doc, $entry, "id", $r->id);
  506. if($r->title)
  507. xml::add_element($doc, $entry, "title", $r->title);
  508. if($r->link) {
  509. if(substr($r->link,0,1) == '<') {
  510. if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
  511. $r->link = str_replace('&','&amp;', $r->link);
  512. $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
  513. // XML does need a single element as root element so we add a dummy element here
  514. $data = parse_xml_string("<dummy>".$r->link."</dummy>", false);
  515. if (is_object($data)) {
  516. foreach ($data->link AS $link) {
  517. $attributes = array();
  518. foreach ($link->attributes() AS $parameter => $value)
  519. $attributes[$parameter] = $value;
  520. xml::add_element($doc, $entry, "link", "", $attributes);
  521. }
  522. }
  523. } else {
  524. $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
  525. xml::add_element($doc, $entry, "link", "", $attributes);
  526. }
  527. }
  528. if($r->content)
  529. xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
  530. return $entry;
  531. }
  532. return false;
  533. }
  534. /**
  535. * @brief Adds the elements for attachments
  536. *
  537. * @param object $doc XML document
  538. * @param object $root XML root
  539. * @param array $item Item element
  540. *
  541. * @return object XML attachment object
  542. */
  543. private function get_attachment($doc, $root, $item) {
  544. $arr = explode('[/attach],',$item['attach']);
  545. if(count($arr)) {
  546. foreach($arr as $r) {
  547. $matches = false;
  548. $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
  549. if($cnt) {
  550. $attributes = array("rel" => "enclosure",
  551. "href" => $matches[1],
  552. "type" => $matches[3]);
  553. if(intval($matches[2]))
  554. $attributes["length"] = intval($matches[2]);
  555. if(trim($matches[4]) != "")
  556. $attributes["title"] = trim($matches[4]);
  557. xml::add_element($doc, $root, "link", "", $attributes);
  558. }
  559. }
  560. }
  561. }
  562. /**
  563. * @brief Adds the "entry" elements for the DFRN protocol
  564. *
  565. * @param object $doc XML document
  566. * @param string $type "text" or "html"
  567. * @param array $item Item element
  568. * @param array $owner Owner record
  569. * @param bool $comment Trigger the sending of the "comment" element
  570. * @param int $cid Contact ID of the recipient
  571. *
  572. * @return object XML entry object
  573. */
  574. private function entry($doc, $type, $item, $owner, $comment = false, $cid = 0) {
  575. $mentioned = array();
  576. if(!$item['parent'])
  577. return;
  578. if($item['deleted']) {
  579. $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
  580. return xml::create_element($doc, "at:deleted-entry", "", $attributes);
  581. }
  582. $entry = $doc->createElement("entry");
  583. if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
  584. $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
  585. else
  586. $body = $item['body'];
  587. // Remove the abstract element. It is only locally important.
  588. $body = remove_abstract($body);
  589. if ($type == 'html') {
  590. $htmlbody = $body;
  591. if ($item['title'] != "")
  592. $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
  593. $htmlbody = bbcode($htmlbody, false, false, 7);
  594. }
  595. $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
  596. $entry->appendChild($author);
  597. $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
  598. $entry->appendChild($dfrnowner);
  599. if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
  600. $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
  601. $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
  602. $attributes = array("ref" => $parent_item, "type" => "text/html",
  603. "href" => app::get_baseurl().'/display/'.$parent[0]['guid'],
  604. "dfrn:diaspora_guid" => $parent[0]['guid']);
  605. xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
  606. }
  607. xml::add_element($doc, $entry, "id", $item["uri"]);
  608. xml::add_element($doc, $entry, "title", $item["title"]);
  609. xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
  610. xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
  611. // "dfrn:env" is used to read the content
  612. xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
  613. // The "content" field is not read by the receiver. We could remove it when the type is "text"
  614. // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
  615. xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
  616. // We save this value in "plink". Maybe we should read it from there as well?
  617. xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
  618. "href" => app::get_baseurl()."/display/".$item["guid"]));
  619. // "comment-allow" is some old fashioned stuff for old Friendica versions.
  620. // It is included in the rewritten code for completeness
  621. if ($comment)
  622. xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
  623. if($item['location'])
  624. xml::add_element($doc, $entry, "dfrn:location", $item['location']);
  625. if($item['coord'])
  626. xml::add_element($doc, $entry, "georss:point", $item['coord']);
  627. if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
  628. xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
  629. if($item['extid'])
  630. xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
  631. if($item['bookmark'])
  632. xml::add_element($doc, $entry, "dfrn:bookmark", "true");
  633. if($item['app'])
  634. xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
  635. xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
  636. // The signed text contains the content in Markdown, the sender handle and the signatur for the content
  637. // It is needed for relayed comments to Diaspora.
  638. if($item['signed_text']) {
  639. $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
  640. xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
  641. }
  642. xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
  643. if ($item['object-type'] != "")
  644. xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
  645. elseif ($item['id'] == $item['parent'])
  646. xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
  647. else
  648. xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
  649. $actobj = self::create_activity($doc, "activity:object", $item['object']);
  650. if ($actobj)
  651. $entry->appendChild($actobj);
  652. $actarg = self::create_activity($doc, "activity:target", $item['target']);
  653. if ($actarg)
  654. $entry->appendChild($actarg);
  655. $tags = item_getfeedtags($item);
  656. if(count($tags)) {
  657. foreach($tags as $t)
  658. if (($type != 'html') OR ($t[0] != "@"))
  659. xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
  660. }
  661. if(count($tags))
  662. foreach($tags as $t)
  663. if ($t[0] == "@")
  664. $mentioned[$t[1]] = $t[1];
  665. foreach ($mentioned AS $mention) {
  666. $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
  667. intval($owner["uid"]),
  668. dbesc(normalise_link($mention)));
  669. if ($r[0]["forum"] OR $r[0]["prv"])
  670. xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
  671. "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
  672. "href" => $mention));
  673. else
  674. xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
  675. "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
  676. "href" => $mention));
  677. }
  678. self::get_attachment($doc, $entry, $item);
  679. return $entry;
  680. }
  681. /**
  682. * @brief Delivers the atom content to the contacts
  683. *
  684. * @param array $owner Owner record
  685. * @param array $contactr Contact record of the receiver
  686. * @param string $atom Content that will be transmitted
  687. * @param bool $dissolve (to be documented)
  688. *
  689. * @return int Deliver status. -1 means an error.
  690. */
  691. public static function deliver($owner,$contact,$atom, $dissolve = false) {
  692. $a = get_app();
  693. $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
  694. if($contact['duplex'] && $contact['dfrn-id'])
  695. $idtosend = '0:' . $orig_id;
  696. if($contact['duplex'] && $contact['issued-id'])
  697. $idtosend = '1:' . $orig_id;
  698. $rino = get_config('system','rino_encrypt');
  699. $rino = intval($rino);
  700. // use RINO1 if mcrypt isn't installed and RINO2 was selected
  701. if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
  702. logger("Local rino version: ". $rino, LOGGER_DEBUG);
  703. $ssl_val = intval(get_config('system','ssl_policy'));
  704. $ssl_policy = '';
  705. switch($ssl_val){
  706. case SSL_POLICY_FULL:
  707. $ssl_policy = 'full';
  708. break;
  709. case SSL_POLICY_SELFSIGN:
  710. $ssl_policy = 'self';
  711. break;
  712. case SSL_POLICY_NONE:
  713. default:
  714. $ssl_policy = 'none';
  715. break;
  716. }
  717. $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
  718. logger('dfrn_deliver: ' . $url);
  719. $xml = fetch_url($url);
  720. $curl_stat = $a->get_curl_code();
  721. if(! $curl_stat)
  722. return(-1); // timed out
  723. logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
  724. if(! $xml)
  725. return 3;
  726. if(strpos($xml,'<?xml') === false) {
  727. logger('dfrn_deliver: no valid XML returned');
  728. logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
  729. return 3;
  730. }
  731. $res = parse_xml_string($xml);
  732. if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
  733. return (($res->status) ? $res->status : 3);
  734. $postvars = array();
  735. $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
  736. $challenge = hex2bin((string) $res->challenge);
  737. $perm = (($res->perm) ? $res->perm : null);
  738. $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
  739. $rino_remote_version = intval($res->rino);
  740. $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
  741. logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
  742. if($owner['page-flags'] == PAGE_PRVGROUP)
  743. $page = 2;
  744. $final_dfrn_id = '';
  745. if($perm) {
  746. if((($perm == 'rw') && (! intval($contact['writable'])))
  747. || (($perm == 'r') && (intval($contact['writable'])))) {
  748. q("update contact set writable = %d where id = %d",
  749. intval(($perm == 'rw') ? 1 : 0),
  750. intval($contact['id'])
  751. );
  752. $contact['writable'] = (string) 1 - intval($contact['writable']);
  753. }
  754. }
  755. if(($contact['duplex'] && strlen($contact['pubkey']))
  756. || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
  757. || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
  758. openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
  759. openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
  760. } else {
  761. openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
  762. openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
  763. }
  764. $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
  765. if(strpos($final_dfrn_id,':') == 1)
  766. $final_dfrn_id = substr($final_dfrn_id,2);
  767. if($final_dfrn_id != $orig_id) {
  768. logger('dfrn_deliver: wrong dfrn_id.');
  769. // did not decode properly - cannot trust this site
  770. return 3;
  771. }
  772. $postvars['dfrn_id'] = $idtosend;
  773. $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
  774. if($dissolve)
  775. $postvars['dissolve'] = '1';
  776. if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
  777. $postvars['data'] = $atom;
  778. $postvars['perm'] = 'rw';
  779. } else {
  780. $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
  781. $postvars['perm'] = 'r';
  782. }
  783. $postvars['ssl_policy'] = $ssl_policy;
  784. if($page)
  785. $postvars['page'] = $page;
  786. if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
  787. logger('rino version: '. $rino_remote_version);
  788. switch($rino_remote_version) {
  789. case 1:
  790. // Deprecated rino version!
  791. $key = substr(random_string(),0,16);
  792. $data = aes_encrypt($postvars['data'],$key);
  793. break;
  794. case 2:
  795. // RINO 2 based on php-encryption
  796. try {
  797. $key = Crypto::createNewRandomKey();
  798. } catch (CryptoTestFailed $ex) {
  799. logger('Cannot safely create a key');
  800. return -1;
  801. } catch (CannotPerformOperation $ex) {
  802. logger('Cannot safely create a key');
  803. return -1;
  804. }
  805. try {
  806. $data = Crypto::encrypt($postvars['data'], $key);
  807. } catch (CryptoTestFailed $ex) {
  808. logger('Cannot safely perform encryption');
  809. return -1;
  810. } catch (CannotPerformOperation $ex) {
  811. logger('Cannot safely perform encryption');
  812. return -1;
  813. }
  814. break;
  815. default:
  816. logger("rino: invalid requested verision '$rino_remote_version'");
  817. return -1;
  818. }
  819. $postvars['rino'] = $rino_remote_version;
  820. $postvars['data'] = bin2hex($data);
  821. #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
  822. if($dfrn_version >= 2.1) {
  823. if(($contact['duplex'] && strlen($contact['pubkey']))
  824. || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
  825. || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey'])))
  826. openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
  827. else
  828. openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
  829. } else {
  830. if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY))
  831. openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
  832. else
  833. openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
  834. }
  835. logger('md5 rawkey ' . md5($postvars['key']));
  836. $postvars['key'] = bin2hex($postvars['key']);
  837. }
  838. logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
  839. $xml = post_url($contact['notify'],$postvars);
  840. logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
  841. $curl_stat = $a->get_curl_code();
  842. if((! $curl_stat) || (! strlen($xml)))
  843. return(-1); // timed out
  844. if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
  845. return(-1);
  846. if(strpos($xml,'<?xml') === false) {
  847. logger('dfrn_deliver: phase 2: no valid XML returned');
  848. logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
  849. return 3;
  850. }
  851. if($contact['term-date'] != '0000-00-00 00:00:00') {
  852. logger("dfrn_deliver: $url back from the dead - removing mark for death");
  853. require_once('include/Contact.php');
  854. unmark_for_death($contact);
  855. }
  856. $res = parse_xml_string($xml);
  857. return $res->status;
  858. }
  859. /**
  860. * @brief Add new birthday event for this person
  861. *
  862. * @param array $contact Contact record
  863. * @param string $birthday Birthday of the contact
  864. *
  865. */
  866. private function birthday_event($contact, $birthday) {
  867. logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
  868. $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
  869. $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
  870. $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
  871. VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
  872. intval($contact["uid"]),
  873. intval($contact["id"]),
  874. dbesc(datetime_convert()),
  875. dbesc(datetime_convert()),
  876. dbesc(datetime_convert("UTC","UTC", $birthday)),
  877. dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
  878. dbesc($bdtext),
  879. dbesc($bdtext2),
  880. dbesc("birthday")
  881. );
  882. }
  883. /**
  884. * @brief Fetch the author data from head or entry items
  885. *
  886. * @param object $xpath XPath object
  887. * @param object $context In which context should the data be searched
  888. * @param array $importer Record of the importer user mixed with contact of the content
  889. * @param string $element Element name from which the data is fetched
  890. * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
  891. *
  892. * @return Returns an array with relevant data of the author
  893. */
  894. private function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
  895. $author = array();
  896. $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
  897. $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
  898. $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
  899. `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
  900. FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
  901. intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
  902. if ($r) {
  903. $contact = $r[0];
  904. $author["contact-id"] = $r[0]["id"];
  905. $author["network"] = $r[0]["network"];
  906. } else {
  907. if (!$onlyfetch)
  908. logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
  909. $author["contact-id"] = $importer["id"];
  910. $author["network"] = $importer["network"];
  911. $onlyfetch = true;
  912. }
  913. // Until now we aren't serving different sizes - but maybe later
  914. $avatarlist = array();
  915. // @todo check if "avatar" or "photo" would be the best field in the specification
  916. $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
  917. foreach($avatars AS $avatar) {
  918. $href = "";
  919. $width = 0;
  920. foreach($avatar->attributes AS $attributes) {
  921. if ($attributes->name == "href")
  922. $href = $attributes->textContent;
  923. if ($attributes->name == "width")
  924. $width = $attributes->textContent;
  925. if ($attributes->name == "updated")
  926. $contact["avatar-date"] = $attributes->textContent;
  927. }
  928. if (($width > 0) AND ($href != ""))
  929. $avatarlist[$width] = $href;
  930. }
  931. if (count($avatarlist) > 0) {
  932. krsort($avatarlist);
  933. $author["avatar"] = current($avatarlist);
  934. }
  935. if ($r AND !$onlyfetch) {
  936. logger("Check if contact details for contact ".$r[0]["id"]." (".$r[0]["nick"].") have to be updated.", LOGGER_DEBUG);
  937. $poco = array("url" => $contact["url"]);
  938. // When was the last change to name or uri?
  939. $name_element = $xpath->query($element."/atom:name", $context)->item(0);
  940. foreach($name_element->attributes AS $attributes)
  941. if ($attributes->name == "updated")
  942. $poco["name-date"] = $attributes->textContent;
  943. $link_element = $xpath->query($element."/atom:link", $context)->item(0);
  944. foreach($link_element->attributes AS $attributes)
  945. if ($attributes->name == "updated")
  946. $poco["uri-date"] = $attributes->textContent;
  947. // Update contact data
  948. $value = $xpath->evaluate($element."/dfrn:handle/text()", $context)->item(0)->nodeValue;
  949. if ($value != "")
  950. $poco["addr"] = $value;
  951. $value = $xpath->evaluate($element."/poco:displayName/text()", $context)->item(0)->nodeValue;
  952. if ($value != "")
  953. $poco["name"] = $value;
  954. $value = $xpath->evaluate($element."/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
  955. if ($value != "")
  956. $poco["nick"] = $value;
  957. $value = $xpath->evaluate($element."/poco:note/text()", $context)->item(0)->nodeValue;
  958. if ($value != "")
  959. $poco["about"] = $value;
  960. $value = $xpath->evaluate($element."/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
  961. if ($value != "")
  962. $poco["location"] = $value;
  963. /// @todo Only search for elements with "poco:type" = "xmpp"
  964. $value = $xpath->evaluate($element."/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
  965. if ($value != "")
  966. $poco["xmpp"] = $value;
  967. /// @todo Add support for the following fields that we don't support by now in the contact table:
  968. /// - poco:utcOffset
  969. /// - poco:urls
  970. /// - poco:locality
  971. /// - poco:region
  972. /// - poco:country
  973. // If the "hide" element is present then the profile isn't searchable.
  974. $hide = intval($xpath->evaluate($element."/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
  975. logger("Hidden status for contact ".$contact["url"].": ".$hide, LOGGER_DEBUG);
  976. // If the contact isn't searchable then set the contact to "hidden".
  977. // Problem: This can be manually overridden by the user.
  978. if ($hide)
  979. $contact["hidden"] = true;
  980. // Save the keywords into the contact table
  981. $tags = array();
  982. $tagelements = $xpath->evaluate($element."/poco:tags/text()", $context);
  983. foreach($tagelements AS $tag)
  984. $tags[$tag->nodeValue] = $tag->nodeValue;
  985. if (count($tags))
  986. $poco["keywords"] = implode(", ", $tags);
  987. // "dfrn:birthday" contains the birthday converted to UTC
  988. $old_bdyear = $contact["bdyear"];
  989. $birthday = $xpath->evaluate($element."/dfrn:birthday/text()", $context)->item(0)->nodeValue;
  990. if (strtotime($birthday) > time()) {
  991. $bd_timestamp = strtotime($birthday);
  992. $poco["bdyear"] = date("Y", $bd_timestamp);
  993. }
  994. // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
  995. $value = $xpath->evaluate($element."/poco:birthday/text()", $context)->item(0)->nodeValue;
  996. if (!in_array($value, array("", "0000-00-00"))) {
  997. $bdyear = date("Y");
  998. $value = str_replace("0000", $bdyear, $value);
  999. if (strtotime($value) < time()) {
  1000. $value = str_replace($bdyear, $bdyear + 1, $value);
  1001. $bdyear = $bdyear + 1;
  1002. }
  1003. $poco["bd"] = $value;
  1004. }
  1005. $contact = array_merge($contact, $poco);
  1006. if ($old_bdyear != $contact["bdyear"])
  1007. self::birthday_event($contact, $birthday);
  1008. // Get all field names
  1009. $fields = array();
  1010. foreach ($r[0] AS $field => $data)
  1011. $fields[$field] = $data;
  1012. unset($fields["id"]);
  1013. unset($fields["uid"]);
  1014. unset($fields["url"]);
  1015. unset($fields["avatar-date"]);
  1016. unset($fields["name-date"]);
  1017. unset($fields["uri-date"]);
  1018. // Update check for this field has to be done differently
  1019. $datefields = array("name-date", "uri-date");
  1020. foreach ($datefields AS $field)
  1021. if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
  1022. logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
  1023. $update = true;
  1024. }
  1025. foreach ($fields AS $field => $data)
  1026. if ($contact[$field] != $r[0][$field]) {
  1027. logger("Difference for contact ".$contact["id"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$r[0][$field]."'", LOGGER_DEBUG);
  1028. $update = true;
  1029. }
  1030. if ($update) {
  1031. logger("Update contact data for contact ".$contact["id"]." (".$contact["nick"].")", LOGGER_DEBUG);
  1032. q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
  1033. `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
  1034. `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
  1035. WHERE `id` = %d AND `network` = '%s'",
  1036. dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
  1037. dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
  1038. dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
  1039. dbesc($contact["name-date"]), dbesc($contact["uri-date"]),
  1040. intval($contact["id"]), dbesc($contact["network"]));
  1041. }
  1042. update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
  1043. (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
  1044. // The generation is a sign for the reliability of the provided data.
  1045. // It is used in the socgraph.php to prevent that old contact data
  1046. // that was relayed over several servers can overwrite contact
  1047. // data that we received directly.
  1048. $poco["generation"] = 2;
  1049. $poco["photo"] = $author["avatar"];
  1050. $poco["hide"] = $hide;
  1051. $poco["contact-type"] = $contact["contact-type"];
  1052. update_gcontact($poco);
  1053. }
  1054. return($author);
  1055. }
  1056. /**
  1057. * @brief Transforms activity objects into an XML string
  1058. *
  1059. * @param object $xpath XPath object
  1060. * @param object $activity Activity object
  1061. * @param text $element element name
  1062. *
  1063. * @return string XML string
  1064. */
  1065. private function transform_activity($xpath, $activity, $element) {
  1066. if (!is_object($activity))
  1067. return "";
  1068. $obj_doc = new DOMDocument("1.0", "utf-8");
  1069. $obj_doc->formatOutput = true;
  1070. $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
  1071. $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
  1072. xml::add_element($obj_doc, $obj_element, "type", $activity_type);
  1073. $id = $xpath->query("atom:id", $activity)->item(0);
  1074. if (is_object($id))
  1075. $obj_element->appendChild($obj_doc->importNode($id, true));
  1076. $title = $xpath->query("atom:title", $activity)->item(0);
  1077. if (is_object($title))
  1078. $obj_element->appendChild($obj_doc->importNode($title, true));
  1079. $links = $xpath->query("atom:link", $activity);
  1080. if (is_object($links))
  1081. foreach ($links AS $link)
  1082. $obj_element->appendChild($obj_doc->importNode($link, true));
  1083. $content = $xpath->query("atom:content", $activity)->item(0);
  1084. if (is_object($content))
  1085. $obj_element->appendChild($obj_doc->importNode($content, true));
  1086. $obj_doc->appendChild($obj_element);
  1087. $objxml = $obj_doc->saveXML($obj_element);
  1088. // @todo This isn't totally clean. We should find a way to transform the namespaces
  1089. $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
  1090. return($objxml);
  1091. }
  1092. /**
  1093. * @brief Processes the mail elements
  1094. *
  1095. * @param object $xpath XPath object
  1096. * @param object $mail mail elements
  1097. * @param array $importer Record of the importer user mixed with contact of the content
  1098. */
  1099. private function process_mail($xpath, $mail, $importer) {
  1100. logger("Processing mails");
  1101. $msg = array();
  1102. $msg["uid"] = $importer["importer_uid"];
  1103. $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
  1104. $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
  1105. $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
  1106. $msg["contact-id"] = $importer["id"];
  1107. $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
  1108. $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
  1109. $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
  1110. $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
  1111. $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
  1112. $msg["seen"] = 0;
  1113. $msg["replied"] = 0;
  1114. dbesc_array($msg);
  1115. $r = dbq("INSERT INTO `mail` (`".implode("`, `", array_keys($msg))."`) VALUES ('".implode("', '", array_values($msg))."')");
  1116. // send notifications.
  1117. $notif_params = array(
  1118. "type" => NOTIFY_MAIL,
  1119. "notify_flags" => $importer["notify-flags"],
  1120. "language" => $importer["language"],
  1121. "to_name" => $importer["username"],
  1122. "to_email" => $importer["email"],
  1123. "uid" => $importer["importer_uid"],
  1124. "item" => $msg,
  1125. "source_name" => $msg["from-name"],
  1126. "source_link" => $importer["url"],
  1127. "source_photo" => $importer["thumb"],
  1128. "verb" => ACTIVITY_POST,
  1129. "otype" => "mail"
  1130. );
  1131. notification($notif_params);
  1132. logger("Mail is processed, notification was sent.");
  1133. }
  1134. /**
  1135. * @brief Processes the suggestion elements
  1136. *
  1137. * @param object $xpath XPath object
  1138. * @param object $suggestion suggestion elements
  1139. * @param array $importer Record of the importer user mixed with contact of the content
  1140. */
  1141. private function process_suggestion($xpath, $suggestion, $importer) {
  1142. $a = get_app();
  1143. logger("Processing suggestions");
  1144. $suggest = array();
  1145. $suggest["uid"] = $importer["importer_uid"];
  1146. $suggest["cid"] = $importer["id"];
  1147. $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
  1148. $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
  1149. $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
  1150. $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
  1151. $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
  1152. // Does our member already have a friend matching this description?
  1153. $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
  1154. dbesc($suggest["name"]),
  1155. dbesc(normalise_link($suggest["url"])),
  1156. intval($suggest["uid"])
  1157. );
  1158. if(count($r))
  1159. return false;
  1160. // Do we already have an fcontact record for this person?
  1161. $fid = 0;
  1162. $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
  1163. dbesc($suggest["url"]),
  1164. dbesc($suggest["name"]),
  1165. dbesc($suggest["request"])
  1166. );
  1167. if(count($r)) {
  1168. $fid = $r[0]["id"];
  1169. // OK, we do. Do we already have an introduction for this person ?
  1170. $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
  1171. intval($suggest["uid"]),
  1172. intval($fid)
  1173. );
  1174. if(count($r))
  1175. return false;
  1176. }
  1177. if(!$fid)
  1178. $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
  1179. dbesc($suggest["name"]),
  1180. dbesc($suggest["url"]),
  1181. dbesc($suggest["photo"]),
  1182. dbesc($suggest["request"])
  1183. );
  1184. $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
  1185. dbesc($suggest["url"]),
  1186. dbesc($suggest["name"]),
  1187. dbesc($suggest["request"])
  1188. );
  1189. if(count($r))
  1190. $fid = $r[0]["id"];
  1191. else
  1192. // database record did not get created. Quietly give up.
  1193. return false;
  1194. $hash = random_string();
  1195. $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
  1196. VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
  1197. intval($suggest["uid"]),
  1198. intval($fid),
  1199. intval($suggest["cid"]),
  1200. dbesc($suggest["body"]),
  1201. dbesc($hash),
  1202. dbesc(datetime_convert()),
  1203. intval(0)
  1204. );
  1205. notification(array(
  1206. "type" => NOTIFY_SUGGEST,
  1207. "notify_flags" => $importer["notify-flags"],
  1208. "language" => $importer["language"],
  1209. "to_name" => $importer["username"],
  1210. "to_email" => $importer["email"],
  1211. "uid" => $importer["importer_uid"],
  1212. "item" => $suggest,
  1213. "link" => $a->get_baseurl()."/notifications/intros",
  1214. "source_name" => $importer["name"],
  1215. "source_link" => $importer["url"],
  1216. "source_photo" => $importer["photo"],
  1217. "verb" => ACTIVITY_REQ_FRIEND,
  1218. "otype" => "intro"
  1219. ));
  1220. return true;
  1221. }
  1222. /**
  1223. * @brief Processes the relocation elements
  1224. *
  1225. * @param object $xpath XPath object
  1226. * @param object $relocation relocation elements
  1227. * @param array $importer Record of the importer user mixed with contact of the content
  1228. */
  1229. private function process_relocation($xpath, $relocation, $importer) {
  1230. logger("Processing relocations");
  1231. $relocate = array();
  1232. $relocate["uid"] = $importer["importer_uid"];
  1233. $relocate["cid"] = $importer["id"];
  1234. $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
  1235. $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
  1236. $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
  1237. $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
  1238. $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
  1239. $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
  1240. $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
  1241. $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
  1242. $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
  1243. $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
  1244. $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
  1245. $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
  1246. if (($relocate["avatar"] == "") AND ($relocate["photo"] != ""))
  1247. $relocate["avatar"] = $relocate["photo"];
  1248. if ($relocate["addr"] == "")
  1249. $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
  1250. // update contact
  1251. $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
  1252. intval($importer["id"]),
  1253. intval($importer["importer_uid"]));
  1254. if (!$r)
  1255. return false;
  1256. $old = $r[0];
  1257. // Update the gcontact entry
  1258. $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
  1259. $x = q("UPDATE `gcontact` SET
  1260. `name` = '%s',
  1261. `photo` = '%s',
  1262. `url` = '%s',
  1263. `nurl` = '%s',
  1264. `addr` = '%s',
  1265. `connect` = '%s',
  1266. `notify` = '%s',
  1267. `server_url` = '%s'
  1268. WHERE `nurl` = '%s';",
  1269. dbesc($relocate["name"]),
  1270. dbesc($relocate["avatar"]),
  1271. dbesc($relocate["url"]),
  1272. dbesc(normalise_link($relocate["url"])),
  1273. dbesc($relocate["addr"]),
  1274. dbesc($relocate["addr"]),
  1275. dbesc($relocate["notify"]),
  1276. dbesc($relocate["server_url"]),
  1277. dbesc(normalise_link($old["url"])));
  1278. // Update the contact table. We try to find every entry.
  1279. $x = q("UPDATE `contact` SET
  1280. `name` = '%s',
  1281. `avatar` = '%s',
  1282. `url` = '%s',
  1283. `nurl` = '%s',
  1284. `addr` = '%s',
  1285. `request` = '%s',
  1286. `confirm` = '%s',
  1287. `notify` = '%s',
  1288. `poll` = '%s',
  1289. `site-pubkey` = '%s'
  1290. WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
  1291. dbesc($relocate["name"]),
  1292. dbesc($relocate["avatar"]),
  1293. dbesc($relocate["url"]),
  1294. dbesc(normalise_link($relocate["url"])),
  1295. dbesc($relocate["addr"]),
  1296. dbesc($relocate["request"]),
  1297. dbesc($relocate["confirm"]),
  1298. dbesc($relocate["notify"]),
  1299. dbesc($relocate["poll"]),
  1300. dbesc($relocate["sitepubkey"]),
  1301. intval($importer["id"]),
  1302. intval($importer["importer_uid"]),
  1303. dbesc(normalise_link($old["url"])));
  1304. update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
  1305. if ($x === false)
  1306. return false;
  1307. // update items
  1308. /// @todo This is an extreme performance killer
  1309. $fields = array(
  1310. 'owner-link' => array($old["url"], $relocate["url"]),
  1311. 'author-link' => array($old["url"], $relocate["url"]),
  1312. //'owner-avatar' => array($old["photo"], $relocate["photo"]),
  1313. //'author-avatar' => array($old["photo"], $relocate["photo"]),
  1314. );
  1315. foreach ($fields as $n=>$f) {
  1316. $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
  1317. $n, dbesc($f[0]),
  1318. intval($importer["importer_uid"]));
  1319. if ($r) {
  1320. $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
  1321. $n, dbesc($f[1]),
  1322. $n, dbesc($f[0]),
  1323. intval($importer["importer_uid"]));
  1324. if ($x === false)
  1325. return false;
  1326. }
  1327. }
  1328. /// @TODO
  1329. /// merge with current record, current contents have priority
  1330. /// update record, set url-updated
  1331. /// update profile photos
  1332. /// schedule a scan?
  1333. return true;
  1334. }
  1335. /**
  1336. * @brief Updates an item
  1337. *
  1338. * @param array $current the current item record
  1339. * @param array $item the new item record
  1340. * @param array $importer Record of the importer user mixed with contact of the content
  1341. * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
  1342. */
  1343. private function update_content($current, $item, $importer, $entrytype) {
  1344. $changed = false;
  1345. if (edited_timestamp_is_newer($current, $item)) {
  1346. // do not accept (ignore) an earlier edit than one we currently have.
  1347. if(datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"])
  1348. return(false);
  1349. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
  1350. dbesc($item["title"]),
  1351. dbesc($item["body"]),
  1352. dbesc($item["tag"]),
  1353. dbesc(datetime_convert("UTC","UTC",$item["edited"])),
  1354. dbesc(datetime_convert()),
  1355. dbesc($item["uri"]),
  1356. intval($importer["importer_uid"])
  1357. );
  1358. create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
  1359. update_thread_uri($item["uri"], $importer["importer_uid"]);
  1360. $changed = true;
  1361. if ($entrytype == DFRN_REPLY_RC)
  1362. proc_run(PRIORITY_HIGH, "include/notifier.php","comment-import", $current["id"]);
  1363. }
  1364. // update last-child if it changes
  1365. if($item["last-child"] AND ($item["last-child"] != $current["last-child"])) {
  1366. $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
  1367. dbesc(datetime_convert()),
  1368. dbesc($item["parent-uri"]),
  1369. intval($importer["importer_uid"])
  1370. );
  1371. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
  1372. intval($item["last-child"]),
  1373. dbesc(datetime_convert()),
  1374. dbesc($item["uri"]),
  1375. intval($importer["importer_uid"])
  1376. );
  1377. }
  1378. return $changed;
  1379. }
  1380. /**
  1381. * @brief Detects the entry type of the item
  1382. *
  1383. * @param array $importer Record of the importer user mixed with contact of the content
  1384. * @param array $item the new item record
  1385. *
  1386. * @return int Is it a toplevel entry, a comment or a relayed comment?
  1387. */
  1388. private function get_entry_type($importer, $item) {
  1389. if ($item["parent-uri"] != $item["uri"]) {
  1390. $community = false;
  1391. if($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
  1392. $sql_extra = "";
  1393. $community = true;
  1394. logger("possible community action");
  1395. } else
  1396. $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
  1397. // was the top-level post for this action written by somebody on this site?
  1398. // Specifically, the recipient?
  1399. $is_a_remote_action = false;
  1400. $r = q("SELECT `item`.`parent-uri` FROM `item`
  1401. WHERE `item`.`uri` = '%s'
  1402. LIMIT 1",
  1403. dbesc($item["parent-uri"])
  1404. );
  1405. if($r && count($r)) {
  1406. $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
  1407. INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  1408. WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
  1409. AND `item`.`uid` = %d
  1410. $sql_extra
  1411. LIMIT 1",
  1412. dbesc($r[0]["parent-uri"]),
  1413. dbesc($r[0]["parent-uri"]),
  1414. dbesc($r[0]["parent-uri"]),
  1415. intval($importer["importer_uid"])
  1416. );
  1417. if($r && count($r))
  1418. $is_a_remote_action = true;
  1419. }
  1420. // Does this have the characteristics of a community or private group action?
  1421. // If it's an action to a wall post on a community/prvgroup page it's a
  1422. // valid community action. Also forum_mode makes it valid for sure.
  1423. // If neither, it's not.
  1424. if($is_a_remote_action && $community) {
  1425. if((!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
  1426. $is_a_remote_action = false;
  1427. logger("not a community action");
  1428. }
  1429. }
  1430. if ($is_a_remote_action)
  1431. return DFRN_REPLY_RC;
  1432. else
  1433. return DFRN_REPLY;
  1434. } else
  1435. return DFRN_TOP_LEVEL;
  1436. }
  1437. /**
  1438. * @brief Send a "poke"
  1439. *
  1440. * @param array $item the new item record
  1441. * @param array $importer Record of the importer user mixed with contact of the content
  1442. * @param int $posted_id The record number of item record that was just posted
  1443. */
  1444. private function do_poke($item, $importer, $posted_id) {
  1445. $a = get_app();
  1446. $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
  1447. if(!$verb)
  1448. return;
  1449. $xo = parse_xml_string($item["object"],false);
  1450. if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
  1451. // somebody was poked/prodded. Was it me?
  1452. foreach($xo->link as $l) {
  1453. $atts = $l->attributes();
  1454. switch($atts["rel"]) {
  1455. case "alternate":
  1456. $Blink = $atts["href"];
  1457. break;
  1458. default:
  1459. break;
  1460. }
  1461. }
  1462. if($Blink && link_compare($Blink,$a->get_baseurl()."/profile/".$importer["nickname"])) {
  1463. // send a notification
  1464. notification(array(
  1465. "type" => NOTIFY_POKE,
  1466. "notify_flags" => $importer["notify-flags"],
  1467. "language" => $importer["language"],
  1468. "to_name" => $importer["username"],
  1469. "to_email" => $importer["email"],
  1470. "uid" => $importer["importer_uid"],
  1471. "item" => $item,
  1472. "link" => $a->get_baseurl()."/display/".urlencode(get_item_guid($posted_id)),
  1473. "source_name" => stripslashes($item["author-name"]),
  1474. "source_link" => $item["author-link"],
  1475. "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
  1476. ? $importer["thumb"] : $item["author-avatar"]),
  1477. "verb" => $item["verb"],
  1478. "otype" => "person",
  1479. "activity" => $verb,
  1480. "parent" => $item["parent"]
  1481. ));
  1482. }
  1483. }
  1484. }
  1485. /**
  1486. * @brief Processes several actions, depending on the verb
  1487. *
  1488. * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
  1489. * @param array $importer Record of the importer user mixed with contact of the content
  1490. * @param array $item the new item record
  1491. * @param bool $is_like Is the verb a "like"?
  1492. *
  1493. * @return bool Should the processing of the entries be continued?
  1494. */
  1495. private function process_verbs($entrytype, $importer, &$item, &$is_like) {
  1496. logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
  1497. if (($entrytype == DFRN_TOP_LEVEL)) {
  1498. // The filling of the the "contact" variable is done for legcy reasons
  1499. // The functions below are partly used by ostatus.php as well - where we have this variable
  1500. $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
  1501. $contact = $r[0];
  1502. $nickname = $contact["nick"];
  1503. // Big question: Do we need these functions? They were part of the "consume_feed" function.
  1504. // This function once was responsible for DFRN and OStatus.
  1505. if(activity_match($item["verb"],ACTIVITY_FOLLOW)) {
  1506. logger("New follower");
  1507. new_follower($importer, $contact, $item, $nickname);
  1508. return false;
  1509. }
  1510. if(activity_match($item["verb"],ACTIVITY_UNFOLLOW)) {
  1511. logger("Lost follower");
  1512. lose_follower($importer, $contact, $item);
  1513. return false;
  1514. }
  1515. if(activity_match($item["verb"],ACTIVITY_REQ_FRIEND)) {
  1516. logger("New friend request");
  1517. new_follower($importer, $contact, $item, $nickname, true);
  1518. return false;
  1519. }
  1520. if(activity_match($item["verb"],ACTIVITY_UNFRIEND)) {
  1521. logger("Lost sharer");
  1522. lose_sharer($importer, $contact, $item);
  1523. return false;
  1524. }
  1525. } else {
  1526. if(($item["verb"] == ACTIVITY_LIKE)
  1527. || ($item["verb"] == ACTIVITY_DISLIKE)
  1528. || ($item["verb"] == ACTIVITY_ATTEND)
  1529. || ($item["verb"] == ACTIVITY_ATTENDNO)
  1530. || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
  1531. $is_like = true;
  1532. $item["type"] = "activity";
  1533. $item["gravity"] = GRAVITY_LIKE;
  1534. // only one like or dislike per person
  1535. // splitted into two queries for performance issues
  1536. $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",
  1537. intval($item["uid"]),
  1538. dbesc($item["author-link"]),
  1539. dbesc($item["verb"]),
  1540. dbesc($item["parent-uri"])
  1541. );
  1542. if($r && count($r))
  1543. return false;
  1544. $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",
  1545. intval($item["uid"]),
  1546. dbesc($item["author-link"]),
  1547. dbesc($item["verb"]),
  1548. dbesc($item["parent-uri"])
  1549. );
  1550. if($r && count($r))
  1551. return false;
  1552. } else
  1553. $is_like = false;
  1554. if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
  1555. $xo = parse_xml_string($item["object"],false);
  1556. $xt = parse_xml_string($item["target"],false);
  1557. if($xt->type == ACTIVITY_OBJ_NOTE) {
  1558. $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1559. dbesc($xt->id),
  1560. intval($importer["importer_uid"])
  1561. );
  1562. if(!count($r))
  1563. return false;
  1564. // extract tag, if not duplicate, add to parent item
  1565. if($xo->content) {
  1566. if(!(stristr($r[0]["tag"],trim($xo->content)))) {
  1567. q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
  1568. dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
  1569. intval($r[0]["id"])
  1570. );
  1571. create_tags_from_item($r[0]["id"]);
  1572. }
  1573. }
  1574. }
  1575. }
  1576. }
  1577. return true;
  1578. }
  1579. /**
  1580. * @brief Processes the link elements
  1581. *
  1582. * @param object $links link elements
  1583. * @param array $item the item record
  1584. */
  1585. private function parse_links($links, &$item) {
  1586. $rel = "";
  1587. $href = "";
  1588. $type = "";
  1589. $length = "0";
  1590. $title = "";
  1591. foreach ($links AS $link) {
  1592. foreach($link->attributes AS $attributes) {
  1593. if ($attributes->name == "href")
  1594. $href = $attributes->textContent;
  1595. if ($attributes->name == "rel")
  1596. $rel = $attributes->textContent;
  1597. if ($attributes->name == "type")
  1598. $type = $attributes->textContent;
  1599. if ($attributes->name == "length")
  1600. $length = $attributes->textContent;
  1601. if ($attributes->name == "title")
  1602. $title = $attributes->textContent;
  1603. }
  1604. if (($rel != "") AND ($href != ""))
  1605. switch($rel) {
  1606. case "alternate":
  1607. $item["plink"] = $href;
  1608. break;
  1609. case "enclosure":
  1610. $enclosure = $href;
  1611. if(strlen($item["attach"]))
  1612. $item["attach"] .= ",";
  1613. $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
  1614. break;
  1615. }
  1616. }
  1617. }
  1618. /**
  1619. * @brief Processes the entry elements which contain the items and comments
  1620. *
  1621. * @param array $header Array of the header elements that always stay the same
  1622. * @param object $xpath XPath object
  1623. * @param object $entry entry elements
  1624. * @param array $importer Record of the importer user mixed with contact of the content
  1625. */
  1626. private function process_entry($header, $xpath, $entry, $importer) {
  1627. logger("Processing entries");
  1628. $item = $header;
  1629. // Get the uri
  1630. $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
  1631. // Fetch the owner
  1632. $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
  1633. $item["owner-name"] = $owner["name"];
  1634. $item["owner-link"] = $owner["link"];
  1635. $item["owner-avatar"] = $owner["avatar"];
  1636. // fetch the author
  1637. $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
  1638. $item["author-name"] = $author["name"];
  1639. $item["author-link"] = $author["link"];
  1640. $item["author-avatar"] = $author["avatar"];
  1641. $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
  1642. $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
  1643. $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
  1644. $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
  1645. $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
  1646. // make sure nobody is trying to sneak some html tags by us
  1647. $item["body"] = notags(base64url_decode($item["body"]));
  1648. $item["body"] = limit_body_size($item["body"]);
  1649. /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
  1650. if((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
  1651. $item['body'] = reltoabs($item['body'],$base_url);
  1652. $item['body'] = html2bb_video($item['body']);
  1653. $item['body'] = oembed_html2bbcode($item['body']);
  1654. $config = HTMLPurifier_Config::createDefault();
  1655. $config->set('Cache.DefinitionImpl', null);
  1656. // we shouldn't need a whitelist, because the bbcode converter
  1657. // will strip out any unsupported tags.
  1658. $purifier = new HTMLPurifier($config);
  1659. $item['body'] = $purifier->purify($item['body']);
  1660. $item['body'] = @html2bbcode($item['body']);
  1661. }
  1662. /// @todo We should check for a repeated post and if we know the repeated author.
  1663. // We don't need the content element since "dfrn:env" is always present
  1664. //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
  1665. $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
  1666. $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
  1667. $georsspoint = $xpath->query("georss:point", $entry);
  1668. if ($georsspoint)
  1669. $item["coord"] = $georsspoint->item(0)->nodeValue;
  1670. $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
  1671. $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
  1672. if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true")
  1673. $item["bookmark"] = true;
  1674. $notice_info = $xpath->query("statusnet:notice_info", $entry);
  1675. if ($notice_info AND ($notice_info->length > 0)) {
  1676. foreach($notice_info->item(0)->attributes AS $attributes) {
  1677. if ($attributes->name == "source")
  1678. $item["app"] = strip_tags($attributes->textContent);
  1679. }
  1680. }
  1681. $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
  1682. // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
  1683. $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
  1684. if ($dsprsig != "")
  1685. $item["dsprsig"] = $dsprsig;
  1686. $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
  1687. if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "")
  1688. $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
  1689. $object = $xpath->query("activity:object", $entry)->item(0);
  1690. $item["object"] = self::transform_activity($xpath, $object, "object");
  1691. if (trim($item["object"]) != "") {
  1692. $r = parse_xml_string($item["object"], false);
  1693. if (isset($r->type))
  1694. $item["object-type"] = $r->type;
  1695. }
  1696. $target = $xpath->query("activity:target", $entry)->item(0);
  1697. $item["target"] = self::transform_activity($xpath, $target, "target");
  1698. $categories = $xpath->query("atom:category", $entry);
  1699. if ($categories) {
  1700. foreach ($categories AS $category) {
  1701. $term = "";
  1702. $scheme = "";
  1703. foreach($category->attributes AS $attributes) {
  1704. if ($attributes->name == "term")
  1705. $term = $attributes->textContent;
  1706. if ($attributes->name == "scheme")
  1707. $scheme = $attributes->textContent;
  1708. }
  1709. if (($term != "") AND ($scheme != "")) {
  1710. $parts = explode(":", $scheme);
  1711. if ((count($parts) >= 4) AND (array_shift($parts) == "X-DFRN")) {
  1712. $termhash = array_shift($parts);
  1713. $termurl = implode(":", $parts);
  1714. if(strlen($item["tag"]))
  1715. $item["tag"] .= ",";
  1716. $item["tag"] .= $termhash."[url=".$termurl."]".$term."[/url]";
  1717. }
  1718. }
  1719. }
  1720. }
  1721. $enclosure = "";
  1722. $links = $xpath->query("atom:link", $entry);
  1723. if ($links)
  1724. self::parse_links($links, $item);
  1725. // Is it a reply or a top level posting?
  1726. $item["parent-uri"] = $item["uri"];
  1727. $inreplyto = $xpath->query("thr:in-reply-to", $entry);
  1728. if (is_object($inreplyto->item(0)))
  1729. foreach($inreplyto->item(0)->attributes AS $attributes)
  1730. if ($attributes->name == "ref")
  1731. $item["parent-uri"] = $attributes->textContent;
  1732. // Get the type of the item (Top level post, reply or remote reply)
  1733. $entrytype = self::get_entry_type($importer, $item);
  1734. // Now assign the rest of the values that depend on the type of the message
  1735. if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
  1736. if (!isset($item["object-type"]))
  1737. $item["object-type"] = ACTIVITY_OBJ_COMMENT;
  1738. if ($item["contact-id"] != $owner["contact-id"])
  1739. $item["contact-id"] = $owner["contact-id"];
  1740. if (($item["network"] != $owner["network"]) AND ($owner["network"] != ""))
  1741. $item["network"] = $owner["network"];
  1742. if ($item["contact-id"] != $author["contact-id"])
  1743. $item["contact-id"] = $author["contact-id"];
  1744. if (($item["network"] != $author["network"]) AND ($author["network"] != ""))
  1745. $item["network"] = $author["network"];
  1746. // This code was taken from the old DFRN code
  1747. // When activated, forums don't work.
  1748. // And: Why should we disallow commenting by followers?
  1749. // the behaviour is now similar to the Diaspora part.
  1750. //if($importer["rel"] == CONTACT_IS_FOLLOWER) {
  1751. // logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
  1752. // return;
  1753. //}
  1754. }
  1755. if ($entrytype == DFRN_REPLY_RC) {
  1756. $item["type"] = "remote-comment";
  1757. $item["wall"] = 1;
  1758. } elseif ($entrytype == DFRN_TOP_LEVEL) {
  1759. if (!isset($item["object-type"]))
  1760. $item["object-type"] = ACTIVITY_OBJ_NOTE;
  1761. // Is it an event?
  1762. if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
  1763. logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
  1764. $ev = bbtoevent($item["body"]);
  1765. if((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
  1766. logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
  1767. $ev["cid"] = $importer["id"];
  1768. $ev["uid"] = $importer["uid"];
  1769. $ev["uri"] = $item["uri"];
  1770. $ev["edited"] = $item["edited"];
  1771. $ev['private'] = $item['private'];
  1772. $ev["guid"] = $item["guid"];
  1773. $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1774. dbesc($item["uri"]),
  1775. intval($importer["uid"])
  1776. );
  1777. if(count($r))
  1778. $ev["id"] = $r[0]["id"];
  1779. $event_id = event_store($ev);
  1780. logger("Event ".$event_id." was stored", LOGGER_DEBUG);
  1781. return;
  1782. }
  1783. }
  1784. }
  1785. $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1786. dbesc($item["uri"]),
  1787. intval($importer["importer_uid"])
  1788. );
  1789. if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
  1790. logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
  1791. return;
  1792. }
  1793. // Update content if 'updated' changes
  1794. if(count($r)) {
  1795. if (self::update_content($r[0], $item, $importer, $entrytype))
  1796. logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
  1797. else
  1798. logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
  1799. return;
  1800. }
  1801. if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
  1802. $posted_id = item_store($item);
  1803. $parent = 0;
  1804. if($posted_id) {
  1805. logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
  1806. $item["id"] = $posted_id;
  1807. $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  1808. intval($posted_id),
  1809. intval($importer["importer_uid"])
  1810. );
  1811. if(count($r)) {
  1812. $parent = $r[0]["parent"];
  1813. $parent_uri = $r[0]["parent-uri"];
  1814. }
  1815. if(!$is_like) {
  1816. $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
  1817. dbesc(datetime_convert()),
  1818. intval($importer["importer_uid"]),
  1819. intval($r[0]["parent"])
  1820. );
  1821. $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
  1822. dbesc(datetime_convert()),
  1823. intval($importer["importer_uid"]),
  1824. intval($posted_id)
  1825. );
  1826. }
  1827. if($posted_id AND $parent AND ($entrytype == DFRN_REPLY_RC)) {
  1828. logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
  1829. proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $posted_id);
  1830. }
  1831. return true;
  1832. }
  1833. } else { // $entrytype == DFRN_TOP_LEVEL
  1834. if(!link_compare($item["owner-link"],$importer["url"])) {
  1835. // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
  1836. // but otherwise there's a possible data mixup on the sender's system.
  1837. // the tgroup delivery code called from item_store will correct it if it's a forum,
  1838. // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
  1839. logger('Correcting item owner.', LOGGER_DEBUG);
  1840. $item["owner-name"] = $importer["senderName"];
  1841. $item["owner-link"] = $importer["url"];
  1842. $item["owner-avatar"] = $importer["thumb"];
  1843. }
  1844. if(($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
  1845. logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
  1846. return;
  1847. }
  1848. // This is my contact on another system, but it's really me.
  1849. // Turn this into a wall post.
  1850. $notify = item_is_remote_self($importer, $item);
  1851. $posted_id = item_store($item, false, $notify);
  1852. logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
  1853. if(stristr($item["verb"],ACTIVITY_POKE))
  1854. self::do_poke($item, $importer, $posted_id);
  1855. }
  1856. }
  1857. /**
  1858. * @brief Deletes items
  1859. *
  1860. * @param object $xpath XPath object
  1861. * @param object $deletion deletion elements
  1862. * @param array $importer Record of the importer user mixed with contact of the content
  1863. */
  1864. private function process_deletion($xpath, $deletion, $importer) {
  1865. logger("Processing deletions");
  1866. foreach($deletion->attributes AS $attributes) {
  1867. if ($attributes->name == "ref")
  1868. $uri = $attributes->textContent;
  1869. if ($attributes->name == "when")
  1870. $when = $attributes->textContent;
  1871. }
  1872. if ($when)
  1873. $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
  1874. else
  1875. $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
  1876. if (!$uri OR !$importer["id"])
  1877. return false;
  1878. /// @todo Only select the used fields
  1879. $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
  1880. WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
  1881. dbesc($uri),
  1882. intval($importer["uid"]),
  1883. intval($importer["id"])
  1884. );
  1885. if(!count($r)) {
  1886. logger("Item with uri ".$uri." from contact ".$importer["id"]." for user ".$importer["uid"]." wasn't found.", LOGGER_DEBUG);
  1887. return;
  1888. } else {
  1889. $item = $r[0];
  1890. $entrytype = self::get_entry_type($importer, $item);
  1891. if(!$item["deleted"])
  1892. logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
  1893. else
  1894. return;
  1895. if($item["object-type"] == ACTIVITY_OBJ_EVENT) {
  1896. logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
  1897. event_delete($item["event-id"]);
  1898. }
  1899. if(($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
  1900. $xo = parse_xml_string($item["object"],false);
  1901. $xt = parse_xml_string($item["target"],false);
  1902. if($xt->type == ACTIVITY_OBJ_NOTE) {
  1903. $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1904. dbesc($xt->id),
  1905. intval($importer["importer_uid"])
  1906. );
  1907. if(count($i)) {
  1908. // For tags, the owner cannot remove the tag on the author's copy of the post.
  1909. $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
  1910. $author_remove = (($item["origin"] && $item["self"]) ? true : false);
  1911. $author_copy = (($item["origin"]) ? true : false);
  1912. if($owner_remove && $author_copy)
  1913. return;
  1914. if($author_remove || $owner_remove) {
  1915. $tags = explode(',',$i[0]["tag"]);
  1916. $newtags = array();
  1917. if(count($tags)) {
  1918. foreach($tags as $tag)
  1919. if(trim($tag) !== trim($xo->body))
  1920. $newtags[] = trim($tag);
  1921. }
  1922. q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
  1923. dbesc(implode(',',$newtags)),
  1924. intval($i[0]["id"])
  1925. );
  1926. create_tags_from_item($i[0]["id"]);
  1927. }
  1928. }
  1929. }
  1930. }
  1931. if($entrytype == DFRN_TOP_LEVEL) {
  1932. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
  1933. `body` = '', `title` = ''
  1934. WHERE `parent-uri` = '%s' AND `uid` = %d",
  1935. dbesc($when),
  1936. dbesc(datetime_convert()),
  1937. dbesc($uri),
  1938. intval($importer["uid"])
  1939. );
  1940. create_tags_from_itemuri($uri, $importer["uid"]);
  1941. create_files_from_itemuri($uri, $importer["uid"]);
  1942. update_thread_uri($uri, $importer["uid"]);
  1943. } else {
  1944. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
  1945. `body` = '', `title` = ''
  1946. WHERE `uri` = '%s' AND `uid` = %d",
  1947. dbesc($when),
  1948. dbesc(datetime_convert()),
  1949. dbesc($uri),
  1950. intval($importer["uid"])
  1951. );
  1952. create_tags_from_itemuri($uri, $importer["uid"]);
  1953. create_files_from_itemuri($uri, $importer["uid"]);
  1954. update_thread_uri($uri, $importer["importer_uid"]);
  1955. if($item["last-child"]) {
  1956. // ensure that last-child is set in case the comment that had it just got wiped.
  1957. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  1958. dbesc(datetime_convert()),
  1959. dbesc($item["parent-uri"]),
  1960. intval($item["uid"])
  1961. );
  1962. // who is the last child now?
  1963. $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
  1964. ORDER BY `created` DESC LIMIT 1",
  1965. dbesc($item["parent-uri"]),
  1966. intval($importer["uid"])
  1967. );
  1968. if(count($r)) {
  1969. q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
  1970. intval($r[0]["id"])
  1971. );
  1972. }
  1973. }
  1974. // if this is a relayed delete, propagate it to other recipients
  1975. if($entrytype == DFRN_REPLY_RC) {
  1976. logger("Notifying followers about deletion of post ".$item["id"], LOGGER_DEBUG);
  1977. proc_run(PRIORITY_HIGH, "include/notifier.php","drop", $item["id"]);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. /**
  1983. * @brief Imports a DFRN message
  1984. *
  1985. * @param text $xml The DFRN message
  1986. * @param array $importer Record of the importer user mixed with contact of the content
  1987. * @param bool $sort_by_date Is used when feeds are polled
  1988. */
  1989. public static function import($xml,$importer, $sort_by_date = false) {
  1990. if ($xml == "")
  1991. return;
  1992. if($importer["readonly"]) {
  1993. // We aren't receiving stuff from this person. But we will quietly ignore them
  1994. // rather than a blatant "go away" message.
  1995. logger('ignoring contact '.$importer["id"]);
  1996. return;
  1997. }
  1998. $doc = new DOMDocument();
  1999. @$doc->loadXML($xml);
  2000. $xpath = new DomXPath($doc);
  2001. $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
  2002. $xpath->registerNamespace("thr", NAMESPACE_THREAD);
  2003. $xpath->registerNamespace("at", NAMESPACE_TOMB);
  2004. $xpath->registerNamespace("media", NAMESPACE_MEDIA);
  2005. $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
  2006. $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
  2007. $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
  2008. $xpath->registerNamespace("poco", NAMESPACE_POCO);
  2009. $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
  2010. $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
  2011. $header = array();
  2012. $header["uid"] = $importer["uid"];
  2013. $header["network"] = NETWORK_DFRN;
  2014. $header["type"] = "remote";
  2015. $header["wall"] = 0;
  2016. $header["origin"] = 0;
  2017. $header["contact-id"] = $importer["id"];
  2018. // Update the contact table if the data has changed
  2019. // The "atom:author" is only present in feeds
  2020. if ($xpath->query("/atom:feed/atom:author")->length > 0)
  2021. self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
  2022. // Only the "dfrn:owner" in the head section contains all data
  2023. if ($xpath->query("/atom:feed/dfrn:owner")->length > 0)
  2024. self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
  2025. logger("Import DFRN message for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
  2026. // The account type is new since 3.5.1
  2027. if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
  2028. $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
  2029. if ($accounttype != $importer["contact-type"])
  2030. q("UPDATE `contact` SET `contact-type` = %d WHERE `id` = %d",
  2031. intval($accounttype),
  2032. intval($importer["id"])
  2033. );
  2034. }
  2035. // is it a public forum? Private forums aren't supported with this method
  2036. // This is deprecated since 3.5.1
  2037. $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
  2038. if ($forum != $importer["forum"])
  2039. q("UPDATE `contact` SET `forum` = %d WHERE `forum` != %d AND `id` = %d",
  2040. intval($forum), intval($forum),
  2041. intval($importer["id"])
  2042. );
  2043. $mails = $xpath->query("/atom:feed/dfrn:mail");
  2044. foreach ($mails AS $mail)
  2045. self::process_mail($xpath, $mail, $importer);
  2046. $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
  2047. foreach ($suggestions AS $suggestion)
  2048. self::process_suggestion($xpath, $suggestion, $importer);
  2049. $relocations = $xpath->query("/atom:feed/dfrn:relocate");
  2050. foreach ($relocations AS $relocation)
  2051. self::process_relocation($xpath, $relocation, $importer);
  2052. $deletions = $xpath->query("/atom:feed/at:deleted-entry");
  2053. foreach ($deletions AS $deletion)
  2054. self::process_deletion($xpath, $deletion, $importer);
  2055. if (!$sort_by_date) {
  2056. $entries = $xpath->query("/atom:feed/atom:entry");
  2057. foreach ($entries AS $entry)
  2058. self::process_entry($header, $xpath, $entry, $importer);
  2059. } else {
  2060. $newentries = array();
  2061. $entries = $xpath->query("/atom:feed/atom:entry");
  2062. foreach ($entries AS $entry) {
  2063. $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
  2064. $newentries[strtotime($created)] = $entry;
  2065. }
  2066. // Now sort after the publishing date
  2067. ksort($newentries);
  2068. foreach ($newentries AS $entry)
  2069. self::process_entry($header, $xpath, $entry, $importer);
  2070. }
  2071. logger("Import done for user ".$importer["uid"]." from contact ".$importer["id"], LOGGER_DEBUG);
  2072. }
  2073. }
  2074. ?>