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.
 
 
 
 
 
 

4112 lines
134 KiB

  1. <?php
  2. require_once('include/bbcode.php');
  3. require_once('include/oembed.php');
  4. require_once('include/salmon.php');
  5. require_once('include/crypto.php');
  6. require_once('include/Photo.php');
  7. function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
  8. $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
  9. $public_feed = (($dfrn_id) ? false : true);
  10. $starred = false; // not yet implemented, possible security issues
  11. $converse = false;
  12. if($public_feed && $a->argc > 2) {
  13. for($x = 2; $x < $a->argc; $x++) {
  14. if($a->argv[$x] == 'converse')
  15. $converse = true;
  16. if($a->argv[$x] == 'starred')
  17. $starred = true;
  18. if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
  19. $category = $a->argv[$x+1];
  20. }
  21. }
  22. // default permissions - anonymous user
  23. $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
  24. $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
  25. FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
  26. WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
  27. dbesc($owner_nick)
  28. );
  29. if(! count($r))
  30. killme();
  31. $owner = $r[0];
  32. $owner_id = $owner['user_uid'];
  33. $owner_nick = $owner['nickname'];
  34. $birthday = feed_birthday($owner_id,$owner['timezone']);
  35. if(! $public_feed) {
  36. $sql_extra = '';
  37. switch($direction) {
  38. case (-1):
  39. $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
  40. $my_id = $dfrn_id;
  41. break;
  42. case 0:
  43. $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
  44. $my_id = '1:' . $dfrn_id;
  45. break;
  46. case 1:
  47. $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
  48. $my_id = '0:' . $dfrn_id;
  49. break;
  50. default:
  51. return false;
  52. break; // NOTREACHED
  53. }
  54. $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
  55. intval($owner_id)
  56. );
  57. if(! count($r))
  58. killme();
  59. $contact = $r[0];
  60. require_once('include/security.php');
  61. $groups = init_groups_visitor($contact['id']);
  62. if(count($groups)) {
  63. for($x = 0; $x < count($groups); $x ++)
  64. $groups[$x] = '<' . intval($groups[$x]) . '>' ;
  65. $gs = implode('|', $groups);
  66. }
  67. else
  68. $gs = '<<>>' ; // Impossible to match
  69. $sql_extra = sprintf("
  70. AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
  71. AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
  72. AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
  73. AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
  74. ",
  75. intval($contact['id']),
  76. intval($contact['id']),
  77. dbesc($gs),
  78. dbesc($gs)
  79. );
  80. }
  81. if($public_feed)
  82. $sort = 'DESC';
  83. else
  84. $sort = 'ASC';
  85. if(! strlen($last_update))
  86. $last_update = 'now -30 days';
  87. if(isset($category)) {
  88. $sql_extra .= file_tag_file_query('item',$category,'category');
  89. }
  90. if($public_feed) {
  91. if(! $converse)
  92. $sql_extra .= " AND `contact`.`self` = 1 ";
  93. }
  94. $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
  95. $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
  96. `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
  97. `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
  98. `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
  99. `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
  100. `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
  101. FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  102. LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
  103. WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
  104. AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
  105. AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
  106. $sql_extra
  107. ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
  108. intval($owner_id),
  109. dbesc($check_date),
  110. dbesc($check_date),
  111. dbesc($sort)
  112. );
  113. // Will check further below if this actually returned results.
  114. // We will provide an empty feed if that is the case.
  115. $items = $r;
  116. $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
  117. $atom = '';
  118. $hubxml = feed_hublinks();
  119. $salmon = feed_salmonlinks($owner_nick);
  120. $atom .= replace_macros($feed_template, array(
  121. '$version' => xmlify(FRIENDICA_VERSION),
  122. '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
  123. '$feed_title' => xmlify($owner['name']),
  124. '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
  125. '$hub' => $hubxml,
  126. '$salmon' => $salmon,
  127. '$name' => xmlify($owner['name']),
  128. '$profile_page' => xmlify($owner['url']),
  129. '$photo' => xmlify($owner['photo']),
  130. '$thumb' => xmlify($owner['thumb']),
  131. '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
  132. '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
  133. '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
  134. '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
  135. '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
  136. ));
  137. call_hooks('atom_feed', $atom);
  138. if(! count($items)) {
  139. call_hooks('atom_feed_end', $atom);
  140. $atom .= '</feed>' . "\r\n";
  141. return $atom;
  142. }
  143. foreach($items as $item) {
  144. // prevent private email from leaking.
  145. if($item['network'] === NETWORK_MAIL)
  146. continue;
  147. // public feeds get html, our own nodes use bbcode
  148. if($public_feed) {
  149. $type = 'html';
  150. // catch any email that's in a public conversation and make sure it doesn't leak
  151. if($item['private'])
  152. continue;
  153. }
  154. else {
  155. $type = 'text';
  156. }
  157. $atom .= atom_entry($item,$type,null,$owner,true);
  158. }
  159. call_hooks('atom_feed_end', $atom);
  160. $atom .= '</feed>' . "\r\n";
  161. return $atom;
  162. }
  163. function construct_verb($item) {
  164. if($item['verb'])
  165. return $item['verb'];
  166. return ACTIVITY_POST;
  167. }
  168. function construct_activity_object($item) {
  169. if($item['object']) {
  170. $o = '<as:object>' . "\r\n";
  171. $r = parse_xml_string($item['object'],false);
  172. if(! $r)
  173. return '';
  174. if($r->type)
  175. $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
  176. if($r->id)
  177. $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
  178. if($r->title)
  179. $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
  180. if($r->link) {
  181. if(substr($r->link,0,1) === '<') {
  182. // patch up some facebook "like" activity objects that got stored incorrectly
  183. // for a couple of months prior to 9-Jun-2011 and generated bad XML.
  184. // we can probably remove this hack here and in the following function in a few months time.
  185. if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
  186. $r->link = str_replace('&','&amp;', $r->link);
  187. $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
  188. $o .= $r->link;
  189. }
  190. else
  191. $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
  192. }
  193. if($r->content)
  194. $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
  195. $o .= '</as:object>' . "\r\n";
  196. return $o;
  197. }
  198. return '';
  199. }
  200. function construct_activity_target($item) {
  201. if($item['target']) {
  202. $o = '<as:target>' . "\r\n";
  203. $r = parse_xml_string($item['target'],false);
  204. if(! $r)
  205. return '';
  206. if($r->type)
  207. $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
  208. if($r->id)
  209. $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
  210. if($r->title)
  211. $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
  212. if($r->link) {
  213. if(substr($r->link,0,1) === '<') {
  214. if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
  215. $r->link = str_replace('&','&amp;', $r->link);
  216. $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
  217. $o .= $r->link;
  218. }
  219. else
  220. $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
  221. }
  222. if($r->content)
  223. $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
  224. $o .= '</as:target>' . "\r\n";
  225. return $o;
  226. }
  227. return '';
  228. }
  229. /* limit_body_size()
  230. *
  231. * The purpose of this function is to apply system message length limits to
  232. * imported messages without including any embedded photos in the length
  233. */
  234. if(! function_exists('limit_body_size')) {
  235. function limit_body_size($body) {
  236. logger('limit_body_size: start', LOGGER_DEBUG);
  237. $maxlen = get_max_import_size();
  238. // If the length of the body, including the embedded images, is smaller
  239. // than the maximum, then don't waste time looking for the images
  240. if($maxlen && (strlen($body) > $maxlen)) {
  241. logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
  242. $orig_body = $body;
  243. $new_body = '';
  244. $textlen = 0;
  245. $max_found = false;
  246. $img_start = strpos($orig_body, '[img');
  247. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  248. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  249. while(($img_st_close !== false) && ($img_end !== false)) {
  250. $img_st_close++; // make it point to AFTER the closing bracket
  251. $img_end += $img_start;
  252. $img_end += strlen('[/img]');
  253. if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
  254. // This is an embedded image
  255. if( ($textlen + $img_start) > $maxlen ) {
  256. if($textlen < $maxlen) {
  257. logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
  258. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  259. $textlen = $maxlen;
  260. }
  261. }
  262. else {
  263. $new_body = $new_body . substr($orig_body, 0, $img_start);
  264. $textlen += $img_start;
  265. }
  266. $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
  267. }
  268. else {
  269. if( ($textlen + $img_end) > $maxlen ) {
  270. if($textlen < $maxlen) {
  271. logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
  272. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  273. $textlen = $maxlen;
  274. }
  275. }
  276. else {
  277. $new_body = $new_body . substr($orig_body, 0, $img_end);
  278. $textlen += $img_end;
  279. }
  280. }
  281. $orig_body = substr($orig_body, $img_end);
  282. if($orig_body === false) // in case the body ends on a closing image tag
  283. $orig_body = '';
  284. $img_start = strpos($orig_body, '[img');
  285. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  286. $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
  287. }
  288. if( ($textlen + strlen($orig_body)) > $maxlen) {
  289. if($textlen < $maxlen) {
  290. logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
  291. $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
  292. $textlen = $maxlen;
  293. }
  294. }
  295. else {
  296. logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
  297. $new_body = $new_body . $orig_body;
  298. $textlen += strlen($orig_body);
  299. }
  300. return $new_body;
  301. }
  302. else
  303. return $body;
  304. }}
  305. function title_is_body($title, $body) {
  306. $title = strip_tags($title);
  307. $title = trim($title);
  308. $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
  309. $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
  310. $body = strip_tags($body);
  311. $body = trim($body);
  312. $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
  313. $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
  314. if (strlen($title) < strlen($body))
  315. $body = substr($body, 0, strlen($title));
  316. if (($title != $body) and (substr($title, -3) == "...")) {
  317. $pos = strrpos($title, "...");
  318. if ($pos > 0) {
  319. $title = substr($title, 0, $pos);
  320. $body = substr($body, 0, $pos);
  321. }
  322. }
  323. return($title == $body);
  324. }
  325. function get_atom_elements($feed,$item) {
  326. require_once('library/HTMLPurifier.auto.php');
  327. require_once('include/html2bbcode.php');
  328. $best_photo = array();
  329. $res = array();
  330. $author = $item->get_author();
  331. if($author) {
  332. $res['author-name'] = unxmlify($author->get_name());
  333. $res['author-link'] = unxmlify($author->get_link());
  334. }
  335. else {
  336. $res['author-name'] = unxmlify($feed->get_title());
  337. $res['author-link'] = unxmlify($feed->get_permalink());
  338. }
  339. $res['uri'] = unxmlify($item->get_id());
  340. $res['title'] = unxmlify($item->get_title());
  341. $res['body'] = unxmlify($item->get_content());
  342. $res['plink'] = unxmlify($item->get_link(0));
  343. // removing the content of the title if its identically to the body
  344. // This helps with auto generated titles e.g. from tumblr
  345. if (title_is_body($res["title"], $res["body"]))
  346. $res['title'] = "";
  347. if($res['plink'])
  348. $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
  349. else
  350. $base_url = '';
  351. // look for a photo. We should check media size and find the best one,
  352. // but for now let's just find any author photo
  353. $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
  354. if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
  355. $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  356. foreach($base as $link) {
  357. if(!x($res, 'author-avatar') || !$res['author-avatar']) {
  358. if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
  359. $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
  360. }
  361. }
  362. }
  363. $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
  364. if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
  365. $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  366. if($base && count($base)) {
  367. foreach($base as $link) {
  368. if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
  369. $res['author-link'] = unxmlify($link['attribs']['']['href']);
  370. if(!x($res, 'author-avatar') || !$res['author-avatar']) {
  371. if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
  372. $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
  373. }
  374. }
  375. }
  376. }
  377. // No photo/profile-link on the item - look at the feed level
  378. if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
  379. $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
  380. if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
  381. $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  382. foreach($base as $link) {
  383. if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
  384. $res['author-link'] = unxmlify($link['attribs']['']['href']);
  385. if(! $res['author-avatar']) {
  386. if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
  387. $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
  388. }
  389. }
  390. }
  391. $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
  392. if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
  393. $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  394. if($base && count($base)) {
  395. foreach($base as $link) {
  396. if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
  397. $res['author-link'] = unxmlify($link['attribs']['']['href']);
  398. if(! (x($res,'author-avatar'))) {
  399. if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
  400. $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
  401. }
  402. }
  403. }
  404. }
  405. }
  406. $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
  407. if($apps && $apps[0]['attribs']['']['source']) {
  408. $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
  409. if($res['app'] === 'web')
  410. $res['app'] = 'OStatus';
  411. }
  412. // base64 encoded json structure representing Diaspora signature
  413. $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
  414. if($dsig) {
  415. $res['dsprsig'] = unxmlify($dsig[0]['data']);
  416. }
  417. $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
  418. if($dguid)
  419. $res['guid'] = unxmlify($dguid[0]['data']);
  420. $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
  421. if($bm)
  422. $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
  423. /**
  424. * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
  425. */
  426. $have_real_body = false;
  427. $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
  428. if($rawenv) {
  429. $have_real_body = true;
  430. $res['body'] = $rawenv[0]['data'];
  431. $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
  432. // make sure nobody is trying to sneak some html tags by us
  433. $res['body'] = notags(base64url_decode($res['body']));
  434. }
  435. $res['body'] = limit_body_size($res['body']);
  436. // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
  437. // the content type. Our own network only emits text normally, though it might have been converted to
  438. // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
  439. // have to assume it is all html and needs to be purified.
  440. // It doesn't matter all that much security wise - because before this content is used anywhere, we are
  441. // going to escape any tags we find regardless, but this lets us import a limited subset of html from
  442. // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
  443. // html.
  444. if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
  445. $res['body'] = reltoabs($res['body'],$base_url);
  446. $res['body'] = html2bb_video($res['body']);
  447. $res['body'] = oembed_html2bbcode($res['body']);
  448. $config = HTMLPurifier_Config::createDefault();
  449. $config->set('Cache.DefinitionImpl', null);
  450. // we shouldn't need a whitelist, because the bbcode converter
  451. // will strip out any unsupported tags.
  452. $purifier = new HTMLPurifier($config);
  453. $res['body'] = $purifier->purify($res['body']);
  454. $res['body'] = @html2bbcode($res['body']);
  455. }
  456. elseif(! $have_real_body) {
  457. // it's not one of our messages and it has no tags
  458. // so it's probably just text. We'll escape it just to be safe.
  459. $res['body'] = escape_tags($res['body']);
  460. }
  461. // this tag is obsolete but we keep it for really old sites
  462. $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
  463. if($allow && $allow[0]['data'] == 1)
  464. $res['last-child'] = 1;
  465. else
  466. $res['last-child'] = 0;
  467. $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
  468. if($private && intval($private[0]['data']) > 0)
  469. $res['private'] = intval($private[0]['data']);
  470. else
  471. $res['private'] = 0;
  472. $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
  473. if($extid && $extid[0]['data'])
  474. $res['extid'] = $extid[0]['data'];
  475. $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
  476. if($rawlocation)
  477. $res['location'] = unxmlify($rawlocation[0]['data']);
  478. $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
  479. if($rawcreated)
  480. $res['created'] = unxmlify($rawcreated[0]['data']);
  481. $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
  482. if($rawedited)
  483. $res['edited'] = unxmlify($rawedited[0]['data']);
  484. if((x($res,'edited')) && (! (x($res,'created'))))
  485. $res['created'] = $res['edited'];
  486. if(! $res['created'])
  487. $res['created'] = $item->get_date('c');
  488. if(! $res['edited'])
  489. $res['edited'] = $item->get_date('c');
  490. // Disallow time travelling posts
  491. $d1 = strtotime($res['created']);
  492. $d2 = strtotime($res['edited']);
  493. $d3 = strtotime('now');
  494. if($d1 > $d3)
  495. $res['created'] = datetime_convert();
  496. if($d2 > $d3)
  497. $res['edited'] = datetime_convert();
  498. $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
  499. if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
  500. $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
  501. elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
  502. $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
  503. if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
  504. $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
  505. elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
  506. $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
  507. if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
  508. $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  509. foreach($base as $link) {
  510. if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
  511. if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
  512. $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
  513. }
  514. }
  515. }
  516. $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
  517. if($rawgeo)
  518. $res['coord'] = unxmlify($rawgeo[0]['data']);
  519. $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
  520. // select between supported verbs
  521. if($rawverb) {
  522. $res['verb'] = unxmlify($rawverb[0]['data']);
  523. }
  524. // translate OStatus unfollow to activity streams if it happened to get selected
  525. if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
  526. $res['verb'] = ACTIVITY_UNFOLLOW;
  527. $cats = $item->get_categories();
  528. if($cats) {
  529. $tag_arr = array();
  530. foreach($cats as $cat) {
  531. $term = $cat->get_term();
  532. if(! $term)
  533. $term = $cat->get_label();
  534. $scheme = $cat->get_scheme();
  535. if($scheme && $term && stristr($scheme,'X-DFRN:'))
  536. $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
  537. elseif($term)
  538. $tag_arr[] = notags(trim($term));
  539. }
  540. $res['tag'] = implode(',', $tag_arr);
  541. }
  542. $attach = $item->get_enclosures();
  543. if($attach) {
  544. $att_arr = array();
  545. foreach($attach as $att) {
  546. $len = intval($att->get_length());
  547. $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
  548. $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
  549. $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
  550. if(strpos($type,';'))
  551. $type = substr($type,0,strpos($type,';'));
  552. if((! $link) || (strpos($link,'http') !== 0))
  553. continue;
  554. if(! $title)
  555. $title = ' ';
  556. if(! $type)
  557. $type = 'application/octet-stream';
  558. $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
  559. }
  560. $res['attach'] = implode(',', $att_arr);
  561. }
  562. $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
  563. if($rawobj) {
  564. $res['object'] = '<object>' . "\n";
  565. $child = $rawobj[0]['child'];
  566. if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
  567. $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
  568. $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
  569. }
  570. if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
  571. $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
  572. if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
  573. $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
  574. if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
  575. $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
  576. if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
  577. $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
  578. if(! $body)
  579. $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
  580. // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
  581. $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
  582. if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
  583. $body = html2bb_video($body);
  584. $config = HTMLPurifier_Config::createDefault();
  585. $config->set('Cache.DefinitionImpl', null);
  586. $purifier = new HTMLPurifier($config);
  587. $body = $purifier->purify($body);
  588. $body = html2bbcode($body);
  589. }
  590. $res['object'] .= '<content>' . $body . '</content>' . "\n";
  591. }
  592. $res['object'] .= '</object>' . "\n";
  593. }
  594. $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
  595. if($rawobj) {
  596. $res['target'] = '<target>' . "\n";
  597. $child = $rawobj[0]['child'];
  598. if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
  599. $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
  600. }
  601. if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
  602. $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
  603. if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
  604. $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
  605. if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
  606. $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
  607. if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
  608. $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
  609. if(! $body)
  610. $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
  611. // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
  612. $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
  613. if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
  614. $body = html2bb_video($body);
  615. $config = HTMLPurifier_Config::createDefault();
  616. $config->set('Cache.DefinitionImpl', null);
  617. $purifier = new HTMLPurifier($config);
  618. $body = $purifier->purify($body);
  619. $body = html2bbcode($body);
  620. }
  621. $res['target'] .= '<content>' . $body . '</content>' . "\n";
  622. }
  623. $res['target'] .= '</target>' . "\n";
  624. }
  625. // This is some experimental stuff. By now retweets are shown with "RT:"
  626. // But: There is data so that the message could be shown similar to native retweets
  627. // There is some better way to parse this array - but it didn't worked for me.
  628. $child = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://activitystrea.ms/spec/1.0/"][object][0]["child"];
  629. if (is_array($child)) {
  630. logger('get_atom_elements: Looking for status.net repeated message');
  631. $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
  632. $orig_uri = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["id"][0]["data"];
  633. $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
  634. $uri = $author["uri"][0]["data"];
  635. $name = $author["name"][0]["data"];
  636. $avatar = @array_shift($author["link"][2]["attribs"]);
  637. $avatar = $avatar["href"];
  638. if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
  639. logger('get_atom_elements: fixing sender of repeated message.');
  640. if (intval(get_config('system','new_share'))) {
  641. $prefix = "[share author='".str_replace("'", "&#039;",$name).
  642. "' profile='".$uri.
  643. "' avatar='".$avatar.
  644. "' link='".$orig_uri."']";
  645. $res["body"] = $prefix.html2bbcode($message)."[/share]";
  646. } else {
  647. $res["owner-name"] = $res["author-name"];
  648. $res["owner-link"] = $res["author-link"];
  649. $res["owner-avatar"] = $res["author-avatar"];
  650. $res["author-name"] = $name;
  651. $res["author-link"] = $uri;
  652. $res["author-avatar"] = $avatar;
  653. $res["body"] = html2bbcode($message);
  654. }
  655. }
  656. }
  657. $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
  658. call_hooks('parse_atom', $arr);
  659. //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
  660. //if (strpos($res["body"], "RT @") !== false) {
  661. // $debugfile = tempnam("/home/ike/log", "item-res2-");
  662. // file_put_contents($debugfile, serialize($arr));
  663. //}
  664. return $res;
  665. }
  666. function encode_rel_links($links) {
  667. $o = '';
  668. if(! ((is_array($links)) && (count($links))))
  669. return $o;
  670. foreach($links as $link) {
  671. $o .= '<link ';
  672. if($link['attribs']['']['rel'])
  673. $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
  674. if($link['attribs']['']['type'])
  675. $o .= 'type="' . $link['attribs']['']['type'] . '" ';
  676. if($link['attribs']['']['href'])
  677. $o .= 'href="' . $link['attribs']['']['href'] . '" ';
  678. if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
  679. $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
  680. if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
  681. $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
  682. $o .= ' />' . "\n" ;
  683. }
  684. return xmlify($o);
  685. }
  686. function item_store($arr,$force_parent = false) {
  687. // If a Diaspora signature structure was passed in, pull it out of the
  688. // item array and set it aside for later storage.
  689. $dsprsig = null;
  690. if(x($arr,'dsprsig')) {
  691. $dsprsig = json_decode(base64_decode($arr['dsprsig']));
  692. unset($arr['dsprsig']);
  693. }
  694. if(x($arr, 'gravity'))
  695. $arr['gravity'] = intval($arr['gravity']);
  696. elseif($arr['parent-uri'] === $arr['uri'])
  697. $arr['gravity'] = 0;
  698. elseif(activity_match($arr['verb'],ACTIVITY_POST))
  699. $arr['gravity'] = 6;
  700. else
  701. $arr['gravity'] = 6; // extensible catchall
  702. if(! x($arr,'type'))
  703. $arr['type'] = 'remote';
  704. // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
  705. if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
  706. $arr['body'] = strip_tags($arr['body']);
  707. if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
  708. require_once('library/langdet/Text/LanguageDetect.php');
  709. $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
  710. $l = new Text_LanguageDetect;
  711. $lng = $l->detectConfidence($naked_body);
  712. $arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
  713. }
  714. $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
  715. $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
  716. $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
  717. $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
  718. $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
  719. $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
  720. $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
  721. $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
  722. $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
  723. $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
  724. $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
  725. $arr['commented'] = datetime_convert();
  726. $arr['received'] = datetime_convert();
  727. $arr['changed'] = datetime_convert();
  728. $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
  729. $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
  730. $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
  731. $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
  732. $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
  733. $arr['deleted'] = 0;
  734. $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
  735. $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
  736. $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
  737. $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
  738. $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
  739. $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
  740. $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
  741. $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
  742. $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
  743. $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
  744. $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
  745. $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
  746. $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
  747. $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
  748. $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
  749. $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
  750. $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
  751. $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
  752. $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
  753. $arr['thr-parent'] = $arr['parent-uri'];
  754. if($arr['parent-uri'] === $arr['uri']) {
  755. $parent_id = 0;
  756. $parent_deleted = 0;
  757. $allow_cid = $arr['allow_cid'];
  758. $allow_gid = $arr['allow_gid'];
  759. $deny_cid = $arr['deny_cid'];
  760. $deny_gid = $arr['deny_gid'];
  761. }
  762. else {
  763. // find the parent and snarf the item id and ACL's
  764. // and anything else we need to inherit
  765. $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
  766. dbesc($arr['parent-uri']),
  767. intval($arr['uid'])
  768. );
  769. if(count($r)) {
  770. // is the new message multi-level threaded?
  771. // even though we don't support it now, preserve the info
  772. // and re-attach to the conversation parent.
  773. if($r[0]['uri'] != $r[0]['parent-uri']) {
  774. $arr['parent-uri'] = $r[0]['parent-uri'];
  775. $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
  776. ORDER BY `id` ASC LIMIT 1",
  777. dbesc($r[0]['parent-uri']),
  778. dbesc($r[0]['parent-uri']),
  779. intval($arr['uid'])
  780. );
  781. if($z && count($z))
  782. $r = $z;
  783. }
  784. $parent_id = $r[0]['id'];
  785. $parent_deleted = $r[0]['deleted'];
  786. $allow_cid = $r[0]['allow_cid'];
  787. $allow_gid = $r[0]['allow_gid'];
  788. $deny_cid = $r[0]['deny_cid'];
  789. $deny_gid = $r[0]['deny_gid'];
  790. $arr['wall'] = $r[0]['wall'];
  791. // if the parent is private, force privacy for the entire conversation
  792. // This differs from the above settings as it subtly allows comments from
  793. // email correspondents to be private even if the overall thread is not.
  794. if($r[0]['private'])
  795. $arr['private'] = $r[0]['private'];
  796. // Edge case. We host a public forum that was originally posted to privately.
  797. // The original author commented, but as this is a comment, the permissions
  798. // weren't fixed up so it will still show the comment as private unless we fix it here.
  799. if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
  800. $arr['private'] = 0;
  801. }
  802. else {
  803. // Allow one to see reply tweets from status.net even when
  804. // we don't have or can't see the original post.
  805. if($force_parent) {
  806. logger('item_store: $force_parent=true, reply converted to top-level post.');
  807. $parent_id = 0;
  808. $arr['parent-uri'] = $arr['uri'];
  809. $arr['gravity'] = 0;
  810. }
  811. else {
  812. logger('item_store: item parent was not found - ignoring item');
  813. return 0;
  814. }
  815. $parent_deleted = 0;
  816. }
  817. }
  818. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  819. dbesc($arr['uri']),
  820. intval($arr['uid'])
  821. );
  822. if($r && count($r)) {
  823. logger('item-store: duplicate item ignored. ' . print_r($arr,true));
  824. return 0;
  825. }
  826. call_hooks('post_remote',$arr);
  827. if(x($arr,'cancel')) {
  828. logger('item_store: post cancelled by plugin.');
  829. return 0;
  830. }
  831. dbesc_array($arr);
  832. logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
  833. $r = dbq("INSERT INTO `item` (`"
  834. . implode("`, `", array_keys($arr))
  835. . "`) VALUES ('"
  836. . implode("', '", array_values($arr))
  837. . "')" );
  838. // find the item we just created
  839. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
  840. $arr['uri'], // already dbesc'd
  841. intval($arr['uid'])
  842. );
  843. if(count($r)) {
  844. $current_post = $r[0]['id'];
  845. logger('item_store: created item ' . $current_post);
  846. }
  847. else {
  848. logger('item_store: could not locate created item');
  849. return 0;
  850. }
  851. if(count($r) > 1) {
  852. logger('item_store: duplicated post occurred. Removing duplicates.');
  853. q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
  854. $arr['uri'],
  855. intval($arr['uid']),
  856. intval($current_post)
  857. );
  858. }
  859. if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
  860. $parent_id = $current_post;
  861. if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
  862. $private = 1;
  863. else
  864. $private = $arr['private'];
  865. // Set parent id - and also make sure to inherit the parent's ACL's.
  866. $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
  867. `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
  868. intval($parent_id),
  869. dbesc($allow_cid),
  870. dbesc($allow_gid),
  871. dbesc($deny_cid),
  872. dbesc($deny_gid),
  873. intval($private),
  874. intval($parent_deleted),
  875. intval($current_post)
  876. );
  877. $arr['id'] = $current_post;
  878. $arr['parent'] = $parent_id;
  879. $arr['allow_cid'] = $allow_cid;
  880. $arr['allow_gid'] = $allow_gid;
  881. $arr['deny_cid'] = $deny_cid;
  882. $arr['deny_gid'] = $deny_gid;
  883. $arr['private'] = $private;
  884. $arr['deleted'] = $parent_deleted;
  885. call_hooks('post_remote_end',$arr);
  886. // update the commented timestamp on the parent
  887. q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
  888. dbesc(datetime_convert()),
  889. dbesc(datetime_convert()),
  890. intval($parent_id)
  891. );
  892. if($dsprsig) {
  893. q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
  894. intval($current_post),
  895. dbesc($dsprsig->signed_text),
  896. dbesc($dsprsig->signature),
  897. dbesc($dsprsig->signer)
  898. );
  899. }
  900. /**
  901. * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
  902. */
  903. if($arr['last-child']) {
  904. $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
  905. dbesc($arr['uri']),
  906. intval($arr['uid']),
  907. intval($current_post)
  908. );
  909. }
  910. tag_deliver($arr['uid'],$current_post);
  911. return $current_post;
  912. }
  913. function get_item_contact($item,$contacts) {
  914. if(! count($contacts) || (! is_array($item)))
  915. return false;
  916. foreach($contacts as $contact) {
  917. if($contact['id'] == $item['contact-id']) {
  918. return $contact;
  919. break; // NOTREACHED
  920. }
  921. }
  922. return false;
  923. }
  924. function tag_deliver($uid,$item_id) {
  925. // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
  926. $a = get_app();
  927. $mention = false;
  928. $u = q("select * from user where uid = %d limit 1",
  929. intval($uid)
  930. );
  931. if(! count($u))
  932. return;
  933. $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
  934. $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
  935. $i = q("select * from item where id = %d and uid = %d limit 1",
  936. intval($item_id),
  937. intval($uid)
  938. );
  939. if(! count($i))
  940. return;
  941. $item = $i[0];
  942. $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
  943. // Diaspora uses their own hardwired link URL in @-tags
  944. // instead of the one we supply with webfinger
  945. $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
  946. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
  947. if($cnt) {
  948. foreach($matches as $mtch) {
  949. if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
  950. $mention = true;
  951. logger('tag_deliver: mention found: ' . $mtch[2]);
  952. }
  953. }
  954. }
  955. if(! $mention)
  956. return;
  957. // send a notification
  958. // use a local photo if we have one
  959. $r = q("select * from contact where uid = %d and nurl = '%s' limit 1",
  960. intval($u[0]['uid']),
  961. dbesc(normalise_link($item['author-link']))
  962. );
  963. $photo = (($r && count($r)) ? $r[0]['thumb'] : $item['author-avatar']);
  964. require_once('include/enotify.php');
  965. notification(array(
  966. 'type' => NOTIFY_TAGSELF,
  967. 'notify_flags' => $u[0]['notify-flags'],
  968. 'language' => $u[0]['language'],
  969. 'to_name' => $u[0]['username'],
  970. 'to_email' => $u[0]['email'],
  971. 'uid' => $u[0]['uid'],
  972. 'item' => $item,
  973. 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
  974. 'source_name' => $item['author-name'],
  975. 'source_link' => $item['author-link'],
  976. 'source_photo' => $photo,
  977. 'verb' => ACTIVITY_TAG,
  978. 'otype' => 'item'
  979. ));
  980. $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
  981. call_hooks('tagged', $arr);
  982. if((! $community_page) && (! $prvgroup))
  983. return;
  984. // tgroup delivery - setup a second delivery chain
  985. // prevent delivery looping - only proceed
  986. // if the message originated elsewhere and is a top-level post
  987. if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
  988. return;
  989. // now change this copy of the post to a forum head message and deliver to all the tgroup members
  990. $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
  991. intval($u[0]['uid'])
  992. );
  993. if(! count($c))
  994. return;
  995. // also reset all the privacy bits to the forum default permissions
  996. $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
  997. $forum_mode = (($prvgroup) ? 2 : 1);
  998. q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
  999. `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
  1000. intval($forum_mode),
  1001. dbesc($c[0]['name']),
  1002. dbesc($c[0]['url']),
  1003. dbesc($c[0]['thumb']),
  1004. intval($private),
  1005. dbesc($u[0]['allow_cid']),
  1006. dbesc($u[0]['allow_gid']),
  1007. dbesc($u[0]['deny_cid']),
  1008. dbesc($u[0]['deny_gid']),
  1009. intval($item_id)
  1010. );
  1011. proc_run('php','include/notifier.php','tgroup',$item_id);
  1012. }
  1013. function tgroup_check($uid,$item) {
  1014. $a = get_app();
  1015. $mention = false;
  1016. // check that the message originated elsewhere and is a top-level post
  1017. if(($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri']))
  1018. return false;
  1019. $u = q("select * from user where uid = %d limit 1",
  1020. intval($uid)
  1021. );
  1022. if(! count($u))
  1023. return false;
  1024. $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
  1025. $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
  1026. $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
  1027. // Diaspora uses their own hardwired link URL in @-tags
  1028. // instead of the one we supply with webfinger
  1029. $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
  1030. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
  1031. if($cnt) {
  1032. foreach($matches as $mtch) {
  1033. if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
  1034. $mention = true;
  1035. logger('tgroup_check: mention found: ' . $mtch[2]);
  1036. }
  1037. }
  1038. }
  1039. if(! $mention)
  1040. return false;
  1041. if((! $community_page) && (! $prvgroup))
  1042. return false;
  1043. return true;
  1044. }
  1045. function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
  1046. $a = get_app();
  1047. $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
  1048. if($contact['duplex'] && $contact['dfrn-id'])
  1049. $idtosend = '0:' . $orig_id;
  1050. if($contact['duplex'] && $contact['issued-id'])
  1051. $idtosend = '1:' . $orig_id;
  1052. $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
  1053. $rino_enable = get_config('system','rino_encrypt');
  1054. if(! $rino_enable)
  1055. $rino = 0;
  1056. $ssl_val = intval(get_config('system','ssl_policy'));
  1057. $ssl_policy = '';
  1058. switch($ssl_val){
  1059. case SSL_POLICY_FULL:
  1060. $ssl_policy = 'full';
  1061. break;
  1062. case SSL_POLICY_SELFSIGN:
  1063. $ssl_policy = 'self';
  1064. break;
  1065. case SSL_POLICY_NONE:
  1066. default:
  1067. $ssl_policy = 'none';
  1068. break;
  1069. }
  1070. $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
  1071. logger('dfrn_deliver: ' . $url);
  1072. $xml = fetch_url($url);
  1073. $curl_stat = $a->get_curl_code();
  1074. if(! $curl_stat)
  1075. return(-1); // timed out
  1076. logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
  1077. if(! $xml)
  1078. return 3;
  1079. if(strpos($xml,'<?xml') === false) {
  1080. logger('dfrn_deliver: no valid XML returned');
  1081. logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
  1082. return 3;
  1083. }
  1084. $res = parse_xml_string($xml);
  1085. if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
  1086. return (($res->status) ? $res->status : 3);
  1087. $postvars = array();
  1088. $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
  1089. $challenge = hex2bin((string) $res->challenge);
  1090. $perm = (($res->perm) ? $res->perm : null);
  1091. $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
  1092. $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
  1093. $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
  1094. if($owner['page-flags'] == PAGE_PRVGROUP)
  1095. $page = 2;
  1096. $final_dfrn_id = '';
  1097. if($perm) {
  1098. if((($perm == 'rw') && (! intval($contact['writable'])))
  1099. || (($perm == 'r') && (intval($contact['writable'])))) {
  1100. q("update contact set writable = %d where id = %d limit 1",
  1101. intval(($perm == 'rw') ? 1 : 0),
  1102. intval($contact['id'])
  1103. );
  1104. $contact['writable'] = (string) 1 - intval($contact['writable']);
  1105. }
  1106. }
  1107. if(($contact['duplex'] && strlen($contact['pubkey']))
  1108. || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
  1109. || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
  1110. openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
  1111. openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
  1112. }
  1113. else {
  1114. openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
  1115. openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
  1116. }
  1117. $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
  1118. if(strpos($final_dfrn_id,':') == 1)
  1119. $final_dfrn_id = substr($final_dfrn_id,2);
  1120. if($final_dfrn_id != $orig_id) {
  1121. logger('dfrn_deliver: wrong dfrn_id.');
  1122. // did not decode properly - cannot trust this site
  1123. return 3;
  1124. }
  1125. $postvars['dfrn_id'] = $idtosend;
  1126. $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
  1127. if($dissolve)
  1128. $postvars['dissolve'] = '1';
  1129. if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
  1130. $postvars['data'] = $atom;
  1131. $postvars['perm'] = 'rw';
  1132. }
  1133. else {
  1134. $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
  1135. $postvars['perm'] = 'r';
  1136. }
  1137. $postvars['ssl_policy'] = $ssl_policy;
  1138. if($page)
  1139. $postvars['page'] = $page;
  1140. if($rino && $rino_allowed && (! $dissolve)) {
  1141. $key = substr(random_string(),0,16);
  1142. $data = bin2hex(aes_encrypt($postvars['data'],$key));
  1143. $postvars['data'] = $data;
  1144. logger('rino: sent key = ' . $key, LOGGER_DEBUG);
  1145. if($dfrn_version >= 2.1) {
  1146. if(($contact['duplex'] && strlen($contact['pubkey']))
  1147. || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
  1148. || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
  1149. openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
  1150. }
  1151. else {
  1152. openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
  1153. }
  1154. }
  1155. else {
  1156. if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
  1157. openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
  1158. }
  1159. else {
  1160. openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
  1161. }
  1162. }
  1163. logger('md5 rawkey ' . md5($postvars['key']));
  1164. $postvars['key'] = bin2hex($postvars['key']);
  1165. }
  1166. logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
  1167. $xml = post_url($contact['notify'],$postvars);
  1168. logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
  1169. $curl_stat = $a->get_curl_code();
  1170. if((! $curl_stat) || (! strlen($xml)))
  1171. return(-1); // timed out
  1172. if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
  1173. return(-1);
  1174. if(strpos($xml,'<?xml') === false) {
  1175. logger('dfrn_deliver: phase 2: no valid XML returned');
  1176. logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
  1177. return 3;
  1178. }
  1179. if($contact['term-date'] != '0000-00-00 00:00:00') {
  1180. logger("dfrn_deliver: $url back from the dead - removing mark for death");
  1181. require_once('include/Contact.php');
  1182. unmark_for_death($contact);
  1183. }
  1184. $res = parse_xml_string($xml);
  1185. return $res->status;
  1186. }
  1187. /**
  1188. *
  1189. * consume_feed - process atom feed and update anything/everything we might need to update
  1190. *
  1191. * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
  1192. *
  1193. * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
  1194. * It is this person's stuff that is going to be updated.
  1195. * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
  1196. * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
  1197. * have a contact record.
  1198. * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
  1199. * might not) try and subscribe to it.
  1200. * $datedir sorts in reverse order
  1201. * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
  1202. * imported prior to its children being seen in the stream unless we are certain
  1203. * of how the feed is arranged/ordered.
  1204. * With $pass = 1, we only pull parent items out of the stream.
  1205. * With $pass = 2, we only pull children (comments/likes).
  1206. *
  1207. * So running this twice, first with pass 1 and then with pass 2 will do the right
  1208. * thing regardless of feed ordering. This won't be adequate in a fully-threaded
  1209. * model where comments can have sub-threads. That would require some massive sorting
  1210. * to get all the feed items into a mostly linear ordering, and might still require
  1211. * recursion.
  1212. */
  1213. function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
  1214. require_once('library/simplepie/simplepie.inc');
  1215. if(! strlen($xml)) {
  1216. logger('consume_feed: empty input');
  1217. return;
  1218. }
  1219. $feed = new SimplePie();
  1220. $feed->set_raw_data($xml);
  1221. if($datedir)
  1222. $feed->enable_order_by_date(true);
  1223. else
  1224. $feed->enable_order_by_date(false);
  1225. $feed->init();
  1226. if($feed->error())
  1227. logger('consume_feed: Error parsing XML: ' . $feed->error());
  1228. $permalink = $feed->get_permalink();
  1229. // Check at the feed level for updated contact name and/or photo
  1230. $name_updated = '';
  1231. $new_name = '';
  1232. $photo_timestamp = '';
  1233. $photo_url = '';
  1234. $birthday = '';
  1235. $hubs = $feed->get_links('hub');
  1236. logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
  1237. if(count($hubs))
  1238. $hub = implode(',', $hubs);
  1239. $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
  1240. if(! $rawtags)
  1241. $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
  1242. if($rawtags) {
  1243. $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
  1244. if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
  1245. $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
  1246. $new_name = $elems['name'][0]['data'];
  1247. }
  1248. if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
  1249. $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
  1250. $photo_url = $elems['link'][0]['attribs']['']['href'];
  1251. }
  1252. if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
  1253. $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
  1254. }
  1255. }
  1256. if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
  1257. logger('consume_feed: Updating photo for ' . $contact['name']);
  1258. require_once("Photo.php");
  1259. $photo_failure = false;
  1260. $have_photo = false;
  1261. $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
  1262. intval($contact['id']),
  1263. intval($contact['uid'])
  1264. );
  1265. if(count($r)) {
  1266. $resource_id = $r[0]['resource-id'];
  1267. $have_photo = true;
  1268. }
  1269. else {
  1270. $resource_id = photo_new_resource();
  1271. }
  1272. $img_str = fetch_url($photo_url,true);
  1273. // guess mimetype from headers or filename
  1274. $type = guess_image_type($photo_url,true);
  1275. $img = new Photo($img_str, $type);
  1276. if($img->is_valid()) {
  1277. if($have_photo) {
  1278. q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
  1279. dbesc($resource_id),
  1280. intval($contact['id']),
  1281. intval($contact['uid'])
  1282. );
  1283. }
  1284. $img->scaleImageSquare(175);
  1285. $hash = $resource_id;
  1286. $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
  1287. $img->scaleImage(80);
  1288. $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
  1289. $img->scaleImage(48);
  1290. $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
  1291. $a = get_app();
  1292. q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
  1293. WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1294. dbesc(datetime_convert()),
  1295. dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
  1296. dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
  1297. dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
  1298. intval($contact['uid']),
  1299. intval($contact['id'])
  1300. );
  1301. }
  1302. }
  1303. if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
  1304. $r = q("select * from contact where uid = %d and id = %d limit 1",
  1305. intval($contact['uid']),
  1306. intval($contact['id'])
  1307. );
  1308. $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1309. dbesc(notags(trim($new_name))),
  1310. dbesc(datetime_convert()),
  1311. intval($contact['uid']),
  1312. intval($contact['id'])
  1313. );
  1314. // do our best to update the name on content items
  1315. if(count($r)) {
  1316. q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
  1317. dbesc(notags(trim($new_name))),
  1318. dbesc($r[0]['name']),
  1319. dbesc($r[0]['url']),
  1320. intval($contact['uid'])
  1321. );
  1322. }
  1323. }
  1324. if(strlen($birthday)) {
  1325. if(substr($birthday,0,4) != $contact['bdyear']) {
  1326. logger('consume_feed: updating birthday: ' . $birthday);
  1327. /**
  1328. *
  1329. * Add new birthday event for this person
  1330. *
  1331. * $bdtext is just a readable placeholder in case the event is shared
  1332. * with others. We will replace it during presentation to our $importer
  1333. * to contain a sparkle link and perhaps a photo.
  1334. *
  1335. */
  1336. $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
  1337. $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
  1338. $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
  1339. VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
  1340. intval($contact['uid']),
  1341. intval($contact['id']),
  1342. dbesc(datetime_convert()),
  1343. dbesc(datetime_convert()),
  1344. dbesc(datetime_convert('UTC','UTC', $birthday)),
  1345. dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
  1346. dbesc($bdtext),
  1347. dbesc($bdtext2),
  1348. dbesc('birthday')
  1349. );
  1350. // update bdyear
  1351. q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1352. dbesc(substr($birthday,0,4)),
  1353. intval($contact['uid']),
  1354. intval($contact['id'])
  1355. );
  1356. // This function is called twice without reloading the contact
  1357. // Make sure we only create one event. This is why &$contact
  1358. // is a reference var in this function
  1359. $contact['bdyear'] = substr($birthday,0,4);
  1360. }
  1361. }
  1362. $community_page = 0;
  1363. $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
  1364. if($rawtags) {
  1365. $community_page = intval($rawtags[0]['data']);
  1366. }
  1367. if(is_array($contact) && intval($contact['forum']) != $community_page) {
  1368. q("update contact set forum = %d where id = %d limit 1",
  1369. intval($community_page),
  1370. intval($contact['id'])
  1371. );
  1372. $contact['forum'] = (string) $community_page;
  1373. }
  1374. // process any deleted entries
  1375. $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
  1376. if(is_array($del_entries) && count($del_entries) && $pass != 2) {
  1377. foreach($del_entries as $dentry) {
  1378. $deleted = false;
  1379. if(isset($dentry['attribs']['']['ref'])) {
  1380. $uri = $dentry['attribs']['']['ref'];
  1381. $deleted = true;
  1382. if(isset($dentry['attribs']['']['when'])) {
  1383. $when = $dentry['attribs']['']['when'];
  1384. $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
  1385. }
  1386. else
  1387. $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
  1388. }
  1389. if($deleted && is_array($contact)) {
  1390. $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
  1391. WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
  1392. dbesc($uri),
  1393. intval($importer['uid']),
  1394. intval($contact['id'])
  1395. );
  1396. if(count($r)) {
  1397. $item = $r[0];
  1398. if(! $item['deleted'])
  1399. logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
  1400. if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
  1401. $xo = parse_xml_string($item['object'],false);
  1402. $xt = parse_xml_string($item['target'],false);
  1403. if($xt->type === ACTIVITY_OBJ_NOTE) {
  1404. $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
  1405. dbesc($xt->id),
  1406. intval($importer['importer_uid'])
  1407. );
  1408. if(count($i)) {
  1409. // For tags, the owner cannot remove the tag on the author's copy of the post.
  1410. $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
  1411. $author_remove = (($item['origin'] && $item['self']) ? true : false);
  1412. $author_copy = (($item['origin']) ? true : false);
  1413. if($owner_remove && $author_copy)
  1414. continue;
  1415. if($author_remove || $owner_remove) {
  1416. $tags = explode(',',$i[0]['tag']);
  1417. $newtags = array();
  1418. if(count($tags)) {
  1419. foreach($tags as $tag)
  1420. if(trim($tag) !== trim($xo->body))
  1421. $newtags[] = trim($tag);
  1422. }
  1423. q("update item set tag = '%s' where id = %d limit 1",
  1424. dbesc(implode(',',$newtags)),
  1425. intval($i[0]['id'])
  1426. );
  1427. }
  1428. }
  1429. }
  1430. }
  1431. if($item['uri'] == $item['parent-uri']) {
  1432. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
  1433. `body` = '', `title` = ''
  1434. WHERE `parent-uri` = '%s' AND `uid` = %d",
  1435. dbesc($when),
  1436. dbesc(datetime_convert()),
  1437. dbesc($item['uri']),
  1438. intval($importer['uid'])
  1439. );
  1440. }
  1441. else {
  1442. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
  1443. `body` = '', `title` = ''
  1444. WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1445. dbesc($when),
  1446. dbesc(datetime_convert()),
  1447. dbesc($uri),
  1448. intval($importer['uid'])
  1449. );
  1450. if($item['last-child']) {
  1451. // ensure that last-child is set in case the comment that had it just got wiped.
  1452. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  1453. dbesc(datetime_convert()),
  1454. dbesc($item['parent-uri']),
  1455. intval($item['uid'])
  1456. );
  1457. // who is the last child now?
  1458. $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
  1459. ORDER BY `created` DESC LIMIT 1",
  1460. dbesc($item['parent-uri']),
  1461. intval($importer['uid'])
  1462. );
  1463. if(count($r)) {
  1464. q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
  1465. intval($r[0]['id'])
  1466. );
  1467. }
  1468. }
  1469. }
  1470. }
  1471. }
  1472. }
  1473. }
  1474. // Now process the feed
  1475. if($feed->get_item_quantity()) {
  1476. logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
  1477. // in inverse date order
  1478. if ($datedir)
  1479. $items = array_reverse($feed->get_items());
  1480. else
  1481. $items = $feed->get_items();
  1482. foreach($items as $item) {
  1483. $is_reply = false;
  1484. $item_id = $item->get_id();
  1485. $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
  1486. if(isset($rawthread[0]['attribs']['']['ref'])) {
  1487. $is_reply = true;
  1488. $parent_uri = $rawthread[0]['attribs']['']['ref'];
  1489. }
  1490. if(($is_reply) && is_array($contact)) {
  1491. if($pass == 1)
  1492. continue;
  1493. // not allowed to post
  1494. if($contact['rel'] == CONTACT_IS_FOLLOWER)
  1495. continue;
  1496. // Have we seen it? If not, import it.
  1497. $item_id = $item->get_id();
  1498. $datarray = get_atom_elements($feed,$item);
  1499. if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
  1500. $datarray['author-name'] = $contact['name'];
  1501. if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
  1502. $datarray['author-link'] = $contact['url'];
  1503. if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
  1504. $datarray['author-avatar'] = $contact['thumb'];
  1505. if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
  1506. logger('consume_feed: no author information! ' . print_r($datarray,true));
  1507. continue;
  1508. }
  1509. $force_parent = false;
  1510. if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
  1511. if($contact['network'] === NETWORK_OSTATUS)
  1512. $force_parent = true;
  1513. if(strlen($datarray['title']))
  1514. unset($datarray['title']);
  1515. $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
  1516. dbesc(datetime_convert()),
  1517. dbesc($parent_uri),
  1518. intval($importer['uid'])
  1519. );
  1520. $datarray['last-child'] = 1;
  1521. }
  1522. $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1523. dbesc($item_id),
  1524. intval($importer['uid'])
  1525. );
  1526. // Update content if 'updated' changes
  1527. if(count($r)) {
  1528. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  1529. // do not accept (ignore) an earlier edit than one we currently have.
  1530. if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
  1531. continue;
  1532. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1533. dbesc($datarray['title']),
  1534. dbesc($datarray['body']),
  1535. dbesc($datarray['tag']),
  1536. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  1537. dbesc($item_id),
  1538. intval($importer['uid'])
  1539. );
  1540. }
  1541. // update last-child if it changes
  1542. $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
  1543. if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
  1544. $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
  1545. dbesc(datetime_convert()),
  1546. dbesc($parent_uri),
  1547. intval($importer['uid'])
  1548. );
  1549. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1550. intval($allow[0]['data']),
  1551. dbesc(datetime_convert()),
  1552. dbesc($item_id),
  1553. intval($importer['uid'])
  1554. );
  1555. }
  1556. continue;
  1557. }
  1558. if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
  1559. // one way feed - no remote comment ability
  1560. $datarray['last-child'] = 0;
  1561. }
  1562. $datarray['parent-uri'] = $parent_uri;
  1563. $datarray['uid'] = $importer['uid'];
  1564. $datarray['contact-id'] = $contact['id'];
  1565. if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
  1566. $datarray['type'] = 'activity';
  1567. $datarray['gravity'] = GRAVITY_LIKE;
  1568. // only one like or dislike per person
  1569. $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s' OR `thr-parent` = '%s') limit 1",
  1570. intval($datarray['uid']),
  1571. intval($datarray['contact-id']),
  1572. dbesc($datarray['verb']),
  1573. dbesc($parent_uri),
  1574. dbesc($parent_uri)
  1575. );
  1576. if($r && count($r))
  1577. continue;
  1578. }
  1579. if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
  1580. $xo = parse_xml_string($datarray['object'],false);
  1581. $xt = parse_xml_string($datarray['target'],false);
  1582. if($xt->type == ACTIVITY_OBJ_NOTE) {
  1583. $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
  1584. dbesc($xt->id),
  1585. intval($importer['importer_uid'])
  1586. );
  1587. if(! count($r))
  1588. continue;
  1589. // extract tag, if not duplicate, add to parent item
  1590. if($xo->id && $xo->content) {
  1591. $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
  1592. if(! (stristr($r[0]['tag'],$newtag))) {
  1593. q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
  1594. dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
  1595. intval($r[0]['id'])
  1596. );
  1597. }
  1598. }
  1599. }
  1600. }
  1601. $r = item_store($datarray,$force_parent);
  1602. continue;
  1603. }
  1604. else {
  1605. // Head post of a conversation. Have we seen it? If not, import it.
  1606. $item_id = $item->get_id();
  1607. $datarray = get_atom_elements($feed,$item);
  1608. if(is_array($contact)) {
  1609. if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
  1610. $datarray['author-name'] = $contact['name'];
  1611. if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
  1612. $datarray['author-link'] = $contact['url'];
  1613. if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
  1614. $datarray['author-avatar'] = $contact['thumb'];
  1615. }
  1616. if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
  1617. logger('consume_feed: no author information! ' . print_r($datarray,true));
  1618. continue;
  1619. }
  1620. // special handling for events
  1621. if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
  1622. $ev = bbtoevent($datarray['body']);
  1623. if(x($ev,'desc') && x($ev,'start')) {
  1624. $ev['uid'] = $importer['uid'];
  1625. $ev['uri'] = $item_id;
  1626. $ev['edited'] = $datarray['edited'];
  1627. $ev['private'] = $datarray['private'];
  1628. if(is_array($contact))
  1629. $ev['cid'] = $contact['id'];
  1630. $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1631. dbesc($item_id),
  1632. intval($importer['uid'])
  1633. );
  1634. if(count($r))
  1635. $ev['id'] = $r[0]['id'];
  1636. $xyz = event_store($ev);
  1637. continue;
  1638. }
  1639. }
  1640. if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
  1641. if(strlen($datarray['title']))
  1642. unset($datarray['title']);
  1643. $datarray['last-child'] = 1;
  1644. }
  1645. $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1646. dbesc($item_id),
  1647. intval($importer['uid'])
  1648. );
  1649. // Update content if 'updated' changes
  1650. if(count($r)) {
  1651. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  1652. // do not accept (ignore) an earlier edit than one we currently have.
  1653. if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
  1654. continue;
  1655. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1656. dbesc($datarray['title']),
  1657. dbesc($datarray['body']),
  1658. dbesc($datarray['tag']),
  1659. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  1660. dbesc($item_id),
  1661. intval($importer['uid'])
  1662. );
  1663. }
  1664. // update last-child if it changes
  1665. $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
  1666. if($allow && $allow[0]['data'] != $r[0]['last-child']) {
  1667. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1668. intval($allow[0]['data']),
  1669. dbesc(datetime_convert()),
  1670. dbesc($item_id),
  1671. intval($importer['uid'])
  1672. );
  1673. }
  1674. continue;
  1675. }
  1676. if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
  1677. logger('consume-feed: New follower');
  1678. new_follower($importer,$contact,$datarray,$item);
  1679. return;
  1680. }
  1681. if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
  1682. lose_follower($importer,$contact,$datarray,$item);
  1683. return;
  1684. }
  1685. if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
  1686. logger('consume-feed: New friend request');
  1687. new_follower($importer,$contact,$datarray,$item,true);
  1688. return;
  1689. }
  1690. if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
  1691. lose_sharer($importer,$contact,$datarray,$item);
  1692. return;
  1693. }
  1694. if(! is_array($contact))
  1695. return;
  1696. if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
  1697. // one way feed - no remote comment ability
  1698. $datarray['last-child'] = 0;
  1699. }
  1700. if($contact['network'] === NETWORK_FEED)
  1701. $datarray['private'] = 2;
  1702. // This is my contact on another system, but it's really me.
  1703. // Turn this into a wall post.
  1704. if($contact['remote_self']) {
  1705. $datarray['wall'] = 1;
  1706. if($contact['network'] === NETWORK_FEED) {
  1707. $datarray['private'] = 0;
  1708. }
  1709. }
  1710. $datarray['parent-uri'] = $item_id;
  1711. $datarray['uid'] = $importer['uid'];
  1712. $datarray['contact-id'] = $contact['id'];
  1713. if(! link_compare($datarray['owner-link'],$contact['url'])) {
  1714. // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
  1715. // but otherwise there's a possible data mixup on the sender's system.
  1716. // the tgroup delivery code called from item_store will correct it if it's a forum,
  1717. // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
  1718. logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
  1719. $datarray['owner-name'] = $contact['name'];
  1720. $datarray['owner-link'] = $contact['url'];
  1721. $datarray['owner-avatar'] = $contact['thumb'];
  1722. }
  1723. // We've allowed "followers" to reach this point so we can decide if they are
  1724. // posting an @-tag delivery, which followers are allowed to do for certain
  1725. // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it.
  1726. if(($contact['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['uid'],$datarray)))
  1727. continue;
  1728. $r = item_store($datarray);
  1729. continue;
  1730. }
  1731. }
  1732. }
  1733. }
  1734. function local_delivery($importer,$data) {
  1735. $a = get_app();
  1736. logger(__function__, LOGGER_TRACE);
  1737. if($importer['readonly']) {
  1738. // We aren't receiving stuff from this person. But we will quietly ignore them
  1739. // rather than a blatant "go away" message.
  1740. logger('local_delivery: ignoring');
  1741. return 0;
  1742. //NOTREACHED
  1743. }
  1744. // Consume notification feed. This may differ from consuming a public feed in several ways
  1745. // - might contain email or friend suggestions
  1746. // - might contain remote followup to our message
  1747. // - in which case we need to accept it and then notify other conversants
  1748. // - we may need to send various email notifications
  1749. $feed = new SimplePie();
  1750. $feed->set_raw_data($data);
  1751. $feed->enable_order_by_date(false);
  1752. $feed->init();
  1753. if($feed->error())
  1754. logger('local_delivery: Error parsing XML: ' . $feed->error());
  1755. // Check at the feed level for updated contact name and/or photo
  1756. $name_updated = '';
  1757. $new_name = '';
  1758. $photo_timestamp = '';
  1759. $photo_url = '';
  1760. $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
  1761. // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
  1762. // if(! $rawtags)
  1763. // $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
  1764. if($rawtags) {
  1765. $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
  1766. if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
  1767. $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
  1768. $new_name = $elems['name'][0]['data'];
  1769. }
  1770. if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
  1771. $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
  1772. $photo_url = $elems['link'][0]['attribs']['']['href'];
  1773. }
  1774. }
  1775. if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
  1776. logger('local_delivery: Updating photo for ' . $importer['name']);
  1777. require_once("Photo.php");
  1778. $photo_failure = false;
  1779. $have_photo = false;
  1780. $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
  1781. intval($importer['id']),
  1782. intval($importer['importer_uid'])
  1783. );
  1784. if(count($r)) {
  1785. $resource_id = $r[0]['resource-id'];
  1786. $have_photo = true;
  1787. }
  1788. else {
  1789. $resource_id = photo_new_resource();
  1790. }
  1791. $img_str = fetch_url($photo_url,true);
  1792. // guess mimetype from headers or filename
  1793. $type = guess_image_type($photo_url,true);
  1794. $img = new Photo($img_str, $type);
  1795. if($img->is_valid()) {
  1796. if($have_photo) {
  1797. q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
  1798. dbesc($resource_id),
  1799. intval($importer['id']),
  1800. intval($importer['importer_uid'])
  1801. );
  1802. }
  1803. $img->scaleImageSquare(175);
  1804. $hash = $resource_id;
  1805. $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 4);
  1806. $img->scaleImage(80);
  1807. $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 5);
  1808. $img->scaleImage(48);
  1809. $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 6);
  1810. $a = get_app();
  1811. q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
  1812. WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1813. dbesc(datetime_convert()),
  1814. dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
  1815. dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
  1816. dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
  1817. intval($importer['importer_uid']),
  1818. intval($importer['id'])
  1819. );
  1820. }
  1821. }
  1822. if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
  1823. $r = q("select * from contact where uid = %d and id = %d limit 1",
  1824. intval($importer['importer_uid']),
  1825. intval($importer['id'])
  1826. );
  1827. $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1828. dbesc(notags(trim($new_name))),
  1829. dbesc(datetime_convert()),
  1830. intval($importer['importer_uid']),
  1831. intval($importer['id'])
  1832. );
  1833. // do our best to update the name on content items
  1834. if(count($r)) {
  1835. q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
  1836. dbesc(notags(trim($new_name))),
  1837. dbesc($r[0]['name']),
  1838. dbesc($r[0]['url']),
  1839. intval($importer['importer_uid'])
  1840. );
  1841. }
  1842. }
  1843. // Currently unsupported - needs a lot of work
  1844. $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
  1845. if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
  1846. $base = $reloc[0]['child'][NAMESPACE_DFRN];
  1847. $newloc = array();
  1848. $newloc['uid'] = $importer['importer_uid'];
  1849. $newloc['cid'] = $importer['id'];
  1850. $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
  1851. $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
  1852. $newloc['thumb'] = notags(unxmlify($base['thumb'][0]['data']));
  1853. $newloc['micro'] = notags(unxmlify($base['micro'][0]['data']));
  1854. $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
  1855. $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
  1856. $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
  1857. $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
  1858. $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
  1859. $newloc['sitepubkey'] = notags(unxmlify($base['sitepubkey'][0]['data']));
  1860. /** relocated user must have original key pair */
  1861. /*$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
  1862. $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));*/
  1863. logger("items:relocate contact ".print_r($newloc, true).print_r($importer, true), LOGGER_DEBUG);
  1864. // update contact
  1865. $r = q("SELECT photo, url FROM contact WHERE id=%d AND uid=%d;",
  1866. intval($importer['id']),
  1867. intval($importer['importer_uid']));
  1868. if ($r === false)
  1869. return 1;
  1870. $old = $r[0];
  1871. $x = q("UPDATE contact SET
  1872. name = '%s',
  1873. photo = '%s',
  1874. thumb = '%s',
  1875. micro = '%s',
  1876. url = '%s',
  1877. request = '%s',
  1878. confirm = '%s',
  1879. notify = '%s',
  1880. poll = '%s',
  1881. `site-pubkey` = '%s'
  1882. WHERE id=%d AND uid=%d;",
  1883. dbesc($newloc['name']),
  1884. dbesc($newloc['photo']),
  1885. dbesc($newloc['thumb']),
  1886. dbesc($newloc['micro']),
  1887. dbesc($newloc['url']),
  1888. dbesc($newloc['request']),
  1889. dbesc($newloc['confirm']),
  1890. dbesc($newloc['notify']),
  1891. dbesc($newloc['poll']),
  1892. dbesc($newloc['sitepubkey']),
  1893. intval($importer['id']),
  1894. intval($importer['importer_uid']));
  1895. if ($x === false)
  1896. return 1;
  1897. // update items
  1898. $fields = array(
  1899. 'owner-link' => array($old['url'], $newloc['url']),
  1900. 'author-link' => array($old['url'], $newloc['url']),
  1901. 'owner-avatar' => array($old['photo'], $newloc['photo']),
  1902. 'author-avatar' => array($old['photo'], $newloc['photo']),
  1903. );
  1904. foreach ($fields as $n=>$f){
  1905. $x = q("UPDATE item SET `%s`='%s' WHERE `%s`='%s' AND uid=%d",
  1906. $n, dbesc($f[1]),
  1907. $n, dbesc($f[0]),
  1908. intval($importer['importer_uid']));
  1909. if ($x === false)
  1910. return 1;
  1911. }
  1912. // TODO
  1913. // merge with current record, current contents have priority
  1914. // update record, set url-updated
  1915. // update profile photos
  1916. // schedule a scan?
  1917. return 0;
  1918. }
  1919. // handle friend suggestion notification
  1920. $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
  1921. if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
  1922. $base = $sugg[0]['child'][NAMESPACE_DFRN];
  1923. $fsugg = array();
  1924. $fsugg['uid'] = $importer['importer_uid'];
  1925. $fsugg['cid'] = $importer['id'];
  1926. $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
  1927. $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
  1928. $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
  1929. $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
  1930. $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
  1931. // Does our member already have a friend matching this description?
  1932. $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
  1933. dbesc($fsugg['name']),
  1934. dbesc(normalise_link($fsugg['url'])),
  1935. intval($fsugg['uid'])
  1936. );
  1937. if(count($r))
  1938. return 0;
  1939. // Do we already have an fcontact record for this person?
  1940. $fid = 0;
  1941. $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
  1942. dbesc($fsugg['url']),
  1943. dbesc($fsugg['name']),
  1944. dbesc($fsugg['request'])
  1945. );
  1946. if(count($r)) {
  1947. $fid = $r[0]['id'];
  1948. // OK, we do. Do we already have an introduction for this person ?
  1949. $r = q("select id from intro where uid = %d and fid = %d limit 1",
  1950. intval($fsugg['uid']),
  1951. intval($fid)
  1952. );
  1953. if(count($r))
  1954. return 0;
  1955. }
  1956. if(! $fid)
  1957. $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
  1958. dbesc($fsugg['name']),
  1959. dbesc($fsugg['url']),
  1960. dbesc($fsugg['photo']),
  1961. dbesc($fsugg['request'])
  1962. );
  1963. $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
  1964. dbesc($fsugg['url']),
  1965. dbesc($fsugg['name']),
  1966. dbesc($fsugg['request'])
  1967. );
  1968. if(count($r)) {
  1969. $fid = $r[0]['id'];
  1970. }
  1971. // database record did not get created. Quietly give up.
  1972. else
  1973. return 0;
  1974. $hash = random_string();
  1975. $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
  1976. VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
  1977. intval($fsugg['uid']),
  1978. intval($fid),
  1979. intval($fsugg['cid']),
  1980. dbesc($fsugg['body']),
  1981. dbesc($hash),
  1982. dbesc(datetime_convert()),
  1983. intval(0)
  1984. );
  1985. notification(array(
  1986. 'type' => NOTIFY_SUGGEST,
  1987. 'notify_flags' => $importer['notify-flags'],
  1988. 'language' => $importer['language'],
  1989. 'to_name' => $importer['username'],
  1990. 'to_email' => $importer['email'],
  1991. 'uid' => $importer['importer_uid'],
  1992. 'item' => $fsugg,
  1993. 'link' => $a->get_baseurl() . '/notifications/intros',
  1994. 'source_name' => $importer['name'],
  1995. 'source_link' => $importer['url'],
  1996. 'source_photo' => $importer['photo'],
  1997. 'verb' => ACTIVITY_REQ_FRIEND,
  1998. 'otype' => 'intro'
  1999. ));
  2000. return 0;
  2001. }
  2002. $ismail = false;
  2003. $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
  2004. if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
  2005. logger('local_delivery: private message received');
  2006. $ismail = true;
  2007. $base = $rawmail[0]['child'][NAMESPACE_DFRN];
  2008. $msg = array();
  2009. $msg['uid'] = $importer['importer_uid'];
  2010. $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
  2011. $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
  2012. $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
  2013. $msg['contact-id'] = $importer['id'];
  2014. $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
  2015. $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
  2016. $msg['seen'] = 0;
  2017. $msg['replied'] = 0;
  2018. $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
  2019. $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
  2020. $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
  2021. dbesc_array($msg);
  2022. $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
  2023. . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
  2024. // send notifications.
  2025. require_once('include/enotify.php');
  2026. $notif_params = array(
  2027. 'type' => NOTIFY_MAIL,
  2028. 'notify_flags' => $importer['notify-flags'],
  2029. 'language' => $importer['language'],
  2030. 'to_name' => $importer['username'],
  2031. 'to_email' => $importer['email'],
  2032. 'uid' => $importer['importer_uid'],
  2033. 'item' => $msg,
  2034. 'source_name' => $msg['from-name'],
  2035. 'source_link' => $importer['url'],
  2036. 'source_photo' => $importer['thumb'],
  2037. 'verb' => ACTIVITY_POST,
  2038. 'otype' => 'mail'
  2039. );
  2040. notification($notif_params);
  2041. return 0;
  2042. // NOTREACHED
  2043. }
  2044. $community_page = 0;
  2045. $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
  2046. if($rawtags) {
  2047. $community_page = intval($rawtags[0]['data']);
  2048. }
  2049. if(intval($importer['forum']) != $community_page) {
  2050. q("update contact set forum = %d where id = %d limit 1",
  2051. intval($community_page),
  2052. intval($importer['id'])
  2053. );
  2054. $importer['forum'] = (string) $community_page;
  2055. }
  2056. logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
  2057. // process any deleted entries
  2058. $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
  2059. if(is_array($del_entries) && count($del_entries)) {
  2060. foreach($del_entries as $dentry) {
  2061. $deleted = false;
  2062. if(isset($dentry['attribs']['']['ref'])) {
  2063. $uri = $dentry['attribs']['']['ref'];
  2064. $deleted = true;
  2065. if(isset($dentry['attribs']['']['when'])) {
  2066. $when = $dentry['attribs']['']['when'];
  2067. $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
  2068. }
  2069. else
  2070. $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
  2071. }
  2072. if($deleted) {
  2073. // check for relayed deletes to our conversation
  2074. $is_reply = false;
  2075. $r = q("select * from item where uri = '%s' and uid = %d limit 1",
  2076. dbesc($uri),
  2077. intval($importer['importer_uid'])
  2078. );
  2079. if(count($r)) {
  2080. $parent_uri = $r[0]['parent-uri'];
  2081. if($r[0]['id'] != $r[0]['parent'])
  2082. $is_reply = true;
  2083. }
  2084. if($is_reply) {
  2085. $community = false;
  2086. if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
  2087. $sql_extra = '';
  2088. $community = true;
  2089. logger('local_delivery: possible community delete');
  2090. }
  2091. else
  2092. $sql_extra = " and contact.self = 1 and item.wall = 1 ";
  2093. // was the top-level post for this reply written by somebody on this site?
  2094. // Specifically, the recipient?
  2095. $is_a_remote_delete = false;
  2096. // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
  2097. $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
  2098. `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
  2099. LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  2100. WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
  2101. AND `item`.`uid` = %d
  2102. $sql_extra
  2103. LIMIT 1",
  2104. dbesc($parent_uri),
  2105. dbesc($parent_uri),
  2106. dbesc($parent_uri),
  2107. intval($importer['importer_uid'])
  2108. );
  2109. if($r && count($r))
  2110. $is_a_remote_delete = true;
  2111. // Does this have the characteristics of a community or private group comment?
  2112. // If it's a reply to a wall post on a community/prvgroup page it's a
  2113. // valid community comment. Also forum_mode makes it valid for sure.
  2114. // If neither, it's not.
  2115. if($is_a_remote_delete && $community) {
  2116. if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
  2117. $is_a_remote_delete = false;
  2118. logger('local_delivery: not a community delete');
  2119. }
  2120. }
  2121. if($is_a_remote_delete) {
  2122. logger('local_delivery: received remote delete');
  2123. }
  2124. }
  2125. $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
  2126. WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
  2127. dbesc($uri),
  2128. intval($importer['importer_uid']),
  2129. intval($importer['id'])
  2130. );
  2131. if(count($r)) {
  2132. $item = $r[0];
  2133. if($item['deleted'])
  2134. continue;
  2135. logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
  2136. if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
  2137. $xo = parse_xml_string($item['object'],false);
  2138. $xt = parse_xml_string($item['target'],false);
  2139. if($xt->type === ACTIVITY_OBJ_NOTE) {
  2140. $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
  2141. dbesc($xt->id),
  2142. intval($importer['importer_uid'])
  2143. );
  2144. if(count($i)) {
  2145. // For tags, the owner cannot remove the tag on the author's copy of the post.
  2146. $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
  2147. $author_remove = (($item['origin'] && $item['self']) ? true : false);
  2148. $author_copy = (($item['origin']) ? true : false);
  2149. if($owner_remove && $author_copy)
  2150. continue;
  2151. if($author_remove || $owner_remove) {
  2152. $tags = explode(',',$i[0]['tag']);
  2153. $newtags = array();
  2154. if(count($tags)) {
  2155. foreach($tags as $tag)
  2156. if(trim($tag) !== trim($xo->body))
  2157. $newtags[] = trim($tag);
  2158. }
  2159. q("update item set tag = '%s' where id = %d limit 1",
  2160. dbesc(implode(',',$newtags)),
  2161. intval($i[0]['id'])
  2162. );
  2163. }
  2164. }
  2165. }
  2166. }
  2167. if($item['uri'] == $item['parent-uri']) {
  2168. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
  2169. `body` = '', `title` = ''
  2170. WHERE `parent-uri` = '%s' AND `uid` = %d",
  2171. dbesc($when),
  2172. dbesc(datetime_convert()),
  2173. dbesc($item['uri']),
  2174. intval($importer['importer_uid'])
  2175. );
  2176. }
  2177. else {
  2178. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
  2179. `body` = '', `title` = ''
  2180. WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2181. dbesc($when),
  2182. dbesc(datetime_convert()),
  2183. dbesc($uri),
  2184. intval($importer['importer_uid'])
  2185. );
  2186. if($item['last-child']) {
  2187. // ensure that last-child is set in case the comment that had it just got wiped.
  2188. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  2189. dbesc(datetime_convert()),
  2190. dbesc($item['parent-uri']),
  2191. intval($item['uid'])
  2192. );
  2193. // who is the last child now?
  2194. $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
  2195. ORDER BY `created` DESC LIMIT 1",
  2196. dbesc($item['parent-uri']),
  2197. intval($importer['importer_uid'])
  2198. );
  2199. if(count($r)) {
  2200. q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
  2201. intval($r[0]['id'])
  2202. );
  2203. }
  2204. }
  2205. // if this is a relayed delete, propagate it to other recipients
  2206. if($is_a_remote_delete)
  2207. proc_run('php',"include/notifier.php","drop",$item['id']);
  2208. }
  2209. }
  2210. }
  2211. }
  2212. }
  2213. foreach($feed->get_items() as $item) {
  2214. $is_reply = false;
  2215. $item_id = $item->get_id();
  2216. $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
  2217. if(isset($rawthread[0]['attribs']['']['ref'])) {
  2218. $is_reply = true;
  2219. $parent_uri = $rawthread[0]['attribs']['']['ref'];
  2220. }
  2221. if($is_reply) {
  2222. $community = false;
  2223. if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
  2224. $sql_extra = '';
  2225. $community = true;
  2226. logger('local_delivery: possible community reply');
  2227. }
  2228. else
  2229. $sql_extra = " and contact.self = 1 and item.wall = 1 ";
  2230. // was the top-level post for this reply written by somebody on this site?
  2231. // Specifically, the recipient?
  2232. $is_a_remote_comment = false;
  2233. $top_uri = $parent_uri;
  2234. $r = q("select `item`.`parent-uri` from `item`
  2235. WHERE `item`.`uri` = '%s'
  2236. LIMIT 1",
  2237. dbesc($parent_uri)
  2238. );
  2239. if($r && count($r)) {
  2240. $top_uri = $r[0]['parent-uri'];
  2241. // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
  2242. $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
  2243. `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
  2244. LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  2245. WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
  2246. AND `item`.`uid` = %d
  2247. $sql_extra
  2248. LIMIT 1",
  2249. dbesc($top_uri),
  2250. dbesc($top_uri),
  2251. dbesc($top_uri),
  2252. intval($importer['importer_uid'])
  2253. );
  2254. if($r && count($r))
  2255. $is_a_remote_comment = true;
  2256. }
  2257. // Does this have the characteristics of a community or private group comment?
  2258. // If it's a reply to a wall post on a community/prvgroup page it's a
  2259. // valid community comment. Also forum_mode makes it valid for sure.
  2260. // If neither, it's not.
  2261. if($is_a_remote_comment && $community) {
  2262. if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
  2263. $is_a_remote_comment = false;
  2264. logger('local_delivery: not a community reply');
  2265. }
  2266. }
  2267. if($is_a_remote_comment) {
  2268. logger('local_delivery: received remote comment');
  2269. $is_like = false;
  2270. // remote reply to our post. Import and then notify everybody else.
  2271. $datarray = get_atom_elements($feed,$item);
  2272. $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2273. dbesc($item_id),
  2274. intval($importer['importer_uid'])
  2275. );
  2276. // Update content if 'updated' changes
  2277. if(count($r)) {
  2278. $iid = $r[0]['id'];
  2279. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  2280. // do not accept (ignore) an earlier edit than one we currently have.
  2281. if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
  2282. continue;
  2283. logger('received updated comment' , LOGGER_DEBUG);
  2284. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2285. dbesc($datarray['title']),
  2286. dbesc($datarray['body']),
  2287. dbesc($datarray['tag']),
  2288. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  2289. dbesc($item_id),
  2290. intval($importer['importer_uid'])
  2291. );
  2292. proc_run('php',"include/notifier.php","comment-import",$iid);
  2293. }
  2294. continue;
  2295. }
  2296. $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
  2297. intval($importer['importer_uid'])
  2298. );
  2299. $datarray['type'] = 'remote-comment';
  2300. $datarray['wall'] = 1;
  2301. $datarray['parent-uri'] = $parent_uri;
  2302. $datarray['uid'] = $importer['importer_uid'];
  2303. $datarray['owner-name'] = $own[0]['name'];
  2304. $datarray['owner-link'] = $own[0]['url'];
  2305. $datarray['owner-avatar'] = $own[0]['thumb'];
  2306. $datarray['contact-id'] = $importer['id'];
  2307. if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
  2308. $is_like = true;
  2309. $datarray['type'] = 'activity';
  2310. $datarray['gravity'] = GRAVITY_LIKE;
  2311. $datarray['last-child'] = 0;
  2312. // only one like or dislike per person
  2313. $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`thr-parent` = '%s' or `parent-uri` = '%s') and deleted = 0 limit 1",
  2314. intval($datarray['uid']),
  2315. intval($datarray['contact-id']),
  2316. dbesc($datarray['verb']),
  2317. dbesc($datarray['parent-uri']),
  2318. dbesc($datarray['parent-uri'])
  2319. );
  2320. if($r && count($r))
  2321. continue;
  2322. }
  2323. if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
  2324. $xo = parse_xml_string($datarray['object'],false);
  2325. $xt = parse_xml_string($datarray['target'],false);
  2326. if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
  2327. // fetch the parent item
  2328. $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
  2329. dbesc($xt->id),
  2330. intval($importer['importer_uid'])
  2331. );
  2332. if(! count($tagp))
  2333. continue;
  2334. // extract tag, if not duplicate, and this user allows tags, add to parent item
  2335. if($xo->id && $xo->content) {
  2336. $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
  2337. if(! (stristr($tagp[0]['tag'],$newtag))) {
  2338. $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
  2339. intval($importer['importer_uid'])
  2340. );
  2341. if(count($i) && ! intval($i[0]['blocktags'])) {
  2342. q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
  2343. dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
  2344. intval($tagp[0]['id']),
  2345. dbesc(datetime_convert())
  2346. );
  2347. }
  2348. }
  2349. }
  2350. }
  2351. }
  2352. $posted_id = item_store($datarray);
  2353. $parent = 0;
  2354. if($posted_id) {
  2355. $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  2356. intval($posted_id),
  2357. intval($importer['importer_uid'])
  2358. );
  2359. if(count($r)) {
  2360. $parent = $r[0]['parent'];
  2361. $parent_uri = $r[0]['parent-uri'];
  2362. }
  2363. if(! $is_like) {
  2364. $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
  2365. dbesc(datetime_convert()),
  2366. intval($importer['importer_uid']),
  2367. intval($r[0]['parent'])
  2368. );
  2369. $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
  2370. dbesc(datetime_convert()),
  2371. intval($importer['importer_uid']),
  2372. intval($posted_id)
  2373. );
  2374. }
  2375. if($posted_id && $parent) {
  2376. proc_run('php',"include/notifier.php","comment-import","$posted_id");
  2377. if((! $is_like) && (! $importer['self'])) {
  2378. require_once('include/enotify.php');
  2379. notification(array(
  2380. 'type' => NOTIFY_COMMENT,
  2381. 'notify_flags' => $importer['notify-flags'],
  2382. 'language' => $importer['language'],
  2383. 'to_name' => $importer['username'],
  2384. 'to_email' => $importer['email'],
  2385. 'uid' => $importer['importer_uid'],
  2386. 'item' => $datarray,
  2387. 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
  2388. 'source_name' => stripslashes($datarray['author-name']),
  2389. 'source_link' => $datarray['author-link'],
  2390. 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
  2391. ? $importer['thumb'] : $datarray['author-avatar']),
  2392. 'verb' => ACTIVITY_POST,
  2393. 'otype' => 'item',
  2394. 'parent' => $parent,
  2395. 'parent_uri' => $parent_uri,
  2396. ));
  2397. }
  2398. }
  2399. return 0;
  2400. // NOTREACHED
  2401. }
  2402. }
  2403. else {
  2404. // regular comment that is part of this total conversation. Have we seen it? If not, import it.
  2405. $item_id = $item->get_id();
  2406. $datarray = get_atom_elements($feed,$item);
  2407. if($importer['rel'] == CONTACT_IS_FOLLOWER)
  2408. continue;
  2409. $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2410. dbesc($item_id),
  2411. intval($importer['importer_uid'])
  2412. );
  2413. // Update content if 'updated' changes
  2414. if(count($r)) {
  2415. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  2416. // do not accept (ignore) an earlier edit than one we currently have.
  2417. if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
  2418. continue;
  2419. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2420. dbesc($datarray['title']),
  2421. dbesc($datarray['body']),
  2422. dbesc($datarray['tag']),
  2423. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  2424. dbesc($item_id),
  2425. intval($importer['importer_uid'])
  2426. );
  2427. }
  2428. // update last-child if it changes
  2429. $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
  2430. if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
  2431. $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
  2432. dbesc(datetime_convert()),
  2433. dbesc($parent_uri),
  2434. intval($importer['importer_uid'])
  2435. );
  2436. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2437. intval($allow[0]['data']),
  2438. dbesc(datetime_convert()),
  2439. dbesc($item_id),
  2440. intval($importer['importer_uid'])
  2441. );
  2442. }
  2443. continue;
  2444. }
  2445. $datarray['parent-uri'] = $parent_uri;
  2446. $datarray['uid'] = $importer['importer_uid'];
  2447. $datarray['contact-id'] = $importer['id'];
  2448. if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
  2449. $datarray['type'] = 'activity';
  2450. $datarray['gravity'] = GRAVITY_LIKE;
  2451. // only one like or dislike per person
  2452. $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s' OR `thr-parent` = '%s') limit 1",
  2453. intval($datarray['uid']),
  2454. intval($datarray['contact-id']),
  2455. dbesc($datarray['verb']),
  2456. dbesc($parent_uri),
  2457. dbesc($parent_uri)
  2458. );
  2459. if($r && count($r))
  2460. continue;
  2461. }
  2462. if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
  2463. $xo = parse_xml_string($datarray['object'],false);
  2464. $xt = parse_xml_string($datarray['target'],false);
  2465. if($xt->type == ACTIVITY_OBJ_NOTE) {
  2466. $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
  2467. dbesc($xt->id),
  2468. intval($importer['importer_uid'])
  2469. );
  2470. if(! count($r))
  2471. continue;
  2472. // extract tag, if not duplicate, add to parent item
  2473. if($xo->content) {
  2474. if(! (stristr($r[0]['tag'],trim($xo->content)))) {
  2475. q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
  2476. dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
  2477. intval($r[0]['id'])
  2478. );
  2479. }
  2480. }
  2481. }
  2482. }
  2483. $posted_id = item_store($datarray);
  2484. // find out if our user is involved in this conversation and wants to be notified.
  2485. if(!x($datarray['type']) || $datarray['type'] != 'activity') {
  2486. $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
  2487. dbesc($top_uri),
  2488. intval($importer['importer_uid'])
  2489. );
  2490. if(count($myconv)) {
  2491. $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
  2492. // first make sure this isn't our own post coming back to us from a wall-to-wall event
  2493. if(! link_compare($datarray['author-link'],$importer_url)) {
  2494. foreach($myconv as $conv) {
  2495. // now if we find a match, it means we're in this conversation
  2496. if(! link_compare($conv['author-link'],$importer_url))
  2497. continue;
  2498. require_once('include/enotify.php');
  2499. $conv_parent = $conv['parent'];
  2500. notification(array(
  2501. 'type' => NOTIFY_COMMENT,
  2502. 'notify_flags' => $importer['notify-flags'],
  2503. 'language' => $importer['language'],
  2504. 'to_name' => $importer['username'],
  2505. 'to_email' => $importer['email'],
  2506. 'uid' => $importer['importer_uid'],
  2507. 'item' => $datarray,
  2508. 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
  2509. 'source_name' => stripslashes($datarray['author-name']),
  2510. 'source_link' => $datarray['author-link'],
  2511. 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
  2512. ? $importer['thumb'] : $datarray['author-avatar']),
  2513. 'verb' => ACTIVITY_POST,
  2514. 'otype' => 'item',
  2515. 'parent' => $conv_parent,
  2516. 'parent_uri' => $parent_uri
  2517. ));
  2518. // only send one notification
  2519. break;
  2520. }
  2521. }
  2522. }
  2523. }
  2524. continue;
  2525. }
  2526. }
  2527. else {
  2528. // Head post of a conversation. Have we seen it? If not, import it.
  2529. $item_id = $item->get_id();
  2530. $datarray = get_atom_elements($feed,$item);
  2531. if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
  2532. $ev = bbtoevent($datarray['body']);
  2533. if(x($ev,'desc') && x($ev,'start')) {
  2534. $ev['cid'] = $importer['id'];
  2535. $ev['uid'] = $importer['uid'];
  2536. $ev['uri'] = $item_id;
  2537. $ev['edited'] = $datarray['edited'];
  2538. $ev['private'] = $datarray['private'];
  2539. $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2540. dbesc($item_id),
  2541. intval($importer['uid'])
  2542. );
  2543. if(count($r))
  2544. $ev['id'] = $r[0]['id'];
  2545. $xyz = event_store($ev);
  2546. continue;
  2547. }
  2548. }
  2549. $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2550. dbesc($item_id),
  2551. intval($importer['importer_uid'])
  2552. );
  2553. // Update content if 'updated' changes
  2554. if(count($r)) {
  2555. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  2556. // do not accept (ignore) an earlier edit than one we currently have.
  2557. if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
  2558. continue;
  2559. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2560. dbesc($datarray['title']),
  2561. dbesc($datarray['body']),
  2562. dbesc($datarray['tag']),
  2563. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  2564. dbesc($item_id),
  2565. intval($importer['importer_uid'])
  2566. );
  2567. }
  2568. // update last-child if it changes
  2569. $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
  2570. if($allow && $allow[0]['data'] != $r[0]['last-child']) {
  2571. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2572. intval($allow[0]['data']),
  2573. dbesc(datetime_convert()),
  2574. dbesc($item_id),
  2575. intval($importer['importer_uid'])
  2576. );
  2577. }
  2578. continue;
  2579. }
  2580. // This is my contact on another system, but it's really me.
  2581. // Turn this into a wall post.
  2582. if($importer['remote_self'])
  2583. $datarray['wall'] = 1;
  2584. $datarray['parent-uri'] = $item_id;
  2585. $datarray['uid'] = $importer['importer_uid'];
  2586. $datarray['contact-id'] = $importer['id'];
  2587. if(! link_compare($datarray['owner-link'],$importer['url'])) {
  2588. // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
  2589. // but otherwise there's a possible data mixup on the sender's system.
  2590. // the tgroup delivery code called from item_store will correct it if it's a forum,
  2591. // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
  2592. logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
  2593. $datarray['owner-name'] = $importer['senderName'];
  2594. $datarray['owner-link'] = $importer['url'];
  2595. $datarray['owner-avatar'] = $importer['thumb'];
  2596. }
  2597. if(($importer['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['importer_uid'],$datarray)))
  2598. continue;
  2599. $posted_id = item_store($datarray);
  2600. if(stristr($datarray['verb'],ACTIVITY_POKE)) {
  2601. $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
  2602. if(! $verb)
  2603. continue;
  2604. $xo = parse_xml_string($datarray['object'],false);
  2605. if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
  2606. // somebody was poked/prodded. Was it me?
  2607. $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
  2608. foreach($links->link as $l) {
  2609. $atts = $l->attributes();
  2610. switch($atts['rel']) {
  2611. case "alternate":
  2612. $Blink = $atts['href'];
  2613. break;
  2614. default:
  2615. break;
  2616. }
  2617. }
  2618. if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
  2619. // send a notification
  2620. require_once('include/enotify.php');
  2621. notification(array(
  2622. 'type' => NOTIFY_POKE,
  2623. 'notify_flags' => $importer['notify-flags'],
  2624. 'language' => $importer['language'],
  2625. 'to_name' => $importer['username'],
  2626. 'to_email' => $importer['email'],
  2627. 'uid' => $importer['importer_uid'],
  2628. 'item' => $datarray,
  2629. 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
  2630. 'source_name' => stripslashes($datarray['author-name']),
  2631. 'source_link' => $datarray['author-link'],
  2632. 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
  2633. ? $importer['thumb'] : $datarray['author-avatar']),
  2634. 'verb' => $datarray['verb'],
  2635. 'otype' => 'person',
  2636. 'activity' => $verb,
  2637. ));
  2638. }
  2639. }
  2640. }
  2641. continue;
  2642. }
  2643. }
  2644. return 0;
  2645. // NOTREACHED
  2646. }
  2647. function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
  2648. $url = notags(trim($datarray['author-link']));
  2649. $name = notags(trim($datarray['author-name']));
  2650. $photo = notags(trim($datarray['author-avatar']));
  2651. $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
  2652. if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
  2653. $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
  2654. if(is_array($contact)) {
  2655. if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
  2656. || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
  2657. $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
  2658. intval(CONTACT_IS_FRIEND),
  2659. intval($contact['id']),
  2660. intval($importer['uid'])
  2661. );
  2662. }
  2663. // send email notification to owner?
  2664. }
  2665. else {
  2666. // create contact record
  2667. $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
  2668. `blocked`, `readonly`, `pending`, `writable` )
  2669. VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
  2670. intval($importer['uid']),
  2671. dbesc(datetime_convert()),
  2672. dbesc($url),
  2673. dbesc(normalise_link($url)),
  2674. dbesc($name),
  2675. dbesc($nick),
  2676. dbesc($photo),
  2677. dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
  2678. intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
  2679. );
  2680. $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
  2681. intval($importer['uid']),
  2682. dbesc($url)
  2683. );
  2684. if(count($r))
  2685. $contact_record = $r[0];
  2686. // create notification
  2687. $hash = random_string();
  2688. if(is_array($contact_record)) {
  2689. $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
  2690. VALUES ( %d, %d, 0, 0, '%s', '%s' )",
  2691. intval($importer['uid']),
  2692. intval($contact_record['id']),
  2693. dbesc($hash),
  2694. dbesc(datetime_convert())
  2695. );
  2696. }
  2697. $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  2698. intval($importer['uid'])
  2699. );
  2700. $a = get_app();
  2701. if(count($r)) {
  2702. if(intval($r[0]['def_gid'])) {
  2703. require_once('include/group.php');
  2704. group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
  2705. }
  2706. if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
  2707. $email_tpl = get_intltext_template('follow_notify_eml.tpl');
  2708. $email = replace_macros($email_tpl, array(
  2709. '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
  2710. '$url' => $url,
  2711. '$myname' => $r[0]['username'],
  2712. '$siteurl' => $a->get_baseurl(),
  2713. '$sitename' => $a->config['sitename']
  2714. ));
  2715. $res = mail($r[0]['email'],
  2716. (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
  2717. $email,
  2718. 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
  2719. . 'Content-type: text/plain; charset=UTF-8' . "\n"
  2720. . 'Content-transfer-encoding: 8bit' );
  2721. }
  2722. }
  2723. }
  2724. }
  2725. function lose_follower($importer,$contact,$datarray,$item) {
  2726. if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
  2727. q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
  2728. intval(CONTACT_IS_SHARING),
  2729. intval($contact['id'])
  2730. );
  2731. }
  2732. else {
  2733. contact_remove($contact['id']);
  2734. }
  2735. }
  2736. function lose_sharer($importer,$contact,$datarray,$item) {
  2737. if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
  2738. q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
  2739. intval(CONTACT_IS_FOLLOWER),
  2740. intval($contact['id'])
  2741. );
  2742. }
  2743. else {
  2744. contact_remove($contact['id']);
  2745. }
  2746. }
  2747. function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
  2748. $a = get_app();
  2749. if(is_array($importer)) {
  2750. $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
  2751. intval($importer['uid'])
  2752. );
  2753. }
  2754. // Diaspora has different message-ids in feeds than they do
  2755. // through the direct Diaspora protocol. If we try and use
  2756. // the feed, we'll get duplicates. So don't.
  2757. if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
  2758. return;
  2759. $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
  2760. // Use a single verify token, even if multiple hubs
  2761. $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
  2762. $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
  2763. logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
  2764. if(! strlen($contact['hub-verify'])) {
  2765. $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
  2766. dbesc($verify_token),
  2767. intval($contact['id'])
  2768. );
  2769. }
  2770. post_url($url,$params);
  2771. logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
  2772. return;
  2773. }
  2774. function atom_author($tag,$name,$uri,$h,$w,$photo) {
  2775. $o = '';
  2776. if(! $tag)
  2777. return $o;
  2778. $name = xmlify($name);
  2779. $uri = xmlify($uri);
  2780. $h = intval($h);
  2781. $w = intval($w);
  2782. $photo = xmlify($photo);
  2783. $o .= "<$tag>\r\n";
  2784. $o .= "<name>$name</name>\r\n";
  2785. $o .= "<uri>$uri</uri>\r\n";
  2786. $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
  2787. $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
  2788. call_hooks('atom_author', $o);
  2789. $o .= "</$tag>\r\n";
  2790. return $o;
  2791. }
  2792. function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
  2793. $a = get_app();
  2794. if(! $item['parent'])
  2795. return;
  2796. if($item['deleted'])
  2797. return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
  2798. if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
  2799. $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
  2800. else
  2801. $body = $item['body'];
  2802. $o = "\r\n\r\n<entry>\r\n";
  2803. if(is_array($author))
  2804. $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
  2805. else
  2806. $o .= atom_author('author',(($item['author-name']) ? $item['author-name'] : $item['name']),(($item['author-link']) ? $item['author-link'] : $item['url']),80,80,(($item['author-avatar']) ? $item['author-avatar'] : $item['thumb']));
  2807. if(strlen($item['owner-name']))
  2808. $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
  2809. if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
  2810. $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
  2811. $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
  2812. }
  2813. $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
  2814. $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
  2815. $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
  2816. $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
  2817. $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
  2818. $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
  2819. $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
  2820. if($comment)
  2821. $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
  2822. if($item['location']) {
  2823. $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
  2824. $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
  2825. }
  2826. if($item['coord'])
  2827. $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
  2828. if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
  2829. $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
  2830. if($item['extid'])
  2831. $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
  2832. if($item['bookmark'])
  2833. $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
  2834. if($item['app'])
  2835. $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
  2836. if($item['guid'])
  2837. $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
  2838. if($item['signed_text']) {
  2839. $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
  2840. $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
  2841. }
  2842. $verb = construct_verb($item);
  2843. $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
  2844. $actobj = construct_activity_object($item);
  2845. if(strlen($actobj))
  2846. $o .= $actobj;
  2847. $actarg = construct_activity_target($item);
  2848. if(strlen($actarg))
  2849. $o .= $actarg;
  2850. $tags = item_getfeedtags($item);
  2851. if(count($tags)) {
  2852. foreach($tags as $t) {
  2853. $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
  2854. }
  2855. }
  2856. $o .= item_getfeedattach($item);
  2857. $mentioned = get_mentions($item);
  2858. if($mentioned)
  2859. $o .= $mentioned;
  2860. call_hooks('atom_entry', $o);
  2861. $o .= '</entry>' . "\r\n";
  2862. return $o;
  2863. }
  2864. function fix_private_photos($s, $uid, $item = null, $cid = 0) {
  2865. $a = get_app();
  2866. logger('fix_private_photos', LOGGER_DEBUG);
  2867. $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
  2868. $orig_body = $s;
  2869. $new_body = '';
  2870. $img_start = strpos($orig_body, '[img');
  2871. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  2872. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  2873. while( ($img_st_close !== false) && ($img_len !== false) ) {
  2874. $img_st_close++; // make it point to AFTER the closing bracket
  2875. $image = substr($orig_body, $img_start + $img_st_close, $img_len);
  2876. logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
  2877. if(stristr($image , $site . '/photo/')) {
  2878. // Only embed locally hosted photos
  2879. $replace = false;
  2880. $i = basename($image);
  2881. $i = str_replace(array('.jpg','.png'),array('',''),$i);
  2882. $x = strpos($i,'-');
  2883. if($x) {
  2884. $res = substr($i,$x+1);
  2885. $i = substr($i,0,$x);
  2886. $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
  2887. dbesc($i),
  2888. intval($res),
  2889. intval($uid)
  2890. );
  2891. if(count($r)) {
  2892. // Check to see if we should replace this photo link with an embedded image
  2893. // 1. No need to do so if the photo is public
  2894. // 2. If there's a contact-id provided, see if they're in the access list
  2895. // for the photo. If so, embed it.
  2896. // 3. Otherwise, if we have an item, see if the item permissions match the photo
  2897. // permissions, regardless of order but first check to see if they're an exact
  2898. // match to save some processing overhead.
  2899. if(has_permissions($r[0])) {
  2900. if($cid) {
  2901. $recips = enumerate_permissions($r[0]);
  2902. if(in_array($cid, $recips)) {
  2903. $replace = true;
  2904. }
  2905. }
  2906. elseif($item) {
  2907. if(compare_permissions($item,$r[0]))
  2908. $replace = true;
  2909. }
  2910. }
  2911. if($replace) {
  2912. $data = $r[0]['data'];
  2913. $type = $r[0]['type'];
  2914. // If a custom width and height were specified, apply before embedding
  2915. if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
  2916. logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
  2917. $width = intval($match[1]);
  2918. $height = intval($match[2]);
  2919. $ph = new Photo($data, $type);
  2920. if($ph->is_valid()) {
  2921. $ph->scaleImage(max($width, $height));
  2922. $data = $ph->imageString();
  2923. $type = $ph->getType();
  2924. }
  2925. }
  2926. logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
  2927. $image = 'data:' . $type . ';base64,' . base64_encode($data);
  2928. logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
  2929. }
  2930. }
  2931. }
  2932. }
  2933. $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
  2934. $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
  2935. if($orig_body === false)
  2936. $orig_body = '';
  2937. $img_start = strpos($orig_body, '[img');
  2938. $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
  2939. $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
  2940. }
  2941. $new_body = $new_body . $orig_body;
  2942. return($new_body);
  2943. }
  2944. function has_permissions($obj) {
  2945. if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
  2946. return true;
  2947. return false;
  2948. }
  2949. function compare_permissions($obj1,$obj2) {
  2950. // first part is easy. Check that these are exactly the same.
  2951. if(($obj1['allow_cid'] == $obj2['allow_cid'])
  2952. && ($obj1['allow_gid'] == $obj2['allow_gid'])
  2953. && ($obj1['deny_cid'] == $obj2['deny_cid'])
  2954. && ($obj1['deny_gid'] == $obj2['deny_gid']))
  2955. return true;
  2956. // This is harder. Parse all the permissions and compare the resulting set.
  2957. $recipients1 = enumerate_permissions($obj1);
  2958. $recipients2 = enumerate_permissions($obj2);
  2959. sort($recipients1);
  2960. sort($recipients2);
  2961. if($recipients1 == $recipients2)
  2962. return true;
  2963. return false;
  2964. }
  2965. // returns an array of contact-ids that are allowed to see this object
  2966. function enumerate_permissions($obj) {
  2967. require_once('include/group.php');
  2968. $allow_people = expand_acl($obj['allow_cid']);
  2969. $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
  2970. $deny_people = expand_acl($obj['deny_cid']);
  2971. $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
  2972. $recipients = array_unique(array_merge($allow_people,$allow_groups));
  2973. $deny = array_unique(array_merge($deny_people,$deny_groups));
  2974. $recipients = array_diff($recipients,$deny);
  2975. return $recipients;
  2976. }
  2977. function item_getfeedtags($item) {
  2978. $ret = array();
  2979. $matches = false;
  2980. $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
  2981. if($cnt) {
  2982. for($x = 0; $x < $cnt; $x ++) {
  2983. if($matches[1][$x])
  2984. $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
  2985. }
  2986. }
  2987. $matches = false;
  2988. $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
  2989. if($cnt) {
  2990. for($x = 0; $x < $cnt; $x ++) {
  2991. if($matches[1][$x])
  2992. $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
  2993. }
  2994. }
  2995. return $ret;
  2996. }
  2997. function item_getfeedattach($item) {
  2998. $ret = '';
  2999. $arr = explode(',',$item['attach']);
  3000. if(count($arr)) {
  3001. foreach($arr as $r) {
  3002. $matches = false;
  3003. $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
  3004. if($cnt) {
  3005. $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
  3006. if(intval($matches[2]))
  3007. $ret .= 'length="' . intval($matches[2]) . '" ';
  3008. if($matches[4] !== ' ')
  3009. $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
  3010. $ret .= ' />' . "\r\n";
  3011. }
  3012. }
  3013. }
  3014. return $ret;
  3015. }
  3016. function item_expire($uid,$days) {
  3017. if((! $uid) || ($days < 1))
  3018. return;
  3019. // $expire_network_only = save your own wall posts
  3020. // and just expire conversations started by others
  3021. $expire_network_only = get_pconfig($uid,'expire','network_only');
  3022. $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
  3023. $r = q("SELECT * FROM `item`
  3024. WHERE `uid` = %d
  3025. AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
  3026. AND `id` = `parent`
  3027. $sql_extra
  3028. AND `deleted` = 0",
  3029. intval($uid),
  3030. intval($days)
  3031. );
  3032. if(! count($r))
  3033. return;
  3034. $expire_items = get_pconfig($uid, 'expire','items');
  3035. $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
  3036. $expire_notes = get_pconfig($uid, 'expire','notes');
  3037. $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
  3038. $expire_starred = get_pconfig($uid, 'expire','starred');
  3039. $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
  3040. $expire_photos = get_pconfig($uid, 'expire','photos');
  3041. $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
  3042. logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
  3043. foreach($r as $item) {
  3044. // don't expire filed items
  3045. if(strpos($item['file'],'[') !== false)
  3046. continue;
  3047. // Only expire posts, not photos and photo comments
  3048. if($expire_photos==0 && strlen($item['resource-id']))
  3049. continue;
  3050. if($expire_starred==0 && intval($item['starred']))
  3051. continue;
  3052. if($expire_notes==0 && $item['type']=='note')
  3053. continue;
  3054. if($expire_items==0 && $item['type']!='note')
  3055. continue;
  3056. drop_item($item['id'],false);
  3057. }
  3058. proc_run('php',"include/notifier.php","expire","$uid");
  3059. }
  3060. function drop_items($items) {
  3061. $uid = 0;
  3062. if(! local_user() && ! remote_user())
  3063. return;
  3064. if(count($items)) {
  3065. foreach($items as $item) {
  3066. $owner = drop_item($item,false);
  3067. if($owner && ! $uid)
  3068. $uid = $owner;
  3069. }
  3070. }
  3071. // multiple threads may have been deleted, send an expire notification
  3072. if($uid)
  3073. proc_run('php',"include/notifier.php","expire","$uid");
  3074. }
  3075. function drop_item($id,$interactive = true) {
  3076. $a = get_app();
  3077. // locate item to be deleted
  3078. $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
  3079. intval($id)
  3080. );
  3081. if(! count($r)) {
  3082. if(! $interactive)
  3083. return 0;
  3084. notice( t('Item not found.') . EOL);
  3085. goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
  3086. }
  3087. $item = $r[0];
  3088. $owner = $item['uid'];
  3089. $cid = 0;
  3090. // check if logged in user is either the author or owner of this item
  3091. if(is_array($_SESSION['remote'])) {
  3092. foreach($_SESSION['remote'] as $visitor) {
  3093. if($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
  3094. $cid = $visitor['cid'];
  3095. break;
  3096. }
  3097. }
  3098. }
  3099. if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
  3100. logger('delete item: ' . $item['id'], LOGGER_DEBUG);
  3101. // delete the item
  3102. $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
  3103. dbesc(datetime_convert()),
  3104. dbesc(datetime_convert()),
  3105. intval($item['id'])
  3106. );
  3107. // clean up categories and tags so they don't end up as orphans
  3108. $matches = false;
  3109. $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
  3110. if($cnt) {
  3111. foreach($matches as $mtch) {
  3112. file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
  3113. }
  3114. }
  3115. $matches = false;
  3116. $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
  3117. if($cnt) {
  3118. foreach($matches as $mtch) {
  3119. file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
  3120. }
  3121. }
  3122. // If item is a link to a photo resource, nuke all the associated photos
  3123. // (visitors will not have photo resources)
  3124. // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
  3125. // generate a resource-id and therefore aren't intimately linked to the item.
  3126. if(strlen($item['resource-id'])) {
  3127. q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
  3128. dbesc($item['resource-id']),
  3129. intval($item['uid'])
  3130. );
  3131. // ignore the result
  3132. }
  3133. // If item is a link to an event, nuke the event record.
  3134. if(intval($item['event-id'])) {
  3135. q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  3136. intval($item['event-id']),
  3137. intval($item['uid'])
  3138. );
  3139. // ignore the result
  3140. }
  3141. // clean up item_id and sign meta-data tables
  3142. $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
  3143. intval($item['id']),
  3144. intval($item['uid'])
  3145. );
  3146. $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
  3147. intval($item['id']),
  3148. intval($item['uid'])
  3149. );
  3150. // If it's the parent of a comment thread, kill all the kids
  3151. if($item['uri'] == $item['parent-uri']) {
  3152. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
  3153. WHERE `parent-uri` = '%s' AND `uid` = %d ",
  3154. dbesc(datetime_convert()),
  3155. dbesc(datetime_convert()),
  3156. dbesc($item['parent-uri']),
  3157. intval($item['uid'])
  3158. );
  3159. // ignore the result
  3160. }
  3161. else {
  3162. // ensure that last-child is set in case the comment that had it just got wiped.
  3163. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  3164. dbesc(datetime_convert()),
  3165. dbesc($item['parent-uri']),
  3166. intval($item['uid'])
  3167. );
  3168. // who is the last child now?
  3169. $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
  3170. dbesc($item['parent-uri']),
  3171. intval($item['uid'])
  3172. );
  3173. if(count($r)) {
  3174. q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
  3175. intval($r[0]['id'])
  3176. );
  3177. }
  3178. // Add a relayable_retraction signature for Diaspora.
  3179. store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
  3180. }
  3181. $drop_id = intval($item['id']);
  3182. // send the notification upstream/downstream as the case may be
  3183. proc_run('php',"include/notifier.php","drop","$drop_id");
  3184. if(! $interactive)
  3185. return $owner;
  3186. goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
  3187. //NOTREACHED
  3188. }
  3189. else {
  3190. if(! $interactive)
  3191. return 0;
  3192. notice( t('Permission denied.') . EOL);
  3193. goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
  3194. //NOTREACHED
  3195. }
  3196. }
  3197. function first_post_date($uid,$wall = false) {
  3198. $r = q("select id, created from item
  3199. where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
  3200. and id = parent
  3201. order by created asc limit 1",
  3202. intval($uid),
  3203. intval($wall ? 1 : 0)
  3204. );
  3205. if(count($r)) {
  3206. // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
  3207. return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
  3208. }
  3209. return false;
  3210. }
  3211. function posted_dates($uid,$wall) {
  3212. $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
  3213. $dthen = first_post_date($uid,$wall);
  3214. if(! $dthen)
  3215. return array();
  3216. // If it's near the end of a long month, backup to the 28th so that in
  3217. // consecutive loops we'll always get a whole month difference.
  3218. if(intval(substr($dnow,8)) > 28)
  3219. $dnow = substr($dnow,0,8) . '28';
  3220. if(intval(substr($dthen,8)) > 28)
  3221. $dnow = substr($dthen,0,8) . '28';
  3222. $ret = array();
  3223. // Starting with the current month, get the first and last days of every
  3224. // month down to and including the month of the first post
  3225. while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
  3226. $dstart = substr($dnow,0,8) . '01';
  3227. $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
  3228. $start_month = datetime_convert('','',$dstart,'Y-m-d');
  3229. $end_month = datetime_convert('','',$dend,'Y-m-d');
  3230. $str = day_translate(datetime_convert('','',$dnow,'F Y'));
  3231. $ret[] = array($str,$end_month,$start_month);
  3232. $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
  3233. }
  3234. return $ret;
  3235. }
  3236. function posted_date_widget($url,$uid,$wall) {
  3237. $o = '';
  3238. if(! feature_enabled($uid,'archives'))
  3239. return $o;
  3240. // For former Facebook folks that left because of "timeline"
  3241. /* if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
  3242. return $o;*/
  3243. $ret = posted_dates($uid,$wall);
  3244. if(! count($ret))
  3245. return $o;
  3246. $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
  3247. '$title' => t('Archives'),
  3248. '$size' => ((count($ret) > 6) ? 6 : count($ret)),
  3249. '$url' => $url,
  3250. '$dates' => $ret
  3251. ));
  3252. return $o;
  3253. }
  3254. function store_diaspora_retract_sig($item, $user, $baseurl) {
  3255. // Note that we can't add a target_author_signature
  3256. // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
  3257. // the comment, that means we're the home of the post, and Diaspora will only
  3258. // check the parent_author_signature of retractions that it doesn't have to relay further
  3259. //
  3260. // I don't think this function gets called for an "unlike," but I'll check anyway
  3261. $enabled = intval(get_config('system','diaspora_enabled'));
  3262. if(! $enabled) {
  3263. logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
  3264. return;
  3265. }
  3266. logger('drop_item: storing diaspora retraction signature');
  3267. $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
  3268. if(local_user() == $item['uid']) {
  3269. $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
  3270. $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
  3271. }
  3272. else {
  3273. $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
  3274. $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
  3275. );
  3276. if(count($r)) {
  3277. // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
  3278. // only handles DFRN deletes
  3279. $handle_baseurl_start = strpos($r['url'],'://') + 3;
  3280. $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
  3281. $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
  3282. $authorsig = '';
  3283. }
  3284. }
  3285. if(isset($handle))
  3286. q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
  3287. intval($item['id']),
  3288. dbesc($signed_text),
  3289. dbesc($authorsig),
  3290. dbesc($handle)
  3291. );
  3292. return;
  3293. }