3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
7 require_once('include/Photo.php');
10 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
13 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
14 $public_feed = (($dfrn_id) ? false : true);
15 $starred = false; // not yet implemented, possible security issues
18 if($public_feed && $a->argc > 2) {
19 for($x = 2; $x < $a->argc; $x++) {
20 if($a->argv[$x] == 'converse')
22 if($a->argv[$x] == 'starred')
24 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
25 $category = $a->argv[$x+1];
31 // default permissions - anonymous user
33 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
35 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
36 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
37 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
45 $owner_id = $owner['user_uid'];
46 $owner_nick = $owner['nickname'];
48 $birthday = feed_birthday($owner_id,$owner['timezone']);
55 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
59 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60 $my_id = '1:' . $dfrn_id;
63 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
64 $my_id = '0:' . $dfrn_id;
71 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
79 $groups = init_groups_visitor($contact['id']);
82 for($x = 0; $x < count($groups); $x ++)
83 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
84 $gs = implode('|', $groups);
87 $gs = '<<>>' ; // Impossible to match
89 $sql_extra = sprintf("
90 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
91 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
92 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
93 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
95 intval($contact['id']),
96 intval($contact['id']),
107 if(! strlen($last_update))
108 $last_update = 'now -30 days';
110 if(isset($category)) {
111 $sql_extra .= file_tag_file_query('item',$category,'category');
116 $sql_extra .= " AND `contact`.`self` = 1 ";
119 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
121 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
122 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
123 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
124 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
125 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
126 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
127 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
128 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
129 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
130 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
131 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
133 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
140 // Will check further below if this actually returned results.
141 // We will provide an empty feed if that is the case.
145 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
149 $hubxml = feed_hublinks();
151 $salmon = feed_salmonlinks($owner_nick);
153 $atom .= replace_macros($feed_template, array(
154 '$version' => xmlify(FRIENDICA_VERSION),
155 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
156 '$feed_title' => xmlify($owner['name']),
157 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
159 '$salmon' => $salmon,
160 '$name' => xmlify($owner['name']),
161 '$profile_page' => xmlify($owner['url']),
162 '$photo' => xmlify($owner['photo']),
163 '$thumb' => xmlify($owner['thumb']),
164 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
165 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
166 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
167 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
168 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
171 call_hooks('atom_feed', $atom);
173 if(! count($items)) {
175 call_hooks('atom_feed_end', $atom);
177 $atom .= '</feed>' . "\r\n";
181 foreach($items as $item) {
183 // prevent private email from leaking.
184 if($item['network'] === NETWORK_MAIL)
187 // public feeds get html, our own nodes use bbcode
191 // catch any email that's in a public conversation and make sure it doesn't leak
199 $atom .= atom_entry($item,$type,null,$owner,true);
202 call_hooks('atom_feed_end', $atom);
204 $atom .= '</feed>' . "\r\n";
210 function construct_verb($item) {
212 return $item['verb'];
213 return ACTIVITY_POST;
216 function construct_activity_object($item) {
218 if($item['object']) {
219 $o = '<as:object>' . "\r\n";
220 $r = parse_xml_string($item['object'],false);
226 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
228 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
230 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
232 if(substr($r->link,0,1) === '<') {
233 // patch up some facebook "like" activity objects that got stored incorrectly
234 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
235 // we can probably remove this hack here and in the following function in a few months time.
236 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
237 $r->link = str_replace('&','&', $r->link);
238 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
242 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
245 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
246 $o .= '</as:object>' . "\r\n";
253 function construct_activity_target($item) {
255 if($item['target']) {
256 $o = '<as:target>' . "\r\n";
257 $r = parse_xml_string($item['target'],false);
261 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
263 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
265 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
267 if(substr($r->link,0,1) === '<') {
268 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
269 $r->link = str_replace('&','&', $r->link);
270 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
274 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
277 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
278 $o .= '</as:target>' . "\r\n";
287 * The purpose of this function is to apply system message length limits to
288 * imported messages without including any embedded photos in the length
290 if(! function_exists('limit_body_size')) {
291 function limit_body_size($body) {
293 logger('limit_body_size: start', LOGGER_DEBUG);
295 $maxlen = get_max_import_size();
297 // If the length of the body, including the embedded images, is smaller
298 // than the maximum, then don't waste time looking for the images
299 if($maxlen && (strlen($body) > $maxlen)) {
301 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
308 $img_start = strpos($orig_body, '[img');
309 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
310 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
311 while(($img_st_close !== false) && ($img_end !== false)) {
313 $img_st_close++; // make it point to AFTER the closing bracket
314 $img_end += $img_start;
315 $img_end += strlen('[/img]');
317 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
318 // This is an embedded image
320 if( ($textlen + $img_start) > $maxlen ) {
321 if($textlen < $maxlen) {
322 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
323 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
328 $new_body = $new_body . substr($orig_body, 0, $img_start);
329 $textlen += $img_start;
332 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
336 if( ($textlen + $img_end) > $maxlen ) {
337 if($textlen < $maxlen) {
338 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
339 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
344 $new_body = $new_body . substr($orig_body, 0, $img_end);
345 $textlen += $img_end;
348 $orig_body = substr($orig_body, $img_end);
350 if($orig_body === false) // in case the body ends on a closing image tag
353 $img_start = strpos($orig_body, '[img');
354 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
355 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
358 if( ($textlen + strlen($orig_body)) > $maxlen) {
359 if($textlen < $maxlen) {
360 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
361 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
366 logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
367 $new_body = $new_body . $orig_body;
368 $textlen += strlen($orig_body);
380 function get_atom_elements($feed,$item) {
382 require_once('library/HTMLPurifier.auto.php');
383 require_once('include/html2bbcode.php');
385 $best_photo = array();
389 $author = $item->get_author();
391 $res['author-name'] = unxmlify($author->get_name());
392 $res['author-link'] = unxmlify($author->get_link());
395 $res['author-name'] = unxmlify($feed->get_title());
396 $res['author-link'] = unxmlify($feed->get_permalink());
398 $res['uri'] = unxmlify($item->get_id());
399 $res['title'] = unxmlify($item->get_title());
400 $res['body'] = unxmlify($item->get_content());
401 $res['plink'] = unxmlify($item->get_link(0));
404 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
408 // look for a photo. We should check media size and find the best one,
409 // but for now let's just find any author photo
411 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
413 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
414 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
415 foreach($base as $link) {
416 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
417 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
418 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
423 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
425 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
426 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
427 if($base && count($base)) {
428 foreach($base as $link) {
429 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
430 $res['author-link'] = unxmlify($link['attribs']['']['href']);
431 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
432 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
433 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
439 // No photo/profile-link on the item - look at the feed level
441 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
442 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
443 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
444 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
445 foreach($base as $link) {
446 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
447 $res['author-link'] = unxmlify($link['attribs']['']['href']);
448 if(! $res['author-avatar']) {
449 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
450 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
455 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
457 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
458 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
460 if($base && count($base)) {
461 foreach($base as $link) {
462 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
463 $res['author-link'] = unxmlify($link['attribs']['']['href']);
464 if(! (x($res,'author-avatar'))) {
465 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
466 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
473 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
474 if($apps && $apps[0]['attribs']['']['source']) {
475 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
476 if($res['app'] === 'web')
477 $res['app'] = 'OStatus';
480 // base64 encoded json structure representing Diaspora signature
482 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
484 $res['dsprsig'] = unxmlify($dsig[0]['data']);
487 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
489 $res['guid'] = unxmlify($dguid[0]['data']);
491 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
493 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
497 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
500 $have_real_body = false;
502 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
504 $have_real_body = true;
505 $res['body'] = $rawenv[0]['data'];
506 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
507 // make sure nobody is trying to sneak some html tags by us
508 $res['body'] = notags(base64url_decode($res['body']));
512 $res['body'] = limit_body_size($res['body']);
514 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
515 // the content type. Our own network only emits text normally, though it might have been converted to
516 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
517 // have to assume it is all html and needs to be purified.
519 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
520 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
521 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
524 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
526 $res['body'] = reltoabs($res['body'],$base_url);
528 $res['body'] = html2bb_video($res['body']);
530 $res['body'] = oembed_html2bbcode($res['body']);
532 $config = HTMLPurifier_Config::createDefault();
533 $config->set('Cache.DefinitionImpl', null);
535 // we shouldn't need a whitelist, because the bbcode converter
536 // will strip out any unsupported tags.
538 $purifier = new HTMLPurifier($config);
539 $res['body'] = $purifier->purify($res['body']);
541 $res['body'] = @html2bbcode($res['body']);
545 elseif(! $have_real_body) {
547 // it's not one of our messages and it has no tags
548 // so it's probably just text. We'll escape it just to be safe.
550 $res['body'] = escape_tags($res['body']);
553 // this tag is obsolete but we keep it for really old sites
555 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
556 if($allow && $allow[0]['data'] == 1)
557 $res['last-child'] = 1;
559 $res['last-child'] = 0;
561 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
562 if($private && intval($private[0]['data']) > 0)
563 $res['private'] = intval($private[0]['data']);
567 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
568 if($extid && $extid[0]['data'])
569 $res['extid'] = $extid[0]['data'];
571 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
573 $res['location'] = unxmlify($rawlocation[0]['data']);
576 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
578 $res['created'] = unxmlify($rawcreated[0]['data']);
581 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
583 $res['edited'] = unxmlify($rawedited[0]['data']);
585 if((x($res,'edited')) && (! (x($res,'created'))))
586 $res['created'] = $res['edited'];
588 if(! $res['created'])
589 $res['created'] = $item->get_date('c');
592 $res['edited'] = $item->get_date('c');
595 // Disallow time travelling posts
597 $d1 = strtotime($res['created']);
598 $d2 = strtotime($res['edited']);
599 $d3 = strtotime('now');
602 $res['created'] = datetime_convert();
604 $res['edited'] = datetime_convert();
606 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
607 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
608 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
609 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
610 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
611 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
612 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
613 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
614 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
616 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
617 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
619 foreach($base as $link) {
620 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
621 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
622 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
627 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
629 $res['coord'] = unxmlify($rawgeo[0]['data']);
632 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
634 // select between supported verbs
637 $res['verb'] = unxmlify($rawverb[0]['data']);
640 // translate OStatus unfollow to activity streams if it happened to get selected
642 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
643 $res['verb'] = ACTIVITY_UNFOLLOW;
645 $cats = $item->get_categories();
648 foreach($cats as $cat) {
649 $term = $cat->get_term();
651 $term = $cat->get_label();
652 $scheme = $cat->get_scheme();
653 if($scheme && $term && stristr($scheme,'X-DFRN:'))
654 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
656 $tag_arr[] = notags(trim($term));
658 $res['tag'] = implode(',', $tag_arr);
661 $attach = $item->get_enclosures();
664 foreach($attach as $att) {
665 $len = intval($att->get_length());
666 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
667 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
668 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
669 if(strpos($type,';'))
670 $type = substr($type,0,strpos($type,';'));
671 if((! $link) || (strpos($link,'http') !== 0))
677 $type = 'application/octet-stream';
679 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
681 $res['attach'] = implode(',', $att_arr);
684 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
687 $res['object'] = '<object>' . "\n";
688 $child = $rawobj[0]['child'];
689 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
690 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
691 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
693 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
694 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
695 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
696 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
697 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
698 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
699 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
700 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
702 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
703 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
704 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
705 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
707 $body = html2bb_video($body);
709 $config = HTMLPurifier_Config::createDefault();
710 $config->set('Cache.DefinitionImpl', null);
712 $purifier = new HTMLPurifier($config);
713 $body = $purifier->purify($body);
714 $body = html2bbcode($body);
717 $res['object'] .= '<content>' . $body . '</content>' . "\n";
720 $res['object'] .= '</object>' . "\n";
723 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
726 $res['target'] = '<target>' . "\n";
727 $child = $rawobj[0]['child'];
728 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
729 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
731 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
732 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
733 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
734 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
735 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
736 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
737 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
738 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
740 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
741 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
742 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
743 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
745 $body = html2bb_video($body);
747 $config = HTMLPurifier_Config::createDefault();
748 $config->set('Cache.DefinitionImpl', null);
750 $purifier = new HTMLPurifier($config);
751 $body = $purifier->purify($body);
752 $body = html2bbcode($body);
755 $res['target'] .= '<content>' . $body . '</content>' . "\n";
758 $res['target'] .= '</target>' . "\n";
761 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
763 call_hooks('parse_atom', $arr);
768 function encode_rel_links($links) {
770 if(! ((is_array($links)) && (count($links))))
772 foreach($links as $link) {
774 if($link['attribs']['']['rel'])
775 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
776 if($link['attribs']['']['type'])
777 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
778 if($link['attribs']['']['href'])
779 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
780 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
781 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
782 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
783 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
791 function item_store($arr,$force_parent = false) {
793 // If a Diaspora signature structure was passed in, pull it out of the
794 // item array and set it aside for later storage.
797 if(x($arr,'dsprsig')) {
798 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
799 unset($arr['dsprsig']);
802 if(x($arr, 'gravity'))
803 $arr['gravity'] = intval($arr['gravity']);
804 elseif($arr['parent-uri'] === $arr['uri'])
806 elseif(activity_match($arr['verb'],ACTIVITY_POST))
809 $arr['gravity'] = 6; // extensible catchall
812 $arr['type'] = 'remote';
814 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
816 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
817 $arr['body'] = strip_tags($arr['body']);
819 require_once('Text/LanguageDetect.php');
820 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
821 $l = new Text_LanguageDetect;
822 $lng = $l->detectConfidence($naked_body);
823 $arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
826 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
827 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
828 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
829 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
830 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
831 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
832 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
833 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
834 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
835 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
836 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
837 $arr['commented'] = datetime_convert();
838 $arr['received'] = datetime_convert();
839 $arr['changed'] = datetime_convert();
840 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
841 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
842 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
843 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
844 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
846 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
847 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
848 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
849 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
850 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
851 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
852 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
853 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
854 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
855 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
856 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
857 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
858 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
859 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
860 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
861 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
862 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
863 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
864 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
866 if($arr['parent-uri'] === $arr['uri']) {
869 $allow_cid = $arr['allow_cid'];
870 $allow_gid = $arr['allow_gid'];
871 $deny_cid = $arr['deny_cid'];
872 $deny_gid = $arr['deny_gid'];
876 // find the parent and snarf the item id and ACL's
877 // and anything else we need to inherit
879 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
880 dbesc($arr['parent-uri']),
886 // is the new message multi-level threaded?
887 // even though we don't support it now, preserve the info
888 // and re-attach to the conversation parent.
890 if($r[0]['uri'] != $r[0]['parent-uri']) {
891 $arr['thr-parent'] = $arr['parent-uri'];
892 $arr['parent-uri'] = $r[0]['parent-uri'];
893 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
894 ORDER BY `id` ASC LIMIT 1",
895 dbesc($r[0]['parent-uri']),
896 dbesc($r[0]['parent-uri']),
903 $parent_id = $r[0]['id'];
904 $parent_deleted = $r[0]['deleted'];
905 $allow_cid = $r[0]['allow_cid'];
906 $allow_gid = $r[0]['allow_gid'];
907 $deny_cid = $r[0]['deny_cid'];
908 $deny_gid = $r[0]['deny_gid'];
909 $arr['wall'] = $r[0]['wall'];
911 // if the parent is private, force privacy for the entire conversation
912 // This differs from the above settings as it subtly allows comments from
913 // email correspondents to be private even if the overall thread is not.
916 $arr['private'] = $r[0]['private'];
918 // Edge case. We host a public forum that was originally posted to privately.
919 // The original author commented, but as this is a comment, the permissions
920 // weren't fixed up so it will still show the comment as private unless we fix it here.
922 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
927 // Allow one to see reply tweets from status.net even when
928 // we don't have or can't see the original post.
931 logger('item_store: $force_parent=true, reply converted to top-level post.');
933 $arr['thr-parent'] = $arr['parent-uri'];
934 $arr['parent-uri'] = $arr['uri'];
938 logger('item_store: item parent was not found - ignoring item');
946 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
950 if($r && count($r)) {
951 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
955 call_hooks('post_remote',$arr);
957 if(x($arr,'cancel')) {
958 logger('item_store: post cancelled by plugin.');
964 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
966 $r = dbq("INSERT INTO `item` (`"
967 . implode("`, `", array_keys($arr))
969 . implode("', '", array_values($arr))
972 // find the item we just created
974 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
975 $arr['uri'], // already dbesc'd
980 $current_post = $r[0]['id'];
981 logger('item_store: created item ' . $current_post);
984 logger('item_store: could not locate created item');
988 logger('item_store: duplicated post occurred. Removing duplicates.');
989 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
992 intval($current_post)
996 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
997 $parent_id = $current_post;
999 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1002 $private = $arr['private'];
1004 // Set parent id - and also make sure to inherit the parent's ACL's.
1006 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1007 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1014 intval($parent_deleted),
1015 intval($current_post)
1018 $arr['id'] = $current_post;
1019 $arr['parent'] = $parent_id;
1020 $arr['allow_cid'] = $allow_cid;
1021 $arr['allow_gid'] = $allow_gid;
1022 $arr['deny_cid'] = $deny_cid;
1023 $arr['deny_gid'] = $deny_gid;
1024 $arr['private'] = $private;
1025 $arr['deleted'] = $parent_deleted;
1026 call_hooks('post_remote_end',$arr);
1028 // update the commented timestamp on the parent
1030 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1031 dbesc(datetime_convert()),
1032 dbesc(datetime_convert()),
1037 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1038 intval($current_post),
1039 dbesc($dsprsig->signed_text),
1040 dbesc($dsprsig->signature),
1041 dbesc($dsprsig->signer)
1047 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1050 if($arr['last-child']) {
1051 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1053 intval($arr['uid']),
1054 intval($current_post)
1058 tag_deliver($arr['uid'],$current_post);
1060 return $current_post;
1063 function get_item_contact($item,$contacts) {
1064 if(! count($contacts) || (! is_array($item)))
1066 foreach($contacts as $contact) {
1067 if($contact['id'] == $item['contact-id']) {
1069 break; // NOTREACHED
1076 function tag_deliver($uid,$item_id) {
1078 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1084 $u = q("select * from user where uid = %d limit 1",
1090 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1091 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1094 $i = q("select * from item where id = %d and uid = %d limit 1",
1103 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1105 // Diaspora uses their own hardwired link URL in @-tags
1106 // instead of the one we supply with webfinger
1108 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1110 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1112 foreach($matches as $mtch) {
1113 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1115 logger('tag_deliver: mention found: ' . $mtch[2]);
1123 // send a notification
1125 require_once('include/enotify.php');
1127 'type' => NOTIFY_TAGSELF,
1128 'notify_flags' => $u[0]['notify-flags'],
1129 'language' => $u[0]['language'],
1130 'to_name' => $u[0]['username'],
1131 'to_email' => $u[0]['email'],
1132 'uid' => $u[0]['uid'],
1134 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1135 'source_name' => $item['author-name'],
1136 'source_link' => $item['author-link'],
1137 'source_photo' => $item['author-avatar'],
1138 'verb' => ACTIVITY_TAG,
1142 if((! $community_page) && (! $prvgroup))
1146 // tgroup delivery - setup a second delivery chain
1147 // prevent delivery looping - only proceed
1148 // if the message originated elsewhere and is a top-level post
1150 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1153 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1156 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1157 intval($u[0]['uid'])
1162 // also reset all the privacy bits to the forum default permissions
1164 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1166 $forum_mode = (($prvgroup) ? 2 : 1);
1168 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1169 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1170 intval($forum_mode),
1171 dbesc($c[0]['name']),
1172 dbesc($c[0]['url']),
1173 dbesc($c[0]['thumb']),
1175 dbesc($u[0]['allow_cid']),
1176 dbesc($u[0]['allow_gid']),
1177 dbesc($u[0]['deny_cid']),
1178 dbesc($u[0]['deny_gid']),
1182 proc_run('php','include/notifier.php','tgroup',$item_id);
1191 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1195 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1197 if($contact['duplex'] && $contact['dfrn-id'])
1198 $idtosend = '0:' . $orig_id;
1199 if($contact['duplex'] && $contact['issued-id'])
1200 $idtosend = '1:' . $orig_id;
1202 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1204 $rino_enable = get_config('system','rino_encrypt');
1209 $ssl_val = intval(get_config('system','ssl_policy'));
1213 case SSL_POLICY_FULL:
1214 $ssl_policy = 'full';
1216 case SSL_POLICY_SELFSIGN:
1217 $ssl_policy = 'self';
1219 case SSL_POLICY_NONE:
1221 $ssl_policy = 'none';
1225 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1227 logger('dfrn_deliver: ' . $url);
1229 $xml = fetch_url($url);
1231 $curl_stat = $a->get_curl_code();
1233 return(-1); // timed out
1235 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1240 if(strpos($xml,'<?xml') === false) {
1241 logger('dfrn_deliver: no valid XML returned');
1242 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1246 $res = parse_xml_string($xml);
1248 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1249 return (($res->status) ? $res->status : 3);
1251 $postvars = array();
1252 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1253 $challenge = hex2bin((string) $res->challenge);
1254 $perm = (($res->perm) ? $res->perm : null);
1255 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1256 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1257 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1259 if($owner['page-flags'] == PAGE_PRVGROUP)
1262 $final_dfrn_id = '';
1265 if((($perm == 'rw') && (! intval($contact['writable'])))
1266 || (($perm == 'r') && (intval($contact['writable'])))) {
1267 q("update contact set writable = %d where id = %d limit 1",
1268 intval(($perm == 'rw') ? 1 : 0),
1269 intval($contact['id'])
1271 $contact['writable'] = (string) 1 - intval($contact['writable']);
1275 if(($contact['duplex'] && strlen($contact['pubkey']))
1276 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1277 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1278 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1279 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1282 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1283 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1286 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1288 if(strpos($final_dfrn_id,':') == 1)
1289 $final_dfrn_id = substr($final_dfrn_id,2);
1291 if($final_dfrn_id != $orig_id) {
1292 logger('dfrn_deliver: wrong dfrn_id.');
1293 // did not decode properly - cannot trust this site
1297 $postvars['dfrn_id'] = $idtosend;
1298 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1300 $postvars['dissolve'] = '1';
1303 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1304 $postvars['data'] = $atom;
1305 $postvars['perm'] = 'rw';
1308 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1309 $postvars['perm'] = 'r';
1312 $postvars['ssl_policy'] = $ssl_policy;
1315 $postvars['page'] = $page;
1317 if($rino && $rino_allowed && (! $dissolve)) {
1318 $key = substr(random_string(),0,16);
1319 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1320 $postvars['data'] = $data;
1321 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1324 if($dfrn_version >= 2.1) {
1325 if(($contact['duplex'] && strlen($contact['pubkey']))
1326 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1327 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1329 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1332 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1336 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1337 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1340 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1344 logger('md5 rawkey ' . md5($postvars['key']));
1346 $postvars['key'] = bin2hex($postvars['key']);
1349 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1351 $xml = post_url($contact['notify'],$postvars);
1353 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1355 $curl_stat = $a->get_curl_code();
1356 if((! $curl_stat) || (! strlen($xml)))
1357 return(-1); // timed out
1359 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1362 if(strpos($xml,'<?xml') === false) {
1363 logger('dfrn_deliver: phase 2: no valid XML returned');
1364 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1368 if($contact['term-date'] != '0000-00-00 00:00:00') {
1369 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1370 require_once('include/Contact.php');
1371 unmark_for_death($contact);
1374 $res = parse_xml_string($xml);
1376 return $res->status;
1382 * consume_feed - process atom feed and update anything/everything we might need to update
1384 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1386 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1387 * It is this person's stuff that is going to be updated.
1388 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1389 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1390 * have a contact record.
1391 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1392 * might not) try and subscribe to it.
1393 * $datedir sorts in reverse order
1394 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1395 * imported prior to its children being seen in the stream unless we are certain
1396 * of how the feed is arranged/ordered.
1397 * With $pass = 1, we only pull parent items out of the stream.
1398 * With $pass = 2, we only pull children (comments/likes).
1400 * So running this twice, first with pass 1 and then with pass 2 will do the right
1401 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1402 * model where comments can have sub-threads. That would require some massive sorting
1403 * to get all the feed items into a mostly linear ordering, and might still require
1407 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1409 require_once('library/simplepie/simplepie.inc');
1411 if(! strlen($xml)) {
1412 logger('consume_feed: empty input');
1416 $feed = new SimplePie();
1417 $feed->set_raw_data($xml);
1419 $feed->enable_order_by_date(true);
1421 $feed->enable_order_by_date(false);
1425 logger('consume_feed: Error parsing XML: ' . $feed->error());
1427 $permalink = $feed->get_permalink();
1429 // Check at the feed level for updated contact name and/or photo
1433 $photo_timestamp = '';
1437 $hubs = $feed->get_links('hub');
1438 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1441 $hub = implode(',', $hubs);
1443 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1445 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1447 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1448 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1449 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1450 $new_name = $elems['name'][0]['data'];
1452 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1453 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1454 $photo_url = $elems['link'][0]['attribs']['']['href'];
1457 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1458 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1462 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1463 logger('consume_feed: Updating photo for ' . $contact['name']);
1464 require_once("Photo.php");
1465 $photo_failure = false;
1466 $have_photo = false;
1468 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1469 intval($contact['id']),
1470 intval($contact['uid'])
1473 $resource_id = $r[0]['resource-id'];
1477 $resource_id = photo_new_resource();
1480 $img_str = fetch_url($photo_url,true);
1481 // guess mimetype from headers or filename
1482 $type = guess_image_type($photo_url,true);
1485 $img = new Photo($img_str, $type);
1486 if($img->is_valid()) {
1488 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1489 dbesc($resource_id),
1490 intval($contact['id']),
1491 intval($contact['uid'])
1495 $img->scaleImageSquare(175);
1497 $hash = $resource_id;
1498 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1500 $img->scaleImage(80);
1501 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1503 $img->scaleImage(48);
1504 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1508 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1509 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1510 dbesc(datetime_convert()),
1511 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1512 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1513 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1514 intval($contact['uid']),
1515 intval($contact['id'])
1520 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1521 $r = q("select * from contact where uid = %d and id = %d limit 1",
1522 intval($contact['uid']),
1523 intval($contact['id'])
1526 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1527 dbesc(notags(trim($new_name))),
1528 dbesc(datetime_convert()),
1529 intval($contact['uid']),
1530 intval($contact['id'])
1533 // do our best to update the name on content items
1536 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1537 dbesc(notags(trim($new_name))),
1538 dbesc($r[0]['name']),
1539 dbesc($r[0]['url']),
1540 intval($contact['uid'])
1545 if(strlen($birthday)) {
1546 if(substr($birthday,0,4) != $contact['bdyear']) {
1547 logger('consume_feed: updating birthday: ' . $birthday);
1551 * Add new birthday event for this person
1553 * $bdtext is just a readable placeholder in case the event is shared
1554 * with others. We will replace it during presentation to our $importer
1555 * to contain a sparkle link and perhaps a photo.
1559 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1560 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1563 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1564 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1565 intval($contact['uid']),
1566 intval($contact['id']),
1567 dbesc(datetime_convert()),
1568 dbesc(datetime_convert()),
1569 dbesc(datetime_convert('UTC','UTC', $birthday)),
1570 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1579 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1580 dbesc(substr($birthday,0,4)),
1581 intval($contact['uid']),
1582 intval($contact['id'])
1585 // This function is called twice without reloading the contact
1586 // Make sure we only create one event. This is why &$contact
1587 // is a reference var in this function
1589 $contact['bdyear'] = substr($birthday,0,4);
1594 $community_page = 0;
1595 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1597 $community_page = intval($rawtags[0]['data']);
1599 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1600 q("update contact set forum = %d where id = %d limit 1",
1601 intval($community_page),
1602 intval($contact['id'])
1604 $contact['forum'] = (string) $community_page;
1608 // process any deleted entries
1610 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1611 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1612 foreach($del_entries as $dentry) {
1614 if(isset($dentry['attribs']['']['ref'])) {
1615 $uri = $dentry['attribs']['']['ref'];
1617 if(isset($dentry['attribs']['']['when'])) {
1618 $when = $dentry['attribs']['']['when'];
1619 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1622 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1624 if($deleted && is_array($contact)) {
1625 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1626 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1628 intval($importer['uid']),
1629 intval($contact['id'])
1634 if(! $item['deleted'])
1635 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1637 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1638 $xo = parse_xml_string($item['object'],false);
1639 $xt = parse_xml_string($item['target'],false);
1640 if($xt->type === ACTIVITY_OBJ_NOTE) {
1641 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1643 intval($importer['importer_uid'])
1647 // For tags, the owner cannot remove the tag on the author's copy of the post.
1649 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1650 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1651 $author_copy = (($item['origin']) ? true : false);
1653 if($owner_remove && $author_copy)
1655 if($author_remove || $owner_remove) {
1656 $tags = explode(',',$i[0]['tag']);
1659 foreach($tags as $tag)
1660 if(trim($tag) !== trim($xo->body))
1661 $newtags[] = trim($tag);
1663 q("update item set tag = '%s' where id = %d limit 1",
1664 dbesc(implode(',',$newtags)),
1672 if($item['uri'] == $item['parent-uri']) {
1673 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1674 `body` = '', `title` = ''
1675 WHERE `parent-uri` = '%s' AND `uid` = %d",
1677 dbesc(datetime_convert()),
1678 dbesc($item['uri']),
1679 intval($importer['uid'])
1683 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1684 `body` = '', `title` = ''
1685 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1687 dbesc(datetime_convert()),
1689 intval($importer['uid'])
1691 if($item['last-child']) {
1692 // ensure that last-child is set in case the comment that had it just got wiped.
1693 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1694 dbesc(datetime_convert()),
1695 dbesc($item['parent-uri']),
1696 intval($item['uid'])
1698 // who is the last child now?
1699 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1700 ORDER BY `created` DESC LIMIT 1",
1701 dbesc($item['parent-uri']),
1702 intval($importer['uid'])
1705 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1716 // Now process the feed
1718 if($feed->get_item_quantity()) {
1720 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1722 // in inverse date order
1724 $items = array_reverse($feed->get_items());
1726 $items = $feed->get_items();
1729 foreach($items as $item) {
1732 $item_id = $item->get_id();
1733 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1734 if(isset($rawthread[0]['attribs']['']['ref'])) {
1736 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1739 if(($is_reply) && is_array($contact)) {
1744 // Have we seen it? If not, import it.
1746 $item_id = $item->get_id();
1747 $datarray = get_atom_elements($feed,$item);
1750 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1751 $datarray['author-name'] = $contact['name'];
1752 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1753 $datarray['author-link'] = $contact['url'];
1754 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1755 $datarray['author-avatar'] = $contact['thumb'];
1757 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1758 logger('consume_feed: no author information! ' . print_r($datarray,true));
1762 $force_parent = false;
1763 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1764 if($contact['network'] === NETWORK_OSTATUS)
1765 $force_parent = true;
1766 if(strlen($datarray['title']))
1767 unset($datarray['title']);
1768 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1769 dbesc(datetime_convert()),
1771 intval($importer['uid'])
1773 $datarray['last-child'] = 1;
1777 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1779 intval($importer['uid'])
1782 // Update content if 'updated' changes
1785 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1787 // do not accept (ignore) an earlier edit than one we currently have.
1788 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1791 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1792 dbesc($datarray['title']),
1793 dbesc($datarray['body']),
1794 dbesc($datarray['tag']),
1795 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1797 intval($importer['uid'])
1801 // update last-child if it changes
1803 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1804 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1805 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1806 dbesc(datetime_convert()),
1808 intval($importer['uid'])
1810 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1811 intval($allow[0]['data']),
1812 dbesc(datetime_convert()),
1814 intval($importer['uid'])
1821 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1822 // one way feed - no remote comment ability
1823 $datarray['last-child'] = 0;
1825 $datarray['parent-uri'] = $parent_uri;
1826 $datarray['uid'] = $importer['uid'];
1827 $datarray['contact-id'] = $contact['id'];
1828 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1829 $datarray['type'] = 'activity';
1830 $datarray['gravity'] = GRAVITY_LIKE;
1831 // only one like or dislike per person
1832 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s' OR `thr-parent` = '%s') limit 1",
1833 intval($datarray['uid']),
1834 intval($datarray['contact-id']),
1835 dbesc($datarray['verb']),
1843 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1844 $xo = parse_xml_string($datarray['object'],false);
1845 $xt = parse_xml_string($datarray['target'],false);
1847 if($xt->type == ACTIVITY_OBJ_NOTE) {
1848 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1850 intval($importer['importer_uid'])
1855 // extract tag, if not duplicate, add to parent item
1856 if($xo->id && $xo->content) {
1857 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1858 if(! (stristr($r[0]['tag'],$newtag))) {
1859 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1860 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1868 $r = item_store($datarray,$force_parent);
1874 // Head post of a conversation. Have we seen it? If not, import it.
1876 $item_id = $item->get_id();
1878 $datarray = get_atom_elements($feed,$item);
1880 if(is_array($contact)) {
1881 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1882 $datarray['author-name'] = $contact['name'];
1883 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1884 $datarray['author-link'] = $contact['url'];
1885 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1886 $datarray['author-avatar'] = $contact['thumb'];
1889 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1890 logger('consume_feed: no author information! ' . print_r($datarray,true));
1894 // special handling for events
1896 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1897 $ev = bbtoevent($datarray['body']);
1898 if(x($ev,'desc') && x($ev,'start')) {
1899 $ev['uid'] = $importer['uid'];
1900 $ev['uri'] = $item_id;
1901 $ev['edited'] = $datarray['edited'];
1902 $ev['private'] = $datarray['private'];
1904 if(is_array($contact))
1905 $ev['cid'] = $contact['id'];
1906 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1908 intval($importer['uid'])
1911 $ev['id'] = $r[0]['id'];
1912 $xyz = event_store($ev);
1917 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1918 if(strlen($datarray['title']))
1919 unset($datarray['title']);
1920 $datarray['last-child'] = 1;
1924 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1926 intval($importer['uid'])
1929 // Update content if 'updated' changes
1932 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1934 // do not accept (ignore) an earlier edit than one we currently have.
1935 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1938 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1939 dbesc($datarray['title']),
1940 dbesc($datarray['body']),
1941 dbesc($datarray['tag']),
1942 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1944 intval($importer['uid'])
1948 // update last-child if it changes
1950 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1951 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1952 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1953 intval($allow[0]['data']),
1954 dbesc(datetime_convert()),
1956 intval($importer['uid'])
1962 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1963 logger('consume-feed: New follower');
1964 new_follower($importer,$contact,$datarray,$item);
1967 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1968 lose_follower($importer,$contact,$datarray,$item);
1972 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1973 logger('consume-feed: New friend request');
1974 new_follower($importer,$contact,$datarray,$item,true);
1977 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1978 lose_sharer($importer,$contact,$datarray,$item);
1983 if(! is_array($contact))
1987 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1988 // one way feed - no remote comment ability
1989 $datarray['last-child'] = 0;
1991 if($contact['network'] === NETWORK_FEED)
1992 $datarray['private'] = 2;
1994 // This is my contact on another system, but it's really me.
1995 // Turn this into a wall post.
1997 if($contact['remote_self']) {
1998 $datarray['wall'] = 1;
1999 if($contact['network'] === NETWORK_FEED) {
2000 $datarray['private'] = 0;
2004 $datarray['parent-uri'] = $item_id;
2005 $datarray['uid'] = $importer['uid'];
2006 $datarray['contact-id'] = $contact['id'];
2008 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2009 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2010 // but otherwise there's a possible data mixup on the sender's system.
2011 // the tgroup delivery code called from item_store will correct it if it's a forum,
2012 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2013 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2014 $datarray['owner-name'] = $contact['name'];
2015 $datarray['owner-link'] = $contact['url'];
2016 $datarray['owner-avatar'] = $contact['thumb'];
2019 $r = item_store($datarray);
2027 function local_delivery($importer,$data) {
2031 if($importer['readonly']) {
2032 // We aren't receiving stuff from this person. But we will quietly ignore them
2033 // rather than a blatant "go away" message.
2034 logger('local_delivery: ignoring');
2039 // Consume notification feed. This may differ from consuming a public feed in several ways
2040 // - might contain email or friend suggestions
2041 // - might contain remote followup to our message
2042 // - in which case we need to accept it and then notify other conversants
2043 // - we may need to send various email notifications
2045 $feed = new SimplePie();
2046 $feed->set_raw_data($data);
2047 $feed->enable_order_by_date(false);
2051 // Currently unsupported - needs a lot of work
2052 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2053 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2054 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2056 $newloc['uid'] = $importer['importer_uid'];
2057 $newloc['cid'] = $importer['id'];
2058 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2059 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2060 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2061 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2062 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2063 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2064 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2065 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
2066 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2067 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
2070 // merge with current record, current contents have priority
2071 // update record, set url-updated
2072 // update profile photos
2078 // handle friend suggestion notification
2080 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2081 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2082 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2084 $fsugg['uid'] = $importer['importer_uid'];
2085 $fsugg['cid'] = $importer['id'];
2086 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2087 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2088 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2089 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2090 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2092 // Does our member already have a friend matching this description?
2094 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2095 dbesc($fsugg['name']),
2096 dbesc(normalise_link($fsugg['url'])),
2097 intval($fsugg['uid'])
2102 // Do we already have an fcontact record for this person?
2105 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2106 dbesc($fsugg['url']),
2107 dbesc($fsugg['name']),
2108 dbesc($fsugg['request'])
2113 // OK, we do. Do we already have an introduction for this person ?
2114 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2115 intval($fsugg['uid']),
2122 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2123 dbesc($fsugg['name']),
2124 dbesc($fsugg['url']),
2125 dbesc($fsugg['photo']),
2126 dbesc($fsugg['request'])
2128 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2129 dbesc($fsugg['url']),
2130 dbesc($fsugg['name']),
2131 dbesc($fsugg['request'])
2136 // database record did not get created. Quietly give up.
2141 $hash = random_string();
2143 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2144 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2145 intval($fsugg['uid']),
2147 intval($fsugg['cid']),
2148 dbesc($fsugg['body']),
2150 dbesc(datetime_convert()),
2155 'type' => NOTIFY_SUGGEST,
2156 'notify_flags' => $importer['notify-flags'],
2157 'language' => $importer['language'],
2158 'to_name' => $importer['username'],
2159 'to_email' => $importer['email'],
2160 'uid' => $importer['importer_uid'],
2162 'link' => $a->get_baseurl() . '/notifications/intros',
2163 'source_name' => $importer['name'],
2164 'source_link' => $importer['url'],
2165 'source_photo' => $importer['photo'],
2166 'verb' => ACTIVITY_REQ_FRIEND,
2175 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2176 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2178 logger('local_delivery: private message received');
2181 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2184 $msg['uid'] = $importer['importer_uid'];
2185 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2186 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2187 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2188 $msg['contact-id'] = $importer['id'];
2189 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2190 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2192 $msg['replied'] = 0;
2193 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2194 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2195 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2199 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2200 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2202 // send notifications.
2204 require_once('include/enotify.php');
2206 $notif_params = array(
2207 'type' => NOTIFY_MAIL,
2208 'notify_flags' => $importer['notify-flags'],
2209 'language' => $importer['language'],
2210 'to_name' => $importer['username'],
2211 'to_email' => $importer['email'],
2212 'uid' => $importer['importer_uid'],
2214 'source_name' => $msg['from-name'],
2215 'source_link' => $importer['url'],
2216 'source_photo' => $importer['thumb'],
2217 'verb' => ACTIVITY_POST,
2221 notification($notif_params);
2227 $community_page = 0;
2228 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2230 $community_page = intval($rawtags[0]['data']);
2232 if(intval($importer['forum']) != $community_page) {
2233 q("update contact set forum = %d where id = %d limit 1",
2234 intval($community_page),
2235 intval($importer['id'])
2237 $importer['forum'] = (string) $community_page;
2240 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2242 // process any deleted entries
2244 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2245 if(is_array($del_entries) && count($del_entries)) {
2246 foreach($del_entries as $dentry) {
2248 if(isset($dentry['attribs']['']['ref'])) {
2249 $uri = $dentry['attribs']['']['ref'];
2251 if(isset($dentry['attribs']['']['when'])) {
2252 $when = $dentry['attribs']['']['when'];
2253 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2256 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2260 // check for relayed deletes to our conversation
2263 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2265 intval($importer['importer_uid'])
2268 $parent_uri = $r[0]['parent-uri'];
2269 if($r[0]['id'] != $r[0]['parent'])
2276 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2279 logger('local_delivery: possible community delete');
2282 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2284 // was the top-level post for this reply written by somebody on this site?
2285 // Specifically, the recipient?
2287 $is_a_remote_delete = false;
2289 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2290 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2291 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2292 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2293 AND `item`.`uid` = %d
2299 intval($importer['importer_uid'])
2302 $is_a_remote_delete = true;
2304 // Does this have the characteristics of a community or private group comment?
2305 // If it's a reply to a wall post on a community/prvgroup page it's a
2306 // valid community comment. Also forum_mode makes it valid for sure.
2307 // If neither, it's not.
2309 if($is_a_remote_delete && $community) {
2310 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2311 $is_a_remote_delete = false;
2312 logger('local_delivery: not a community delete');
2316 if($is_a_remote_delete) {
2317 logger('local_delivery: received remote delete');
2321 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2322 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2324 intval($importer['importer_uid']),
2325 intval($importer['id'])
2331 if($item['deleted'])
2334 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2336 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2337 $xo = parse_xml_string($item['object'],false);
2338 $xt = parse_xml_string($item['target'],false);
2340 if($xt->type === ACTIVITY_OBJ_NOTE) {
2341 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2343 intval($importer['importer_uid'])
2347 // For tags, the owner cannot remove the tag on the author's copy of the post.
2349 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2350 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2351 $author_copy = (($item['origin']) ? true : false);
2353 if($owner_remove && $author_copy)
2355 if($author_remove || $owner_remove) {
2356 $tags = explode(',',$i[0]['tag']);
2359 foreach($tags as $tag)
2360 if(trim($tag) !== trim($xo->body))
2361 $newtags[] = trim($tag);
2363 q("update item set tag = '%s' where id = %d limit 1",
2364 dbesc(implode(',',$newtags)),
2372 if($item['uri'] == $item['parent-uri']) {
2373 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2374 `body` = '', `title` = ''
2375 WHERE `parent-uri` = '%s' AND `uid` = %d",
2377 dbesc(datetime_convert()),
2378 dbesc($item['uri']),
2379 intval($importer['importer_uid'])
2383 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2384 `body` = '', `title` = ''
2385 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2387 dbesc(datetime_convert()),
2389 intval($importer['importer_uid'])
2391 if($item['last-child']) {
2392 // ensure that last-child is set in case the comment that had it just got wiped.
2393 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2394 dbesc(datetime_convert()),
2395 dbesc($item['parent-uri']),
2396 intval($item['uid'])
2398 // who is the last child now?
2399 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2400 ORDER BY `created` DESC LIMIT 1",
2401 dbesc($item['parent-uri']),
2402 intval($importer['importer_uid'])
2405 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2410 // if this is a relayed delete, propagate it to other recipients
2412 if($is_a_remote_delete)
2413 proc_run('php',"include/notifier.php","drop",$item['id']);
2421 foreach($feed->get_items() as $item) {
2424 $item_id = $item->get_id();
2425 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2426 if(isset($rawthread[0]['attribs']['']['ref'])) {
2428 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2434 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2437 logger('local_delivery: possible community reply');
2440 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2442 // was the top-level post for this reply written by somebody on this site?
2443 // Specifically, the recipient?
2445 $is_a_remote_comment = false;
2447 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2448 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2449 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2450 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2451 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2452 AND `item`.`uid` = %d
2458 intval($importer['importer_uid'])
2461 $is_a_remote_comment = true;
2463 // Does this have the characteristics of a community or private group comment?
2464 // If it's a reply to a wall post on a community/prvgroup page it's a
2465 // valid community comment. Also forum_mode makes it valid for sure.
2466 // If neither, it's not.
2468 if($is_a_remote_comment && $community) {
2469 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2470 $is_a_remote_comment = false;
2471 logger('local_delivery: not a community reply');
2475 if($is_a_remote_comment) {
2476 logger('local_delivery: received remote comment');
2478 // remote reply to our post. Import and then notify everybody else.
2480 $datarray = get_atom_elements($feed,$item);
2482 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2484 intval($importer['importer_uid'])
2487 // Update content if 'updated' changes
2491 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2493 // do not accept (ignore) an earlier edit than one we currently have.
2494 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2497 logger('received updated comment' , LOGGER_DEBUG);
2498 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2499 dbesc($datarray['title']),
2500 dbesc($datarray['body']),
2501 dbesc($datarray['tag']),
2502 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2504 intval($importer['importer_uid'])
2507 proc_run('php',"include/notifier.php","comment-import",$iid);
2515 // TODO: make this next part work against both delivery threads of a community post
2517 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2518 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2519 // they won't know what to do so don't report an error. Just quietly die.
2523 // our user with $importer['importer_uid'] is the owner
2525 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2526 intval($importer['importer_uid'])
2530 $datarray['type'] = 'remote-comment';
2531 $datarray['wall'] = 1;
2532 $datarray['parent-uri'] = $parent_uri;
2533 $datarray['uid'] = $importer['importer_uid'];
2534 $datarray['owner-name'] = $own[0]['name'];
2535 $datarray['owner-link'] = $own[0]['url'];
2536 $datarray['owner-avatar'] = $own[0]['thumb'];
2537 $datarray['contact-id'] = $importer['id'];
2539 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2541 $datarray['type'] = 'activity';
2542 $datarray['gravity'] = GRAVITY_LIKE;
2543 $datarray['last-child'] = 0;
2544 // only one like or dislike per person
2545 $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`thr-parent` = '%s' or `parent-uri` = '%s') and deleted = 0 limit 1",
2546 intval($datarray['uid']),
2547 intval($datarray['contact-id']),
2548 dbesc($datarray['verb']),
2549 dbesc($datarray['parent-uri']),
2550 dbesc($datarray['parent-uri'])
2557 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2559 $xo = parse_xml_string($datarray['object'],false);
2560 $xt = parse_xml_string($datarray['target'],false);
2562 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2564 // fetch the parent item
2566 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2568 intval($importer['importer_uid'])
2573 // extract tag, if not duplicate, and this user allows tags, add to parent item
2575 if($xo->id && $xo->content) {
2576 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2577 if(! (stristr($tagp[0]['tag'],$newtag))) {
2578 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2579 intval($importer['importer_uid'])
2581 if(count($i) && ! intval($i[0]['blocktags'])) {
2582 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2583 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2584 intval($tagp[0]['id']),
2585 dbesc(datetime_convert())
2594 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2595 // if(! stristr($datarray['tag'],$newtag)) {
2596 // if(strlen($datarray['tag']))
2597 // $datarray['tag'] .= ',';
2598 // $datarray['tag'] .= $newtag;
2603 $posted_id = item_store($datarray);
2607 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2609 intval($importer['importer_uid'])
2612 $parent = $r[0]['parent'];
2615 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2616 dbesc(datetime_convert()),
2617 intval($importer['importer_uid']),
2618 intval($r[0]['parent'])
2621 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2622 dbesc(datetime_convert()),
2623 intval($importer['importer_uid']),
2628 if($posted_id && $parent) {
2630 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2632 if((! $is_like) && (! $importer['self'])) {
2634 require_once('include/enotify.php');
2637 'type' => NOTIFY_COMMENT,
2638 'notify_flags' => $importer['notify-flags'],
2639 'language' => $importer['language'],
2640 'to_name' => $importer['username'],
2641 'to_email' => $importer['email'],
2642 'uid' => $importer['importer_uid'],
2643 'item' => $datarray,
2644 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2645 'source_name' => stripslashes($datarray['author-name']),
2646 'source_link' => $datarray['author-link'],
2647 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2648 ? $importer['thumb'] : $datarray['author-avatar']),
2649 'verb' => ACTIVITY_POST,
2651 'parent' => $parent,
2664 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2666 $item_id = $item->get_id();
2667 $datarray = get_atom_elements($feed,$item);
2669 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2671 intval($importer['importer_uid'])
2674 // Update content if 'updated' changes
2677 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2679 // do not accept (ignore) an earlier edit than one we currently have.
2680 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2683 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2684 dbesc($datarray['title']),
2685 dbesc($datarray['body']),
2686 dbesc($datarray['tag']),
2687 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2689 intval($importer['importer_uid'])
2693 // update last-child if it changes
2695 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2696 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2697 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2698 dbesc(datetime_convert()),
2700 intval($importer['importer_uid'])
2702 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2703 intval($allow[0]['data']),
2704 dbesc(datetime_convert()),
2706 intval($importer['importer_uid'])
2712 $datarray['parent-uri'] = $parent_uri;
2713 $datarray['uid'] = $importer['importer_uid'];
2714 $datarray['contact-id'] = $importer['id'];
2715 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2716 $datarray['type'] = 'activity';
2717 $datarray['gravity'] = GRAVITY_LIKE;
2718 // only one like or dislike per person
2719 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s' OR `thr-parent` = '%s') limit 1",
2720 intval($datarray['uid']),
2721 intval($datarray['contact-id']),
2722 dbesc($datarray['verb']),
2731 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2733 $xo = parse_xml_string($datarray['object'],false);
2734 $xt = parse_xml_string($datarray['target'],false);
2736 if($xt->type == ACTIVITY_OBJ_NOTE) {
2737 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2739 intval($importer['importer_uid'])
2744 // extract tag, if not duplicate, add to parent item
2746 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2747 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2748 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2756 $posted_id = item_store($datarray);
2758 // find out if our user is involved in this conversation and wants to be notified.
2760 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2762 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2764 intval($importer['importer_uid'])
2767 if(count($myconv)) {
2768 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2770 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2771 if(! link_compare($datarray['author-link'],$importer_url)) {
2774 foreach($myconv as $conv) {
2776 // now if we find a match, it means we're in this conversation
2778 if(! link_compare($conv['author-link'],$importer_url))
2781 require_once('include/enotify.php');
2783 $conv_parent = $conv['parent'];
2786 'type' => NOTIFY_COMMENT,
2787 'notify_flags' => $importer['notify-flags'],
2788 'language' => $importer['language'],
2789 'to_name' => $importer['username'],
2790 'to_email' => $importer['email'],
2791 'uid' => $importer['importer_uid'],
2792 'item' => $datarray,
2793 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2794 'source_name' => stripslashes($datarray['author-name']),
2795 'source_link' => $datarray['author-link'],
2796 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2797 ? $importer['thumb'] : $datarray['author-avatar']),
2798 'verb' => ACTIVITY_POST,
2800 'parent' => $conv_parent,
2804 // only send one notification
2816 // Head post of a conversation. Have we seen it? If not, import it.
2819 $item_id = $item->get_id();
2820 $datarray = get_atom_elements($feed,$item);
2822 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2823 $ev = bbtoevent($datarray['body']);
2824 if(x($ev,'desc') && x($ev,'start')) {
2825 $ev['cid'] = $importer['id'];
2826 $ev['uid'] = $importer['uid'];
2827 $ev['uri'] = $item_id;
2828 $ev['edited'] = $datarray['edited'];
2829 $ev['private'] = $datarray['private'];
2831 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2833 intval($importer['uid'])
2836 $ev['id'] = $r[0]['id'];
2837 $xyz = event_store($ev);
2842 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2844 intval($importer['importer_uid'])
2847 // Update content if 'updated' changes
2850 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2852 // do not accept (ignore) an earlier edit than one we currently have.
2853 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2856 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2857 dbesc($datarray['title']),
2858 dbesc($datarray['body']),
2859 dbesc($datarray['tag']),
2860 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2862 intval($importer['importer_uid'])
2866 // update last-child if it changes
2868 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2869 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2870 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2871 intval($allow[0]['data']),
2872 dbesc(datetime_convert()),
2874 intval($importer['importer_uid'])
2880 // This is my contact on another system, but it's really me.
2881 // Turn this into a wall post.
2883 if($importer['remote_self'])
2884 $datarray['wall'] = 1;
2886 $datarray['parent-uri'] = $item_id;
2887 $datarray['uid'] = $importer['importer_uid'];
2888 $datarray['contact-id'] = $importer['id'];
2890 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2891 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2892 // but otherwise there's a possible data mixup on the sender's system.
2893 // the tgroup delivery code called from item_store will correct it if it's a forum,
2894 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2895 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2896 $datarray['owner-name'] = $importer['senderName'];
2897 $datarray['owner-link'] = $importer['url'];
2898 $datarray['owner-avatar'] = $importer['thumb'];
2901 $r = item_store($datarray);
2912 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2913 $url = notags(trim($datarray['author-link']));
2914 $name = notags(trim($datarray['author-name']));
2915 $photo = notags(trim($datarray['author-avatar']));
2917 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2918 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2919 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2921 if(is_array($contact)) {
2922 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2923 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2924 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2925 intval(CONTACT_IS_FRIEND),
2926 intval($contact['id']),
2927 intval($importer['uid'])
2930 // send email notification to owner?
2934 // create contact record
2936 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2937 `blocked`, `readonly`, `pending`, `writable` )
2938 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2939 intval($importer['uid']),
2940 dbesc(datetime_convert()),
2942 dbesc(normalise_link($url)),
2946 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2947 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2949 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2950 intval($importer['uid']),
2954 $contact_record = $r[0];
2956 // create notification
2957 $hash = random_string();
2959 if(is_array($contact_record)) {
2960 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2961 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2962 intval($importer['uid']),
2963 intval($contact_record['id']),
2965 dbesc(datetime_convert())
2968 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2969 intval($importer['uid'])
2974 if(intval($r[0]['def_gid'])) {
2975 require_once('include/group.php');
2976 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2979 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2980 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2981 $email = replace_macros($email_tpl, array(
2982 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2984 '$myname' => $r[0]['username'],
2985 '$siteurl' => $a->get_baseurl(),
2986 '$sitename' => $a->config['sitename']
2988 $res = mail($r[0]['email'],
2989 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2991 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2992 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2993 . 'Content-transfer-encoding: 8bit' );
3000 function lose_follower($importer,$contact,$datarray,$item) {
3002 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
3003 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3004 intval(CONTACT_IS_SHARING),
3005 intval($contact['id'])
3009 contact_remove($contact['id']);
3013 function lose_sharer($importer,$contact,$datarray,$item) {
3015 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3016 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3017 intval(CONTACT_IS_FOLLOWER),
3018 intval($contact['id'])
3022 contact_remove($contact['id']);
3027 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3031 if(is_array($importer)) {
3032 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3033 intval($importer['uid'])
3037 // Diaspora has different message-ids in feeds than they do
3038 // through the direct Diaspora protocol. If we try and use
3039 // the feed, we'll get duplicates. So don't.
3041 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3044 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3046 // Use a single verify token, even if multiple hubs
3048 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3050 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3052 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
3054 if(! strlen($contact['hub-verify'])) {
3055 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3056 dbesc($verify_token),
3057 intval($contact['id'])
3061 post_url($url,$params);
3063 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3070 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3074 $name = xmlify($name);
3075 $uri = xmlify($uri);
3078 $photo = xmlify($photo);
3082 $o .= "<name>$name</name>\r\n";
3083 $o .= "<uri>$uri</uri>\r\n";
3084 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3085 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3087 call_hooks('atom_author', $o);
3089 $o .= "</$tag>\r\n";
3093 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3097 if(! $item['parent'])
3100 if($item['deleted'])
3101 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3104 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3105 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3107 $body = $item['body'];
3110 $o = "\r\n\r\n<entry>\r\n";
3112 if(is_array($author))
3113 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3115 $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']));
3116 if(strlen($item['owner-name']))
3117 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3119 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || ($item['thr-parent'])) {
3120 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3121 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3124 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3125 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3126 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3127 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3128 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3129 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3130 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3132 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3134 if($item['location']) {
3135 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3136 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3140 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3142 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3143 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3146 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3147 if($item['bookmark'])
3148 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3151 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3154 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3156 if($item['signed_text']) {
3157 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3158 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3161 $verb = construct_verb($item);
3162 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3163 $actobj = construct_activity_object($item);
3166 $actarg = construct_activity_target($item);
3170 $tags = item_getfeedtags($item);
3172 foreach($tags as $t) {
3173 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3177 $o .= item_getfeedattach($item);
3179 $mentioned = get_mentions($item);
3183 call_hooks('atom_entry', $o);
3185 $o .= '</entry>' . "\r\n";
3190 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3193 logger('fix_private_photos', LOGGER_DEBUG);
3194 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3199 $img_start = strpos($orig_body, '[img');
3200 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3201 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3202 while( ($img_st_close !== false) && ($img_len !== false) ) {
3204 $img_st_close++; // make it point to AFTER the closing bracket
3205 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3207 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3210 if(stristr($image , $site . '/photo/')) {
3211 // Only embed locally hosted photos
3213 $i = basename($image);
3214 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3215 $x = strpos($i,'-');
3218 $res = substr($i,$x+1);
3219 $i = substr($i,0,$x);
3220 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3227 // Check to see if we should replace this photo link with an embedded image
3228 // 1. No need to do so if the photo is public
3229 // 2. If there's a contact-id provided, see if they're in the access list
3230 // for the photo. If so, embed it.
3231 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3232 // permissions, regardless of order but first check to see if they're an exact
3233 // match to save some processing overhead.
3235 if(has_permissions($r[0])) {
3237 $recips = enumerate_permissions($r[0]);
3238 if(in_array($cid, $recips)) {
3243 if(compare_permissions($item,$r[0]))
3248 $data = $r[0]['data'];
3249 $type = $r[0]['type'];
3251 // If a custom width and height were specified, apply before embedding
3252 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3253 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3255 $width = intval($match[1]);
3256 $height = intval($match[2]);
3258 $ph = new Photo($data, $type);
3259 if($ph->is_valid()) {
3260 $ph->scaleImage(max($width, $height));
3261 $data = $ph->imageString();
3262 $type = $ph->getType();
3266 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3267 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3268 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3274 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3275 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3276 if($orig_body === false)
3279 $img_start = strpos($orig_body, '[img');
3280 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3281 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3284 $new_body = $new_body . $orig_body;
3290 function has_permissions($obj) {
3291 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3296 function compare_permissions($obj1,$obj2) {
3297 // first part is easy. Check that these are exactly the same.
3298 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3299 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3300 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3301 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3304 // This is harder. Parse all the permissions and compare the resulting set.
3306 $recipients1 = enumerate_permissions($obj1);
3307 $recipients2 = enumerate_permissions($obj2);
3310 if($recipients1 == $recipients2)
3315 // returns an array of contact-ids that are allowed to see this object
3317 function enumerate_permissions($obj) {
3318 require_once('include/group.php');
3319 $allow_people = expand_acl($obj['allow_cid']);
3320 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3321 $deny_people = expand_acl($obj['deny_cid']);
3322 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3323 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3324 $deny = array_unique(array_merge($deny_people,$deny_groups));
3325 $recipients = array_diff($recipients,$deny);
3329 function item_getfeedtags($item) {
3332 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3334 for($x = 0; $x < $cnt; $x ++) {
3336 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3340 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3342 for($x = 0; $x < $cnt; $x ++) {
3344 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3350 function item_getfeedattach($item) {
3352 $arr = explode(',',$item['attach']);
3354 foreach($arr as $r) {
3356 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3358 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3359 if(intval($matches[2]))
3360 $ret .= 'length="' . intval($matches[2]) . '" ';
3361 if($matches[4] !== ' ')
3362 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3363 $ret .= ' />' . "\r\n";
3372 function item_expire($uid,$days) {
3374 if((! $uid) || ($days < 1))
3377 // $expire_network_only = save your own wall posts
3378 // and just expire conversations started by others
3380 $expire_network_only = get_pconfig($uid,'expire','network_only');
3381 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3383 $r = q("SELECT * FROM `item`
3385 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3396 $expire_items = get_pconfig($uid, 'expire','items');
3397 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3399 $expire_notes = get_pconfig($uid, 'expire','notes');
3400 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3402 $expire_starred = get_pconfig($uid, 'expire','starred');
3403 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3405 $expire_photos = get_pconfig($uid, 'expire','photos');
3406 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3408 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3410 foreach($r as $item) {
3412 // don't expire filed items
3414 if(strpos($item['file'],'[') !== false)
3417 // Only expire posts, not photos and photo comments
3419 if($expire_photos==0 && strlen($item['resource-id']))
3421 if($expire_starred==0 && intval($item['starred']))
3423 if($expire_notes==0 && $item['type']=='note')
3425 if($expire_items==0 && $item['type']!='note')
3428 drop_item($item['id'],false);
3431 proc_run('php',"include/notifier.php","expire","$uid");
3436 function drop_items($items) {
3439 if(! local_user() && ! remote_user())
3443 foreach($items as $item) {
3444 $owner = drop_item($item,false);
3445 if($owner && ! $uid)
3450 // multiple threads may have been deleted, send an expire notification
3453 proc_run('php',"include/notifier.php","expire","$uid");
3457 function drop_item($id,$interactive = true) {
3461 // locate item to be deleted
3463 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3470 notice( t('Item not found.') . EOL);
3471 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3476 $owner = $item['uid'];
3478 // check if logged in user is either the author or owner of this item
3480 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3484 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3485 dbesc(datetime_convert()),
3486 dbesc(datetime_convert()),
3490 // clean up categories and tags so they don't end up as orphans
3493 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3495 foreach($matches as $mtch) {
3496 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3502 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3504 foreach($matches as $mtch) {
3505 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3509 // If item is a link to a photo resource, nuke all the associated photos
3510 // (visitors will not have photo resources)
3511 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3512 // generate a resource-id and therefore aren't intimately linked to the item.
3514 if(strlen($item['resource-id'])) {
3515 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3516 dbesc($item['resource-id']),
3517 intval($item['uid'])
3519 // ignore the result
3522 // If item is a link to an event, nuke the event record.
3524 if(intval($item['event-id'])) {
3525 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3526 intval($item['event-id']),
3527 intval($item['uid'])
3529 // ignore the result
3532 // clean up item_id and sign meta-data tables
3534 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3535 intval($item['id']),
3536 intval($item['uid'])
3539 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3540 intval($item['id']),
3541 intval($item['uid'])
3544 // If it's the parent of a comment thread, kill all the kids
3546 if($item['uri'] == $item['parent-uri']) {
3547 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3548 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3549 dbesc(datetime_convert()),
3550 dbesc(datetime_convert()),
3551 dbesc($item['parent-uri']),
3552 intval($item['uid'])
3554 // ignore the result
3557 // ensure that last-child is set in case the comment that had it just got wiped.
3558 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3559 dbesc(datetime_convert()),
3560 dbesc($item['parent-uri']),
3561 intval($item['uid'])
3563 // who is the last child now?
3564 $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",
3565 dbesc($item['parent-uri']),
3566 intval($item['uid'])
3569 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3574 // Add a relayable_retraction signature for Diaspora.
3575 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
3577 $drop_id = intval($item['id']);
3579 // send the notification upstream/downstream as the case may be
3584 proc_run('php',"include/notifier.php","drop","$drop_id");
3585 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3591 notice( t('Permission denied.') . EOL);
3592 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3599 function first_post_date($uid,$wall = false) {
3600 $r = q("select id, created from item
3601 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3603 order by created asc limit 1",
3605 intval($wall ? 1 : 0)
3608 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3609 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3614 function posted_dates($uid,$wall) {
3615 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3617 $dthen = first_post_date($uid,$wall);
3621 // If it's near the end of a long month, backup to the 28th so that in
3622 // consecutive loops we'll always get a whole month difference.
3624 if(intval(substr($dnow,8)) > 28)
3625 $dnow = substr($dnow,0,8) . '28';
3626 if(intval(substr($dthen,8)) > 28)
3627 $dnow = substr($dthen,0,8) . '28';
3630 // Starting with the current month, get the first and last days of every
3631 // month down to and including the month of the first post
3632 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
3633 $dstart = substr($dnow,0,8) . '01';
3634 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3635 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3636 $end_month = datetime_convert('','',$dend,'Y-m-d');
3637 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3638 $ret[] = array($str,$end_month,$start_month);
3639 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3645 function posted_date_widget($url,$uid,$wall) {
3648 // For former Facebook folks that left because of "timeline"
3650 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3653 $ret = posted_dates($uid,$wall);
3657 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3658 '$title' => t('Archives'),
3659 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3667 function store_diaspora_retract_sig($item, $user, $baseurl) {
3668 // Note that we can't add a target_author_signature
3669 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3670 // the comment, that means we're the home of the post, and Diaspora will only
3671 // check the parent_author_signature of retractions that it doesn't have to relay further
3673 // I don't think this function gets called for an "unlike," but I'll check anyway
3675 $enabled = intval(get_config('system','diaspora_enabled'));
3677 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
3681 logger('drop_item: storing diaspora retraction signature');
3683 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3685 if(local_user() == $item['uid']) {
3687 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
3688 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
3691 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3692 $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
3695 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3696 // only handles DFRN deletes
3697 $handle_baseurl_start = strpos($r['url'],'://') + 3;
3698 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3699 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3705 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3706 intval($item['id']),
3707 dbesc($signed_text),