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 require_once('include/security.php');
80 $groups = init_groups_visitor($contact['id']);
83 for($x = 0; $x < count($groups); $x ++)
84 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
85 $gs = implode('|', $groups);
88 $gs = '<<>>' ; // Impossible to match
90 $sql_extra = sprintf("
91 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
92 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
93 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
94 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
96 intval($contact['id']),
97 intval($contact['id']),
108 if(! strlen($last_update))
109 $last_update = 'now -30 days';
111 if(isset($category)) {
112 $sql_extra .= file_tag_file_query('item',$category,'category');
117 $sql_extra .= " AND `contact`.`self` = 1 ";
120 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
122 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
123 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
124 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
125 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
126 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
127 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
128 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
129 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
130 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
131 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
132 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
134 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
141 // Will check further below if this actually returned results.
142 // We will provide an empty feed if that is the case.
146 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
150 $hubxml = feed_hublinks();
152 $salmon = feed_salmonlinks($owner_nick);
154 $atom .= replace_macros($feed_template, array(
155 '$version' => xmlify(FRIENDICA_VERSION),
156 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
157 '$feed_title' => xmlify($owner['name']),
158 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
160 '$salmon' => $salmon,
161 '$name' => xmlify($owner['name']),
162 '$profile_page' => xmlify($owner['url']),
163 '$photo' => xmlify($owner['photo']),
164 '$thumb' => xmlify($owner['thumb']),
165 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
166 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
167 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
168 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
169 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
172 call_hooks('atom_feed', $atom);
174 if(! count($items)) {
176 call_hooks('atom_feed_end', $atom);
178 $atom .= '</feed>' . "\r\n";
182 foreach($items as $item) {
184 // prevent private email from leaking.
185 if($item['network'] === NETWORK_MAIL)
188 // public feeds get html, our own nodes use bbcode
192 // catch any email that's in a public conversation and make sure it doesn't leak
200 $atom .= atom_entry($item,$type,null,$owner,true);
203 call_hooks('atom_feed_end', $atom);
205 $atom .= '</feed>' . "\r\n";
211 function construct_verb($item) {
213 return $item['verb'];
214 return ACTIVITY_POST;
217 function construct_activity_object($item) {
219 if($item['object']) {
220 $o = '<as:object>' . "\r\n";
221 $r = parse_xml_string($item['object'],false);
227 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
229 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
231 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
233 if(substr($r->link,0,1) === '<') {
234 // patch up some facebook "like" activity objects that got stored incorrectly
235 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
236 // we can probably remove this hack here and in the following function in a few months time.
237 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
238 $r->link = str_replace('&','&', $r->link);
239 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
243 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
246 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
247 $o .= '</as:object>' . "\r\n";
254 function construct_activity_target($item) {
256 if($item['target']) {
257 $o = '<as:target>' . "\r\n";
258 $r = parse_xml_string($item['target'],false);
262 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
264 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
266 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
268 if(substr($r->link,0,1) === '<') {
269 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
270 $r->link = str_replace('&','&', $r->link);
271 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
275 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
278 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
279 $o .= '</as:target>' . "\r\n";
288 * The purpose of this function is to apply system message length limits to
289 * imported messages without including any embedded photos in the length
291 if(! function_exists('limit_body_size')) {
292 function limit_body_size($body) {
294 logger('limit_body_size: start', LOGGER_DEBUG);
296 $maxlen = get_max_import_size();
298 // If the length of the body, including the embedded images, is smaller
299 // than the maximum, then don't waste time looking for the images
300 if($maxlen && (strlen($body) > $maxlen)) {
302 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
309 $img_start = strpos($orig_body, '[img');
310 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
311 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
312 while(($img_st_close !== false) && ($img_end !== false)) {
314 $img_st_close++; // make it point to AFTER the closing bracket
315 $img_end += $img_start;
316 $img_end += strlen('[/img]');
318 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
319 // This is an embedded image
321 if( ($textlen + $img_start) > $maxlen ) {
322 if($textlen < $maxlen) {
323 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
324 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
329 $new_body = $new_body . substr($orig_body, 0, $img_start);
330 $textlen += $img_start;
333 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
337 if( ($textlen + $img_end) > $maxlen ) {
338 if($textlen < $maxlen) {
339 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
340 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
345 $new_body = $new_body . substr($orig_body, 0, $img_end);
346 $textlen += $img_end;
349 $orig_body = substr($orig_body, $img_end);
351 if($orig_body === false) // in case the body ends on a closing image tag
354 $img_start = strpos($orig_body, '[img');
355 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
356 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
359 if( ($textlen + strlen($orig_body)) > $maxlen) {
360 if($textlen < $maxlen) {
361 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
362 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
367 logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
368 $new_body = $new_body . $orig_body;
369 $textlen += strlen($orig_body);
378 function title_is_body($title, $body) {
380 $title = strip_tags($title);
381 $title = trim($title);
382 $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
384 $body = strip_tags($body);
386 $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
388 if (strlen($title) < strlen($body))
389 $body = substr($body, 0, strlen($title));
391 if (($title != $body) and (substr($title, -3) == "...")) {
392 $pos = strrpos($title, "...");
394 $title = substr($title, 0, $pos);
395 $body = substr($body, 0, $pos);
399 return($title == $body);
404 function get_atom_elements($feed,$item) {
406 require_once('library/HTMLPurifier.auto.php');
407 require_once('include/html2bbcode.php');
409 $best_photo = array();
413 $author = $item->get_author();
415 $res['author-name'] = unxmlify($author->get_name());
416 $res['author-link'] = unxmlify($author->get_link());
419 $res['author-name'] = unxmlify($feed->get_title());
420 $res['author-link'] = unxmlify($feed->get_permalink());
422 $res['uri'] = unxmlify($item->get_id());
423 $res['title'] = unxmlify($item->get_title());
424 $res['body'] = unxmlify($item->get_content());
425 $res['plink'] = unxmlify($item->get_link(0));
427 // removing the content of the title if its identically to the body
428 // This helps with auto generated titles e.g. from tumblr
429 if (title_is_body($res["title"], $res["body"]))
433 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
437 // look for a photo. We should check media size and find the best one,
438 // but for now let's just find any author photo
440 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
442 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
443 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
444 foreach($base as $link) {
445 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
446 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
447 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
452 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
454 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
455 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
456 if($base && count($base)) {
457 foreach($base as $link) {
458 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
459 $res['author-link'] = unxmlify($link['attribs']['']['href']);
460 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
461 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
462 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
468 // No photo/profile-link on the item - look at the feed level
470 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
471 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
472 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
473 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
474 foreach($base as $link) {
475 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
476 $res['author-link'] = unxmlify($link['attribs']['']['href']);
477 if(! $res['author-avatar']) {
478 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
479 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
484 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
486 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
487 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
489 if($base && count($base)) {
490 foreach($base as $link) {
491 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
492 $res['author-link'] = unxmlify($link['attribs']['']['href']);
493 if(! (x($res,'author-avatar'))) {
494 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
495 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
502 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
503 if($apps && $apps[0]['attribs']['']['source']) {
504 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
505 if($res['app'] === 'web')
506 $res['app'] = 'OStatus';
509 // base64 encoded json structure representing Diaspora signature
511 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
513 $res['dsprsig'] = unxmlify($dsig[0]['data']);
516 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
518 $res['guid'] = unxmlify($dguid[0]['data']);
520 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
522 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
526 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
529 $have_real_body = false;
531 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
533 $have_real_body = true;
534 $res['body'] = $rawenv[0]['data'];
535 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
536 // make sure nobody is trying to sneak some html tags by us
537 $res['body'] = notags(base64url_decode($res['body']));
541 $res['body'] = limit_body_size($res['body']);
543 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
544 // the content type. Our own network only emits text normally, though it might have been converted to
545 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
546 // have to assume it is all html and needs to be purified.
548 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
549 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
550 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
553 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
555 $res['body'] = reltoabs($res['body'],$base_url);
557 $res['body'] = html2bb_video($res['body']);
559 $res['body'] = oembed_html2bbcode($res['body']);
561 $config = HTMLPurifier_Config::createDefault();
562 $config->set('Cache.DefinitionImpl', null);
564 // we shouldn't need a whitelist, because the bbcode converter
565 // will strip out any unsupported tags.
567 $purifier = new HTMLPurifier($config);
568 $res['body'] = $purifier->purify($res['body']);
570 $res['body'] = @html2bbcode($res['body']);
574 elseif(! $have_real_body) {
576 // it's not one of our messages and it has no tags
577 // so it's probably just text. We'll escape it just to be safe.
579 $res['body'] = escape_tags($res['body']);
583 // this tag is obsolete but we keep it for really old sites
585 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
586 if($allow && $allow[0]['data'] == 1)
587 $res['last-child'] = 1;
589 $res['last-child'] = 0;
591 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
592 if($private && intval($private[0]['data']) > 0)
593 $res['private'] = intval($private[0]['data']);
597 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
598 if($extid && $extid[0]['data'])
599 $res['extid'] = $extid[0]['data'];
601 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
603 $res['location'] = unxmlify($rawlocation[0]['data']);
606 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
608 $res['created'] = unxmlify($rawcreated[0]['data']);
611 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
613 $res['edited'] = unxmlify($rawedited[0]['data']);
615 if((x($res,'edited')) && (! (x($res,'created'))))
616 $res['created'] = $res['edited'];
618 if(! $res['created'])
619 $res['created'] = $item->get_date('c');
622 $res['edited'] = $item->get_date('c');
625 // Disallow time travelling posts
627 $d1 = strtotime($res['created']);
628 $d2 = strtotime($res['edited']);
629 $d3 = strtotime('now');
632 $res['created'] = datetime_convert();
634 $res['edited'] = datetime_convert();
636 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
637 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
638 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
639 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
640 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
641 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
642 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
643 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
644 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
646 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
647 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
649 foreach($base as $link) {
650 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
651 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
652 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
657 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
659 $res['coord'] = unxmlify($rawgeo[0]['data']);
662 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
664 // select between supported verbs
667 $res['verb'] = unxmlify($rawverb[0]['data']);
670 // translate OStatus unfollow to activity streams if it happened to get selected
672 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
673 $res['verb'] = ACTIVITY_UNFOLLOW;
675 $cats = $item->get_categories();
678 foreach($cats as $cat) {
679 $term = $cat->get_term();
681 $term = $cat->get_label();
682 $scheme = $cat->get_scheme();
683 if($scheme && $term && stristr($scheme,'X-DFRN:'))
684 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
686 $tag_arr[] = notags(trim($term));
688 $res['tag'] = implode(',', $tag_arr);
691 $attach = $item->get_enclosures();
694 foreach($attach as $att) {
695 $len = intval($att->get_length());
696 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
697 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
698 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
699 if(strpos($type,';'))
700 $type = substr($type,0,strpos($type,';'));
701 if((! $link) || (strpos($link,'http') !== 0))
707 $type = 'application/octet-stream';
709 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
711 $res['attach'] = implode(',', $att_arr);
714 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
717 $res['object'] = '<object>' . "\n";
718 $child = $rawobj[0]['child'];
719 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
720 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
721 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
723 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
724 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
725 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
726 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
727 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
728 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
729 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
730 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
732 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
733 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
734 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
735 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
737 $body = html2bb_video($body);
739 $config = HTMLPurifier_Config::createDefault();
740 $config->set('Cache.DefinitionImpl', null);
742 $purifier = new HTMLPurifier($config);
743 $body = $purifier->purify($body);
744 $body = html2bbcode($body);
747 $res['object'] .= '<content>' . $body . '</content>' . "\n";
750 $res['object'] .= '</object>' . "\n";
753 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
756 $res['target'] = '<target>' . "\n";
757 $child = $rawobj[0]['child'];
758 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
759 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
761 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
762 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
763 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
764 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
765 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
766 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
767 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
768 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
770 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
771 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
772 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
773 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
775 $body = html2bb_video($body);
777 $config = HTMLPurifier_Config::createDefault();
778 $config->set('Cache.DefinitionImpl', null);
780 $purifier = new HTMLPurifier($config);
781 $body = $purifier->purify($body);
782 $body = html2bbcode($body);
785 $res['target'] .= '<content>' . $body . '</content>' . "\n";
788 $res['target'] .= '</target>' . "\n";
791 // This is some experimental stuff. By now retweets are shown with "RT:"
792 // But: There is data so that the message could be shown similar to native retweets
793 // There is some better way to parse this array - but it didn't worked for me.
794 $child = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://activitystrea.ms/spec/1.0/"][object][0]["child"];
795 if (is_array($child)) {
796 $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
797 $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
798 $uri = $author["uri"][0]["data"];
799 $name = $author["name"][0]["data"];
800 $avatar = @array_shift($author["link"][2]["attribs"]);
801 $avatar = $avatar["href"];
803 if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
804 $res["owner-name"] = $res["author-name"];
805 $res["owner-link"] = $res["author-link"];
806 $res["owner-avatar"] = $res["author-avatar"];
808 $res["author-name"] = $name;
809 $res["author-link"] = $uri;
810 $res["author-avatar"] = $avatar;
812 $res["body"] = html2bbcode($message);
816 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
818 call_hooks('parse_atom', $arr);
820 //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
821 //if (strpos($res["body"], "RT @") !== false) {
822 // $debugfile = tempnam("/home/ike/log", "item-res2-");
823 // file_put_contents($debugfile, serialize($arr));
829 function encode_rel_links($links) {
831 if(! ((is_array($links)) && (count($links))))
833 foreach($links as $link) {
835 if($link['attribs']['']['rel'])
836 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
837 if($link['attribs']['']['type'])
838 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
839 if($link['attribs']['']['href'])
840 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
841 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
842 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
843 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
844 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
852 function item_store($arr,$force_parent = false) {
854 // If a Diaspora signature structure was passed in, pull it out of the
855 // item array and set it aside for later storage.
858 if(x($arr,'dsprsig')) {
859 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
860 unset($arr['dsprsig']);
863 if(x($arr, 'gravity'))
864 $arr['gravity'] = intval($arr['gravity']);
865 elseif($arr['parent-uri'] === $arr['uri'])
867 elseif(activity_match($arr['verb'],ACTIVITY_POST))
870 $arr['gravity'] = 6; // extensible catchall
873 $arr['type'] = 'remote';
875 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
877 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
878 $arr['body'] = strip_tags($arr['body']);
881 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
882 require_once('Text/LanguageDetect.php');
883 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
884 $l = new Text_LanguageDetect;
885 $lng = $l->detectConfidence($naked_body);
886 $arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
889 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
890 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
891 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
892 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
893 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
894 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
895 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
896 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
897 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
898 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
899 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
900 $arr['commented'] = datetime_convert();
901 $arr['received'] = datetime_convert();
902 $arr['changed'] = datetime_convert();
903 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
904 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
905 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
906 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
907 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
909 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
910 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
911 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
912 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
913 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
914 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
915 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
916 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
917 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
918 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
919 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
920 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
921 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
922 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
923 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
924 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
925 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
926 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
927 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
930 $arr['thr-parent'] = $arr['parent-uri'];
931 if($arr['parent-uri'] === $arr['uri']) {
934 $allow_cid = $arr['allow_cid'];
935 $allow_gid = $arr['allow_gid'];
936 $deny_cid = $arr['deny_cid'];
937 $deny_gid = $arr['deny_gid'];
941 // find the parent and snarf the item id and ACL's
942 // and anything else we need to inherit
944 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
945 dbesc($arr['parent-uri']),
951 // is the new message multi-level threaded?
952 // even though we don't support it now, preserve the info
953 // and re-attach to the conversation parent.
955 if($r[0]['uri'] != $r[0]['parent-uri']) {
956 $arr['parent-uri'] = $r[0]['parent-uri'];
957 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
958 ORDER BY `id` ASC LIMIT 1",
959 dbesc($r[0]['parent-uri']),
960 dbesc($r[0]['parent-uri']),
967 $parent_id = $r[0]['id'];
968 $parent_deleted = $r[0]['deleted'];
969 $allow_cid = $r[0]['allow_cid'];
970 $allow_gid = $r[0]['allow_gid'];
971 $deny_cid = $r[0]['deny_cid'];
972 $deny_gid = $r[0]['deny_gid'];
973 $arr['wall'] = $r[0]['wall'];
975 // if the parent is private, force privacy for the entire conversation
976 // This differs from the above settings as it subtly allows comments from
977 // email correspondents to be private even if the overall thread is not.
980 $arr['private'] = $r[0]['private'];
982 // Edge case. We host a public forum that was originally posted to privately.
983 // The original author commented, but as this is a comment, the permissions
984 // weren't fixed up so it will still show the comment as private unless we fix it here.
986 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
991 // Allow one to see reply tweets from status.net even when
992 // we don't have or can't see the original post.
995 logger('item_store: $force_parent=true, reply converted to top-level post.');
997 $arr['parent-uri'] = $arr['uri'];
1001 logger('item_store: item parent was not found - ignoring item');
1005 $parent_deleted = 0;
1009 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1013 if($r && count($r)) {
1014 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
1018 call_hooks('post_remote',$arr);
1020 if(x($arr,'cancel')) {
1021 logger('item_store: post cancelled by plugin.');
1027 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
1029 $r = dbq("INSERT INTO `item` (`"
1030 . implode("`, `", array_keys($arr))
1032 . implode("', '", array_values($arr))
1035 // find the item we just created
1037 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
1038 $arr['uri'], // already dbesc'd
1043 $current_post = $r[0]['id'];
1044 logger('item_store: created item ' . $current_post);
1047 logger('item_store: could not locate created item');
1051 logger('item_store: duplicated post occurred. Removing duplicates.');
1052 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
1054 intval($arr['uid']),
1055 intval($current_post)
1059 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
1060 $parent_id = $current_post;
1062 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1065 $private = $arr['private'];
1067 // Set parent id - and also make sure to inherit the parent's ACL's.
1069 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1070 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1077 intval($parent_deleted),
1078 intval($current_post)
1081 $arr['id'] = $current_post;
1082 $arr['parent'] = $parent_id;
1083 $arr['allow_cid'] = $allow_cid;
1084 $arr['allow_gid'] = $allow_gid;
1085 $arr['deny_cid'] = $deny_cid;
1086 $arr['deny_gid'] = $deny_gid;
1087 $arr['private'] = $private;
1088 $arr['deleted'] = $parent_deleted;
1089 call_hooks('post_remote_end',$arr);
1091 // update the commented timestamp on the parent
1093 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1094 dbesc(datetime_convert()),
1095 dbesc(datetime_convert()),
1100 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1101 intval($current_post),
1102 dbesc($dsprsig->signed_text),
1103 dbesc($dsprsig->signature),
1104 dbesc($dsprsig->signer)
1110 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1113 if($arr['last-child']) {
1114 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1116 intval($arr['uid']),
1117 intval($current_post)
1121 tag_deliver($arr['uid'],$current_post);
1123 return $current_post;
1126 function get_item_contact($item,$contacts) {
1127 if(! count($contacts) || (! is_array($item)))
1129 foreach($contacts as $contact) {
1130 if($contact['id'] == $item['contact-id']) {
1132 break; // NOTREACHED
1139 function tag_deliver($uid,$item_id) {
1141 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1147 $u = q("select * from user where uid = %d limit 1",
1153 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1154 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1157 $i = q("select * from item where id = %d and uid = %d limit 1",
1166 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1168 // Diaspora uses their own hardwired link URL in @-tags
1169 // instead of the one we supply with webfinger
1171 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1173 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1175 foreach($matches as $mtch) {
1176 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1178 logger('tag_deliver: mention found: ' . $mtch[2]);
1186 // send a notification
1188 // use a local photo if we have one
1190 $r = q("select * from contact where uid = %d and nurl = '%s' limit 1",
1191 intval($u[0]['uid']),
1192 dbesc(normalise_link($item['author-link']))
1194 $photo = (($r && count($r)) ? $r[0]['thumb'] : $item['author-avatar']);
1197 require_once('include/enotify.php');
1199 'type' => NOTIFY_TAGSELF,
1200 'notify_flags' => $u[0]['notify-flags'],
1201 'language' => $u[0]['language'],
1202 'to_name' => $u[0]['username'],
1203 'to_email' => $u[0]['email'],
1204 'uid' => $u[0]['uid'],
1206 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1207 'source_name' => $item['author-name'],
1208 'source_link' => $item['author-link'],
1209 'source_photo' => $photo,
1210 'verb' => ACTIVITY_TAG,
1215 $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1217 call_hooks('tagged', $arr);
1219 if((! $community_page) && (! $prvgroup))
1223 // tgroup delivery - setup a second delivery chain
1224 // prevent delivery looping - only proceed
1225 // if the message originated elsewhere and is a top-level post
1227 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1230 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1233 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1234 intval($u[0]['uid'])
1239 // also reset all the privacy bits to the forum default permissions
1241 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1243 $forum_mode = (($prvgroup) ? 2 : 1);
1245 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1246 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1247 intval($forum_mode),
1248 dbesc($c[0]['name']),
1249 dbesc($c[0]['url']),
1250 dbesc($c[0]['thumb']),
1252 dbesc($u[0]['allow_cid']),
1253 dbesc($u[0]['allow_gid']),
1254 dbesc($u[0]['deny_cid']),
1255 dbesc($u[0]['deny_gid']),
1259 proc_run('php','include/notifier.php','tgroup',$item_id);
1265 function tgroup_check($uid,$item) {
1271 // check that the message originated elsewhere and is a top-level post
1273 if(($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri']))
1277 $u = q("select * from user where uid = %d limit 1",
1283 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1284 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1287 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1289 // Diaspora uses their own hardwired link URL in @-tags
1290 // instead of the one we supply with webfinger
1292 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1294 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1296 foreach($matches as $mtch) {
1297 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1299 logger('tgroup_check: mention found: ' . $mtch[2]);
1307 if((! $community_page) && (! $prvgroup))
1321 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1325 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1327 if($contact['duplex'] && $contact['dfrn-id'])
1328 $idtosend = '0:' . $orig_id;
1329 if($contact['duplex'] && $contact['issued-id'])
1330 $idtosend = '1:' . $orig_id;
1332 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1334 $rino_enable = get_config('system','rino_encrypt');
1339 $ssl_val = intval(get_config('system','ssl_policy'));
1343 case SSL_POLICY_FULL:
1344 $ssl_policy = 'full';
1346 case SSL_POLICY_SELFSIGN:
1347 $ssl_policy = 'self';
1349 case SSL_POLICY_NONE:
1351 $ssl_policy = 'none';
1355 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1357 logger('dfrn_deliver: ' . $url);
1359 $xml = fetch_url($url);
1361 $curl_stat = $a->get_curl_code();
1363 return(-1); // timed out
1365 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1370 if(strpos($xml,'<?xml') === false) {
1371 logger('dfrn_deliver: no valid XML returned');
1372 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1376 $res = parse_xml_string($xml);
1378 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1379 return (($res->status) ? $res->status : 3);
1381 $postvars = array();
1382 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1383 $challenge = hex2bin((string) $res->challenge);
1384 $perm = (($res->perm) ? $res->perm : null);
1385 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1386 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1387 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1389 if($owner['page-flags'] == PAGE_PRVGROUP)
1392 $final_dfrn_id = '';
1395 if((($perm == 'rw') && (! intval($contact['writable'])))
1396 || (($perm == 'r') && (intval($contact['writable'])))) {
1397 q("update contact set writable = %d where id = %d limit 1",
1398 intval(($perm == 'rw') ? 1 : 0),
1399 intval($contact['id'])
1401 $contact['writable'] = (string) 1 - intval($contact['writable']);
1405 if(($contact['duplex'] && strlen($contact['pubkey']))
1406 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1407 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1408 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1409 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1412 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1413 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1416 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1418 if(strpos($final_dfrn_id,':') == 1)
1419 $final_dfrn_id = substr($final_dfrn_id,2);
1421 if($final_dfrn_id != $orig_id) {
1422 logger('dfrn_deliver: wrong dfrn_id.');
1423 // did not decode properly - cannot trust this site
1427 $postvars['dfrn_id'] = $idtosend;
1428 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1430 $postvars['dissolve'] = '1';
1433 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1434 $postvars['data'] = $atom;
1435 $postvars['perm'] = 'rw';
1438 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1439 $postvars['perm'] = 'r';
1442 $postvars['ssl_policy'] = $ssl_policy;
1445 $postvars['page'] = $page;
1447 if($rino && $rino_allowed && (! $dissolve)) {
1448 $key = substr(random_string(),0,16);
1449 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1450 $postvars['data'] = $data;
1451 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1454 if($dfrn_version >= 2.1) {
1455 if(($contact['duplex'] && strlen($contact['pubkey']))
1456 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1457 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1459 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1462 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1466 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1467 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1470 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1474 logger('md5 rawkey ' . md5($postvars['key']));
1476 $postvars['key'] = bin2hex($postvars['key']);
1479 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1481 $xml = post_url($contact['notify'],$postvars);
1483 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1485 $curl_stat = $a->get_curl_code();
1486 if((! $curl_stat) || (! strlen($xml)))
1487 return(-1); // timed out
1489 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1492 if(strpos($xml,'<?xml') === false) {
1493 logger('dfrn_deliver: phase 2: no valid XML returned');
1494 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1498 if($contact['term-date'] != '0000-00-00 00:00:00') {
1499 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1500 require_once('include/Contact.php');
1501 unmark_for_death($contact);
1504 $res = parse_xml_string($xml);
1506 return $res->status;
1512 * consume_feed - process atom feed and update anything/everything we might need to update
1514 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1516 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1517 * It is this person's stuff that is going to be updated.
1518 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1519 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1520 * have a contact record.
1521 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1522 * might not) try and subscribe to it.
1523 * $datedir sorts in reverse order
1524 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1525 * imported prior to its children being seen in the stream unless we are certain
1526 * of how the feed is arranged/ordered.
1527 * With $pass = 1, we only pull parent items out of the stream.
1528 * With $pass = 2, we only pull children (comments/likes).
1530 * So running this twice, first with pass 1 and then with pass 2 will do the right
1531 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1532 * model where comments can have sub-threads. That would require some massive sorting
1533 * to get all the feed items into a mostly linear ordering, and might still require
1537 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1539 require_once('library/simplepie/simplepie.inc');
1541 if(! strlen($xml)) {
1542 logger('consume_feed: empty input');
1546 $feed = new SimplePie();
1547 $feed->set_raw_data($xml);
1549 $feed->enable_order_by_date(true);
1551 $feed->enable_order_by_date(false);
1555 logger('consume_feed: Error parsing XML: ' . $feed->error());
1557 $permalink = $feed->get_permalink();
1559 // Check at the feed level for updated contact name and/or photo
1563 $photo_timestamp = '';
1567 $hubs = $feed->get_links('hub');
1568 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1571 $hub = implode(',', $hubs);
1573 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1575 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1577 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1578 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1579 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1580 $new_name = $elems['name'][0]['data'];
1582 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1583 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1584 $photo_url = $elems['link'][0]['attribs']['']['href'];
1587 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1588 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1592 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1593 logger('consume_feed: Updating photo for ' . $contact['name']);
1594 require_once("Photo.php");
1595 $photo_failure = false;
1596 $have_photo = false;
1598 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1599 intval($contact['id']),
1600 intval($contact['uid'])
1603 $resource_id = $r[0]['resource-id'];
1607 $resource_id = photo_new_resource();
1610 $img_str = fetch_url($photo_url,true);
1611 // guess mimetype from headers or filename
1612 $type = guess_image_type($photo_url,true);
1615 $img = new Photo($img_str, $type);
1616 if($img->is_valid()) {
1618 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1619 dbesc($resource_id),
1620 intval($contact['id']),
1621 intval($contact['uid'])
1625 $img->scaleImageSquare(175);
1627 $hash = $resource_id;
1628 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1630 $img->scaleImage(80);
1631 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1633 $img->scaleImage(48);
1634 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1638 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1639 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1640 dbesc(datetime_convert()),
1641 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1642 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1643 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1644 intval($contact['uid']),
1645 intval($contact['id'])
1650 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1651 $r = q("select * from contact where uid = %d and id = %d limit 1",
1652 intval($contact['uid']),
1653 intval($contact['id'])
1656 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1657 dbesc(notags(trim($new_name))),
1658 dbesc(datetime_convert()),
1659 intval($contact['uid']),
1660 intval($contact['id'])
1663 // do our best to update the name on content items
1666 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1667 dbesc(notags(trim($new_name))),
1668 dbesc($r[0]['name']),
1669 dbesc($r[0]['url']),
1670 intval($contact['uid'])
1675 if(strlen($birthday)) {
1676 if(substr($birthday,0,4) != $contact['bdyear']) {
1677 logger('consume_feed: updating birthday: ' . $birthday);
1681 * Add new birthday event for this person
1683 * $bdtext is just a readable placeholder in case the event is shared
1684 * with others. We will replace it during presentation to our $importer
1685 * to contain a sparkle link and perhaps a photo.
1689 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1690 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1693 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1694 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1695 intval($contact['uid']),
1696 intval($contact['id']),
1697 dbesc(datetime_convert()),
1698 dbesc(datetime_convert()),
1699 dbesc(datetime_convert('UTC','UTC', $birthday)),
1700 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1709 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1710 dbesc(substr($birthday,0,4)),
1711 intval($contact['uid']),
1712 intval($contact['id'])
1715 // This function is called twice without reloading the contact
1716 // Make sure we only create one event. This is why &$contact
1717 // is a reference var in this function
1719 $contact['bdyear'] = substr($birthday,0,4);
1724 $community_page = 0;
1725 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1727 $community_page = intval($rawtags[0]['data']);
1729 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1730 q("update contact set forum = %d where id = %d limit 1",
1731 intval($community_page),
1732 intval($contact['id'])
1734 $contact['forum'] = (string) $community_page;
1738 // process any deleted entries
1740 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1741 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1742 foreach($del_entries as $dentry) {
1744 if(isset($dentry['attribs']['']['ref'])) {
1745 $uri = $dentry['attribs']['']['ref'];
1747 if(isset($dentry['attribs']['']['when'])) {
1748 $when = $dentry['attribs']['']['when'];
1749 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1752 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1754 if($deleted && is_array($contact)) {
1755 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1756 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1758 intval($importer['uid']),
1759 intval($contact['id'])
1764 if(! $item['deleted'])
1765 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1767 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1768 $xo = parse_xml_string($item['object'],false);
1769 $xt = parse_xml_string($item['target'],false);
1770 if($xt->type === ACTIVITY_OBJ_NOTE) {
1771 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1773 intval($importer['importer_uid'])
1777 // For tags, the owner cannot remove the tag on the author's copy of the post.
1779 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1780 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1781 $author_copy = (($item['origin']) ? true : false);
1783 if($owner_remove && $author_copy)
1785 if($author_remove || $owner_remove) {
1786 $tags = explode(',',$i[0]['tag']);
1789 foreach($tags as $tag)
1790 if(trim($tag) !== trim($xo->body))
1791 $newtags[] = trim($tag);
1793 q("update item set tag = '%s' where id = %d limit 1",
1794 dbesc(implode(',',$newtags)),
1802 if($item['uri'] == $item['parent-uri']) {
1803 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1804 `body` = '', `title` = ''
1805 WHERE `parent-uri` = '%s' AND `uid` = %d",
1807 dbesc(datetime_convert()),
1808 dbesc($item['uri']),
1809 intval($importer['uid'])
1813 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1814 `body` = '', `title` = ''
1815 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1817 dbesc(datetime_convert()),
1819 intval($importer['uid'])
1821 if($item['last-child']) {
1822 // ensure that last-child is set in case the comment that had it just got wiped.
1823 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1824 dbesc(datetime_convert()),
1825 dbesc($item['parent-uri']),
1826 intval($item['uid'])
1828 // who is the last child now?
1829 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1830 ORDER BY `created` DESC LIMIT 1",
1831 dbesc($item['parent-uri']),
1832 intval($importer['uid'])
1835 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1846 // Now process the feed
1848 if($feed->get_item_quantity()) {
1850 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1852 // in inverse date order
1854 $items = array_reverse($feed->get_items());
1856 $items = $feed->get_items();
1859 foreach($items as $item) {
1862 $item_id = $item->get_id();
1863 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1864 if(isset($rawthread[0]['attribs']['']['ref'])) {
1866 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1869 if(($is_reply) && is_array($contact)) {
1874 // not allowed to post
1876 if($contact['rel'] == CONTACT_IS_FOLLOWER)
1880 // Have we seen it? If not, import it.
1882 $item_id = $item->get_id();
1883 $datarray = get_atom_elements($feed,$item);
1885 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1886 $datarray['author-name'] = $contact['name'];
1887 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1888 $datarray['author-link'] = $contact['url'];
1889 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1890 $datarray['author-avatar'] = $contact['thumb'];
1892 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1893 logger('consume_feed: no author information! ' . print_r($datarray,true));
1897 $force_parent = false;
1898 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1899 if($contact['network'] === NETWORK_OSTATUS)
1900 $force_parent = true;
1901 if(strlen($datarray['title']))
1902 unset($datarray['title']);
1903 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1904 dbesc(datetime_convert()),
1906 intval($importer['uid'])
1908 $datarray['last-child'] = 1;
1912 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1914 intval($importer['uid'])
1917 // Update content if 'updated' changes
1920 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1922 // do not accept (ignore) an earlier edit than one we currently have.
1923 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1926 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1927 dbesc($datarray['title']),
1928 dbesc($datarray['body']),
1929 dbesc($datarray['tag']),
1930 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1932 intval($importer['uid'])
1936 // update last-child if it changes
1938 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1939 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1940 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1941 dbesc(datetime_convert()),
1943 intval($importer['uid'])
1945 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1946 intval($allow[0]['data']),
1947 dbesc(datetime_convert()),
1949 intval($importer['uid'])
1956 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1957 // one way feed - no remote comment ability
1958 $datarray['last-child'] = 0;
1960 $datarray['parent-uri'] = $parent_uri;
1961 $datarray['uid'] = $importer['uid'];
1962 $datarray['contact-id'] = $contact['id'];
1963 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1964 $datarray['type'] = 'activity';
1965 $datarray['gravity'] = GRAVITY_LIKE;
1966 // only one like or dislike per person
1967 $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",
1968 intval($datarray['uid']),
1969 intval($datarray['contact-id']),
1970 dbesc($datarray['verb']),
1978 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1979 $xo = parse_xml_string($datarray['object'],false);
1980 $xt = parse_xml_string($datarray['target'],false);
1982 if($xt->type == ACTIVITY_OBJ_NOTE) {
1983 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1985 intval($importer['importer_uid'])
1990 // extract tag, if not duplicate, add to parent item
1991 if($xo->id && $xo->content) {
1992 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1993 if(! (stristr($r[0]['tag'],$newtag))) {
1994 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1995 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2003 $r = item_store($datarray,$force_parent);
2009 // Head post of a conversation. Have we seen it? If not, import it.
2011 $item_id = $item->get_id();
2013 $datarray = get_atom_elements($feed,$item);
2015 if(is_array($contact)) {
2016 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
2017 $datarray['author-name'] = $contact['name'];
2018 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
2019 $datarray['author-link'] = $contact['url'];
2020 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
2021 $datarray['author-avatar'] = $contact['thumb'];
2024 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
2025 logger('consume_feed: no author information! ' . print_r($datarray,true));
2029 // special handling for events
2031 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2032 $ev = bbtoevent($datarray['body']);
2033 if(x($ev,'desc') && x($ev,'start')) {
2034 $ev['uid'] = $importer['uid'];
2035 $ev['uri'] = $item_id;
2036 $ev['edited'] = $datarray['edited'];
2037 $ev['private'] = $datarray['private'];
2039 if(is_array($contact))
2040 $ev['cid'] = $contact['id'];
2041 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2043 intval($importer['uid'])
2046 $ev['id'] = $r[0]['id'];
2047 $xyz = event_store($ev);
2052 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
2053 if(strlen($datarray['title']))
2054 unset($datarray['title']);
2055 $datarray['last-child'] = 1;
2059 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2061 intval($importer['uid'])
2064 // Update content if 'updated' changes
2067 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2069 // do not accept (ignore) an earlier edit than one we currently have.
2070 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2073 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2074 dbesc($datarray['title']),
2075 dbesc($datarray['body']),
2076 dbesc($datarray['tag']),
2077 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2079 intval($importer['uid'])
2083 // update last-child if it changes
2085 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2086 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2087 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2088 intval($allow[0]['data']),
2089 dbesc(datetime_convert()),
2091 intval($importer['uid'])
2097 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
2098 logger('consume-feed: New follower');
2099 new_follower($importer,$contact,$datarray,$item);
2102 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
2103 lose_follower($importer,$contact,$datarray,$item);
2107 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
2108 logger('consume-feed: New friend request');
2109 new_follower($importer,$contact,$datarray,$item,true);
2112 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
2113 lose_sharer($importer,$contact,$datarray,$item);
2118 if(! is_array($contact))
2122 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2123 // one way feed - no remote comment ability
2124 $datarray['last-child'] = 0;
2126 if($contact['network'] === NETWORK_FEED)
2127 $datarray['private'] = 2;
2129 // This is my contact on another system, but it's really me.
2130 // Turn this into a wall post.
2132 if($contact['remote_self']) {
2133 $datarray['wall'] = 1;
2134 if($contact['network'] === NETWORK_FEED) {
2135 $datarray['private'] = 0;
2139 $datarray['parent-uri'] = $item_id;
2140 $datarray['uid'] = $importer['uid'];
2141 $datarray['contact-id'] = $contact['id'];
2143 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2144 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2145 // but otherwise there's a possible data mixup on the sender's system.
2146 // the tgroup delivery code called from item_store will correct it if it's a forum,
2147 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2148 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2149 $datarray['owner-name'] = $contact['name'];
2150 $datarray['owner-link'] = $contact['url'];
2151 $datarray['owner-avatar'] = $contact['thumb'];
2154 // We've allowed "followers" to reach this point so we can decide if they are
2155 // posting an @-tag delivery, which followers are allowed to do for certain
2156 // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it.
2158 if(($contact['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['uid'],$datarray)))
2162 $r = item_store($datarray);
2170 function local_delivery($importer,$data) {
2174 if($importer['readonly']) {
2175 // We aren't receiving stuff from this person. But we will quietly ignore them
2176 // rather than a blatant "go away" message.
2177 logger('local_delivery: ignoring');
2182 // Consume notification feed. This may differ from consuming a public feed in several ways
2183 // - might contain email or friend suggestions
2184 // - might contain remote followup to our message
2185 // - in which case we need to accept it and then notify other conversants
2186 // - we may need to send various email notifications
2188 $feed = new SimplePie();
2189 $feed->set_raw_data($data);
2190 $feed->enable_order_by_date(false);
2195 logger('local_delivery: Error parsing XML: ' . $feed->error());
2198 // Check at the feed level for updated contact name and/or photo
2202 $photo_timestamp = '';
2206 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
2208 // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
2210 // $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
2213 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
2214 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
2215 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
2216 $new_name = $elems['name'][0]['data'];
2218 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
2219 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
2220 $photo_url = $elems['link'][0]['attribs']['']['href'];
2224 if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
2225 logger('local_delivery: Updating photo for ' . $importer['name']);
2226 require_once("Photo.php");
2227 $photo_failure = false;
2228 $have_photo = false;
2230 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
2231 intval($importer['id']),
2232 intval($importer['importer_uid'])
2235 $resource_id = $r[0]['resource-id'];
2239 $resource_id = photo_new_resource();
2242 $img_str = fetch_url($photo_url,true);
2243 // guess mimetype from headers or filename
2244 $type = guess_image_type($photo_url,true);
2247 $img = new Photo($img_str, $type);
2248 if($img->is_valid()) {
2250 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
2251 dbesc($resource_id),
2252 intval($importer['id']),
2253 intval($importer['importer_uid'])
2257 $img->scaleImageSquare(175);
2259 $hash = $resource_id;
2260 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 4);
2262 $img->scaleImage(80);
2263 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 5);
2265 $img->scaleImage(48);
2266 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 6);
2270 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
2271 WHERE `uid` = %d AND `id` = %d LIMIT 1",
2272 dbesc(datetime_convert()),
2273 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
2274 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
2275 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
2276 intval($importer['importer_uid']),
2277 intval($importer['id'])
2282 if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
2283 $r = q("select * from contact where uid = %d and id = %d limit 1",
2284 intval($importer['importer_uid']),
2285 intval($importer['id'])
2288 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2289 dbesc(notags(trim($new_name))),
2290 dbesc(datetime_convert()),
2291 intval($importer['importer_uid']),
2292 intval($importer['id'])
2295 // do our best to update the name on content items
2298 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
2299 dbesc(notags(trim($new_name))),
2300 dbesc($r[0]['name']),
2301 dbesc($r[0]['url']),
2302 intval($importer['importer_uid'])
2309 // Currently unsupported - needs a lot of work
2310 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2311 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2312 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2314 $newloc['uid'] = $importer['importer_uid'];
2315 $newloc['cid'] = $importer['id'];
2316 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2317 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2318 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2319 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2320 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2321 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2322 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2323 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
2324 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2325 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
2328 // merge with current record, current contents have priority
2329 // update record, set url-updated
2330 // update profile photos
2336 // handle friend suggestion notification
2338 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2339 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2340 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2342 $fsugg['uid'] = $importer['importer_uid'];
2343 $fsugg['cid'] = $importer['id'];
2344 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2345 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2346 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2347 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2348 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2350 // Does our member already have a friend matching this description?
2352 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2353 dbesc($fsugg['name']),
2354 dbesc(normalise_link($fsugg['url'])),
2355 intval($fsugg['uid'])
2360 // Do we already have an fcontact record for this person?
2363 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2364 dbesc($fsugg['url']),
2365 dbesc($fsugg['name']),
2366 dbesc($fsugg['request'])
2371 // OK, we do. Do we already have an introduction for this person ?
2372 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2373 intval($fsugg['uid']),
2380 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2381 dbesc($fsugg['name']),
2382 dbesc($fsugg['url']),
2383 dbesc($fsugg['photo']),
2384 dbesc($fsugg['request'])
2386 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2387 dbesc($fsugg['url']),
2388 dbesc($fsugg['name']),
2389 dbesc($fsugg['request'])
2394 // database record did not get created. Quietly give up.
2399 $hash = random_string();
2401 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2402 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2403 intval($fsugg['uid']),
2405 intval($fsugg['cid']),
2406 dbesc($fsugg['body']),
2408 dbesc(datetime_convert()),
2413 'type' => NOTIFY_SUGGEST,
2414 'notify_flags' => $importer['notify-flags'],
2415 'language' => $importer['language'],
2416 'to_name' => $importer['username'],
2417 'to_email' => $importer['email'],
2418 'uid' => $importer['importer_uid'],
2420 'link' => $a->get_baseurl() . '/notifications/intros',
2421 'source_name' => $importer['name'],
2422 'source_link' => $importer['url'],
2423 'source_photo' => $importer['photo'],
2424 'verb' => ACTIVITY_REQ_FRIEND,
2433 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2434 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2436 logger('local_delivery: private message received');
2439 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2442 $msg['uid'] = $importer['importer_uid'];
2443 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2444 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2445 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2446 $msg['contact-id'] = $importer['id'];
2447 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2448 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2450 $msg['replied'] = 0;
2451 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2452 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2453 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2457 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2458 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2460 // send notifications.
2462 require_once('include/enotify.php');
2464 $notif_params = array(
2465 'type' => NOTIFY_MAIL,
2466 'notify_flags' => $importer['notify-flags'],
2467 'language' => $importer['language'],
2468 'to_name' => $importer['username'],
2469 'to_email' => $importer['email'],
2470 'uid' => $importer['importer_uid'],
2472 'source_name' => $msg['from-name'],
2473 'source_link' => $importer['url'],
2474 'source_photo' => $importer['thumb'],
2475 'verb' => ACTIVITY_POST,
2479 notification($notif_params);
2485 $community_page = 0;
2486 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2488 $community_page = intval($rawtags[0]['data']);
2490 if(intval($importer['forum']) != $community_page) {
2491 q("update contact set forum = %d where id = %d limit 1",
2492 intval($community_page),
2493 intval($importer['id'])
2495 $importer['forum'] = (string) $community_page;
2498 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2500 // process any deleted entries
2502 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2503 if(is_array($del_entries) && count($del_entries)) {
2504 foreach($del_entries as $dentry) {
2506 if(isset($dentry['attribs']['']['ref'])) {
2507 $uri = $dentry['attribs']['']['ref'];
2509 if(isset($dentry['attribs']['']['when'])) {
2510 $when = $dentry['attribs']['']['when'];
2511 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2514 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2518 // check for relayed deletes to our conversation
2521 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2523 intval($importer['importer_uid'])
2526 $parent_uri = $r[0]['parent-uri'];
2527 if($r[0]['id'] != $r[0]['parent'])
2534 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2537 logger('local_delivery: possible community delete');
2540 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2542 // was the top-level post for this reply written by somebody on this site?
2543 // Specifically, the recipient?
2545 $is_a_remote_delete = false;
2547 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2548 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2549 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2550 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2551 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2552 AND `item`.`uid` = %d
2558 intval($importer['importer_uid'])
2561 $is_a_remote_delete = true;
2563 // Does this have the characteristics of a community or private group comment?
2564 // If it's a reply to a wall post on a community/prvgroup page it's a
2565 // valid community comment. Also forum_mode makes it valid for sure.
2566 // If neither, it's not.
2568 if($is_a_remote_delete && $community) {
2569 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2570 $is_a_remote_delete = false;
2571 logger('local_delivery: not a community delete');
2575 if($is_a_remote_delete) {
2576 logger('local_delivery: received remote delete');
2580 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2581 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2583 intval($importer['importer_uid']),
2584 intval($importer['id'])
2590 if($item['deleted'])
2593 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2595 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2596 $xo = parse_xml_string($item['object'],false);
2597 $xt = parse_xml_string($item['target'],false);
2599 if($xt->type === ACTIVITY_OBJ_NOTE) {
2600 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2602 intval($importer['importer_uid'])
2606 // For tags, the owner cannot remove the tag on the author's copy of the post.
2608 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2609 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2610 $author_copy = (($item['origin']) ? true : false);
2612 if($owner_remove && $author_copy)
2614 if($author_remove || $owner_remove) {
2615 $tags = explode(',',$i[0]['tag']);
2618 foreach($tags as $tag)
2619 if(trim($tag) !== trim($xo->body))
2620 $newtags[] = trim($tag);
2622 q("update item set tag = '%s' where id = %d limit 1",
2623 dbesc(implode(',',$newtags)),
2631 if($item['uri'] == $item['parent-uri']) {
2632 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2633 `body` = '', `title` = ''
2634 WHERE `parent-uri` = '%s' AND `uid` = %d",
2636 dbesc(datetime_convert()),
2637 dbesc($item['uri']),
2638 intval($importer['importer_uid'])
2642 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2643 `body` = '', `title` = ''
2644 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2646 dbesc(datetime_convert()),
2648 intval($importer['importer_uid'])
2650 if($item['last-child']) {
2651 // ensure that last-child is set in case the comment that had it just got wiped.
2652 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2653 dbesc(datetime_convert()),
2654 dbesc($item['parent-uri']),
2655 intval($item['uid'])
2657 // who is the last child now?
2658 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2659 ORDER BY `created` DESC LIMIT 1",
2660 dbesc($item['parent-uri']),
2661 intval($importer['importer_uid'])
2664 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2669 // if this is a relayed delete, propagate it to other recipients
2671 if($is_a_remote_delete)
2672 proc_run('php',"include/notifier.php","drop",$item['id']);
2680 foreach($feed->get_items() as $item) {
2683 $item_id = $item->get_id();
2684 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2685 if(isset($rawthread[0]['attribs']['']['ref'])) {
2687 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2693 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2696 logger('local_delivery: possible community reply');
2699 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2701 // was the top-level post for this reply written by somebody on this site?
2702 // Specifically, the recipient?
2704 $is_a_remote_comment = false;
2705 $top_uri = $parent_uri;
2707 $r = q("select `item`.`parent-uri` from `item`
2708 WHERE `item`.`uri` = '%s'
2712 if($r && count($r)) {
2713 $top_uri = $r[0]['parent-uri'];
2715 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2716 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2717 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2718 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2719 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2720 AND `item`.`uid` = %d
2726 intval($importer['importer_uid'])
2729 $is_a_remote_comment = true;
2732 // Does this have the characteristics of a community or private group comment?
2733 // If it's a reply to a wall post on a community/prvgroup page it's a
2734 // valid community comment. Also forum_mode makes it valid for sure.
2735 // If neither, it's not.
2737 if($is_a_remote_comment && $community) {
2738 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2739 $is_a_remote_comment = false;
2740 logger('local_delivery: not a community reply');
2744 if($is_a_remote_comment) {
2745 logger('local_delivery: received remote comment');
2747 // remote reply to our post. Import and then notify everybody else.
2749 $datarray = get_atom_elements($feed,$item);
2751 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2753 intval($importer['importer_uid'])
2756 // Update content if 'updated' changes
2760 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2762 // do not accept (ignore) an earlier edit than one we currently have.
2763 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2766 logger('received updated comment' , LOGGER_DEBUG);
2767 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2768 dbesc($datarray['title']),
2769 dbesc($datarray['body']),
2770 dbesc($datarray['tag']),
2771 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2773 intval($importer['importer_uid'])
2776 proc_run('php',"include/notifier.php","comment-import",$iid);
2785 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2786 intval($importer['importer_uid'])
2790 $datarray['type'] = 'remote-comment';
2791 $datarray['wall'] = 1;
2792 $datarray['parent-uri'] = $parent_uri;
2793 $datarray['uid'] = $importer['importer_uid'];
2794 $datarray['owner-name'] = $own[0]['name'];
2795 $datarray['owner-link'] = $own[0]['url'];
2796 $datarray['owner-avatar'] = $own[0]['thumb'];
2797 $datarray['contact-id'] = $importer['id'];
2799 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2801 $datarray['type'] = 'activity';
2802 $datarray['gravity'] = GRAVITY_LIKE;
2803 $datarray['last-child'] = 0;
2804 // only one like or dislike per person
2805 $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",
2806 intval($datarray['uid']),
2807 intval($datarray['contact-id']),
2808 dbesc($datarray['verb']),
2809 dbesc($datarray['parent-uri']),
2810 dbesc($datarray['parent-uri'])
2817 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2819 $xo = parse_xml_string($datarray['object'],false);
2820 $xt = parse_xml_string($datarray['target'],false);
2822 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2824 // fetch the parent item
2826 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2828 intval($importer['importer_uid'])
2833 // extract tag, if not duplicate, and this user allows tags, add to parent item
2835 if($xo->id && $xo->content) {
2836 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2837 if(! (stristr($tagp[0]['tag'],$newtag))) {
2838 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2839 intval($importer['importer_uid'])
2841 if(count($i) && ! intval($i[0]['blocktags'])) {
2842 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2843 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2844 intval($tagp[0]['id']),
2845 dbesc(datetime_convert())
2854 $posted_id = item_store($datarray);
2858 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2860 intval($importer['importer_uid'])
2863 $parent = $r[0]['parent'];
2864 $parent_uri = $r[0]['parent-uri'];
2868 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2869 dbesc(datetime_convert()),
2870 intval($importer['importer_uid']),
2871 intval($r[0]['parent'])
2874 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2875 dbesc(datetime_convert()),
2876 intval($importer['importer_uid']),
2881 if($posted_id && $parent) {
2883 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2885 if((! $is_like) && (! $importer['self'])) {
2887 require_once('include/enotify.php');
2890 'type' => NOTIFY_COMMENT,
2891 'notify_flags' => $importer['notify-flags'],
2892 'language' => $importer['language'],
2893 'to_name' => $importer['username'],
2894 'to_email' => $importer['email'],
2895 'uid' => $importer['importer_uid'],
2896 'item' => $datarray,
2897 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2898 'source_name' => stripslashes($datarray['author-name']),
2899 'source_link' => $datarray['author-link'],
2900 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2901 ? $importer['thumb'] : $datarray['author-avatar']),
2902 'verb' => ACTIVITY_POST,
2904 'parent' => $parent,
2905 'parent_uri' => $parent_uri,
2917 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2919 $item_id = $item->get_id();
2920 $datarray = get_atom_elements($feed,$item);
2922 if($importer['rel'] == CONTACT_IS_FOLLOWER)
2925 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2927 intval($importer['importer_uid'])
2930 // Update content if 'updated' changes
2933 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2935 // do not accept (ignore) an earlier edit than one we currently have.
2936 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2939 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2940 dbesc($datarray['title']),
2941 dbesc($datarray['body']),
2942 dbesc($datarray['tag']),
2943 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2945 intval($importer['importer_uid'])
2949 // update last-child if it changes
2951 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2952 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2953 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2954 dbesc(datetime_convert()),
2956 intval($importer['importer_uid'])
2958 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2959 intval($allow[0]['data']),
2960 dbesc(datetime_convert()),
2962 intval($importer['importer_uid'])
2968 $datarray['parent-uri'] = $parent_uri;
2969 $datarray['uid'] = $importer['importer_uid'];
2970 $datarray['contact-id'] = $importer['id'];
2971 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2972 $datarray['type'] = 'activity';
2973 $datarray['gravity'] = GRAVITY_LIKE;
2974 // only one like or dislike per person
2975 $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",
2976 intval($datarray['uid']),
2977 intval($datarray['contact-id']),
2978 dbesc($datarray['verb']),
2987 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2989 $xo = parse_xml_string($datarray['object'],false);
2990 $xt = parse_xml_string($datarray['target'],false);
2992 if($xt->type == ACTIVITY_OBJ_NOTE) {
2993 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2995 intval($importer['importer_uid'])
3000 // extract tag, if not duplicate, add to parent item
3002 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
3003 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
3004 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
3012 $posted_id = item_store($datarray);
3014 // find out if our user is involved in this conversation and wants to be notified.
3016 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
3018 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
3020 intval($importer['importer_uid'])
3023 if(count($myconv)) {
3024 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
3026 // first make sure this isn't our own post coming back to us from a wall-to-wall event
3027 if(! link_compare($datarray['author-link'],$importer_url)) {
3030 foreach($myconv as $conv) {
3032 // now if we find a match, it means we're in this conversation
3034 if(! link_compare($conv['author-link'],$importer_url))
3037 require_once('include/enotify.php');
3039 $conv_parent = $conv['parent'];
3042 'type' => NOTIFY_COMMENT,
3043 'notify_flags' => $importer['notify-flags'],
3044 'language' => $importer['language'],
3045 'to_name' => $importer['username'],
3046 'to_email' => $importer['email'],
3047 'uid' => $importer['importer_uid'],
3048 'item' => $datarray,
3049 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3050 'source_name' => stripslashes($datarray['author-name']),
3051 'source_link' => $datarray['author-link'],
3052 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3053 ? $importer['thumb'] : $datarray['author-avatar']),
3054 'verb' => ACTIVITY_POST,
3056 'parent' => $conv_parent,
3057 'parent_uri' => $parent_uri
3061 // only send one notification
3073 // Head post of a conversation. Have we seen it? If not, import it.
3076 $item_id = $item->get_id();
3077 $datarray = get_atom_elements($feed,$item);
3079 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
3080 $ev = bbtoevent($datarray['body']);
3081 if(x($ev,'desc') && x($ev,'start')) {
3082 $ev['cid'] = $importer['id'];
3083 $ev['uid'] = $importer['uid'];
3084 $ev['uri'] = $item_id;
3085 $ev['edited'] = $datarray['edited'];
3086 $ev['private'] = $datarray['private'];
3088 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3090 intval($importer['uid'])
3093 $ev['id'] = $r[0]['id'];
3094 $xyz = event_store($ev);
3099 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3101 intval($importer['importer_uid'])
3104 // Update content if 'updated' changes
3107 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
3109 // do not accept (ignore) an earlier edit than one we currently have.
3110 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3113 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3114 dbesc($datarray['title']),
3115 dbesc($datarray['body']),
3116 dbesc($datarray['tag']),
3117 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3119 intval($importer['importer_uid'])
3123 // update last-child if it changes
3125 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3126 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
3127 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3128 intval($allow[0]['data']),
3129 dbesc(datetime_convert()),
3131 intval($importer['importer_uid'])
3137 // This is my contact on another system, but it's really me.
3138 // Turn this into a wall post.
3140 if($importer['remote_self'])
3141 $datarray['wall'] = 1;
3143 $datarray['parent-uri'] = $item_id;
3144 $datarray['uid'] = $importer['importer_uid'];
3145 $datarray['contact-id'] = $importer['id'];
3148 if(! link_compare($datarray['owner-link'],$importer['url'])) {
3149 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
3150 // but otherwise there's a possible data mixup on the sender's system.
3151 // the tgroup delivery code called from item_store will correct it if it's a forum,
3152 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
3153 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
3154 $datarray['owner-name'] = $importer['senderName'];
3155 $datarray['owner-link'] = $importer['url'];
3156 $datarray['owner-avatar'] = $importer['thumb'];
3159 if(($importer['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['importer_uid'],$datarray)))
3162 $posted_id = item_store($datarray);
3164 if(stristr($datarray['verb'],ACTIVITY_POKE)) {
3165 $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
3168 $xo = parse_xml_string($datarray['object'],false);
3170 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
3172 // somebody was poked/prodded. Was it me?
3174 $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
3176 foreach($links->link as $l) {
3177 $atts = $l->attributes();
3178 switch($atts['rel']) {
3180 $Blink = $atts['href'];
3186 if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
3188 // send a notification
3189 require_once('include/enotify.php');
3192 'type' => NOTIFY_POKE,
3193 'notify_flags' => $importer['notify-flags'],
3194 'language' => $importer['language'],
3195 'to_name' => $importer['username'],
3196 'to_email' => $importer['email'],
3197 'uid' => $importer['importer_uid'],
3198 'item' => $datarray,
3199 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3200 'source_name' => stripslashes($datarray['author-name']),
3201 'source_link' => $datarray['author-link'],
3202 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3203 ? $importer['thumb'] : $datarray['author-avatar']),
3204 'verb' => $datarray['verb'],
3205 'otype' => 'person',
3206 'activity' => $verb,
3223 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
3224 $url = notags(trim($datarray['author-link']));
3225 $name = notags(trim($datarray['author-name']));
3226 $photo = notags(trim($datarray['author-avatar']));
3228 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
3229 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
3230 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
3232 if(is_array($contact)) {
3233 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
3234 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
3235 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
3236 intval(CONTACT_IS_FRIEND),
3237 intval($contact['id']),
3238 intval($importer['uid'])
3241 // send email notification to owner?
3245 // create contact record
3247 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
3248 `blocked`, `readonly`, `pending`, `writable` )
3249 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
3250 intval($importer['uid']),
3251 dbesc(datetime_convert()),
3253 dbesc(normalise_link($url)),
3257 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
3258 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
3260 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
3261 intval($importer['uid']),
3265 $contact_record = $r[0];
3267 // create notification
3268 $hash = random_string();
3270 if(is_array($contact_record)) {
3271 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
3272 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
3273 intval($importer['uid']),
3274 intval($contact_record['id']),
3276 dbesc(datetime_convert())
3279 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3280 intval($importer['uid'])
3285 if(intval($r[0]['def_gid'])) {
3286 require_once('include/group.php');
3287 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
3290 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
3291 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
3292 $email = replace_macros($email_tpl, array(
3293 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
3295 '$myname' => $r[0]['username'],
3296 '$siteurl' => $a->get_baseurl(),
3297 '$sitename' => $a->config['sitename']
3299 $res = mail($r[0]['email'],
3300 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
3302 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
3303 . 'Content-type: text/plain; charset=UTF-8' . "\n"
3304 . 'Content-transfer-encoding: 8bit' );
3311 function lose_follower($importer,$contact,$datarray,$item) {
3313 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
3314 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3315 intval(CONTACT_IS_SHARING),
3316 intval($contact['id'])
3320 contact_remove($contact['id']);
3324 function lose_sharer($importer,$contact,$datarray,$item) {
3326 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3327 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3328 intval(CONTACT_IS_FOLLOWER),
3329 intval($contact['id'])
3333 contact_remove($contact['id']);
3338 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3342 if(is_array($importer)) {
3343 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3344 intval($importer['uid'])
3348 // Diaspora has different message-ids in feeds than they do
3349 // through the direct Diaspora protocol. If we try and use
3350 // the feed, we'll get duplicates. So don't.
3352 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3355 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3357 // Use a single verify token, even if multiple hubs
3359 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3361 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3363 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
3365 if(! strlen($contact['hub-verify'])) {
3366 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3367 dbesc($verify_token),
3368 intval($contact['id'])
3372 post_url($url,$params);
3374 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3381 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3385 $name = xmlify($name);
3386 $uri = xmlify($uri);
3389 $photo = xmlify($photo);
3393 $o .= "<name>$name</name>\r\n";
3394 $o .= "<uri>$uri</uri>\r\n";
3395 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3396 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3398 call_hooks('atom_author', $o);
3400 $o .= "</$tag>\r\n";
3404 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3408 if(! $item['parent'])
3411 if($item['deleted'])
3412 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3415 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3416 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3418 $body = $item['body'];
3420 $o = "\r\n\r\n<entry>\r\n";
3422 if(is_array($author))
3423 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3425 $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']));
3426 if(strlen($item['owner-name']))
3427 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3429 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
3430 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3431 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3434 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3435 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3436 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3437 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3438 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3439 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3440 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3442 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3444 if($item['location']) {
3445 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3446 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3450 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3452 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3453 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3456 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3457 if($item['bookmark'])
3458 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3461 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3464 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3466 if($item['signed_text']) {
3467 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3468 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3471 $verb = construct_verb($item);
3472 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3473 $actobj = construct_activity_object($item);
3476 $actarg = construct_activity_target($item);
3480 $tags = item_getfeedtags($item);
3482 foreach($tags as $t) {
3483 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3487 $o .= item_getfeedattach($item);
3489 $mentioned = get_mentions($item);
3493 call_hooks('atom_entry', $o);
3495 $o .= '</entry>' . "\r\n";
3500 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3503 logger('fix_private_photos', LOGGER_DEBUG);
3504 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3509 $img_start = strpos($orig_body, '[img');
3510 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3511 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3512 while( ($img_st_close !== false) && ($img_len !== false) ) {
3514 $img_st_close++; // make it point to AFTER the closing bracket
3515 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3517 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3520 if(stristr($image , $site . '/photo/')) {
3521 // Only embed locally hosted photos
3523 $i = basename($image);
3524 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3525 $x = strpos($i,'-');
3528 $res = substr($i,$x+1);
3529 $i = substr($i,0,$x);
3530 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3537 // Check to see if we should replace this photo link with an embedded image
3538 // 1. No need to do so if the photo is public
3539 // 2. If there's a contact-id provided, see if they're in the access list
3540 // for the photo. If so, embed it.
3541 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3542 // permissions, regardless of order but first check to see if they're an exact
3543 // match to save some processing overhead.
3545 if(has_permissions($r[0])) {
3547 $recips = enumerate_permissions($r[0]);
3548 if(in_array($cid, $recips)) {
3553 if(compare_permissions($item,$r[0]))
3558 $data = $r[0]['data'];
3559 $type = $r[0]['type'];
3561 // If a custom width and height were specified, apply before embedding
3562 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3563 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3565 $width = intval($match[1]);
3566 $height = intval($match[2]);
3568 $ph = new Photo($data, $type);
3569 if($ph->is_valid()) {
3570 $ph->scaleImage(max($width, $height));
3571 $data = $ph->imageString();
3572 $type = $ph->getType();
3576 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3577 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3578 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3584 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3585 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3586 if($orig_body === false)
3589 $img_start = strpos($orig_body, '[img');
3590 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3591 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3594 $new_body = $new_body . $orig_body;
3600 function has_permissions($obj) {
3601 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3606 function compare_permissions($obj1,$obj2) {
3607 // first part is easy. Check that these are exactly the same.
3608 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3609 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3610 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3611 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3614 // This is harder. Parse all the permissions and compare the resulting set.
3616 $recipients1 = enumerate_permissions($obj1);
3617 $recipients2 = enumerate_permissions($obj2);
3620 if($recipients1 == $recipients2)
3625 // returns an array of contact-ids that are allowed to see this object
3627 function enumerate_permissions($obj) {
3628 require_once('include/group.php');
3629 $allow_people = expand_acl($obj['allow_cid']);
3630 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3631 $deny_people = expand_acl($obj['deny_cid']);
3632 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3633 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3634 $deny = array_unique(array_merge($deny_people,$deny_groups));
3635 $recipients = array_diff($recipients,$deny);
3639 function item_getfeedtags($item) {
3642 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3644 for($x = 0; $x < $cnt; $x ++) {
3646 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3650 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3652 for($x = 0; $x < $cnt; $x ++) {
3654 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3660 function item_getfeedattach($item) {
3662 $arr = explode(',',$item['attach']);
3664 foreach($arr as $r) {
3666 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3668 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3669 if(intval($matches[2]))
3670 $ret .= 'length="' . intval($matches[2]) . '" ';
3671 if($matches[4] !== ' ')
3672 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3673 $ret .= ' />' . "\r\n";
3682 function item_expire($uid,$days) {
3684 if((! $uid) || ($days < 1))
3687 // $expire_network_only = save your own wall posts
3688 // and just expire conversations started by others
3690 $expire_network_only = get_pconfig($uid,'expire','network_only');
3691 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3693 $r = q("SELECT * FROM `item`
3695 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3706 $expire_items = get_pconfig($uid, 'expire','items');
3707 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3709 $expire_notes = get_pconfig($uid, 'expire','notes');
3710 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3712 $expire_starred = get_pconfig($uid, 'expire','starred');
3713 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3715 $expire_photos = get_pconfig($uid, 'expire','photos');
3716 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3718 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3720 foreach($r as $item) {
3722 // don't expire filed items
3724 if(strpos($item['file'],'[') !== false)
3727 // Only expire posts, not photos and photo comments
3729 if($expire_photos==0 && strlen($item['resource-id']))
3731 if($expire_starred==0 && intval($item['starred']))
3733 if($expire_notes==0 && $item['type']=='note')
3735 if($expire_items==0 && $item['type']!='note')
3738 drop_item($item['id'],false);
3741 proc_run('php',"include/notifier.php","expire","$uid");
3746 function drop_items($items) {
3749 if(! local_user() && ! remote_user())
3753 foreach($items as $item) {
3754 $owner = drop_item($item,false);
3755 if($owner && ! $uid)
3760 // multiple threads may have been deleted, send an expire notification
3763 proc_run('php',"include/notifier.php","expire","$uid");
3767 function drop_item($id,$interactive = true) {
3771 // locate item to be deleted
3773 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3780 notice( t('Item not found.') . EOL);
3781 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3786 $owner = $item['uid'];
3790 // check if logged in user is either the author or owner of this item
3792 if(is_array($_SESSION['remote'])) {
3793 foreach($_SESSION['remote'] as $visitor) {
3794 if($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
3795 $cid = $visitor['cid'];
3802 if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
3804 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
3807 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3808 dbesc(datetime_convert()),
3809 dbesc(datetime_convert()),
3813 // clean up categories and tags so they don't end up as orphans
3816 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3818 foreach($matches as $mtch) {
3819 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3825 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3827 foreach($matches as $mtch) {
3828 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3832 // If item is a link to a photo resource, nuke all the associated photos
3833 // (visitors will not have photo resources)
3834 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3835 // generate a resource-id and therefore aren't intimately linked to the item.
3837 if(strlen($item['resource-id'])) {
3838 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3839 dbesc($item['resource-id']),
3840 intval($item['uid'])
3842 // ignore the result
3845 // If item is a link to an event, nuke the event record.
3847 if(intval($item['event-id'])) {
3848 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3849 intval($item['event-id']),
3850 intval($item['uid'])
3852 // ignore the result
3855 // clean up item_id and sign meta-data tables
3857 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3858 intval($item['id']),
3859 intval($item['uid'])
3862 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3863 intval($item['id']),
3864 intval($item['uid'])
3867 // If it's the parent of a comment thread, kill all the kids
3869 if($item['uri'] == $item['parent-uri']) {
3870 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3871 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3872 dbesc(datetime_convert()),
3873 dbesc(datetime_convert()),
3874 dbesc($item['parent-uri']),
3875 intval($item['uid'])
3877 // ignore the result
3880 // ensure that last-child is set in case the comment that had it just got wiped.
3881 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3882 dbesc(datetime_convert()),
3883 dbesc($item['parent-uri']),
3884 intval($item['uid'])
3886 // who is the last child now?
3887 $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",
3888 dbesc($item['parent-uri']),
3889 intval($item['uid'])
3892 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3897 // Add a relayable_retraction signature for Diaspora.
3898 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
3900 $drop_id = intval($item['id']);
3902 // send the notification upstream/downstream as the case may be
3907 proc_run('php',"include/notifier.php","drop","$drop_id");
3908 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3914 notice( t('Permission denied.') . EOL);
3915 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3922 function first_post_date($uid,$wall = false) {
3923 $r = q("select id, created from item
3924 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3926 order by created asc limit 1",
3928 intval($wall ? 1 : 0)
3931 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3932 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3937 function posted_dates($uid,$wall) {
3938 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3940 $dthen = first_post_date($uid,$wall);
3944 // If it's near the end of a long month, backup to the 28th so that in
3945 // consecutive loops we'll always get a whole month difference.
3947 if(intval(substr($dnow,8)) > 28)
3948 $dnow = substr($dnow,0,8) . '28';
3949 if(intval(substr($dthen,8)) > 28)
3950 $dnow = substr($dthen,0,8) . '28';
3953 // Starting with the current month, get the first and last days of every
3954 // month down to and including the month of the first post
3955 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
3956 $dstart = substr($dnow,0,8) . '01';
3957 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3958 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3959 $end_month = datetime_convert('','',$dend,'Y-m-d');
3960 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3961 $ret[] = array($str,$end_month,$start_month);
3962 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3968 function posted_date_widget($url,$uid,$wall) {
3971 // For former Facebook folks that left because of "timeline"
3973 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3976 $ret = posted_dates($uid,$wall);
3980 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3981 '$title' => t('Archives'),
3982 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3989 function store_diaspora_retract_sig($item, $user, $baseurl) {
3990 // Note that we can't add a target_author_signature
3991 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3992 // the comment, that means we're the home of the post, and Diaspora will only
3993 // check the parent_author_signature of retractions that it doesn't have to relay further
3995 // I don't think this function gets called for an "unlike," but I'll check anyway
3997 $enabled = intval(get_config('system','diaspora_enabled'));
3999 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
4003 logger('drop_item: storing diaspora retraction signature');
4005 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
4007 if(local_user() == $item['uid']) {
4009 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
4010 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
4013 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
4014 $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
4017 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
4018 // only handles DFRN deletes
4019 $handle_baseurl_start = strpos($r['url'],'://') + 3;
4020 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
4021 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
4027 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
4028 intval($item['id']),
4029 dbesc($signed_text),