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']);
820 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
821 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
822 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
823 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
824 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
825 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
826 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
827 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
828 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
829 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
830 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
831 $arr['commented'] = datetime_convert();
832 $arr['received'] = datetime_convert();
833 $arr['changed'] = datetime_convert();
834 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
835 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
836 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
837 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
838 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
840 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
841 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
842 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
843 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
844 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
845 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
846 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
847 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
848 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
849 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
850 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
851 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
852 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
853 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
854 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
855 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
856 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
857 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
858 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
860 if($arr['parent-uri'] === $arr['uri']) {
863 $allow_cid = $arr['allow_cid'];
864 $allow_gid = $arr['allow_gid'];
865 $deny_cid = $arr['deny_cid'];
866 $deny_gid = $arr['deny_gid'];
870 // find the parent and snarf the item id and ACL's
871 // and anything else we need to inherit
873 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
874 dbesc($arr['parent-uri']),
880 // is the new message multi-level threaded?
881 // even though we don't support it now, preserve the info
882 // and re-attach to the conversation parent.
884 if($r[0]['uri'] != $r[0]['parent-uri']) {
885 $arr['thr-parent'] = $arr['parent-uri'];
886 $arr['parent-uri'] = $r[0]['parent-uri'];
887 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
888 ORDER BY `id` ASC LIMIT 1",
889 dbesc($r[0]['parent-uri']),
890 dbesc($r[0]['parent-uri']),
897 $parent_id = $r[0]['id'];
898 $parent_deleted = $r[0]['deleted'];
899 $allow_cid = $r[0]['allow_cid'];
900 $allow_gid = $r[0]['allow_gid'];
901 $deny_cid = $r[0]['deny_cid'];
902 $deny_gid = $r[0]['deny_gid'];
903 $arr['wall'] = $r[0]['wall'];
905 // if the parent is private, force privacy for the entire conversation
906 // This differs from the above settings as it subtly allows comments from
907 // email correspondents to be private even if the overall thread is not.
910 $arr['private'] = $r[0]['private'];
912 // Edge case. We host a public forum that was originally posted to privately.
913 // The original author commented, but as this is a comment, the permissions
914 // weren't fixed up so it will still show the comment as private unless we fix it here.
916 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
921 // Allow one to see reply tweets from status.net even when
922 // we don't have or can't see the original post.
925 logger('item_store: $force_parent=true, reply converted to top-level post.');
927 $arr['thr-parent'] = $arr['parent-uri'];
928 $arr['parent-uri'] = $arr['uri'];
932 logger('item_store: item parent was not found - ignoring item');
940 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
944 if($r && count($r)) {
945 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
949 call_hooks('post_remote',$arr);
951 if(x($arr,'cancel')) {
952 logger('item_store: post cancelled by plugin.');
958 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
960 $r = dbq("INSERT INTO `item` (`"
961 . implode("`, `", array_keys($arr))
963 . implode("', '", array_values($arr))
966 // find the item we just created
968 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
969 $arr['uri'], // already dbesc'd
974 $current_post = $r[0]['id'];
975 logger('item_store: created item ' . $current_post);
978 logger('item_store: could not locate created item');
982 logger('item_store: duplicated post occurred. Removing duplicates.');
983 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
986 intval($current_post)
990 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
991 $parent_id = $current_post;
993 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
996 $private = $arr['private'];
998 // Set parent id - and also make sure to inherit the parent's ACL's.
1000 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1001 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1008 intval($parent_deleted),
1009 intval($current_post)
1012 $arr['id'] = $current_post;
1013 $arr['parent'] = $parent_id;
1014 $arr['allow_cid'] = $allow_cid;
1015 $arr['allow_gid'] = $allow_gid;
1016 $arr['deny_cid'] = $deny_cid;
1017 $arr['deny_gid'] = $deny_gid;
1018 $arr['private'] = $private;
1019 $arr['deleted'] = $parent_deleted;
1020 call_hooks('post_remote_end',$arr);
1022 // update the commented timestamp on the parent
1024 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1025 dbesc(datetime_convert()),
1026 dbesc(datetime_convert()),
1031 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1032 intval($current_post),
1033 dbesc($dsprsig->signed_text),
1034 dbesc($dsprsig->signature),
1035 dbesc($dsprsig->signer)
1041 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1044 if($arr['last-child']) {
1045 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1047 intval($arr['uid']),
1048 intval($current_post)
1052 tag_deliver($arr['uid'],$current_post);
1054 return $current_post;
1057 function get_item_contact($item,$contacts) {
1058 if(! count($contacts) || (! is_array($item)))
1060 foreach($contacts as $contact) {
1061 if($contact['id'] == $item['contact-id']) {
1063 break; // NOTREACHED
1070 function tag_deliver($uid,$item_id) {
1072 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1078 $u = q("select * from user where uid = %d limit 1",
1084 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1085 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1088 $i = q("select * from item where id = %d and uid = %d limit 1",
1097 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1099 // Diaspora uses their own hardwired link URL in @-tags
1100 // instead of the one we supply with webfinger
1102 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1104 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1106 foreach($matches as $mtch) {
1107 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1109 logger('tag_deliver: mention found: ' . $mtch[2]);
1117 // send a notification
1119 require_once('include/enotify.php');
1121 'type' => NOTIFY_TAGSELF,
1122 'notify_flags' => $u[0]['notify-flags'],
1123 'language' => $u[0]['language'],
1124 'to_name' => $u[0]['username'],
1125 'to_email' => $u[0]['email'],
1126 'uid' => $u[0]['uid'],
1128 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1129 'source_name' => $item['author-name'],
1130 'source_link' => $item['author-link'],
1131 'source_photo' => $item['author-avatar'],
1132 'verb' => ACTIVITY_TAG,
1136 if((! $community_page) && (! $prvgroup))
1140 // tgroup delivery - setup a second delivery chain
1141 // prevent delivery looping - only proceed
1142 // if the message originated elsewhere and is a top-level post
1144 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1147 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1150 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1151 intval($u[0]['uid'])
1156 // also reset all the privacy bits to the forum default permissions
1158 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1160 $forum_mode = (($prvgroup) ? 2 : 1);
1162 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1163 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1164 intval($forum_mode),
1165 dbesc($c[0]['name']),
1166 dbesc($c[0]['url']),
1167 dbesc($c[0]['thumb']),
1169 dbesc($u[0]['allow_cid']),
1170 dbesc($u[0]['allow_gid']),
1171 dbesc($u[0]['deny_cid']),
1172 dbesc($u[0]['deny_gid']),
1176 proc_run('php','include/notifier.php','tgroup',$item_id);
1185 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1189 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1191 if($contact['duplex'] && $contact['dfrn-id'])
1192 $idtosend = '0:' . $orig_id;
1193 if($contact['duplex'] && $contact['issued-id'])
1194 $idtosend = '1:' . $orig_id;
1196 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1198 $rino_enable = get_config('system','rino_encrypt');
1203 $ssl_val = intval(get_config('system','ssl_policy'));
1207 case SSL_POLICY_FULL:
1208 $ssl_policy = 'full';
1210 case SSL_POLICY_SELFSIGN:
1211 $ssl_policy = 'self';
1213 case SSL_POLICY_NONE:
1215 $ssl_policy = 'none';
1219 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1221 logger('dfrn_deliver: ' . $url);
1223 $xml = fetch_url($url);
1225 $curl_stat = $a->get_curl_code();
1227 return(-1); // timed out
1229 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1234 if(strpos($xml,'<?xml') === false) {
1235 logger('dfrn_deliver: no valid XML returned');
1236 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1240 $res = parse_xml_string($xml);
1242 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1243 return (($res->status) ? $res->status : 3);
1245 $postvars = array();
1246 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1247 $challenge = hex2bin((string) $res->challenge);
1248 $perm = (($res->perm) ? $res->perm : null);
1249 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1250 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1251 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1253 if($owner['page-flags'] == PAGE_PRVGROUP)
1256 $final_dfrn_id = '';
1259 if((($perm == 'rw') && (! intval($contact['writable'])))
1260 || (($perm == 'r') && (intval($contact['writable'])))) {
1261 q("update contact set writable = %d where id = %d limit 1",
1262 intval(($perm == 'rw') ? 1 : 0),
1263 intval($contact['id'])
1265 $contact['writable'] = (string) 1 - intval($contact['writable']);
1269 if(($contact['duplex'] && strlen($contact['pubkey']))
1270 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1271 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1272 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1273 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1276 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1277 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1280 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1282 if(strpos($final_dfrn_id,':') == 1)
1283 $final_dfrn_id = substr($final_dfrn_id,2);
1285 if($final_dfrn_id != $orig_id) {
1286 logger('dfrn_deliver: wrong dfrn_id.');
1287 // did not decode properly - cannot trust this site
1291 $postvars['dfrn_id'] = $idtosend;
1292 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1294 $postvars['dissolve'] = '1';
1297 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1298 $postvars['data'] = $atom;
1299 $postvars['perm'] = 'rw';
1302 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1303 $postvars['perm'] = 'r';
1306 $postvars['ssl_policy'] = $ssl_policy;
1309 $postvars['page'] = $page;
1311 if($rino && $rino_allowed && (! $dissolve)) {
1312 $key = substr(random_string(),0,16);
1313 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1314 $postvars['data'] = $data;
1315 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1318 if($dfrn_version >= 2.1) {
1319 if(($contact['duplex'] && strlen($contact['pubkey']))
1320 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1321 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1323 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1326 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1330 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1331 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1334 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1338 logger('md5 rawkey ' . md5($postvars['key']));
1340 $postvars['key'] = bin2hex($postvars['key']);
1343 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1345 $xml = post_url($contact['notify'],$postvars);
1347 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1349 $curl_stat = $a->get_curl_code();
1350 if((! $curl_stat) || (! strlen($xml)))
1351 return(-1); // timed out
1353 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1356 if(strpos($xml,'<?xml') === false) {
1357 logger('dfrn_deliver: phase 2: no valid XML returned');
1358 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1362 if($contact['term-date'] != '0000-00-00 00:00:00') {
1363 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1364 require_once('include/Contact.php');
1365 unmark_for_death($contact);
1368 $res = parse_xml_string($xml);
1370 return $res->status;
1376 * consume_feed - process atom feed and update anything/everything we might need to update
1378 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1380 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1381 * It is this person's stuff that is going to be updated.
1382 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1383 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1384 * have a contact record.
1385 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1386 * might not) try and subscribe to it.
1387 * $datedir sorts in reverse order
1388 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1389 * imported prior to its children being seen in the stream unless we are certain
1390 * of how the feed is arranged/ordered.
1391 * With $pass = 1, we only pull parent items out of the stream.
1392 * With $pass = 2, we only pull children (comments/likes).
1394 * So running this twice, first with pass 1 and then with pass 2 will do the right
1395 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1396 * model where comments can have sub-threads. That would require some massive sorting
1397 * to get all the feed items into a mostly linear ordering, and might still require
1401 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1403 require_once('library/simplepie/simplepie.inc');
1405 if(! strlen($xml)) {
1406 logger('consume_feed: empty input');
1410 $feed = new SimplePie();
1411 $feed->set_raw_data($xml);
1413 $feed->enable_order_by_date(true);
1415 $feed->enable_order_by_date(false);
1419 logger('consume_feed: Error parsing XML: ' . $feed->error());
1421 $permalink = $feed->get_permalink();
1423 // Check at the feed level for updated contact name and/or photo
1427 $photo_timestamp = '';
1431 $hubs = $feed->get_links('hub');
1432 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1435 $hub = implode(',', $hubs);
1437 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1439 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1441 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1442 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1443 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1444 $new_name = $elems['name'][0]['data'];
1446 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1447 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1448 $photo_url = $elems['link'][0]['attribs']['']['href'];
1451 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1452 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1456 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1457 logger('consume_feed: Updating photo for ' . $contact['name']);
1458 require_once("Photo.php");
1459 $photo_failure = false;
1460 $have_photo = false;
1462 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1463 intval($contact['id']),
1464 intval($contact['uid'])
1467 $resource_id = $r[0]['resource-id'];
1471 $resource_id = photo_new_resource();
1474 $img_str = fetch_url($photo_url,true);
1475 // guess mimetype from headers or filename
1476 $type = guess_image_type($photo_url,true);
1479 $img = new Photo($img_str, $type);
1480 if($img->is_valid()) {
1482 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1483 dbesc($resource_id),
1484 intval($contact['id']),
1485 intval($contact['uid'])
1489 $img->scaleImageSquare(175);
1491 $hash = $resource_id;
1492 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1494 $img->scaleImage(80);
1495 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1497 $img->scaleImage(48);
1498 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1502 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1503 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1504 dbesc(datetime_convert()),
1505 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1506 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1507 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1508 intval($contact['uid']),
1509 intval($contact['id'])
1514 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1515 $r = q("select * from contact where uid = %d and id = %d limit 1",
1516 intval($contact['uid']),
1517 intval($contact['id'])
1520 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1521 dbesc(notags(trim($new_name))),
1522 dbesc(datetime_convert()),
1523 intval($contact['uid']),
1524 intval($contact['id'])
1527 // do our best to update the name on content items
1530 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1531 dbesc(notags(trim($new_name))),
1532 dbesc($r[0]['name']),
1533 dbesc($r[0]['url']),
1534 intval($contact['uid'])
1539 if(strlen($birthday)) {
1540 if(substr($birthday,0,4) != $contact['bdyear']) {
1541 logger('consume_feed: updating birthday: ' . $birthday);
1545 * Add new birthday event for this person
1547 * $bdtext is just a readable placeholder in case the event is shared
1548 * with others. We will replace it during presentation to our $importer
1549 * to contain a sparkle link and perhaps a photo.
1553 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1554 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1557 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1558 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1559 intval($contact['uid']),
1560 intval($contact['id']),
1561 dbesc(datetime_convert()),
1562 dbesc(datetime_convert()),
1563 dbesc(datetime_convert('UTC','UTC', $birthday)),
1564 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1573 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1574 dbesc(substr($birthday,0,4)),
1575 intval($contact['uid']),
1576 intval($contact['id'])
1579 // This function is called twice without reloading the contact
1580 // Make sure we only create one event. This is why &$contact
1581 // is a reference var in this function
1583 $contact['bdyear'] = substr($birthday,0,4);
1588 $community_page = 0;
1589 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1591 $community_page = intval($rawtags[0]['data']);
1593 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1594 q("update contact set forum = %d where id = %d limit 1",
1595 intval($community_page),
1596 intval($contact['id'])
1598 $contact['forum'] = (string) $community_page;
1602 // process any deleted entries
1604 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1605 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1606 foreach($del_entries as $dentry) {
1608 if(isset($dentry['attribs']['']['ref'])) {
1609 $uri = $dentry['attribs']['']['ref'];
1611 if(isset($dentry['attribs']['']['when'])) {
1612 $when = $dentry['attribs']['']['when'];
1613 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1616 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1618 if($deleted && is_array($contact)) {
1619 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1620 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1622 intval($importer['uid']),
1623 intval($contact['id'])
1628 if(! $item['deleted'])
1629 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1631 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1632 $xo = parse_xml_string($item['object'],false);
1633 $xt = parse_xml_string($item['target'],false);
1634 if($xt->type === ACTIVITY_OBJ_NOTE) {
1635 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1637 intval($importer['importer_uid'])
1641 // For tags, the owner cannot remove the tag on the author's copy of the post.
1643 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1644 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1645 $author_copy = (($item['origin']) ? true : false);
1647 if($owner_remove && $author_copy)
1649 if($author_remove || $owner_remove) {
1650 $tags = explode(',',$i[0]['tag']);
1653 foreach($tags as $tag)
1654 if(trim($tag) !== trim($xo->body))
1655 $newtags[] = trim($tag);
1657 q("update item set tag = '%s' where id = %d limit 1",
1658 dbesc(implode(',',$newtags)),
1666 if($item['uri'] == $item['parent-uri']) {
1667 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1668 `body` = '', `title` = ''
1669 WHERE `parent-uri` = '%s' AND `uid` = %d",
1671 dbesc(datetime_convert()),
1672 dbesc($item['uri']),
1673 intval($importer['uid'])
1677 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1678 `body` = '', `title` = ''
1679 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1681 dbesc(datetime_convert()),
1683 intval($importer['uid'])
1685 if($item['last-child']) {
1686 // ensure that last-child is set in case the comment that had it just got wiped.
1687 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1688 dbesc(datetime_convert()),
1689 dbesc($item['parent-uri']),
1690 intval($item['uid'])
1692 // who is the last child now?
1693 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1694 ORDER BY `created` DESC LIMIT 1",
1695 dbesc($item['parent-uri']),
1696 intval($importer['uid'])
1699 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1710 // Now process the feed
1712 if($feed->get_item_quantity()) {
1714 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1716 // in inverse date order
1718 $items = array_reverse($feed->get_items());
1720 $items = $feed->get_items();
1723 foreach($items as $item) {
1726 $item_id = $item->get_id();
1727 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1728 if(isset($rawthread[0]['attribs']['']['ref'])) {
1730 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1733 if(($is_reply) && is_array($contact)) {
1738 // Have we seen it? If not, import it.
1740 $item_id = $item->get_id();
1741 $datarray = get_atom_elements($feed,$item);
1744 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1745 $datarray['author-name'] = $contact['name'];
1746 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1747 $datarray['author-link'] = $contact['url'];
1748 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1749 $datarray['author-avatar'] = $contact['thumb'];
1751 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1752 logger('consume_feed: no author information! ' . print_r($datarray,true));
1756 $force_parent = false;
1757 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1758 if($contact['network'] === NETWORK_OSTATUS)
1759 $force_parent = true;
1760 if(strlen($datarray['title']))
1761 unset($datarray['title']);
1762 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1763 dbesc(datetime_convert()),
1765 intval($importer['uid'])
1767 $datarray['last-child'] = 1;
1771 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1773 intval($importer['uid'])
1776 // Update content if 'updated' changes
1779 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1781 // do not accept (ignore) an earlier edit than one we currently have.
1782 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1785 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1786 dbesc($datarray['title']),
1787 dbesc($datarray['body']),
1788 dbesc($datarray['tag']),
1789 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1791 intval($importer['uid'])
1795 // update last-child if it changes
1797 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1798 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1799 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1800 dbesc(datetime_convert()),
1802 intval($importer['uid'])
1804 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1805 intval($allow[0]['data']),
1806 dbesc(datetime_convert()),
1808 intval($importer['uid'])
1815 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1816 // one way feed - no remote comment ability
1817 $datarray['last-child'] = 0;
1819 $datarray['parent-uri'] = $parent_uri;
1820 $datarray['uid'] = $importer['uid'];
1821 $datarray['contact-id'] = $contact['id'];
1822 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1823 $datarray['type'] = 'activity';
1824 $datarray['gravity'] = GRAVITY_LIKE;
1825 // only one like or dislike per person
1826 $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",
1827 intval($datarray['uid']),
1828 intval($datarray['contact-id']),
1829 dbesc($datarray['verb']),
1837 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1838 $xo = parse_xml_string($datarray['object'],false);
1839 $xt = parse_xml_string($datarray['target'],false);
1841 if($xt->type == ACTIVITY_OBJ_NOTE) {
1842 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1844 intval($importer['importer_uid'])
1849 // extract tag, if not duplicate, add to parent item
1850 if($xo->id && $xo->content) {
1851 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1852 if(! (stristr($r[0]['tag'],$newtag))) {
1853 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1854 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1862 $r = item_store($datarray,$force_parent);
1868 // Head post of a conversation. Have we seen it? If not, import it.
1870 $item_id = $item->get_id();
1872 $datarray = get_atom_elements($feed,$item);
1874 if(is_array($contact)) {
1875 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1876 $datarray['author-name'] = $contact['name'];
1877 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1878 $datarray['author-link'] = $contact['url'];
1879 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1880 $datarray['author-avatar'] = $contact['thumb'];
1883 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1884 logger('consume_feed: no author information! ' . print_r($datarray,true));
1888 // special handling for events
1890 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1891 $ev = bbtoevent($datarray['body']);
1892 if(x($ev,'desc') && x($ev,'start')) {
1893 $ev['uid'] = $importer['uid'];
1894 $ev['uri'] = $item_id;
1895 $ev['edited'] = $datarray['edited'];
1896 $ev['private'] = $datarray['private'];
1898 if(is_array($contact))
1899 $ev['cid'] = $contact['id'];
1900 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1902 intval($importer['uid'])
1905 $ev['id'] = $r[0]['id'];
1906 $xyz = event_store($ev);
1911 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1912 if(strlen($datarray['title']))
1913 unset($datarray['title']);
1914 $datarray['last-child'] = 1;
1918 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1920 intval($importer['uid'])
1923 // Update content if 'updated' changes
1926 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1928 // do not accept (ignore) an earlier edit than one we currently have.
1929 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1932 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1933 dbesc($datarray['title']),
1934 dbesc($datarray['body']),
1935 dbesc($datarray['tag']),
1936 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1938 intval($importer['uid'])
1942 // update last-child if it changes
1944 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1945 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1946 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1947 intval($allow[0]['data']),
1948 dbesc(datetime_convert()),
1950 intval($importer['uid'])
1956 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1957 logger('consume-feed: New follower');
1958 new_follower($importer,$contact,$datarray,$item);
1961 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1962 lose_follower($importer,$contact,$datarray,$item);
1966 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1967 logger('consume-feed: New friend request');
1968 new_follower($importer,$contact,$datarray,$item,true);
1971 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1972 lose_sharer($importer,$contact,$datarray,$item);
1977 if(! is_array($contact))
1981 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1982 // one way feed - no remote comment ability
1983 $datarray['last-child'] = 0;
1985 if($contact['network'] === NETWORK_FEED)
1986 $datarray['private'] = 2;
1988 // This is my contact on another system, but it's really me.
1989 // Turn this into a wall post.
1991 if($contact['remote_self']) {
1992 $datarray['wall'] = 1;
1993 if($contact['network'] === NETWORK_FEED) {
1994 $datarray['private'] = 0;
1998 $datarray['parent-uri'] = $item_id;
1999 $datarray['uid'] = $importer['uid'];
2000 $datarray['contact-id'] = $contact['id'];
2002 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2003 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2004 // but otherwise there's a possible data mixup on the sender's system.
2005 // the tgroup delivery code called from item_store will correct it if it's a forum,
2006 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2007 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2008 $datarray['owner-name'] = $contact['name'];
2009 $datarray['owner-link'] = $contact['url'];
2010 $datarray['owner-avatar'] = $contact['thumb'];
2013 $r = item_store($datarray);
2021 function local_delivery($importer,$data) {
2025 if($importer['readonly']) {
2026 // We aren't receiving stuff from this person. But we will quietly ignore them
2027 // rather than a blatant "go away" message.
2028 logger('local_delivery: ignoring');
2033 // Consume notification feed. This may differ from consuming a public feed in several ways
2034 // - might contain email or friend suggestions
2035 // - might contain remote followup to our message
2036 // - in which case we need to accept it and then notify other conversants
2037 // - we may need to send various email notifications
2039 $feed = new SimplePie();
2040 $feed->set_raw_data($data);
2041 $feed->enable_order_by_date(false);
2045 // Currently unsupported - needs a lot of work
2046 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2047 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2048 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2050 $newloc['uid'] = $importer['importer_uid'];
2051 $newloc['cid'] = $importer['id'];
2052 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2053 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2054 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2055 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2056 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2057 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2058 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2059 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
2060 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2061 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
2064 // merge with current record, current contents have priority
2065 // update record, set url-updated
2066 // update profile photos
2072 // handle friend suggestion notification
2074 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2075 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2076 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2078 $fsugg['uid'] = $importer['importer_uid'];
2079 $fsugg['cid'] = $importer['id'];
2080 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2081 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2082 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2083 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2084 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2086 // Does our member already have a friend matching this description?
2088 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2089 dbesc($fsugg['name']),
2090 dbesc(normalise_link($fsugg['url'])),
2091 intval($fsugg['uid'])
2096 // Do we already have an fcontact record for this person?
2099 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2100 dbesc($fsugg['url']),
2101 dbesc($fsugg['name']),
2102 dbesc($fsugg['request'])
2107 // OK, we do. Do we already have an introduction for this person ?
2108 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2109 intval($fsugg['uid']),
2116 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2117 dbesc($fsugg['name']),
2118 dbesc($fsugg['url']),
2119 dbesc($fsugg['photo']),
2120 dbesc($fsugg['request'])
2122 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2123 dbesc($fsugg['url']),
2124 dbesc($fsugg['name']),
2125 dbesc($fsugg['request'])
2130 // database record did not get created. Quietly give up.
2135 $hash = random_string();
2137 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2138 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2139 intval($fsugg['uid']),
2141 intval($fsugg['cid']),
2142 dbesc($fsugg['body']),
2144 dbesc(datetime_convert()),
2149 'type' => NOTIFY_SUGGEST,
2150 'notify_flags' => $importer['notify-flags'],
2151 'language' => $importer['language'],
2152 'to_name' => $importer['username'],
2153 'to_email' => $importer['email'],
2154 'uid' => $importer['importer_uid'],
2156 'link' => $a->get_baseurl() . '/notifications/intros',
2157 'source_name' => $importer['name'],
2158 'source_link' => $importer['url'],
2159 'source_photo' => $importer['photo'],
2160 'verb' => ACTIVITY_REQ_FRIEND,
2169 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2170 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2172 logger('local_delivery: private message received');
2175 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2178 $msg['uid'] = $importer['importer_uid'];
2179 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2180 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2181 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2182 $msg['contact-id'] = $importer['id'];
2183 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2184 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2186 $msg['replied'] = 0;
2187 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2188 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2189 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2193 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2194 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2196 // send notifications.
2198 require_once('include/enotify.php');
2200 $notif_params = array(
2201 'type' => NOTIFY_MAIL,
2202 'notify_flags' => $importer['notify-flags'],
2203 'language' => $importer['language'],
2204 'to_name' => $importer['username'],
2205 'to_email' => $importer['email'],
2206 'uid' => $importer['importer_uid'],
2208 'source_name' => $msg['from-name'],
2209 'source_link' => $importer['url'],
2210 'source_photo' => $importer['thumb'],
2211 'verb' => ACTIVITY_POST,
2215 notification($notif_params);
2221 $community_page = 0;
2222 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2224 $community_page = intval($rawtags[0]['data']);
2226 if(intval($importer['forum']) != $community_page) {
2227 q("update contact set forum = %d where id = %d limit 1",
2228 intval($community_page),
2229 intval($importer['id'])
2231 $importer['forum'] = (string) $community_page;
2234 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2236 // process any deleted entries
2238 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2239 if(is_array($del_entries) && count($del_entries)) {
2240 foreach($del_entries as $dentry) {
2242 if(isset($dentry['attribs']['']['ref'])) {
2243 $uri = $dentry['attribs']['']['ref'];
2245 if(isset($dentry['attribs']['']['when'])) {
2246 $when = $dentry['attribs']['']['when'];
2247 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2250 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2254 // check for relayed deletes to our conversation
2257 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2259 intval($importer['importer_uid'])
2262 $parent_uri = $r[0]['parent-uri'];
2263 if($r[0]['id'] != $r[0]['parent'])
2270 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2273 logger('local_delivery: possible community delete');
2276 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2278 // was the top-level post for this reply written by somebody on this site?
2279 // Specifically, the recipient?
2281 $is_a_remote_delete = false;
2283 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2284 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2285 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2286 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2287 AND `item`.`uid` = %d
2293 intval($importer['importer_uid'])
2296 $is_a_remote_delete = true;
2298 // Does this have the characteristics of a community or private group comment?
2299 // If it's a reply to a wall post on a community/prvgroup page it's a
2300 // valid community comment. Also forum_mode makes it valid for sure.
2301 // If neither, it's not.
2303 if($is_a_remote_delete && $community) {
2304 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2305 $is_a_remote_delete = false;
2306 logger('local_delivery: not a community delete');
2310 if($is_a_remote_delete) {
2311 logger('local_delivery: received remote delete');
2315 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2316 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2318 intval($importer['importer_uid']),
2319 intval($importer['id'])
2325 if($item['deleted'])
2328 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2330 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2331 $xo = parse_xml_string($item['object'],false);
2332 $xt = parse_xml_string($item['target'],false);
2334 if($xt->type === ACTIVITY_OBJ_NOTE) {
2335 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2337 intval($importer['importer_uid'])
2341 // For tags, the owner cannot remove the tag on the author's copy of the post.
2343 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2344 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2345 $author_copy = (($item['origin']) ? true : false);
2347 if($owner_remove && $author_copy)
2349 if($author_remove || $owner_remove) {
2350 $tags = explode(',',$i[0]['tag']);
2353 foreach($tags as $tag)
2354 if(trim($tag) !== trim($xo->body))
2355 $newtags[] = trim($tag);
2357 q("update item set tag = '%s' where id = %d limit 1",
2358 dbesc(implode(',',$newtags)),
2366 if($item['uri'] == $item['parent-uri']) {
2367 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2368 `body` = '', `title` = ''
2369 WHERE `parent-uri` = '%s' AND `uid` = %d",
2371 dbesc(datetime_convert()),
2372 dbesc($item['uri']),
2373 intval($importer['importer_uid'])
2377 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2378 `body` = '', `title` = ''
2379 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2381 dbesc(datetime_convert()),
2383 intval($importer['importer_uid'])
2385 if($item['last-child']) {
2386 // ensure that last-child is set in case the comment that had it just got wiped.
2387 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2388 dbesc(datetime_convert()),
2389 dbesc($item['parent-uri']),
2390 intval($item['uid'])
2392 // who is the last child now?
2393 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2394 ORDER BY `created` DESC LIMIT 1",
2395 dbesc($item['parent-uri']),
2396 intval($importer['importer_uid'])
2399 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2404 // if this is a relayed delete, propagate it to other recipients
2406 if($is_a_remote_delete)
2407 proc_run('php',"include/notifier.php","drop",$item['id']);
2415 foreach($feed->get_items() as $item) {
2418 $item_id = $item->get_id();
2419 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2420 if(isset($rawthread[0]['attribs']['']['ref'])) {
2422 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2428 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2431 logger('local_delivery: possible community reply');
2434 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2436 // was the top-level post for this reply written by somebody on this site?
2437 // Specifically, the recipient?
2439 $is_a_remote_comment = false;
2441 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2442 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2443 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2444 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2445 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2446 AND `item`.`uid` = %d
2452 intval($importer['importer_uid'])
2455 $is_a_remote_comment = true;
2457 // Does this have the characteristics of a community or private group comment?
2458 // If it's a reply to a wall post on a community/prvgroup page it's a
2459 // valid community comment. Also forum_mode makes it valid for sure.
2460 // If neither, it's not.
2462 if($is_a_remote_comment && $community) {
2463 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2464 $is_a_remote_comment = false;
2465 logger('local_delivery: not a community reply');
2469 if($is_a_remote_comment) {
2470 logger('local_delivery: received remote comment');
2472 // remote reply to our post. Import and then notify everybody else.
2474 $datarray = get_atom_elements($feed,$item);
2476 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2478 intval($importer['importer_uid'])
2481 // Update content if 'updated' changes
2485 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2487 // do not accept (ignore) an earlier edit than one we currently have.
2488 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2491 logger('received updated comment' , LOGGER_DEBUG);
2492 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2493 dbesc($datarray['title']),
2494 dbesc($datarray['body']),
2495 dbesc($datarray['tag']),
2496 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2498 intval($importer['importer_uid'])
2501 proc_run('php',"include/notifier.php","comment-import",$iid);
2509 // TODO: make this next part work against both delivery threads of a community post
2511 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2512 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2513 // they won't know what to do so don't report an error. Just quietly die.
2517 // our user with $importer['importer_uid'] is the owner
2519 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2520 intval($importer['importer_uid'])
2524 $datarray['type'] = 'remote-comment';
2525 $datarray['wall'] = 1;
2526 $datarray['parent-uri'] = $parent_uri;
2527 $datarray['uid'] = $importer['importer_uid'];
2528 $datarray['owner-name'] = $own[0]['name'];
2529 $datarray['owner-link'] = $own[0]['url'];
2530 $datarray['owner-avatar'] = $own[0]['thumb'];
2531 $datarray['contact-id'] = $importer['id'];
2533 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2535 $datarray['type'] = 'activity';
2536 $datarray['gravity'] = GRAVITY_LIKE;
2537 $datarray['last-child'] = 0;
2538 // only one like or dislike per person
2539 $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",
2540 intval($datarray['uid']),
2541 intval($datarray['contact-id']),
2542 dbesc($datarray['verb']),
2543 dbesc($datarray['parent-uri']),
2544 dbesc($datarray['parent-uri'])
2551 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2553 $xo = parse_xml_string($datarray['object'],false);
2554 $xt = parse_xml_string($datarray['target'],false);
2556 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2558 // fetch the parent item
2560 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2562 intval($importer['importer_uid'])
2567 // extract tag, if not duplicate, and this user allows tags, add to parent item
2569 if($xo->id && $xo->content) {
2570 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2571 if(! (stristr($tagp[0]['tag'],$newtag))) {
2572 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2573 intval($importer['importer_uid'])
2575 if(count($i) && ! intval($i[0]['blocktags'])) {
2576 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2577 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2578 intval($tagp[0]['id']),
2579 dbesc(datetime_convert())
2588 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2589 // if(! stristr($datarray['tag'],$newtag)) {
2590 // if(strlen($datarray['tag']))
2591 // $datarray['tag'] .= ',';
2592 // $datarray['tag'] .= $newtag;
2597 $posted_id = item_store($datarray);
2601 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2603 intval($importer['importer_uid'])
2606 $parent = $r[0]['parent'];
2609 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2610 dbesc(datetime_convert()),
2611 intval($importer['importer_uid']),
2612 intval($r[0]['parent'])
2615 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2616 dbesc(datetime_convert()),
2617 intval($importer['importer_uid']),
2622 if($posted_id && $parent) {
2624 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2626 if((! $is_like) && (! $importer['self'])) {
2628 require_once('include/enotify.php');
2631 'type' => NOTIFY_COMMENT,
2632 'notify_flags' => $importer['notify-flags'],
2633 'language' => $importer['language'],
2634 'to_name' => $importer['username'],
2635 'to_email' => $importer['email'],
2636 'uid' => $importer['importer_uid'],
2637 'item' => $datarray,
2638 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2639 'source_name' => stripslashes($datarray['author-name']),
2640 'source_link' => $datarray['author-link'],
2641 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2642 ? $importer['thumb'] : $datarray['author-avatar']),
2643 'verb' => ACTIVITY_POST,
2645 'parent' => $parent,
2658 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2660 $item_id = $item->get_id();
2661 $datarray = get_atom_elements($feed,$item);
2663 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2665 intval($importer['importer_uid'])
2668 // Update content if 'updated' changes
2671 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2673 // do not accept (ignore) an earlier edit than one we currently have.
2674 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2677 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2678 dbesc($datarray['title']),
2679 dbesc($datarray['body']),
2680 dbesc($datarray['tag']),
2681 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2683 intval($importer['importer_uid'])
2687 // update last-child if it changes
2689 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2690 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2691 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2692 dbesc(datetime_convert()),
2694 intval($importer['importer_uid'])
2696 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2697 intval($allow[0]['data']),
2698 dbesc(datetime_convert()),
2700 intval($importer['importer_uid'])
2706 $datarray['parent-uri'] = $parent_uri;
2707 $datarray['uid'] = $importer['importer_uid'];
2708 $datarray['contact-id'] = $importer['id'];
2709 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2710 $datarray['type'] = 'activity';
2711 $datarray['gravity'] = GRAVITY_LIKE;
2712 // only one like or dislike per person
2713 $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",
2714 intval($datarray['uid']),
2715 intval($datarray['contact-id']),
2716 dbesc($datarray['verb']),
2725 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2727 $xo = parse_xml_string($datarray['object'],false);
2728 $xt = parse_xml_string($datarray['target'],false);
2730 if($xt->type == ACTIVITY_OBJ_NOTE) {
2731 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2733 intval($importer['importer_uid'])
2738 // extract tag, if not duplicate, add to parent item
2740 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2741 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2742 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2750 $posted_id = item_store($datarray);
2752 // find out if our user is involved in this conversation and wants to be notified.
2754 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2756 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2758 intval($importer['importer_uid'])
2761 if(count($myconv)) {
2762 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2764 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2765 if(! link_compare($datarray['author-link'],$importer_url)) {
2768 foreach($myconv as $conv) {
2770 // now if we find a match, it means we're in this conversation
2772 if(! link_compare($conv['author-link'],$importer_url))
2775 require_once('include/enotify.php');
2777 $conv_parent = $conv['parent'];
2780 'type' => NOTIFY_COMMENT,
2781 'notify_flags' => $importer['notify-flags'],
2782 'language' => $importer['language'],
2783 'to_name' => $importer['username'],
2784 'to_email' => $importer['email'],
2785 'uid' => $importer['importer_uid'],
2786 'item' => $datarray,
2787 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2788 'source_name' => stripslashes($datarray['author-name']),
2789 'source_link' => $datarray['author-link'],
2790 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2791 ? $importer['thumb'] : $datarray['author-avatar']),
2792 'verb' => ACTIVITY_POST,
2794 'parent' => $conv_parent,
2798 // only send one notification
2810 // Head post of a conversation. Have we seen it? If not, import it.
2813 $item_id = $item->get_id();
2814 $datarray = get_atom_elements($feed,$item);
2816 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2817 $ev = bbtoevent($datarray['body']);
2818 if(x($ev,'desc') && x($ev,'start')) {
2819 $ev['cid'] = $importer['id'];
2820 $ev['uid'] = $importer['uid'];
2821 $ev['uri'] = $item_id;
2822 $ev['edited'] = $datarray['edited'];
2823 $ev['private'] = $datarray['private'];
2825 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2827 intval($importer['uid'])
2830 $ev['id'] = $r[0]['id'];
2831 $xyz = event_store($ev);
2836 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2838 intval($importer['importer_uid'])
2841 // Update content if 'updated' changes
2844 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2846 // do not accept (ignore) an earlier edit than one we currently have.
2847 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2850 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2851 dbesc($datarray['title']),
2852 dbesc($datarray['body']),
2853 dbesc($datarray['tag']),
2854 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2856 intval($importer['importer_uid'])
2860 // update last-child if it changes
2862 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2863 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2864 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2865 intval($allow[0]['data']),
2866 dbesc(datetime_convert()),
2868 intval($importer['importer_uid'])
2874 // This is my contact on another system, but it's really me.
2875 // Turn this into a wall post.
2877 if($importer['remote_self'])
2878 $datarray['wall'] = 1;
2880 $datarray['parent-uri'] = $item_id;
2881 $datarray['uid'] = $importer['importer_uid'];
2882 $datarray['contact-id'] = $importer['id'];
2884 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2885 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2886 // but otherwise there's a possible data mixup on the sender's system.
2887 // the tgroup delivery code called from item_store will correct it if it's a forum,
2888 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2889 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2890 $datarray['owner-name'] = $importer['senderName'];
2891 $datarray['owner-link'] = $importer['url'];
2892 $datarray['owner-avatar'] = $importer['thumb'];
2895 $r = item_store($datarray);
2906 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2907 $url = notags(trim($datarray['author-link']));
2908 $name = notags(trim($datarray['author-name']));
2909 $photo = notags(trim($datarray['author-avatar']));
2911 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2912 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2913 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2915 if(is_array($contact)) {
2916 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2917 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2918 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2919 intval(CONTACT_IS_FRIEND),
2920 intval($contact['id']),
2921 intval($importer['uid'])
2924 // send email notification to owner?
2928 // create contact record
2930 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2931 `blocked`, `readonly`, `pending`, `writable` )
2932 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2933 intval($importer['uid']),
2934 dbesc(datetime_convert()),
2936 dbesc(normalise_link($url)),
2940 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2941 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2943 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2944 intval($importer['uid']),
2948 $contact_record = $r[0];
2950 // create notification
2951 $hash = random_string();
2953 if(is_array($contact_record)) {
2954 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2955 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2956 intval($importer['uid']),
2957 intval($contact_record['id']),
2959 dbesc(datetime_convert())
2962 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2963 intval($importer['uid'])
2968 if(intval($r[0]['def_gid'])) {
2969 require_once('include/group.php');
2970 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2973 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2974 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2975 $email = replace_macros($email_tpl, array(
2976 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2978 '$myname' => $r[0]['username'],
2979 '$siteurl' => $a->get_baseurl(),
2980 '$sitename' => $a->config['sitename']
2982 $res = mail($r[0]['email'],
2983 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2985 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2986 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2987 . 'Content-transfer-encoding: 8bit' );
2994 function lose_follower($importer,$contact,$datarray,$item) {
2996 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2997 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2998 intval(CONTACT_IS_SHARING),
2999 intval($contact['id'])
3003 contact_remove($contact['id']);
3007 function lose_sharer($importer,$contact,$datarray,$item) {
3009 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3010 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3011 intval(CONTACT_IS_FOLLOWER),
3012 intval($contact['id'])
3016 contact_remove($contact['id']);
3021 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3025 if(is_array($importer)) {
3026 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3027 intval($importer['uid'])
3031 // Diaspora has different message-ids in feeds than they do
3032 // through the direct Diaspora protocol. If we try and use
3033 // the feed, we'll get duplicates. So don't.
3035 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3038 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3040 // Use a single verify token, even if multiple hubs
3042 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3044 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3046 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
3048 if(! strlen($contact['hub-verify'])) {
3049 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3050 dbesc($verify_token),
3051 intval($contact['id'])
3055 post_url($url,$params);
3057 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3064 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3068 $name = xmlify($name);
3069 $uri = xmlify($uri);
3072 $photo = xmlify($photo);
3076 $o .= "<name>$name</name>\r\n";
3077 $o .= "<uri>$uri</uri>\r\n";
3078 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3079 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3081 call_hooks('atom_author', $o);
3083 $o .= "</$tag>\r\n";
3087 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3091 if(! $item['parent'])
3094 if($item['deleted'])
3095 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3098 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3099 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3101 $body = $item['body'];
3104 $o = "\r\n\r\n<entry>\r\n";
3106 if(is_array($author))
3107 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3109 $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']));
3110 if(strlen($item['owner-name']))
3111 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3113 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || ($item['thr-parent'])) {
3114 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3115 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3118 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3119 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3120 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3121 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3122 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3123 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3124 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3126 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3128 if($item['location']) {
3129 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3130 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3134 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3136 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3137 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3140 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3141 if($item['bookmark'])
3142 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3145 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3148 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3150 if($item['signed_text']) {
3151 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3152 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3155 $verb = construct_verb($item);
3156 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3157 $actobj = construct_activity_object($item);
3160 $actarg = construct_activity_target($item);
3164 $tags = item_getfeedtags($item);
3166 foreach($tags as $t) {
3167 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3171 $o .= item_getfeedattach($item);
3173 $mentioned = get_mentions($item);
3177 call_hooks('atom_entry', $o);
3179 $o .= '</entry>' . "\r\n";
3184 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3187 logger('fix_private_photos', LOGGER_DEBUG);
3188 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3193 $img_start = strpos($orig_body, '[img');
3194 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3195 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3196 while( ($img_st_close !== false) && ($img_len !== false) ) {
3198 $img_st_close++; // make it point to AFTER the closing bracket
3199 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3201 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3204 if(stristr($image , $site . '/photo/')) {
3205 // Only embed locally hosted photos
3207 $i = basename($image);
3208 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3209 $x = strpos($i,'-');
3212 $res = substr($i,$x+1);
3213 $i = substr($i,0,$x);
3214 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3221 // Check to see if we should replace this photo link with an embedded image
3222 // 1. No need to do so if the photo is public
3223 // 2. If there's a contact-id provided, see if they're in the access list
3224 // for the photo. If so, embed it.
3225 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3226 // permissions, regardless of order but first check to see if they're an exact
3227 // match to save some processing overhead.
3229 if(has_permissions($r[0])) {
3231 $recips = enumerate_permissions($r[0]);
3232 if(in_array($cid, $recips)) {
3237 if(compare_permissions($item,$r[0]))
3242 $data = $r[0]['data'];
3243 $type = $r[0]['type'];
3245 // If a custom width and height were specified, apply before embedding
3246 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3247 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3249 $width = intval($match[1]);
3250 $height = intval($match[2]);
3252 $ph = new Photo($data, $type);
3253 if($ph->is_valid()) {
3254 $ph->scaleImage(max($width, $height));
3255 $data = $ph->imageString();
3256 $type = $ph->getType();
3260 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3261 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3262 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3268 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3269 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3270 if($orig_body === false)
3273 $img_start = strpos($orig_body, '[img');
3274 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3275 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3278 $new_body = $new_body . $orig_body;
3284 function has_permissions($obj) {
3285 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3290 function compare_permissions($obj1,$obj2) {
3291 // first part is easy. Check that these are exactly the same.
3292 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3293 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3294 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3295 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3298 // This is harder. Parse all the permissions and compare the resulting set.
3300 $recipients1 = enumerate_permissions($obj1);
3301 $recipients2 = enumerate_permissions($obj2);
3304 if($recipients1 == $recipients2)
3309 // returns an array of contact-ids that are allowed to see this object
3311 function enumerate_permissions($obj) {
3312 require_once('include/group.php');
3313 $allow_people = expand_acl($obj['allow_cid']);
3314 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3315 $deny_people = expand_acl($obj['deny_cid']);
3316 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3317 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3318 $deny = array_unique(array_merge($deny_people,$deny_groups));
3319 $recipients = array_diff($recipients,$deny);
3323 function item_getfeedtags($item) {
3326 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3328 for($x = 0; $x < $cnt; $x ++) {
3330 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3334 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3336 for($x = 0; $x < $cnt; $x ++) {
3338 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3344 function item_getfeedattach($item) {
3346 $arr = explode(',',$item['attach']);
3348 foreach($arr as $r) {
3350 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3352 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3353 if(intval($matches[2]))
3354 $ret .= 'length="' . intval($matches[2]) . '" ';
3355 if($matches[4] !== ' ')
3356 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3357 $ret .= ' />' . "\r\n";
3366 function item_expire($uid,$days) {
3368 if((! $uid) || ($days < 1))
3371 // $expire_network_only = save your own wall posts
3372 // and just expire conversations started by others
3374 $expire_network_only = get_pconfig($uid,'expire','network_only');
3375 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3377 $r = q("SELECT * FROM `item`
3379 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3390 $expire_items = get_pconfig($uid, 'expire','items');
3391 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3393 $expire_notes = get_pconfig($uid, 'expire','notes');
3394 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3396 $expire_starred = get_pconfig($uid, 'expire','starred');
3397 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3399 $expire_photos = get_pconfig($uid, 'expire','photos');
3400 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3402 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3404 foreach($r as $item) {
3406 // don't expire filed items
3408 if(strpos($item['file'],'[') !== false)
3411 // Only expire posts, not photos and photo comments
3413 if($expire_photos==0 && strlen($item['resource-id']))
3415 if($expire_starred==0 && intval($item['starred']))
3417 if($expire_notes==0 && $item['type']=='note')
3419 if($expire_items==0 && $item['type']!='note')
3422 drop_item($item['id'],false);
3425 proc_run('php',"include/notifier.php","expire","$uid");
3430 function drop_items($items) {
3433 if(! local_user() && ! remote_user())
3437 foreach($items as $item) {
3438 $owner = drop_item($item,false);
3439 if($owner && ! $uid)
3444 // multiple threads may have been deleted, send an expire notification
3447 proc_run('php',"include/notifier.php","expire","$uid");
3451 function drop_item($id,$interactive = true) {
3455 // locate item to be deleted
3457 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3464 notice( t('Item not found.') . EOL);
3465 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3470 $owner = $item['uid'];
3472 // check if logged in user is either the author or owner of this item
3474 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3478 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3479 dbesc(datetime_convert()),
3480 dbesc(datetime_convert()),
3484 // clean up categories and tags so they don't end up as orphans
3487 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3489 foreach($matches as $mtch) {
3490 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3496 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3498 foreach($matches as $mtch) {
3499 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3503 // If item is a link to a photo resource, nuke all the associated photos
3504 // (visitors will not have photo resources)
3505 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3506 // generate a resource-id and therefore aren't intimately linked to the item.
3508 if(strlen($item['resource-id'])) {
3509 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3510 dbesc($item['resource-id']),
3511 intval($item['uid'])
3513 // ignore the result
3516 // If item is a link to an event, nuke the event record.
3518 if(intval($item['event-id'])) {
3519 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3520 intval($item['event-id']),
3521 intval($item['uid'])
3523 // ignore the result
3526 // clean up item_id and sign meta-data tables
3528 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3529 intval($item['id']),
3530 intval($item['uid'])
3533 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3534 intval($item['id']),
3535 intval($item['uid'])
3538 // If it's the parent of a comment thread, kill all the kids
3540 if($item['uri'] == $item['parent-uri']) {
3541 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3542 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3543 dbesc(datetime_convert()),
3544 dbesc(datetime_convert()),
3545 dbesc($item['parent-uri']),
3546 intval($item['uid'])
3548 // ignore the result
3551 // ensure that last-child is set in case the comment that had it just got wiped.
3552 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3553 dbesc(datetime_convert()),
3554 dbesc($item['parent-uri']),
3555 intval($item['uid'])
3557 // who is the last child now?
3558 $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",
3559 dbesc($item['parent-uri']),
3560 intval($item['uid'])
3563 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3568 // Add a relayable_retraction signature for Diaspora.
3569 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
3571 $drop_id = intval($item['id']);
3573 // send the notification upstream/downstream as the case may be
3578 proc_run('php',"include/notifier.php","drop","$drop_id");
3579 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3585 notice( t('Permission denied.') . EOL);
3586 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3593 function first_post_date($uid,$wall = false) {
3594 $r = q("select id, created from item
3595 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3597 order by created asc limit 1",
3599 intval($wall ? 1 : 0)
3602 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3603 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3608 function posted_dates($uid,$wall) {
3609 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3611 $dthen = first_post_date($uid,$wall);
3615 // If it's near the end of a long month, backup to the 28th so that in
3616 // consecutive loops we'll always get a whole month difference.
3618 if(intval(substr($dnow,8)) > 28)
3619 $dnow = substr($dnow,0,8) . '28';
3620 if(intval(substr($dthen,8)) > 28)
3621 $dnow = substr($dthen,0,8) . '28';
3624 // Starting with the current month, get the first and last days of every
3625 // month down to and including the month of the first post
3626 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
3627 $dstart = substr($dnow,0,8) . '01';
3628 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3629 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3630 $end_month = datetime_convert('','',$dend,'Y-m-d');
3631 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3632 $ret[] = array($str,$end_month,$start_month);
3633 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3639 function posted_date_widget($url,$uid,$wall) {
3642 // For former Facebook folks that left because of "timeline"
3644 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3647 $ret = posted_dates($uid,$wall);
3651 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3652 '$title' => t('Archives'),
3653 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3661 function store_diaspora_retract_sig($item, $user, $baseurl) {
3662 // Note that we can't add a target_author_signature
3663 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3664 // the comment, that means we're the home of the post, and Diaspora will only
3665 // check the parent_author_signature of retractions that it doesn't have to relay further
3667 // I don't think this function gets called for an "unlike," but I'll check anyway
3669 $enabled = intval(get_config('system','diaspora_enabled'));
3671 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
3675 logger('drop_item: storing diaspora retraction signature');
3677 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3679 if(local_user() == $item['uid']) {
3681 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
3682 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
3685 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3689 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3690 // only handles DFRN deletes
3691 $handle_baseurl_start = strpos($r['url'],'://') + 3;
3692 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3693 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3699 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3700 intval($item['id']),
3701 dbesc($signed_text),