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.
 
 
 
 
 
 

3056 lines
99 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. function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
  7. // default permissions - anonymous user
  8. if(! strlen($owner_nick))
  9. killme();
  10. $public_feed = (($dfrn_id) ? false : true);
  11. $starred = false;
  12. $converse = false;
  13. if($public_feed && $a->argc > 2) {
  14. for($x = 2; $x < $a->argc; $x++) {
  15. if($a->argv[$x] == 'converse')
  16. $converse = true;
  17. if($a->argv[$x] == 'starred')
  18. $starred = true;
  19. }
  20. }
  21. $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
  22. $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
  23. FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
  24. WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
  25. dbesc($owner_nick)
  26. );
  27. if(! count($r))
  28. killme();
  29. $owner = $r[0];
  30. $owner_id = $owner['user_uid'];
  31. $owner_nick = $owner['nickname'];
  32. $birthday = feed_birthday($owner_id,$owner['timezone']);
  33. if(! $public_feed) {
  34. $sql_extra = '';
  35. switch($direction) {
  36. case (-1):
  37. $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
  38. $my_id = $dfrn_id;
  39. break;
  40. case 0:
  41. $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
  42. $my_id = '1:' . $dfrn_id;
  43. break;
  44. case 1:
  45. $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
  46. $my_id = '0:' . $dfrn_id;
  47. break;
  48. default:
  49. return false;
  50. break; // NOTREACHED
  51. }
  52. $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
  53. intval($owner_id)
  54. );
  55. if(! count($r))
  56. killme();
  57. $contact = $r[0];
  58. $groups = init_groups_visitor($contact['id']);
  59. if(count($groups)) {
  60. for($x = 0; $x < count($groups); $x ++)
  61. $groups[$x] = '<' . intval($groups[$x]) . '>' ;
  62. $gs = implode('|', $groups);
  63. }
  64. else
  65. $gs = '<<>>' ; // Impossible to match
  66. $sql_extra = sprintf("
  67. AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
  68. AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
  69. AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
  70. AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
  71. ",
  72. intval($contact['id']),
  73. intval($contact['id']),
  74. dbesc($gs),
  75. dbesc($gs)
  76. );
  77. }
  78. if($public_feed)
  79. $sort = 'DESC';
  80. else
  81. $sort = 'ASC';
  82. if(! strlen($last_update))
  83. $last_update = 'now -30 days';
  84. if($public_feed) {
  85. if(! $converse)
  86. $sql_extra .= " AND `contact`.`self` = 1 ";
  87. }
  88. $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
  89. $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
  90. `contact`.`name`, `contact`.`photo`, `contact`.`url`,
  91. `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
  92. `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
  93. `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
  94. `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
  95. FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  96. LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
  97. WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
  98. AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
  99. AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
  100. $sql_extra
  101. ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
  102. intval($owner_id),
  103. dbesc($check_date),
  104. dbesc($check_date),
  105. dbesc($sort)
  106. );
  107. // Will check further below if this actually returned results.
  108. // We will provide an empty feed if that is the case.
  109. $items = $r;
  110. $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
  111. $atom = '';
  112. $hubxml = feed_hublinks();
  113. $salmon = feed_salmonlinks($owner_nick);
  114. $atom .= replace_macros($feed_template, array(
  115. '$version' => xmlify(FRIENDICA_VERSION),
  116. '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
  117. '$feed_title' => xmlify($owner['name']),
  118. '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
  119. '$hub' => $hubxml,
  120. '$salmon' => $salmon,
  121. '$name' => xmlify($owner['name']),
  122. '$profile_page' => xmlify($owner['url']),
  123. '$photo' => xmlify($owner['photo']),
  124. '$thumb' => xmlify($owner['thumb']),
  125. '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
  126. '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
  127. '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
  128. '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
  129. ));
  130. call_hooks('atom_feed', $atom);
  131. if(! count($items)) {
  132. call_hooks('atom_feed_end', $atom);
  133. $atom .= '</feed>' . "\r\n";
  134. return $atom;
  135. }
  136. foreach($items as $item) {
  137. // public feeds get html, our own nodes use bbcode
  138. if($public_feed) {
  139. $type = 'html';
  140. // catch any email that's in a public conversation and make sure it doesn't leak
  141. if($item['private'])
  142. continue;
  143. }
  144. else {
  145. $type = 'text';
  146. }
  147. $atom .= atom_entry($item,$type,null,$owner,true);
  148. }
  149. call_hooks('atom_feed_end', $atom);
  150. $atom .= '</feed>' . "\r\n";
  151. return $atom;
  152. }
  153. function construct_verb($item) {
  154. if($item['verb'])
  155. return $item['verb'];
  156. return ACTIVITY_POST;
  157. }
  158. function construct_activity_object($item) {
  159. if($item['object']) {
  160. $o = '<as:object>' . "\r\n";
  161. $r = parse_xml_string($item['object'],false);
  162. if(! $r)
  163. return '';
  164. if($r->type)
  165. $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
  166. if($r->id)
  167. $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
  168. if($r->title)
  169. $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
  170. if($r->link) {
  171. if(substr($r->link,0,1) === '<') {
  172. // patch up some facebook "like" activity objects that got stored incorrectly
  173. // for a couple of months prior to 9-Jun-2011 and generated bad XML.
  174. // we can probably remove this hack here and in the following function in a few months time.
  175. if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
  176. $r->link = str_replace('&','&amp;', $r->link);
  177. $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
  178. $o .= $r->link;
  179. }
  180. else
  181. $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
  182. }
  183. if($r->content)
  184. $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
  185. $o .= '</as:object>' . "\r\n";
  186. return $o;
  187. }
  188. return '';
  189. }
  190. function construct_activity_target($item) {
  191. if($item['target']) {
  192. $o = '<as:target>' . "\r\n";
  193. $r = parse_xml_string($item['target'],false);
  194. if(! $r)
  195. return '';
  196. if($r->type)
  197. $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
  198. if($r->id)
  199. $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
  200. if($r->title)
  201. $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
  202. if($r->link) {
  203. if(substr($r->link,0,1) === '<') {
  204. if(strstr($r->link,'&') && (! strstr($r->link,'&amp;')))
  205. $r->link = str_replace('&','&amp;', $r->link);
  206. $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
  207. $o .= $r->link;
  208. }
  209. else
  210. $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
  211. }
  212. if($r->content)
  213. $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
  214. $o .= '</as:target>' . "\r\n";
  215. return $o;
  216. }
  217. return '';
  218. }
  219. function get_atom_elements($feed,$item) {
  220. require_once('library/HTMLPurifier.auto.php');
  221. require_once('include/html2bbcode.php');
  222. $best_photo = array();
  223. $res = array();
  224. $author = $item->get_author();
  225. if($author) {
  226. $res['author-name'] = unxmlify($author->get_name());
  227. $res['author-link'] = unxmlify($author->get_link());
  228. }
  229. else {
  230. $res['author-name'] = unxmlify($feed->get_title());
  231. $res['author-link'] = unxmlify($feed->get_permalink());
  232. }
  233. $res['uri'] = unxmlify($item->get_id());
  234. $res['title'] = unxmlify($item->get_title());
  235. $res['body'] = unxmlify($item->get_content());
  236. $res['plink'] = unxmlify($item->get_link(0));
  237. if($res['plink'])
  238. $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
  239. else
  240. $base_url = '';
  241. // look for a photo. We should check media size and find the best one,
  242. // but for now let's just find any author photo
  243. $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
  244. if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
  245. $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  246. foreach($base as $link) {
  247. if(!x($res, 'author-avatar') || !$res['author-avatar']) {
  248. if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
  249. $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
  250. }
  251. }
  252. }
  253. $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
  254. if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
  255. $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  256. if($base && count($base)) {
  257. foreach($base as $link) {
  258. if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
  259. $res['author-link'] = unxmlify($link['attribs']['']['href']);
  260. if(!x($res, 'author-avatar') || !$res['author-avatar']) {
  261. if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
  262. $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
  263. }
  264. }
  265. }
  266. }
  267. // No photo/profile-link on the item - look at the feed level
  268. if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
  269. $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
  270. if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
  271. $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  272. foreach($base as $link) {
  273. if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
  274. $res['author-link'] = unxmlify($link['attribs']['']['href']);
  275. if(! $res['author-avatar']) {
  276. if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
  277. $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
  278. }
  279. }
  280. }
  281. $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
  282. if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
  283. $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  284. if($base && count($base)) {
  285. foreach($base as $link) {
  286. if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
  287. $res['author-link'] = unxmlify($link['attribs']['']['href']);
  288. if(! (x($res,'author-avatar'))) {
  289. if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
  290. $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
  291. }
  292. }
  293. }
  294. }
  295. }
  296. $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
  297. if($apps && $apps[0]['attribs']['']['source']) {
  298. $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
  299. if($res['app'] === 'web')
  300. $res['app'] = 'OStatus';
  301. }
  302. // base64 encoded json structure representing Diaspora signature
  303. $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
  304. if($dsig) {
  305. $res['dsprsig'] = unxmlify($dsig[0]['data']);
  306. }
  307. $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
  308. if($dguid)
  309. $res['guid'] = unxmlify($dguid[0]['data']);
  310. $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
  311. if($bm)
  312. $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
  313. /**
  314. * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
  315. */
  316. $have_real_body = false;
  317. $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
  318. if($rawenv) {
  319. $have_real_body = true;
  320. $res['body'] = $rawenv[0]['data'];
  321. $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
  322. // make sure nobody is trying to sneak some html tags by us
  323. $res['body'] = notags(base64url_decode($res['body']));
  324. }
  325. $maxlen = get_max_import_size();
  326. if($maxlen && (strlen($res['body']) > $maxlen))
  327. $res['body'] = substr($res['body'],0, $maxlen);
  328. // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
  329. // the content type. Our own network only emits text normally, though it might have been converted to
  330. // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
  331. // have to assume it is all html and needs to be purified.
  332. // It doesn't matter all that much security wise - because before this content is used anywhere, we are
  333. // going to escape any tags we find regardless, but this lets us import a limited subset of html from
  334. // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
  335. // html.
  336. if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
  337. $res['body'] = reltoabs($res['body'],$base_url);
  338. $res['body'] = html2bb_video($res['body']);
  339. $res['body'] = oembed_html2bbcode($res['body']);
  340. $config = HTMLPurifier_Config::createDefault();
  341. $config->set('Cache.DefinitionImpl', null);
  342. // we shouldn't need a whitelist, because the bbcode converter
  343. // will strip out any unsupported tags.
  344. // $config->set('HTML.Allowed', 'p,b,a[href],i');
  345. $purifier = new HTMLPurifier($config);
  346. $res['body'] = $purifier->purify($res['body']);
  347. $res['body'] = html2bbcode($res['body']);
  348. }
  349. $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
  350. if($allow && $allow[0]['data'] == 1)
  351. $res['last-child'] = 1;
  352. else
  353. $res['last-child'] = 0;
  354. $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
  355. if($private && $private[0]['data'] == 1)
  356. $res['private'] = 1;
  357. else
  358. $res['private'] = 0;
  359. $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
  360. if($extid && $extid[0]['data'])
  361. $res['extid'] = $extid[0]['data'];
  362. $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
  363. if($rawlocation)
  364. $res['location'] = unxmlify($rawlocation[0]['data']);
  365. $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
  366. if($rawcreated)
  367. $res['created'] = unxmlify($rawcreated[0]['data']);
  368. $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
  369. if($rawedited)
  370. $res['edited'] = unxmlify($rawedited[0]['data']);
  371. if((x($res,'edited')) && (! (x($res,'created'))))
  372. $res['created'] = $res['edited'];
  373. if(! $res['created'])
  374. $res['created'] = $item->get_date('c');
  375. if(! $res['edited'])
  376. $res['edited'] = $item->get_date('c');
  377. // Disallow time travelling posts
  378. $d1 = strtotime($res['created']);
  379. $d2 = strtotime($res['edited']);
  380. $d3 = strtotime('now');
  381. if($d1 > $d3)
  382. $res['created'] = datetime_convert();
  383. if($d2 > $d3)
  384. $res['edited'] = datetime_convert();
  385. $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
  386. if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
  387. $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
  388. elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
  389. $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
  390. if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
  391. $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
  392. elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
  393. $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
  394. if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
  395. $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
  396. foreach($base as $link) {
  397. if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
  398. if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
  399. $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
  400. }
  401. }
  402. }
  403. $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
  404. if($rawgeo)
  405. $res['coord'] = unxmlify($rawgeo[0]['data']);
  406. $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
  407. // select between supported verbs
  408. if($rawverb) {
  409. $res['verb'] = unxmlify($rawverb[0]['data']);
  410. }
  411. // translate OStatus unfollow to activity streams if it happened to get selected
  412. if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
  413. $res['verb'] = ACTIVITY_UNFOLLOW;
  414. $cats = $item->get_categories();
  415. if($cats) {
  416. $tag_arr = array();
  417. foreach($cats as $cat) {
  418. $term = $cat->get_term();
  419. if(! $term)
  420. $term = $cat->get_label();
  421. $scheme = $cat->get_scheme();
  422. if($scheme && $term && stristr($scheme,'X-DFRN:'))
  423. $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
  424. elseif($term)
  425. $tag_arr[] = notags(trim($term));
  426. }
  427. $res['tag'] = implode(',', $tag_arr);
  428. }
  429. $attach = $item->get_enclosures();
  430. if($attach) {
  431. $att_arr = array();
  432. foreach($attach as $att) {
  433. $len = intval($att->get_length());
  434. $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
  435. $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
  436. $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
  437. if(strpos($type,';'))
  438. $type = substr($type,0,strpos($type,';'));
  439. if((! $link) || (strpos($link,'http') !== 0))
  440. continue;
  441. if(! $title)
  442. $title = ' ';
  443. if(! $type)
  444. $type = 'application/octet-stream';
  445. $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
  446. }
  447. $res['attach'] = implode(',', $att_arr);
  448. }
  449. $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
  450. if($rawobj) {
  451. $res['object'] = '<object>' . "\n";
  452. if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
  453. $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
  454. $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
  455. }
  456. if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
  457. $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
  458. if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
  459. $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
  460. if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
  461. $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
  462. if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
  463. $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
  464. if(! $body)
  465. $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
  466. // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
  467. $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
  468. if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
  469. $body = html2bb_video($body);
  470. $config = HTMLPurifier_Config::createDefault();
  471. $config->set('Cache.DefinitionImpl', null);
  472. $purifier = new HTMLPurifier($config);
  473. $body = $purifier->purify($body);
  474. $body = html2bbcode($body);
  475. }
  476. $res['object'] .= '<content>' . $body . '</content>' . "\n";
  477. }
  478. $res['object'] .= '</object>' . "\n";
  479. }
  480. $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
  481. if($rawobj) {
  482. $res['target'] = '<target>' . "\n";
  483. if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
  484. $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
  485. }
  486. if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
  487. $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
  488. if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
  489. $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
  490. if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
  491. $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
  492. if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
  493. $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
  494. if(! $body)
  495. $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
  496. // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
  497. $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
  498. if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
  499. $body = html2bb_video($body);
  500. $config = HTMLPurifier_Config::createDefault();
  501. $config->set('Cache.DefinitionImpl', null);
  502. $purifier = new HTMLPurifier($config);
  503. $body = $purifier->purify($body);
  504. $body = html2bbcode($body);
  505. }
  506. $res['target'] .= '<content>' . $body . '</content>' . "\n";
  507. }
  508. $res['target'] .= '</target>' . "\n";
  509. }
  510. $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
  511. call_hooks('parse_atom', $arr);
  512. return $res;
  513. }
  514. function encode_rel_links($links) {
  515. $o = '';
  516. if(! ((is_array($links)) && (count($links))))
  517. return $o;
  518. foreach($links as $link) {
  519. $o .= '<link ';
  520. if($link['attribs']['']['rel'])
  521. $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
  522. if($link['attribs']['']['type'])
  523. $o .= 'type="' . $link['attribs']['']['type'] . '" ';
  524. if($link['attribs']['']['href'])
  525. $o .= 'href="' . $link['attribs']['']['href'] . '" ';
  526. if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
  527. $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
  528. if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
  529. $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
  530. $o .= ' />' . "\n" ;
  531. }
  532. return xmlify($o);
  533. }
  534. function item_store($arr,$force_parent = false) {
  535. // If a Diaspora signature structure was passed in, pull it out of the
  536. // item array and set it aside for later storage.
  537. $dsprsig = null;
  538. if(x($arr,'dsprsig')) {
  539. $dsprsig = json_decode(base64_decode($arr['dsprsig']));
  540. unset($arr['dsprsig']);
  541. }
  542. if(x($arr, 'gravity'))
  543. $arr['gravity'] = intval($arr['gravity']);
  544. elseif($arr['parent-uri'] === $arr['uri'])
  545. $arr['gravity'] = 0;
  546. elseif(activity_match($arr['verb'],ACTIVITY_POST))
  547. $arr['gravity'] = 6;
  548. else
  549. $arr['gravity'] = 6; // extensible catchall
  550. if(! x($arr,'type'))
  551. $arr['type'] = 'remote';
  552. // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
  553. if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
  554. $arr['body'] = strip_tags($arr['body']);
  555. $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
  556. $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
  557. $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
  558. $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
  559. $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
  560. $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
  561. $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
  562. $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
  563. $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
  564. $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
  565. $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
  566. $arr['commented'] = datetime_convert();
  567. $arr['received'] = datetime_convert();
  568. $arr['changed'] = datetime_convert();
  569. $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
  570. $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
  571. $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
  572. $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
  573. $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
  574. $arr['deleted'] = 0;
  575. $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
  576. $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
  577. $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
  578. $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
  579. $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
  580. $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
  581. $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
  582. $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
  583. $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
  584. $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
  585. $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
  586. $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
  587. $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
  588. $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
  589. $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
  590. $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
  591. $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
  592. $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
  593. $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
  594. if($arr['parent-uri'] === $arr['uri']) {
  595. $parent_id = 0;
  596. $parent_deleted = 0;
  597. $allow_cid = $arr['allow_cid'];
  598. $allow_gid = $arr['allow_gid'];
  599. $deny_cid = $arr['deny_cid'];
  600. $deny_gid = $arr['deny_gid'];
  601. }
  602. else {
  603. // find the parent and snarf the item id and ACL's
  604. // and anything else we need to inherit
  605. $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
  606. dbesc($arr['parent-uri']),
  607. intval($arr['uid'])
  608. );
  609. if(count($r)) {
  610. // is the new message multi-level threaded?
  611. // even though we don't support it now, preserve the info
  612. // and re-attach to the conversation parent.
  613. if($r[0]['uri'] != $r[0]['parent-uri']) {
  614. $arr['thr-parent'] = $arr['parent-uri'];
  615. $arr['parent-uri'] = $r[0]['parent-uri'];
  616. $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
  617. ORDER BY `id` ASC LIMIT 1",
  618. dbesc($r[0]['parent-uri']),
  619. dbesc($r[0]['parent-uri']),
  620. intval($arr['uid'])
  621. );
  622. if($z && count($z))
  623. $r = $z;
  624. }
  625. $parent_id = $r[0]['id'];
  626. $parent_deleted = $r[0]['deleted'];
  627. $allow_cid = $r[0]['allow_cid'];
  628. $allow_gid = $r[0]['allow_gid'];
  629. $deny_cid = $r[0]['deny_cid'];
  630. $deny_gid = $r[0]['deny_gid'];
  631. $arr['wall'] = $r[0]['wall'];
  632. }
  633. else {
  634. // Allow one to see reply tweets from status.net even when
  635. // we don't have or can't see the original post.
  636. if($force_parent) {
  637. logger('item_store: $force_parent=true, reply converted to top-level post.');
  638. $parent_id = 0;
  639. $arr['thr-parent'] = $arr['parent-uri'];
  640. $arr['parent-uri'] = $arr['uri'];
  641. $arr['gravity'] = 0;
  642. }
  643. else {
  644. logger('item_store: item parent was not found - ignoring item');
  645. return 0;
  646. }
  647. $parent_deleted = 0;
  648. }
  649. }
  650. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  651. dbesc($arr['uri']),
  652. intval($arr['uid'])
  653. );
  654. if($r && count($r)) {
  655. logger('item-store: duplicate item ignored. ' . print_r($arr,true));
  656. return 0;
  657. }
  658. call_hooks('post_remote',$arr);
  659. if(x($arr,'cancel')) {
  660. logger('item_store: post cancelled by plugin.');
  661. return 0;
  662. }
  663. dbesc_array($arr);
  664. logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
  665. $r = dbq("INSERT INTO `item` (`"
  666. . implode("`, `", array_keys($arr))
  667. . "`) VALUES ('"
  668. . implode("', '", array_values($arr))
  669. . "')" );
  670. // find the item we just created
  671. $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
  672. $arr['uri'], // already dbesc'd
  673. intval($arr['uid'])
  674. );
  675. if(count($r)) {
  676. $current_post = $r[0]['id'];
  677. logger('item_store: created item ' . $current_post);
  678. }
  679. else {
  680. logger('item_store: could not locate created item');
  681. return 0;
  682. }
  683. if(count($r) > 1) {
  684. logger('item_store: duplicated post occurred. Removing duplicates.');
  685. q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
  686. $arr['uri'],
  687. intval($arr['uid']),
  688. intval($current_post)
  689. );
  690. }
  691. if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
  692. $parent_id = $current_post;
  693. if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
  694. $private = 1;
  695. else
  696. $private = $arr['private'];
  697. // Set parent id - and also make sure to inherit the parent's ACL's.
  698. $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
  699. `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
  700. intval($parent_id),
  701. dbesc($allow_cid),
  702. dbesc($allow_gid),
  703. dbesc($deny_cid),
  704. dbesc($deny_gid),
  705. intval($private),
  706. intval($parent_deleted),
  707. intval($current_post)
  708. );
  709. // update the commented timestamp on the parent
  710. q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
  711. dbesc(datetime_convert()),
  712. dbesc(datetime_convert()),
  713. intval($parent_id)
  714. );
  715. if($dsprsig) {
  716. q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
  717. intval($current_post),
  718. dbesc($dsprsig->signed_text),
  719. dbesc($dsprsig->signature),
  720. dbesc($dsprsig->signer)
  721. );
  722. }
  723. /**
  724. * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
  725. */
  726. if($arr['last-child']) {
  727. $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
  728. dbesc($arr['uri']),
  729. intval($arr['uid']),
  730. intval($current_post)
  731. );
  732. }
  733. tag_deliver($arr['uid'],$current_post);
  734. return $current_post;
  735. }
  736. function get_item_contact($item,$contacts) {
  737. if(! count($contacts) || (! is_array($item)))
  738. return false;
  739. foreach($contacts as $contact) {
  740. if($contact['id'] == $item['contact-id']) {
  741. return $contact;
  742. break; // NOTREACHED
  743. }
  744. }
  745. return false;
  746. }
  747. function tag_deliver($uid,$item_id) {
  748. // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
  749. $a = get_app();
  750. $mention = false;
  751. $u = q("select uid, nickname, language, username, email, `page-flags`, `notify-flags` from user where uid = %d limit 1",
  752. intval($uid)
  753. );
  754. if(! count($u))
  755. return;
  756. $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
  757. $i = q("select * from item where id = %d and uid = %d limit 1",
  758. intval($item_id),
  759. intval($uid)
  760. );
  761. if(! count($i))
  762. return;
  763. $item = $i[0];
  764. $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
  765. // Diaspora uses their own hardwired link URL in @-tags
  766. // instead of the one we supply with webfinger
  767. $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
  768. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
  769. if($cnt) {
  770. foreach($matches as $mtch) {
  771. if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
  772. $mention = true;
  773. logger('tag_deliver: mention found: ' . $mtch[2]);
  774. }
  775. }
  776. }
  777. if(! $mention)
  778. return;
  779. // send a notification
  780. require_once('include/enotify.php');
  781. notification(array(
  782. 'type' => NOTIFY_TAGSELF,
  783. 'notify_flags' => $u[0]['notify-flags'],
  784. 'language' => $u[0]['language'],
  785. 'to_name' => $u[0]['username'],
  786. 'to_email' => $u[0]['email'],
  787. 'uid' => $u[0]['uid'],
  788. 'item' => $item,
  789. 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
  790. 'source_name' => $item['author-name'],
  791. 'source_link' => $item['author-link'],
  792. 'source_photo' => $item['author-avatar'],
  793. 'verb' => ACTIVITY_TAG,
  794. 'otype' => 'item'
  795. ));
  796. if(! $community_page)
  797. return;
  798. // tgroup delivery - setup a second delivery chain
  799. // prevent delivery looping - only proceed
  800. // if the message originated elsewhere and is a top-level post
  801. if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
  802. return;
  803. // now change this copy of the post to a forum head message and deliver to all the tgroup members
  804. $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
  805. intval($u[0]['uid'])
  806. );
  807. if(! count($c))
  808. return;
  809. q("update item set wall = 1, origin = 1, forum_mode = 1, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s' where id = %d limit 1",
  810. dbesc($c[0]['name']),
  811. dbesc($c[0]['url']),
  812. dbesc($c[0]['thumb']),
  813. intval($item_id)
  814. );
  815. proc_run('php','include/notifier.php','tgroup',$item_id);
  816. }
  817. function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
  818. $a = get_app();
  819. // if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
  820. // return 3;
  821. $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
  822. if($contact['duplex'] && $contact['dfrn-id'])
  823. $idtosend = '0:' . $orig_id;
  824. if($contact['duplex'] && $contact['issued-id'])
  825. $idtosend = '1:' . $orig_id;
  826. $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
  827. $rino_enable = get_config('system','rino_encrypt');
  828. if(! $rino_enable)
  829. $rino = 0;
  830. $ssl_val = intval(get_config('system','ssl_policy'));
  831. $ssl_policy = '';
  832. switch($ssl_val){
  833. case SSL_POLICY_FULL:
  834. $ssl_policy = 'full';
  835. break;
  836. case SSL_POLICY_SELFSIGN:
  837. $ssl_policy = 'self';
  838. break;
  839. case SSL_POLICY_NONE:
  840. default:
  841. $ssl_policy = 'none';
  842. break;
  843. }
  844. $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
  845. logger('dfrn_deliver: ' . $url);
  846. $xml = fetch_url($url);
  847. $curl_stat = $a->get_curl_code();
  848. if(! $curl_stat)
  849. return(-1); // timed out
  850. logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
  851. if(! $xml)
  852. return 3;
  853. if(strpos($xml,'<?xml') === false) {
  854. logger('dfrn_deliver: no valid XML returned');
  855. logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
  856. return 3;
  857. }
  858. $res = parse_xml_string($xml);
  859. if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
  860. return (($res->status) ? $res->status : 3);
  861. $postvars = array();
  862. $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
  863. $challenge = hex2bin((string) $res->challenge);
  864. $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
  865. $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
  866. $final_dfrn_id = '';
  867. if(($contact['duplex'] && strlen($contact['pubkey']))
  868. || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
  869. || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
  870. openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
  871. openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
  872. }
  873. else {
  874. openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
  875. openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
  876. }
  877. $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
  878. if(strpos($final_dfrn_id,':') == 1)
  879. $final_dfrn_id = substr($final_dfrn_id,2);
  880. if($final_dfrn_id != $orig_id) {
  881. logger('dfrn_deliver: wrong dfrn_id.');
  882. // did not decode properly - cannot trust this site
  883. return 3;
  884. }
  885. $postvars['dfrn_id'] = $idtosend;
  886. $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
  887. if($dissolve)
  888. $postvars['dissolve'] = '1';
  889. if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
  890. $postvars['data'] = $atom;
  891. $postvars['perm'] = 'rw';
  892. }
  893. else {
  894. $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
  895. $postvars['perm'] = 'r';
  896. }
  897. $postvars['ssl_policy'] = $ssl_policy;
  898. if($rino && $rino_allowed && (! $dissolve)) {
  899. $key = substr(random_string(),0,16);
  900. $data = bin2hex(aes_encrypt($postvars['data'],$key));
  901. $postvars['data'] = $data;
  902. logger('rino: sent key = ' . $key, LOGGER_DEBUG);
  903. if($dfrn_version >= 2.1) {
  904. if(($contact['duplex'] && strlen($contact['pubkey']))
  905. || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
  906. || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
  907. openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
  908. }
  909. else {
  910. openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
  911. }
  912. }
  913. else {
  914. if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
  915. openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
  916. }
  917. else {
  918. openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
  919. }
  920. }
  921. logger('md5 rawkey ' . md5($postvars['key']));
  922. $postvars['key'] = bin2hex($postvars['key']);
  923. }
  924. logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
  925. $xml = post_url($contact['notify'],$postvars);
  926. logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
  927. $curl_stat = $a->get_curl_code();
  928. if((! $curl_stat) || (! strlen($xml)))
  929. return(-1); // timed out
  930. if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
  931. return(-1);
  932. if(strpos($xml,'<?xml') === false) {
  933. logger('dfrn_deliver: phase 2: no valid XML returned');
  934. logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
  935. return 3;
  936. }
  937. $res = parse_xml_string($xml);
  938. return $res->status;
  939. }
  940. /**
  941. *
  942. * consume_feed - process atom feed and update anything/everything we might need to update
  943. *
  944. * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
  945. *
  946. * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
  947. * It is this person's stuff that is going to be updated.
  948. * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
  949. * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
  950. * have a contact record.
  951. * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
  952. * might not) try and subscribe to it.
  953. * $datedir sorts in reverse order
  954. * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
  955. * imported prior to its children being seen in the stream unless we are certain
  956. * of how the feed is arranged/ordered.
  957. * With $pass = 1, we only pull parent items out of the stream.
  958. * With $pass = 2, we only pull children (comments/likes).
  959. *
  960. * So running this twice, first with pass 1 and then with pass 2 will do the right
  961. * thing regardless of feed ordering. This won't be adequate in a fully-threaded
  962. * model where comments can have sub-threads. That would require some massive sorting
  963. * to get all the feed items into a mostly linear ordering, and might still require
  964. * recursion.
  965. */
  966. function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
  967. require_once('library/simplepie/simplepie.inc');
  968. if(! strlen($xml)) {
  969. logger('consume_feed: empty input');
  970. return;
  971. }
  972. $feed = new SimplePie();
  973. $feed->set_raw_data($xml);
  974. if($datedir)
  975. $feed->enable_order_by_date(true);
  976. else
  977. $feed->enable_order_by_date(false);
  978. $feed->init();
  979. if($feed->error())
  980. logger('consume_feed: Error parsing XML: ' . $feed->error());
  981. $permalink = $feed->get_permalink();
  982. // Check at the feed level for updated contact name and/or photo
  983. $name_updated = '';
  984. $new_name = '';
  985. $photo_timestamp = '';
  986. $photo_url = '';
  987. $birthday = '';
  988. $hubs = $feed->get_links('hub');
  989. if(count($hubs))
  990. $hub = implode(',', $hubs);
  991. $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
  992. if(! $rawtags)
  993. $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
  994. if($rawtags) {
  995. $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
  996. if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
  997. $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
  998. $new_name = $elems['name'][0]['data'];
  999. }
  1000. if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
  1001. $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
  1002. $photo_url = $elems['link'][0]['attribs']['']['href'];
  1003. }
  1004. if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
  1005. $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
  1006. }
  1007. }
  1008. if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
  1009. logger('consume_feed: Updating photo for ' . $contact['name']);
  1010. require_once("Photo.php");
  1011. $photo_failure = false;
  1012. $have_photo = false;
  1013. $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
  1014. intval($contact['id']),
  1015. intval($contact['uid'])
  1016. );
  1017. if(count($r)) {
  1018. $resource_id = $r[0]['resource-id'];
  1019. $have_photo = true;
  1020. }
  1021. else {
  1022. $resource_id = photo_new_resource();
  1023. }
  1024. $img_str = fetch_url($photo_url,true);
  1025. $img = new Photo($img_str);
  1026. if($img->is_valid()) {
  1027. if($have_photo) {
  1028. q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
  1029. dbesc($resource_id),
  1030. intval($contact['id']),
  1031. intval($contact['uid'])
  1032. );
  1033. }
  1034. $img->scaleImageSquare(175);
  1035. $hash = $resource_id;
  1036. $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
  1037. $img->scaleImage(80);
  1038. $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
  1039. $img->scaleImage(48);
  1040. $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
  1041. $a = get_app();
  1042. q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
  1043. WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1044. dbesc(datetime_convert()),
  1045. dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
  1046. dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
  1047. dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
  1048. intval($contact['uid']),
  1049. intval($contact['id'])
  1050. );
  1051. }
  1052. }
  1053. if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
  1054. $r = q("select * from contact where uid = %d and id = %d limit 1",
  1055. intval($contact['uid']),
  1056. intval($contact['id'])
  1057. );
  1058. $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1059. dbesc(notags(trim($new_name))),
  1060. dbesc(datetime_convert()),
  1061. intval($contact['uid']),
  1062. intval($contact['id'])
  1063. );
  1064. // do our best to update the name on content items
  1065. if(count($r)) {
  1066. q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
  1067. dbesc(notags(trim($new_name))),
  1068. dbesc($r[0]['name']),
  1069. dbesc($r[0]['url']),
  1070. intval($contact['uid'])
  1071. );
  1072. }
  1073. }
  1074. if(strlen($birthday)) {
  1075. if(substr($birthday,0,4) != $contact['bdyear']) {
  1076. logger('consume_feed: updating birthday: ' . $birthday);
  1077. /**
  1078. *
  1079. * Add new birthday event for this person
  1080. *
  1081. * $bdtext is just a readable placeholder in case the event is shared
  1082. * with others. We will replace it during presentation to our $importer
  1083. * to contain a sparkle link and perhaps a photo.
  1084. *
  1085. */
  1086. $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
  1087. $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
  1088. VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
  1089. intval($contact['uid']),
  1090. intval($contact['id']),
  1091. dbesc(datetime_convert()),
  1092. dbesc(datetime_convert()),
  1093. dbesc(datetime_convert('UTC','UTC', $birthday)),
  1094. dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
  1095. dbesc($bdtext),
  1096. dbesc('birthday')
  1097. );
  1098. // update bdyear
  1099. q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1100. dbesc(substr($birthday,0,4)),
  1101. intval($contact['uid']),
  1102. intval($contact['id'])
  1103. );
  1104. // This function is called twice without reloading the contact
  1105. // Make sure we only create one event. This is why &$contact
  1106. // is a reference var in this function
  1107. $contact['bdyear'] = substr($birthday,0,4);
  1108. }
  1109. }
  1110. // process any deleted entries
  1111. $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
  1112. if(is_array($del_entries) && count($del_entries) && $pass != 2) {
  1113. foreach($del_entries as $dentry) {
  1114. $deleted = false;
  1115. if(isset($dentry['attribs']['']['ref'])) {
  1116. $uri = $dentry['attribs']['']['ref'];
  1117. $deleted = true;
  1118. if(isset($dentry['attribs']['']['when'])) {
  1119. $when = $dentry['attribs']['']['when'];
  1120. $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
  1121. }
  1122. else
  1123. $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
  1124. }
  1125. if($deleted && is_array($contact)) {
  1126. $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
  1127. WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
  1128. dbesc($uri),
  1129. intval($importer['uid']),
  1130. intval($contact['id'])
  1131. );
  1132. if(count($r)) {
  1133. $item = $r[0];
  1134. if(! $item['deleted'])
  1135. logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
  1136. if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
  1137. $xo = parse_xml_string($item['object'],false);
  1138. $xt = parse_xml_string($item['target'],false);
  1139. if($xt->type === ACTIVITY_OBJ_NOTE) {
  1140. $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
  1141. dbesc($xt->id),
  1142. intval($importer['importer_uid'])
  1143. );
  1144. if(count($i)) {
  1145. // For tags, the owner cannot remove the tag on the author's copy of the post.
  1146. $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
  1147. $author_remove = (($item['origin'] && $item['self']) ? true : false);
  1148. $author_copy = (($item['origin']) ? true : false);
  1149. if($owner_remove && $author_copy)
  1150. continue;
  1151. if($author_remove || $owner_remove) {
  1152. $tags = explode(',',$i[0]['tag']);
  1153. $newtags = array();
  1154. if(count($tags)) {
  1155. foreach($tags as $tag)
  1156. if(trim($tag) !== trim($xo->body))
  1157. $newtags[] = trim($tag);
  1158. }
  1159. q("update item set tag = '%s' where id = %d limit 1",
  1160. dbesc(implode(',',$newtags)),
  1161. intval($i[0]['id'])
  1162. );
  1163. }
  1164. }
  1165. }
  1166. }
  1167. if($item['uri'] == $item['parent-uri']) {
  1168. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
  1169. `body` = '', `title` = ''
  1170. WHERE `parent-uri` = '%s' AND `uid` = %d",
  1171. dbesc($when),
  1172. dbesc(datetime_convert()),
  1173. dbesc($item['uri']),
  1174. intval($importer['uid'])
  1175. );
  1176. }
  1177. else {
  1178. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
  1179. `body` = '', `title` = ''
  1180. WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1181. dbesc($when),
  1182. dbesc(datetime_convert()),
  1183. dbesc($uri),
  1184. intval($importer['uid'])
  1185. );
  1186. if($item['last-child']) {
  1187. // ensure that last-child is set in case the comment that had it just got wiped.
  1188. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  1189. dbesc(datetime_convert()),
  1190. dbesc($item['parent-uri']),
  1191. intval($item['uid'])
  1192. );
  1193. // who is the last child now?
  1194. $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
  1195. ORDER BY `created` DESC LIMIT 1",
  1196. dbesc($item['parent-uri']),
  1197. intval($importer['uid'])
  1198. );
  1199. if(count($r)) {
  1200. q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
  1201. intval($r[0]['id'])
  1202. );
  1203. }
  1204. }
  1205. }
  1206. }
  1207. }
  1208. }
  1209. }
  1210. // Now process the feed
  1211. if($feed->get_item_quantity()) {
  1212. logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
  1213. // in inverse date order
  1214. if ($datedir)
  1215. $items = array_reverse($feed->get_items());
  1216. else
  1217. $items = $feed->get_items();
  1218. foreach($items as $item) {
  1219. $is_reply = false;
  1220. $item_id = $item->get_id();
  1221. $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
  1222. if(isset($rawthread[0]['attribs']['']['ref'])) {
  1223. $is_reply = true;
  1224. $parent_uri = $rawthread[0]['attribs']['']['ref'];
  1225. }
  1226. if(($is_reply) && is_array($contact)) {
  1227. if($pass == 1)
  1228. continue;
  1229. // Have we seen it? If not, import it.
  1230. $item_id = $item->get_id();
  1231. $datarray = get_atom_elements($feed,$item);
  1232. if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
  1233. $datarray['author-name'] = $contact['name'];
  1234. if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
  1235. $datarray['author-link'] = $contact['url'];
  1236. if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
  1237. $datarray['author-avatar'] = $contact['thumb'];
  1238. if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
  1239. logger('consume_feed: no author information! ' . print_r($datarray,true));
  1240. continue;
  1241. }
  1242. $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1243. dbesc($item_id),
  1244. intval($importer['uid'])
  1245. );
  1246. // Update content if 'updated' changes
  1247. if(count($r)) {
  1248. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  1249. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1250. dbesc($datarray['title']),
  1251. dbesc($datarray['body']),
  1252. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  1253. dbesc($item_id),
  1254. intval($importer['uid'])
  1255. );
  1256. }
  1257. // update last-child if it changes
  1258. $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
  1259. if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
  1260. $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
  1261. dbesc(datetime_convert()),
  1262. dbesc($parent_uri),
  1263. intval($importer['uid'])
  1264. );
  1265. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1266. intval($allow[0]['data']),
  1267. dbesc(datetime_convert()),
  1268. dbesc($item_id),
  1269. intval($importer['uid'])
  1270. );
  1271. }
  1272. continue;
  1273. }
  1274. $force_parent = false;
  1275. if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
  1276. if($contact['network'] === NETWORK_OSTATUS)
  1277. $force_parent = true;
  1278. if(strlen($datarray['title']))
  1279. unset($datarray['title']);
  1280. $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
  1281. dbesc(datetime_convert()),
  1282. dbesc($parent_uri),
  1283. intval($importer['uid'])
  1284. );
  1285. $datarray['last-child'] = 1;
  1286. }
  1287. if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
  1288. // one way feed - no remote comment ability
  1289. $datarray['last-child'] = 0;
  1290. }
  1291. $datarray['parent-uri'] = $parent_uri;
  1292. $datarray['uid'] = $importer['uid'];
  1293. $datarray['contact-id'] = $contact['id'];
  1294. if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
  1295. $datarray['type'] = 'activity';
  1296. $datarray['gravity'] = GRAVITY_LIKE;
  1297. // only one like or dislike per person
  1298. $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
  1299. intval($datarray['uid']),
  1300. intval($datarray['contact-id']),
  1301. dbesc($datarray['verb'])
  1302. );
  1303. if($r && count($r))
  1304. continue;
  1305. }
  1306. if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
  1307. $xo = parse_xml_string($datarray['object'],false);
  1308. $xt = parse_xml_string($datarray['target'],false);
  1309. if($xt->type == ACTIVITY_OBJ_NOTE) {
  1310. $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
  1311. dbesc($xt->id),
  1312. intval($importer['importer_uid'])
  1313. );
  1314. if(! count($r))
  1315. continue;
  1316. // extract tag, if not duplicate, add to parent item
  1317. if($xo->id && $xo->content) {
  1318. $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
  1319. if(! (stristr($r[0]['tag'],$newtag))) {
  1320. q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
  1321. dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
  1322. intval($r[0]['id'])
  1323. );
  1324. }
  1325. }
  1326. }
  1327. }
  1328. $r = item_store($datarray,$force_parent);
  1329. continue;
  1330. }
  1331. else {
  1332. // Head post of a conversation. Have we seen it? If not, import it.
  1333. $item_id = $item->get_id();
  1334. $datarray = get_atom_elements($feed,$item);
  1335. if(is_array($contact)) {
  1336. if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
  1337. $datarray['author-name'] = $contact['name'];
  1338. if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
  1339. $datarray['author-link'] = $contact['url'];
  1340. if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
  1341. $datarray['author-avatar'] = $contact['thumb'];
  1342. }
  1343. if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
  1344. logger('consume_feed: no author information! ' . print_r($datarray,true));
  1345. continue;
  1346. }
  1347. // special handling for events
  1348. if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
  1349. $ev = bbtoevent($datarray['body']);
  1350. if(x($ev,'desc') && x($ev,'start')) {
  1351. $ev['uid'] = $importer['uid'];
  1352. $ev['uri'] = $item_id;
  1353. $ev['edited'] = $datarray['edited'];
  1354. $ev['private'] = $datarray['private'];
  1355. if(is_array($contact))
  1356. $ev['cid'] = $contact['id'];
  1357. $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1358. dbesc($item_id),
  1359. intval($importer['uid'])
  1360. );
  1361. if(count($r))
  1362. $ev['id'] = $r[0]['id'];
  1363. $xyz = event_store($ev);
  1364. continue;
  1365. }
  1366. }
  1367. $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1368. dbesc($item_id),
  1369. intval($importer['uid'])
  1370. );
  1371. // Update content if 'updated' changes
  1372. if(count($r)) {
  1373. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  1374. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1375. dbesc($datarray['title']),
  1376. dbesc($datarray['body']),
  1377. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  1378. dbesc($item_id),
  1379. intval($importer['uid'])
  1380. );
  1381. }
  1382. // update last-child if it changes
  1383. $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
  1384. if($allow && $allow[0]['data'] != $r[0]['last-child']) {
  1385. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1386. intval($allow[0]['data']),
  1387. dbesc(datetime_convert()),
  1388. dbesc($item_id),
  1389. intval($importer['uid'])
  1390. );
  1391. }
  1392. continue;
  1393. }
  1394. if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
  1395. logger('consume-feed: New follower');
  1396. new_follower($importer,$contact,$datarray,$item);
  1397. return;
  1398. }
  1399. if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
  1400. lose_follower($importer,$contact,$datarray,$item);
  1401. return;
  1402. }
  1403. if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
  1404. logger('consume-feed: New friend request');
  1405. new_follower($importer,$contact,$datarray,$item,true);
  1406. return;
  1407. }
  1408. if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
  1409. lose_sharer($importer,$contact,$datarray,$item);
  1410. return;
  1411. }
  1412. if(! is_array($contact))
  1413. return;
  1414. if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
  1415. if(strlen($datarray['title']))
  1416. unset($datarray['title']);
  1417. $datarray['last-child'] = 1;
  1418. }
  1419. if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
  1420. // one way feed - no remote comment ability
  1421. $datarray['last-child'] = 0;
  1422. }
  1423. // This is my contact on another system, but it's really me.
  1424. // Turn this into a wall post.
  1425. if($contact['remote_self'])
  1426. $datarray['wall'] = 1;
  1427. $datarray['parent-uri'] = $item_id;
  1428. $datarray['uid'] = $importer['uid'];
  1429. $datarray['contact-id'] = $contact['id'];
  1430. if(! link_compare($datarray['owner-link'],$contact['url'])) {
  1431. // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
  1432. // but otherwise there's a possible data mixup on the sender's system.
  1433. // the tgroup delivery code called from item_store will correct it if it's a forum,
  1434. // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
  1435. logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
  1436. $datarray['owner-name'] = $contact['name'];
  1437. $datarray['owner-link'] = $contact['url'];
  1438. $datarray['owner-avatar'] = $contact['thumb'];
  1439. }
  1440. $r = item_store($datarray);
  1441. continue;
  1442. }
  1443. }
  1444. }
  1445. }
  1446. function local_delivery($importer,$data) {
  1447. $a = get_app();
  1448. if($importer['readonly']) {
  1449. // We aren't receiving stuff from this person. But we will quietly ignore them
  1450. // rather than a blatant "go away" message.
  1451. logger('local_delivery: ignoring');
  1452. return 0;
  1453. //NOTREACHED
  1454. }
  1455. // Consume notification feed. This may differ from consuming a public feed in several ways
  1456. // - might contain email or friend suggestions
  1457. // - might contain remote followup to our message
  1458. // - in which case we need to accept it and then notify other conversants
  1459. // - we may need to send various email notifications
  1460. $feed = new SimplePie();
  1461. $feed->set_raw_data($data);
  1462. $feed->enable_order_by_date(false);
  1463. $feed->init();
  1464. $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
  1465. if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
  1466. $base = $reloc[0]['child'][NAMESPACE_DFRN];
  1467. $newloc = array();
  1468. $newloc['uid'] = $importer['importer_uid'];
  1469. $newloc['cid'] = $importer['id'];
  1470. $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
  1471. $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
  1472. $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
  1473. $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
  1474. $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
  1475. $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
  1476. $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
  1477. $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
  1478. $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
  1479. $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
  1480. // TODO
  1481. // merge with current record, current contents have priority
  1482. // update record, set url-updated
  1483. // update profile photos
  1484. // schedule a scan?
  1485. }
  1486. // handle friend suggestion notification
  1487. $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
  1488. if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
  1489. $base = $sugg[0]['child'][NAMESPACE_DFRN];
  1490. $fsugg = array();
  1491. $fsugg['uid'] = $importer['importer_uid'];
  1492. $fsugg['cid'] = $importer['id'];
  1493. $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
  1494. $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
  1495. $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
  1496. $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
  1497. $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
  1498. // Does our member already have a friend matching this description?
  1499. $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
  1500. dbesc($fsugg['name']),
  1501. dbesc(normalise_link($fsugg['url'])),
  1502. intval($fsugg['uid'])
  1503. );
  1504. if(count($r))
  1505. return 0;
  1506. // Do we already have an fcontact record for this person?
  1507. $fid = 0;
  1508. $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
  1509. dbesc($fsugg['url']),
  1510. dbesc($fsugg['name']),
  1511. dbesc($fsugg['request'])
  1512. );
  1513. if(count($r)) {
  1514. $fid = $r[0]['id'];
  1515. }
  1516. if(! $fid)
  1517. $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
  1518. dbesc($fsugg['name']),
  1519. dbesc($fsugg['url']),
  1520. dbesc($fsugg['photo']),
  1521. dbesc($fsugg['request'])
  1522. );
  1523. $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
  1524. dbesc($fsugg['url']),
  1525. dbesc($fsugg['name']),
  1526. dbesc($fsugg['request'])
  1527. );
  1528. if(count($r)) {
  1529. $fid = $r[0]['id'];
  1530. }
  1531. // database record did not get created. Quietly give up.
  1532. else
  1533. return 0;
  1534. $hash = random_string();
  1535. $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
  1536. VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
  1537. intval($fsugg['uid']),
  1538. intval($fid),
  1539. intval($fsugg['cid']),
  1540. dbesc($fsugg['body']),
  1541. dbesc($hash),
  1542. dbesc(datetime_convert()),
  1543. intval(0)
  1544. );
  1545. notification(array(
  1546. 'type' => NOTIFY_SUGGEST,
  1547. 'notify_flags' => $importer['notify-flags'],
  1548. 'language' => $importer['language'],
  1549. 'to_name' => $importer['username'],
  1550. 'to_email' => $importer['email'],
  1551. 'uid' => $importer['importer_uid'],
  1552. 'item' => $fsugg,
  1553. 'link' => $a->get_baseurl() . '/notifications/intros',
  1554. 'source_name' => $importer['name'],
  1555. 'source_link' => $importer['url'],
  1556. 'source_photo' => $importer['photo'],
  1557. 'verb' => ACTIVITY_REQ_FRIEND,
  1558. 'otype' => 'intro'
  1559. ));
  1560. return 0;
  1561. }
  1562. $ismail = false;
  1563. $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
  1564. if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
  1565. logger('local_delivery: private message received');
  1566. $ismail = true;
  1567. $base = $rawmail[0]['child'][NAMESPACE_DFRN];
  1568. $msg = array();
  1569. $msg['uid'] = $importer['importer_uid'];
  1570. $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
  1571. $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
  1572. $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
  1573. $msg['contact-id'] = $importer['id'];
  1574. $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
  1575. $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
  1576. $msg['seen'] = 0;
  1577. $msg['replied'] = 0;
  1578. $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
  1579. $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
  1580. $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
  1581. dbesc_array($msg);
  1582. $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
  1583. . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
  1584. // send notifications.
  1585. require_once('include/enotify.php');
  1586. $notif_params = array(
  1587. 'type' => NOTIFY_MAIL,
  1588. 'notify_flags' => $importer['notify-flags'],
  1589. 'language' => $importer['language'],
  1590. 'to_name' => $importer['username'],
  1591. 'to_email' => $importer['email'],
  1592. 'uid' => $importer['importer_uid'],
  1593. 'item' => $msg,
  1594. 'source_name' => $msg['from-name'],
  1595. 'source_link' => $importer['url'],
  1596. 'source_photo' => $importer['thumb'],
  1597. 'verb' => ACTIVITY_POST,
  1598. 'otype' => 'mail'
  1599. );
  1600. notification($notif_params);
  1601. return 0;
  1602. // NOTREACHED
  1603. }
  1604. logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
  1605. // process any deleted entries
  1606. $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
  1607. if(is_array($del_entries) && count($del_entries)) {
  1608. foreach($del_entries as $dentry) {
  1609. $deleted = false;
  1610. if(isset($dentry['attribs']['']['ref'])) {
  1611. $uri = $dentry['attribs']['']['ref'];
  1612. $deleted = true;
  1613. if(isset($dentry['attribs']['']['when'])) {
  1614. $when = $dentry['attribs']['']['when'];
  1615. $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
  1616. }
  1617. else
  1618. $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
  1619. }
  1620. if($deleted) {
  1621. $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
  1622. WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
  1623. dbesc($uri),
  1624. intval($importer['importer_uid']),
  1625. intval($importer['id'])
  1626. );
  1627. if(count($r)) {
  1628. $item = $r[0];
  1629. if($item['deleted'])
  1630. continue;
  1631. logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
  1632. if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
  1633. $xo = parse_xml_string($item['object'],false);
  1634. $xt = parse_xml_string($item['target'],false);
  1635. if($xt->type === ACTIVITY_OBJ_NOTE) {
  1636. $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
  1637. dbesc($xt->id),
  1638. intval($importer['importer_uid'])
  1639. );
  1640. if(count($i)) {
  1641. // For tags, the owner cannot remove the tag on the author's copy of the post.
  1642. $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
  1643. $author_remove = (($item['origin'] && $item['self']) ? true : false);
  1644. $author_copy = (($item['origin']) ? true : false);
  1645. if($owner_remove && $author_copy)
  1646. continue;
  1647. if($author_remove || $owner_remove) {
  1648. $tags = explode(',',$i[0]['tag']);
  1649. $newtags = array();
  1650. if(count($tags)) {
  1651. foreach($tags as $tag)
  1652. if(trim($tag) !== trim($xo->body))
  1653. $newtags[] = trim($tag);
  1654. }
  1655. q("update item set tag = '%s' where id = %d limit 1",
  1656. dbesc(implode(',',$newtags)),
  1657. intval($i[0]['id'])
  1658. );
  1659. }
  1660. }
  1661. }
  1662. }
  1663. if($item['uri'] == $item['parent-uri']) {
  1664. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
  1665. WHERE `parent-uri` = '%s' AND `uid` = %d",
  1666. dbesc($when),
  1667. dbesc(datetime_convert()),
  1668. dbesc($item['uri']),
  1669. intval($importer['importer_uid'])
  1670. );
  1671. }
  1672. else {
  1673. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
  1674. WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1675. dbesc($when),
  1676. dbesc(datetime_convert()),
  1677. dbesc($uri),
  1678. intval($importer['importer_uid'])
  1679. );
  1680. if($item['last-child']) {
  1681. // ensure that last-child is set in case the comment that had it just got wiped.
  1682. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  1683. dbesc(datetime_convert()),
  1684. dbesc($item['parent-uri']),
  1685. intval($item['uid'])
  1686. );
  1687. // who is the last child now?
  1688. $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
  1689. ORDER BY `created` DESC LIMIT 1",
  1690. dbesc($item['parent-uri']),
  1691. intval($importer['importer_uid'])
  1692. );
  1693. if(count($r)) {
  1694. q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
  1695. intval($r[0]['id'])
  1696. );
  1697. }
  1698. }
  1699. }
  1700. }
  1701. }
  1702. }
  1703. }
  1704. foreach($feed->get_items() as $item) {
  1705. $is_reply = false;
  1706. $item_id = $item->get_id();
  1707. $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
  1708. if(isset($rawthread[0]['attribs']['']['ref'])) {
  1709. $is_reply = true;
  1710. $parent_uri = $rawthread[0]['attribs']['']['ref'];
  1711. }
  1712. if($is_reply) {
  1713. $community = false;
  1714. if($importer['page-flags'] == PAGE_COMMUNITY) {
  1715. $sql_extra = '';
  1716. $community = true;
  1717. logger('local_delivery: possible community reply');
  1718. }
  1719. else
  1720. $sql_extra = " and contact.self = 1 and item.wall = 1 ";
  1721. // was the top-level post for this reply written by somebody on this site?
  1722. // Specifically, the recipient?
  1723. $is_a_remote_comment = false;
  1724. $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
  1725. `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
  1726. LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  1727. WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
  1728. AND `item`.`uid` = %d
  1729. $sql_extra
  1730. LIMIT 1",
  1731. dbesc($parent_uri),
  1732. dbesc($parent_uri),
  1733. intval($importer['importer_uid'])
  1734. );
  1735. if($r && count($r))
  1736. $is_a_remote_comment = true;
  1737. // Does this have the characteristics of a community comment?
  1738. // If it's a reply to a wall post on a community page it's a
  1739. // valid community comment. Also forum_mode makes it valid for sure.
  1740. // If neither, it's not.
  1741. if($is_a_remote_comment && $community) {
  1742. if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
  1743. $is_a_remote_comment = false;
  1744. logger('local_delivery: not a community reply');
  1745. }
  1746. }
  1747. if($is_a_remote_comment) {
  1748. logger('local_delivery: received remote comment');
  1749. $is_like = false;
  1750. // remote reply to our post. Import and then notify everybody else.
  1751. $datarray = get_atom_elements($feed,$item);
  1752. // TODO: make this next part work against both delivery threads of a community post
  1753. // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
  1754. // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
  1755. // they won't know what to do so don't report an error. Just quietly die.
  1756. // return 0;
  1757. // }
  1758. $datarray['type'] = 'remote-comment';
  1759. $datarray['wall'] = 1;
  1760. $datarray['parent-uri'] = $parent_uri;
  1761. $datarray['uid'] = $importer['importer_uid'];
  1762. $datarray['owner-name'] = $r[0]['name'];
  1763. $datarray['owner-link'] = $r[0]['url'];
  1764. $datarray['owner-avatar'] = $r[0]['thumb'];
  1765. $datarray['contact-id'] = $importer['id'];
  1766. if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
  1767. $is_like = true;
  1768. $datarray['type'] = 'activity';
  1769. $datarray['gravity'] = GRAVITY_LIKE;
  1770. $datarray['last-child'] = 0;
  1771. // only one like or dislike per person
  1772. $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
  1773. intval($datarray['uid']),
  1774. intval($datarray['contact-id']),
  1775. dbesc($datarray['verb'])
  1776. );
  1777. if($r && count($r))
  1778. continue;
  1779. }
  1780. if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
  1781. $xo = parse_xml_string($datarray['object'],false);
  1782. $xt = parse_xml_string($datarray['target'],false);
  1783. if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
  1784. // extract tag, if not duplicate, and this user allows tags, add to parent item
  1785. if($xo->id && $xo->content) {
  1786. $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
  1787. if(! (stristr($r[0]['tag'],$newtag))) {
  1788. $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
  1789. intval($importer['importer_uid'])
  1790. );
  1791. if(count($i) && ! ($i[0]['blocktags'])) {
  1792. q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
  1793. dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
  1794. intval($r[0]['id'])
  1795. );
  1796. }
  1797. }
  1798. }
  1799. }
  1800. }
  1801. // if($community) {
  1802. // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
  1803. // if(! stristr($datarray['tag'],$newtag)) {
  1804. // if(strlen($datarray['tag']))
  1805. // $datarray['tag'] .= ',';
  1806. // $datarray['tag'] .= $newtag;
  1807. // }
  1808. // }
  1809. $posted_id = item_store($datarray);
  1810. $parent = 0;
  1811. if($posted_id) {
  1812. $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  1813. intval($posted_id),
  1814. intval($importer['importer_uid'])
  1815. );
  1816. if(count($r))
  1817. $parent = $r[0]['parent'];
  1818. if(! $is_like) {
  1819. $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
  1820. dbesc(datetime_convert()),
  1821. intval($importer['importer_uid']),
  1822. intval($r[0]['parent'])
  1823. );
  1824. $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
  1825. dbesc(datetime_convert()),
  1826. intval($importer['importer_uid']),
  1827. intval($posted_id)
  1828. );
  1829. }
  1830. if($posted_id && $parent) {
  1831. proc_run('php',"include/notifier.php","comment-import","$posted_id");
  1832. if((! $is_like) && (! $importer['self'])) {
  1833. require_once('include/enotify.php');
  1834. notification(array(
  1835. 'type' => NOTIFY_COMMENT,
  1836. 'notify_flags' => $importer['notify-flags'],
  1837. 'language' => $importer['language'],
  1838. 'to_name' => $importer['username'],
  1839. 'to_email' => $importer['email'],
  1840. 'uid' => $importer['importer_uid'],
  1841. 'item' => $datarray,
  1842. 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
  1843. 'source_name' => stripslashes($datarray['author-name']),
  1844. 'source_link' => $datarray['author-link'],
  1845. 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
  1846. ? $importer['thumb'] : $datarray['author-avatar']),
  1847. 'verb' => ACTIVITY_POST,
  1848. 'otype' => 'item',
  1849. 'parent' => $parent,
  1850. ));
  1851. }
  1852. }
  1853. return 0;
  1854. // NOTREACHED
  1855. }
  1856. }
  1857. else {
  1858. // regular comment that is part of this total conversation. Have we seen it? If not, import it.
  1859. $item_id = $item->get_id();
  1860. $datarray = get_atom_elements($feed,$item);
  1861. $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1862. dbesc($item_id),
  1863. intval($importer['importer_uid'])
  1864. );
  1865. // Update content if 'updated' changes
  1866. if(count($r)) {
  1867. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  1868. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1869. dbesc($datarray['title']),
  1870. dbesc($datarray['body']),
  1871. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  1872. dbesc($item_id),
  1873. intval($importer['importer_uid'])
  1874. );
  1875. }
  1876. // update last-child if it changes
  1877. $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
  1878. if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
  1879. $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
  1880. dbesc(datetime_convert()),
  1881. dbesc($parent_uri),
  1882. intval($importer['importer_uid'])
  1883. );
  1884. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1885. intval($allow[0]['data']),
  1886. dbesc(datetime_convert()),
  1887. dbesc($item_id),
  1888. intval($importer['importer_uid'])
  1889. );
  1890. }
  1891. continue;
  1892. }
  1893. $datarray['parent-uri'] = $parent_uri;
  1894. $datarray['uid'] = $importer['importer_uid'];
  1895. $datarray['contact-id'] = $importer['id'];
  1896. if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
  1897. $datarray['type'] = 'activity';
  1898. $datarray['gravity'] = GRAVITY_LIKE;
  1899. // only one like or dislike per person
  1900. $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
  1901. intval($datarray['uid']),
  1902. intval($datarray['contact-id']),
  1903. dbesc($datarray['verb'])
  1904. );
  1905. if($r && count($r))
  1906. continue;
  1907. }
  1908. if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
  1909. $xo = parse_xml_string($datarray['object'],false);
  1910. $xt = parse_xml_string($datarray['target'],false);
  1911. if($xt->type == ACTIVITY_OBJ_NOTE) {
  1912. $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
  1913. dbesc($xt->id),
  1914. intval($importer['importer_uid'])
  1915. );
  1916. if(! count($r))
  1917. continue;
  1918. // extract tag, if not duplicate, add to parent item
  1919. if($xo->content) {
  1920. if(! (stristr($r[0]['tag'],trim($xo->content)))) {
  1921. q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
  1922. dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
  1923. intval($r[0]['id'])
  1924. );
  1925. }
  1926. }
  1927. }
  1928. }
  1929. $posted_id = item_store($datarray);
  1930. // find out if our user is involved in this conversation and wants to be notified.
  1931. if($datarray['type'] != 'activity') {
  1932. $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
  1933. dbesc($parent_uri),
  1934. intval($importer['importer_uid'])
  1935. );
  1936. if(count($myconv)) {
  1937. $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
  1938. // first make sure this isn't our own post coming back to us from a wall-to-wall event
  1939. if(! link_compare($datarray['author-link'],$importer_url)) {
  1940. foreach($myconv as $conv) {
  1941. // now if we find a match, it means we're in this conversation
  1942. if(! link_compare($conv['author-link'],$importer_url))
  1943. continue;
  1944. require_once('include/enotify.php');
  1945. $conv_parent = $conv['parent'];
  1946. notification(array(
  1947. 'type' => NOTIFY_COMMENT,
  1948. 'notify_flags' => $importer['notify-flags'],
  1949. 'language' => $importer['language'],
  1950. 'to_name' => $importer['username'],
  1951. 'to_email' => $importer['email'],
  1952. 'uid' => $importer['importer_uid'],
  1953. 'item' => $datarray,
  1954. 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
  1955. 'source_name' => stripslashes($datarray['author-name']),
  1956. 'source_link' => $datarray['author-link'],
  1957. 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
  1958. ? $importer['thumb'] : $datarray['author-avatar']),
  1959. 'verb' => ACTIVITY_POST,
  1960. 'otype' => 'item',
  1961. 'parent' => $conv_parent,
  1962. ));
  1963. // only send one notification
  1964. break;
  1965. }
  1966. }
  1967. }
  1968. }
  1969. continue;
  1970. }
  1971. }
  1972. else {
  1973. // Head post of a conversation. Have we seen it? If not, import it.
  1974. $item_id = $item->get_id();
  1975. $datarray = get_atom_elements($feed,$item);
  1976. if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
  1977. $ev = bbtoevent($datarray['body']);
  1978. if(x($ev,'desc') && x($ev,'start')) {
  1979. $ev['cid'] = $importer['id'];
  1980. $ev['uid'] = $importer['uid'];
  1981. $ev['uri'] = $item_id;
  1982. $ev['edited'] = $datarray['edited'];
  1983. $ev['private'] = $datarray['private'];
  1984. $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1985. dbesc($item_id),
  1986. intval($importer['uid'])
  1987. );
  1988. if(count($r))
  1989. $ev['id'] = $r[0]['id'];
  1990. $xyz = event_store($ev);
  1991. continue;
  1992. }
  1993. }
  1994. $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1995. dbesc($item_id),
  1996. intval($importer['importer_uid'])
  1997. );
  1998. // Update content if 'updated' changes
  1999. if(count($r)) {
  2000. if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
  2001. $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2002. dbesc($datarray['title']),
  2003. dbesc($datarray['body']),
  2004. dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
  2005. dbesc($item_id),
  2006. intval($importer['importer_uid'])
  2007. );
  2008. }
  2009. // update last-child if it changes
  2010. $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
  2011. if($allow && $allow[0]['data'] != $r[0]['last-child']) {
  2012. $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2013. intval($allow[0]['data']),
  2014. dbesc(datetime_convert()),
  2015. dbesc($item_id),
  2016. intval($importer['importer_uid'])
  2017. );
  2018. }
  2019. continue;
  2020. }
  2021. // This is my contact on another system, but it's really me.
  2022. // Turn this into a wall post.
  2023. if($importer['remote_self'])
  2024. $datarray['wall'] = 1;
  2025. $datarray['parent-uri'] = $item_id;
  2026. $datarray['uid'] = $importer['importer_uid'];
  2027. $datarray['contact-id'] = $importer['id'];
  2028. if(! link_compare($datarray['owner-link'],$contact['url'])) {
  2029. // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
  2030. // but otherwise there's a possible data mixup on the sender's system.
  2031. // the tgroup delivery code called from item_store will correct it if it's a forum,
  2032. // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
  2033. logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
  2034. $datarray['owner-name'] = $importer['senderName'];
  2035. $datarray['owner-link'] = $importer['url'];
  2036. $datarray['owner-avatar'] = $importer['thumb'];
  2037. }
  2038. $r = item_store($datarray);
  2039. continue;
  2040. }
  2041. }
  2042. return 0;
  2043. // NOTREACHED
  2044. }
  2045. function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
  2046. $url = notags(trim($datarray['author-link']));
  2047. $name = notags(trim($datarray['author-name']));
  2048. $photo = notags(trim($datarray['author-avatar']));
  2049. $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
  2050. if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
  2051. $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
  2052. if(is_array($contact)) {
  2053. if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
  2054. || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
  2055. $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
  2056. intval(CONTACT_IS_FRIEND),
  2057. intval($contact['id']),
  2058. intval($importer['uid'])
  2059. );
  2060. }
  2061. // send email notification to owner?
  2062. }
  2063. else {
  2064. // create contact record
  2065. $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
  2066. `blocked`, `readonly`, `pending`, `writable` )
  2067. VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
  2068. intval($importer['uid']),
  2069. dbesc(datetime_convert()),
  2070. dbesc($url),
  2071. dbesc(normalise_link($url)),
  2072. dbesc($name),
  2073. dbesc($nick),
  2074. dbesc($photo),
  2075. dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
  2076. intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
  2077. );
  2078. $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
  2079. intval($importer['uid']),
  2080. dbesc($url)
  2081. );
  2082. if(count($r))
  2083. $contact_record = $r[0];
  2084. // create notification
  2085. $hash = random_string();
  2086. if(is_array($contact_record)) {
  2087. $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
  2088. VALUES ( %d, %d, 0, 0, '%s', '%s' )",
  2089. intval($importer['uid']),
  2090. intval($contact_record['id']),
  2091. dbesc($hash),
  2092. dbesc(datetime_convert())
  2093. );
  2094. }
  2095. $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  2096. intval($importer['uid'])
  2097. );
  2098. $a = get_app();
  2099. if(count($r)) {
  2100. if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
  2101. $email_tpl = get_intltext_template('follow_notify_eml.tpl');
  2102. $email = replace_macros($email_tpl, array(
  2103. '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
  2104. '$url' => $url,
  2105. '$myname' => $r[0]['username'],
  2106. '$siteurl' => $a->get_baseurl(),
  2107. '$sitename' => $a->config['sitename']
  2108. ));
  2109. $res = mail($r[0]['email'],
  2110. (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
  2111. $email,
  2112. 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
  2113. . 'Content-type: text/plain; charset=UTF-8' . "\n"
  2114. . 'Content-transfer-encoding: 8bit' );
  2115. }
  2116. }
  2117. }
  2118. }
  2119. function lose_follower($importer,$contact,$datarray,$item) {
  2120. if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
  2121. q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
  2122. intval(CONTACT_IS_SHARING),
  2123. intval($contact['id'])
  2124. );
  2125. }
  2126. else {
  2127. contact_remove($contact['id']);
  2128. }
  2129. }
  2130. function lose_sharer($importer,$contact,$datarray,$item) {
  2131. if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
  2132. q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
  2133. intval(CONTACT_IS_FOLLOWER),
  2134. intval($contact['id'])
  2135. );
  2136. }
  2137. else {
  2138. contact_remove($contact['id']);
  2139. }
  2140. }
  2141. function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
  2142. if(is_array($importer)) {
  2143. $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
  2144. intval($importer['uid'])
  2145. );
  2146. }
  2147. // Diaspora has different message-ids in feeds than they do
  2148. // through the direct Diaspora protocol. If we try and use
  2149. // the feed, we'll get duplicates. So don't.
  2150. if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
  2151. return;
  2152. $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
  2153. // Use a single verify token, even if multiple hubs
  2154. $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
  2155. $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
  2156. logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
  2157. if(! strlen($contact['hub-verify'])) {
  2158. $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
  2159. dbesc($verify_token),
  2160. intval($contact['id'])
  2161. );
  2162. }
  2163. post_url($url,$params);
  2164. return;
  2165. }
  2166. function atom_author($tag,$name,$uri,$h,$w,$photo) {
  2167. $o = '';
  2168. if(! $tag)
  2169. return $o;
  2170. $name = xmlify($name);
  2171. $uri = xmlify($uri);
  2172. $h = intval($h);
  2173. $w = intval($w);
  2174. $photo = xmlify($photo);
  2175. $o .= "<$tag>\r\n";
  2176. $o .= "<name>$name</name>\r\n";
  2177. $o .= "<uri>$uri</uri>\r\n";
  2178. $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
  2179. $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
  2180. call_hooks('atom_author', $o);
  2181. $o .= "</$tag>\r\n";
  2182. return $o;
  2183. }
  2184. function atom_entry($item,$type,$author,$owner,$comment = false) {
  2185. $a = get_app();
  2186. if(! $item['parent'])
  2187. return;
  2188. if($item['deleted'])
  2189. return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
  2190. if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
  2191. $body = fix_private_photos($item['body'],$owner['uid']);
  2192. else
  2193. $body = $item['body'];
  2194. $o = "\r\n\r\n<entry>\r\n";
  2195. if(is_array($author))
  2196. $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
  2197. else
  2198. $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']));
  2199. if(strlen($item['owner-name']))
  2200. $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
  2201. if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
  2202. $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
  2203. $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
  2204. $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
  2205. $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
  2206. $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
  2207. $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
  2208. $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
  2209. $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
  2210. if($comment)
  2211. $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
  2212. if($item['location']) {
  2213. $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
  2214. $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
  2215. }
  2216. if($item['coord'])
  2217. $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
  2218. if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
  2219. $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
  2220. if($item['extid'])
  2221. $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
  2222. if($item['bookmark'])
  2223. $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
  2224. if($item['app'])
  2225. $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
  2226. if($item['guid'])
  2227. $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
  2228. if($item['signed_text']) {
  2229. $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
  2230. $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
  2231. }
  2232. $verb = construct_verb($item);
  2233. $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
  2234. $actobj = construct_activity_object($item);
  2235. if(strlen($actobj))
  2236. $o .= $actobj;
  2237. $actarg = construct_activity_target($item);
  2238. if(strlen($actarg))
  2239. $o .= $actarg;
  2240. $tags = item_getfeedtags($item);
  2241. if(count($tags)) {
  2242. foreach($tags as $t) {
  2243. $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
  2244. }
  2245. }
  2246. $o .= item_getfeedattach($item);
  2247. $mentioned = get_mentions($item);
  2248. if($mentioned)
  2249. $o .= $mentioned;
  2250. call_hooks('atom_entry', $o);
  2251. $o .= '</entry>' . "\r\n";
  2252. return $o;
  2253. }
  2254. function fix_private_photos($s,$uid) {
  2255. $a = get_app();
  2256. logger('fix_private_photos');
  2257. if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
  2258. $image = $matches[1];
  2259. logger('fix_private_photos: found photo ' . $image);
  2260. if(stristr($image ,$a->get_baseurl() . '/photo/')) {
  2261. $i = basename($image);
  2262. $i = str_replace('.jpg','',$i);
  2263. $x = strpos($i,'-');
  2264. if($x) {
  2265. $res = substr($i,$x+1);
  2266. $i = substr($i,0,$x);
  2267. $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
  2268. dbesc($i),
  2269. intval($res),
  2270. intval($uid)
  2271. );
  2272. if(count($r)) {
  2273. logger('replacing photo');
  2274. $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
  2275. }
  2276. }
  2277. logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
  2278. }
  2279. }
  2280. return($s);
  2281. }
  2282. function item_getfeedtags($item) {
  2283. $ret = array();
  2284. $matches = false;
  2285. $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
  2286. if($cnt) {
  2287. for($x = 0; $x < $cnt; $x ++) {
  2288. if($matches[1][$x])
  2289. $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
  2290. }
  2291. }
  2292. $matches = false;
  2293. $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
  2294. if($cnt) {
  2295. for($x = 0; $x < $cnt; $x ++) {
  2296. if($matches[1][$x])
  2297. $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
  2298. }
  2299. }
  2300. return $ret;
  2301. }
  2302. function item_getfeedattach($item) {
  2303. $ret = '';
  2304. $arr = explode(',',$item['attach']);
  2305. if(count($arr)) {
  2306. foreach($arr as $r) {
  2307. $matches = false;
  2308. $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
  2309. if($cnt) {
  2310. $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
  2311. if(intval($matches[2]))
  2312. $ret .= 'length="' . intval($matches[2]) . '" ';
  2313. if($matches[4] !== ' ')
  2314. $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
  2315. $ret .= ' />' . "\r\n";
  2316. }
  2317. }
  2318. }
  2319. return $ret;
  2320. }
  2321. function item_expire($uid,$days) {
  2322. if((! $uid) || (! $days))
  2323. return;
  2324. $r = q("SELECT * FROM `item`
  2325. WHERE `uid` = %d
  2326. AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
  2327. AND `id` = `parent`
  2328. AND `deleted` = 0",
  2329. intval($uid),
  2330. intval($days)
  2331. );
  2332. if(! count($r))
  2333. return;
  2334. $expire_items = get_pconfig($uid, 'expire','items');
  2335. $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
  2336. $expire_notes = get_pconfig($uid, 'expire','notes');
  2337. $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
  2338. $expire_starred = get_pconfig($uid, 'expire','starred');
  2339. $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
  2340. $expire_photos = get_pconfig($uid, 'expire','photos');
  2341. $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
  2342. logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
  2343. foreach($r as $item) {
  2344. // Only expire posts, not photos and photo comments
  2345. if($expire_photos==0 && strlen($item['resource-id']))
  2346. continue;
  2347. if($expire_starred==0 && intval($item['starred']))
  2348. continue;
  2349. if($expire_notes==0 && $item['type']=='note')
  2350. continue;
  2351. if($expire_items==0 && $item['type']!='note')
  2352. continue;
  2353. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
  2354. dbesc(datetime_convert()),
  2355. dbesc(datetime_convert()),
  2356. intval($item['id'])
  2357. );
  2358. // kill the kids
  2359. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  2360. dbesc(datetime_convert()),
  2361. dbesc(datetime_convert()),
  2362. dbesc($item['parent-uri']),
  2363. intval($item['uid'])
  2364. );
  2365. }
  2366. proc_run('php',"include/notifier.php","expire","$uid");
  2367. }
  2368. function drop_items($items) {
  2369. $uid = 0;
  2370. if((! local_user()) && (! $remote_user()))
  2371. return;
  2372. if(count($items)) {
  2373. foreach($items as $item) {
  2374. $owner = drop_item($item,false);
  2375. if($owner && ! $uid)
  2376. $uid = $owner;
  2377. }
  2378. }
  2379. // multiple threads may have been deleted, send an expire notification
  2380. if($uid)
  2381. proc_run('php',"include/notifier.php","expire","$uid");
  2382. }
  2383. function drop_item($id,$interactive = true) {
  2384. $a = get_app();
  2385. // locate item to be deleted
  2386. $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
  2387. intval($id)
  2388. );
  2389. if(! count($r)) {
  2390. if(! $interactive)
  2391. return 0;
  2392. notice( t('Item not found.') . EOL);
  2393. goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
  2394. }
  2395. $item = $r[0];
  2396. $owner = $item['uid'];
  2397. // check if logged in user is either the author or owner of this item
  2398. if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
  2399. // delete the item
  2400. $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
  2401. dbesc(datetime_convert()),
  2402. dbesc(datetime_convert()),
  2403. intval($item['id'])
  2404. );
  2405. // If item is a link to a photo resource, nuke all the associated photos
  2406. // (visitors will not have photo resources)
  2407. // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
  2408. // generate a resource-id and therefore aren't intimately linked to the item.
  2409. if(strlen($item['resource-id'])) {
  2410. q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
  2411. dbesc($item['resource-id']),
  2412. intval($item['uid'])
  2413. );
  2414. // ignore the result
  2415. }
  2416. // If item is a link to an event, nuke the event record.
  2417. if(intval($item['event-id'])) {
  2418. q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
  2419. intval($item['event-id']),
  2420. intval($item['uid'])
  2421. );
  2422. // ignore the result
  2423. }
  2424. // If it's the parent of a comment thread, kill all the kids
  2425. if($item['uri'] == $item['parent-uri']) {
  2426. $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
  2427. WHERE `parent-uri` = '%s' AND `uid` = %d ",
  2428. dbesc(datetime_convert()),
  2429. dbesc(datetime_convert()),
  2430. dbesc($item['parent-uri']),
  2431. intval($item['uid'])
  2432. );
  2433. // ignore the result
  2434. }
  2435. else {
  2436. // ensure that last-child is set in case the comment that had it just got wiped.
  2437. q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
  2438. dbesc(datetime_convert()),
  2439. dbesc($item['parent-uri']),
  2440. intval($item['uid'])
  2441. );
  2442. // who is the last child now?
  2443. $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",
  2444. dbesc($item['parent-uri']),
  2445. intval($item['uid'])
  2446. );
  2447. if(count($r)) {
  2448. q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
  2449. intval($r[0]['id'])
  2450. );
  2451. }
  2452. }
  2453. $drop_id = intval($item['id']);
  2454. // send the notification upstream/downstream as the case may be
  2455. if(! $interactive)
  2456. return $owner;
  2457. proc_run('php',"include/notifier.php","drop","$drop_id");
  2458. goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
  2459. //NOTREACHED
  2460. }
  2461. else {
  2462. if(! $interactive)
  2463. return 0;
  2464. notice( t('Permission denied.') . EOL);
  2465. goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
  2466. //NOTREACHED
  2467. }
  2468. }