3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
7 require_once('include/Photo.php');
10 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
13 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
14 $public_feed = (($dfrn_id) ? false : true);
15 $starred = false; // not yet implemented, possible security issues
18 if($public_feed && $a->argc > 2) {
19 for($x = 2; $x < $a->argc; $x++) {
20 if($a->argv[$x] == 'converse')
22 if($a->argv[$x] == 'starred')
24 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
25 $category = $a->argv[$x+1];
31 // default permissions - anonymous user
33 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
35 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
36 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
37 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
45 $owner_id = $owner['user_uid'];
46 $owner_nick = $owner['nickname'];
48 $birthday = feed_birthday($owner_id,$owner['timezone']);
55 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
59 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60 $my_id = '1:' . $dfrn_id;
63 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
64 $my_id = '0:' . $dfrn_id;
71 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
79 $groups = init_groups_visitor($contact['id']);
82 for($x = 0; $x < count($groups); $x ++)
83 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
84 $gs = implode('|', $groups);
87 $gs = '<<>>' ; // Impossible to match
89 $sql_extra = sprintf("
90 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
91 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
92 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
93 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
95 intval($contact['id']),
96 intval($contact['id']),
107 if(! strlen($last_update))
108 $last_update = 'now -30 days';
110 if(isset($category)) {
111 $sql_extra .= file_tag_file_query('item',$category,'category');
116 $sql_extra .= " AND `contact`.`self` = 1 ";
119 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
121 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
122 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
123 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
124 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
125 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
126 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
127 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
128 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
129 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
130 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
131 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
133 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
140 // Will check further below if this actually returned results.
141 // We will provide an empty feed if that is the case.
145 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
149 $hubxml = feed_hublinks();
151 $salmon = feed_salmonlinks($owner_nick);
153 $atom .= replace_macros($feed_template, array(
154 '$version' => xmlify(FRIENDICA_VERSION),
155 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
156 '$feed_title' => xmlify($owner['name']),
157 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
159 '$salmon' => $salmon,
160 '$name' => xmlify($owner['name']),
161 '$profile_page' => xmlify($owner['url']),
162 '$photo' => xmlify($owner['photo']),
163 '$thumb' => xmlify($owner['thumb']),
164 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
165 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
166 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
167 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
168 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
171 call_hooks('atom_feed', $atom);
173 if(! count($items)) {
175 call_hooks('atom_feed_end', $atom);
177 $atom .= '</feed>' . "\r\n";
181 foreach($items as $item) {
183 // prevent private email from leaking.
184 if($item['network'] === NETWORK_MAIL)
187 // public feeds get html, our own nodes use bbcode
191 // catch any email that's in a public conversation and make sure it doesn't leak
199 $atom .= atom_entry($item,$type,null,$owner,true);
202 call_hooks('atom_feed_end', $atom);
204 $atom .= '</feed>' . "\r\n";
210 function construct_verb($item) {
212 return $item['verb'];
213 return ACTIVITY_POST;
216 function construct_activity_object($item) {
218 if($item['object']) {
219 $o = '<as:object>' . "\r\n";
220 $r = parse_xml_string($item['object'],false);
226 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
228 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
230 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
232 if(substr($r->link,0,1) === '<') {
233 // patch up some facebook "like" activity objects that got stored incorrectly
234 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
235 // we can probably remove this hack here and in the following function in a few months time.
236 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
237 $r->link = str_replace('&','&', $r->link);
238 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
242 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
245 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
246 $o .= '</as:object>' . "\r\n";
253 function construct_activity_target($item) {
255 if($item['target']) {
256 $o = '<as:target>' . "\r\n";
257 $r = parse_xml_string($item['target'],false);
261 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
263 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
265 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
267 if(substr($r->link,0,1) === '<') {
268 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
269 $r->link = str_replace('&','&', $r->link);
270 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
274 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
277 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
278 $o .= '</as:target>' . "\r\n";
287 * The purpose of this function is to apply system message length limits to
288 * imported messages without including any embedded photos in the length
290 if(! function_exists('limit_body_size')) {
291 function limit_body_size($body) {
293 logger('limit_body_size: start', LOGGER_DEBUG);
295 $maxlen = get_max_import_size();
297 // If the length of the body, including the embedded images, is smaller
298 // than the maximum, then don't waste time looking for the images
299 if($maxlen && (strlen($body) > $maxlen)) {
301 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
308 $img_start = strpos($orig_body, '[img');
309 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
310 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
311 while(($img_st_close !== false) && ($img_end !== false)) {
313 $img_st_close++; // make it point to AFTER the closing bracket
314 $img_end += $img_start;
315 $img_end += strlen('[/img]');
317 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
318 // This is an embedded image
320 if( ($textlen + $img_start) > $maxlen ) {
321 if($textlen < $maxlen) {
322 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
323 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
328 $new_body = $new_body . substr($orig_body, 0, $img_start);
329 $textlen += $img_start;
332 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
336 if( ($textlen + $img_end) > $maxlen ) {
337 if($textlen < $maxlen) {
338 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
339 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
344 $new_body = $new_body . substr($orig_body, 0, $img_end);
345 $textlen += $img_end;
348 $orig_body = substr($orig_body, $img_end);
350 if($orig_body === false) // in case the body ends on a closing image tag
353 $img_start = strpos($orig_body, '[img');
354 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
355 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
358 if( ($textlen + strlen($orig_body)) > $maxlen) {
359 if($textlen < $maxlen) {
360 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
361 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
366 logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
367 $new_body = $new_body . $orig_body;
368 $textlen += strlen($orig_body);
377 function title_is_body($title, $body) {
379 $title = strip_tags($title);
380 $title = trim($title);
381 $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
383 $body = strip_tags($body);
385 $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
387 if (strlen($title) < strlen($body))
388 $body = substr($body, 0, strlen($title));
390 if (($title != $body) and (substr($title, -3) == "...")) {
391 $pos = strrpos($title, "...");
393 $title = substr($title, 0, $pos);
394 $body = substr($body, 0, $pos);
398 return($title == $body);
403 function get_atom_elements($feed,$item) {
405 require_once('library/HTMLPurifier.auto.php');
406 require_once('include/html2bbcode.php');
408 $best_photo = array();
412 $author = $item->get_author();
414 $res['author-name'] = unxmlify($author->get_name());
415 $res['author-link'] = unxmlify($author->get_link());
418 $res['author-name'] = unxmlify($feed->get_title());
419 $res['author-link'] = unxmlify($feed->get_permalink());
421 $res['uri'] = unxmlify($item->get_id());
422 $res['title'] = unxmlify($item->get_title());
423 $res['body'] = unxmlify($item->get_content());
424 $res['plink'] = unxmlify($item->get_link(0));
426 // removing the content of the title if its identically to the body
427 // This helps with auto generated titles e.g. from tumblr
428 if (title_is_body($res["title"], $res["body"]))
432 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
436 // look for a photo. We should check media size and find the best one,
437 // but for now let's just find any author photo
439 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
441 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
442 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
443 foreach($base as $link) {
444 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
445 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
446 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
451 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
453 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
454 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
455 if($base && count($base)) {
456 foreach($base as $link) {
457 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
458 $res['author-link'] = unxmlify($link['attribs']['']['href']);
459 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
460 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
461 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
467 // No photo/profile-link on the item - look at the feed level
469 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
470 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
471 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
472 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
473 foreach($base as $link) {
474 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
475 $res['author-link'] = unxmlify($link['attribs']['']['href']);
476 if(! $res['author-avatar']) {
477 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
478 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
483 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
485 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
486 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
488 if($base && count($base)) {
489 foreach($base as $link) {
490 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
491 $res['author-link'] = unxmlify($link['attribs']['']['href']);
492 if(! (x($res,'author-avatar'))) {
493 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
494 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
501 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
502 if($apps && $apps[0]['attribs']['']['source']) {
503 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
504 if($res['app'] === 'web')
505 $res['app'] = 'OStatus';
508 // base64 encoded json structure representing Diaspora signature
510 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
512 $res['dsprsig'] = unxmlify($dsig[0]['data']);
515 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
517 $res['guid'] = unxmlify($dguid[0]['data']);
519 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
521 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
525 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
528 $have_real_body = false;
530 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
532 $have_real_body = true;
533 $res['body'] = $rawenv[0]['data'];
534 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
535 // make sure nobody is trying to sneak some html tags by us
536 $res['body'] = notags(base64url_decode($res['body']));
540 $res['body'] = limit_body_size($res['body']);
542 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
543 // the content type. Our own network only emits text normally, though it might have been converted to
544 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
545 // have to assume it is all html and needs to be purified.
547 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
548 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
549 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
552 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
554 $res['body'] = reltoabs($res['body'],$base_url);
556 $res['body'] = html2bb_video($res['body']);
558 $res['body'] = oembed_html2bbcode($res['body']);
560 $config = HTMLPurifier_Config::createDefault();
561 $config->set('Cache.DefinitionImpl', null);
563 // we shouldn't need a whitelist, because the bbcode converter
564 // will strip out any unsupported tags.
566 $purifier = new HTMLPurifier($config);
567 $res['body'] = $purifier->purify($res['body']);
569 $res['body'] = @html2bbcode($res['body']);
573 elseif(! $have_real_body) {
575 // it's not one of our messages and it has no tags
576 // so it's probably just text. We'll escape it just to be safe.
578 $res['body'] = escape_tags($res['body']);
582 // this tag is obsolete but we keep it for really old sites
584 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
585 if($allow && $allow[0]['data'] == 1)
586 $res['last-child'] = 1;
588 $res['last-child'] = 0;
590 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
591 if($private && intval($private[0]['data']) > 0)
592 $res['private'] = intval($private[0]['data']);
596 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
597 if($extid && $extid[0]['data'])
598 $res['extid'] = $extid[0]['data'];
600 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
602 $res['location'] = unxmlify($rawlocation[0]['data']);
605 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
607 $res['created'] = unxmlify($rawcreated[0]['data']);
610 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
612 $res['edited'] = unxmlify($rawedited[0]['data']);
614 if((x($res,'edited')) && (! (x($res,'created'))))
615 $res['created'] = $res['edited'];
617 if(! $res['created'])
618 $res['created'] = $item->get_date('c');
621 $res['edited'] = $item->get_date('c');
624 // Disallow time travelling posts
626 $d1 = strtotime($res['created']);
627 $d2 = strtotime($res['edited']);
628 $d3 = strtotime('now');
631 $res['created'] = datetime_convert();
633 $res['edited'] = datetime_convert();
635 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
636 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
637 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
638 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
639 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
640 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
641 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
642 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
643 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
645 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
646 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
648 foreach($base as $link) {
649 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
650 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
651 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
656 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
658 $res['coord'] = unxmlify($rawgeo[0]['data']);
661 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
663 // select between supported verbs
666 $res['verb'] = unxmlify($rawverb[0]['data']);
669 // translate OStatus unfollow to activity streams if it happened to get selected
671 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
672 $res['verb'] = ACTIVITY_UNFOLLOW;
674 $cats = $item->get_categories();
677 foreach($cats as $cat) {
678 $term = $cat->get_term();
680 $term = $cat->get_label();
681 $scheme = $cat->get_scheme();
682 if($scheme && $term && stristr($scheme,'X-DFRN:'))
683 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
685 $tag_arr[] = notags(trim($term));
687 $res['tag'] = implode(',', $tag_arr);
690 $attach = $item->get_enclosures();
693 foreach($attach as $att) {
694 $len = intval($att->get_length());
695 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
696 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
697 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
698 if(strpos($type,';'))
699 $type = substr($type,0,strpos($type,';'));
700 if((! $link) || (strpos($link,'http') !== 0))
706 $type = 'application/octet-stream';
708 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
710 $res['attach'] = implode(',', $att_arr);
713 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
716 $res['object'] = '<object>' . "\n";
717 $child = $rawobj[0]['child'];
718 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
719 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
720 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
722 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
723 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
724 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
725 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
726 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
727 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
728 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
729 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
731 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
732 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
733 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
734 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
736 $body = html2bb_video($body);
738 $config = HTMLPurifier_Config::createDefault();
739 $config->set('Cache.DefinitionImpl', null);
741 $purifier = new HTMLPurifier($config);
742 $body = $purifier->purify($body);
743 $body = html2bbcode($body);
746 $res['object'] .= '<content>' . $body . '</content>' . "\n";
749 $res['object'] .= '</object>' . "\n";
752 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
755 $res['target'] = '<target>' . "\n";
756 $child = $rawobj[0]['child'];
757 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
758 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
760 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
761 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
762 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
763 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
764 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
765 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
766 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
767 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
769 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
770 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
771 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
772 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
774 $body = html2bb_video($body);
776 $config = HTMLPurifier_Config::createDefault();
777 $config->set('Cache.DefinitionImpl', null);
779 $purifier = new HTMLPurifier($config);
780 $body = $purifier->purify($body);
781 $body = html2bbcode($body);
784 $res['target'] .= '<content>' . $body . '</content>' . "\n";
787 $res['target'] .= '</target>' . "\n";
790 // This is some experimental stuff. By now retweets are shown with "RT:"
791 // But: There is data so that the message could be shown similar to native retweets
792 // There is some better way to parse this array - but it didn't worked for me.
793 $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"];
794 if (is_array($child)) {
795 $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
796 $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
797 $uri = $author["uri"][0]["data"];
798 $name = $author["name"][0]["data"];
799 $avatar = @array_shift($author["link"][2]["attribs"]);
800 $avatar = $avatar["href"];
802 if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
803 $res["owner-name"] = $res["author-name"];
804 $res["owner-link"] = $res["author-link"];
805 $res["owner-avatar"] = $res["author-avatar"];
807 $res["author-name"] = $name;
808 $res["author-link"] = $uri;
809 $res["author-avatar"] = $avatar;
811 $res["body"] = html2bbcode($message);
815 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
817 call_hooks('parse_atom', $arr);
819 //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
820 //if (strpos($res["body"], "RT @") !== false) {
821 // $debugfile = tempnam("/home/ike/log", "item-res2-");
822 // file_put_contents($debugfile, serialize($arr));
828 function encode_rel_links($links) {
830 if(! ((is_array($links)) && (count($links))))
832 foreach($links as $link) {
834 if($link['attribs']['']['rel'])
835 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
836 if($link['attribs']['']['type'])
837 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
838 if($link['attribs']['']['href'])
839 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
840 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
841 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
842 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
843 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
851 function item_store($arr,$force_parent = false) {
853 // If a Diaspora signature structure was passed in, pull it out of the
854 // item array and set it aside for later storage.
857 if(x($arr,'dsprsig')) {
858 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
859 unset($arr['dsprsig']);
862 if(x($arr, 'gravity'))
863 $arr['gravity'] = intval($arr['gravity']);
864 elseif($arr['parent-uri'] === $arr['uri'])
866 elseif(activity_match($arr['verb'],ACTIVITY_POST))
869 $arr['gravity'] = 6; // extensible catchall
872 $arr['type'] = 'remote';
874 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
876 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
877 $arr['body'] = strip_tags($arr['body']);
880 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
881 require_once('Text/LanguageDetect.php');
882 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
883 $l = new Text_LanguageDetect;
884 $lng = $l->detectConfidence($naked_body);
885 $arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
888 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
889 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
890 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
891 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
892 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
893 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
894 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
895 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
896 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
897 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
898 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
899 $arr['commented'] = datetime_convert();
900 $arr['received'] = datetime_convert();
901 $arr['changed'] = datetime_convert();
902 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
903 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
904 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
905 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
906 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
908 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
909 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
910 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
911 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
912 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
913 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
914 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
915 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
916 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
917 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
918 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
919 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
920 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
921 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
922 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
923 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
924 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
925 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
926 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
929 $arr['thr-parent'] = $arr['parent-uri'];
930 if($arr['parent-uri'] === $arr['uri']) {
933 $allow_cid = $arr['allow_cid'];
934 $allow_gid = $arr['allow_gid'];
935 $deny_cid = $arr['deny_cid'];
936 $deny_gid = $arr['deny_gid'];
940 // find the parent and snarf the item id and ACL's
941 // and anything else we need to inherit
943 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
944 dbesc($arr['parent-uri']),
950 // is the new message multi-level threaded?
951 // even though we don't support it now, preserve the info
952 // and re-attach to the conversation parent.
954 if($r[0]['uri'] != $r[0]['parent-uri']) {
955 $arr['parent-uri'] = $r[0]['parent-uri'];
956 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
957 ORDER BY `id` ASC LIMIT 1",
958 dbesc($r[0]['parent-uri']),
959 dbesc($r[0]['parent-uri']),
966 $parent_id = $r[0]['id'];
967 $parent_deleted = $r[0]['deleted'];
968 $allow_cid = $r[0]['allow_cid'];
969 $allow_gid = $r[0]['allow_gid'];
970 $deny_cid = $r[0]['deny_cid'];
971 $deny_gid = $r[0]['deny_gid'];
972 $arr['wall'] = $r[0]['wall'];
974 // if the parent is private, force privacy for the entire conversation
975 // This differs from the above settings as it subtly allows comments from
976 // email correspondents to be private even if the overall thread is not.
979 $arr['private'] = $r[0]['private'];
981 // Edge case. We host a public forum that was originally posted to privately.
982 // The original author commented, but as this is a comment, the permissions
983 // weren't fixed up so it will still show the comment as private unless we fix it here.
985 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
990 // Allow one to see reply tweets from status.net even when
991 // we don't have or can't see the original post.
994 logger('item_store: $force_parent=true, reply converted to top-level post.');
996 $arr['parent-uri'] = $arr['uri'];
1000 logger('item_store: item parent was not found - ignoring item');
1004 $parent_deleted = 0;
1008 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1012 if($r && count($r)) {
1013 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
1017 call_hooks('post_remote',$arr);
1019 if(x($arr,'cancel')) {
1020 logger('item_store: post cancelled by plugin.');
1026 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
1028 $r = dbq("INSERT INTO `item` (`"
1029 . implode("`, `", array_keys($arr))
1031 . implode("', '", array_values($arr))
1034 // find the item we just created
1036 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
1037 $arr['uri'], // already dbesc'd
1042 $current_post = $r[0]['id'];
1043 logger('item_store: created item ' . $current_post);
1046 logger('item_store: could not locate created item');
1050 logger('item_store: duplicated post occurred. Removing duplicates.');
1051 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
1053 intval($arr['uid']),
1054 intval($current_post)
1058 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
1059 $parent_id = $current_post;
1061 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1064 $private = $arr['private'];
1066 // Set parent id - and also make sure to inherit the parent's ACL's.
1068 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1069 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1076 intval($parent_deleted),
1077 intval($current_post)
1080 $arr['id'] = $current_post;
1081 $arr['parent'] = $parent_id;
1082 $arr['allow_cid'] = $allow_cid;
1083 $arr['allow_gid'] = $allow_gid;
1084 $arr['deny_cid'] = $deny_cid;
1085 $arr['deny_gid'] = $deny_gid;
1086 $arr['private'] = $private;
1087 $arr['deleted'] = $parent_deleted;
1088 call_hooks('post_remote_end',$arr);
1090 // update the commented timestamp on the parent
1092 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1093 dbesc(datetime_convert()),
1094 dbesc(datetime_convert()),
1099 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1100 intval($current_post),
1101 dbesc($dsprsig->signed_text),
1102 dbesc($dsprsig->signature),
1103 dbesc($dsprsig->signer)
1109 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1112 if($arr['last-child']) {
1113 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1115 intval($arr['uid']),
1116 intval($current_post)
1120 tag_deliver($arr['uid'],$current_post);
1122 return $current_post;
1125 function get_item_contact($item,$contacts) {
1126 if(! count($contacts) || (! is_array($item)))
1128 foreach($contacts as $contact) {
1129 if($contact['id'] == $item['contact-id']) {
1131 break; // NOTREACHED
1138 function tag_deliver($uid,$item_id) {
1140 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1146 $u = q("select * from user where uid = %d limit 1",
1152 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1153 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1156 $i = q("select * from item where id = %d and uid = %d limit 1",
1165 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1167 // Diaspora uses their own hardwired link URL in @-tags
1168 // instead of the one we supply with webfinger
1170 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1172 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1174 foreach($matches as $mtch) {
1175 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1177 logger('tag_deliver: mention found: ' . $mtch[2]);
1185 // send a notification
1187 // use a local photo if we have one
1189 $r = q("select * from contact where uid = %d and nurl = '%s' limit 1",
1190 intval($u[0]['uid']),
1191 dbesc(normalise_link($item['author-link']))
1193 $photo = (($r && count($r)) ? $r[0]['thumb'] : $item['author-avatar']);
1196 require_once('include/enotify.php');
1198 'type' => NOTIFY_TAGSELF,
1199 'notify_flags' => $u[0]['notify-flags'],
1200 'language' => $u[0]['language'],
1201 'to_name' => $u[0]['username'],
1202 'to_email' => $u[0]['email'],
1203 'uid' => $u[0]['uid'],
1205 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1206 'source_name' => $item['author-name'],
1207 'source_link' => $item['author-link'],
1208 'source_photo' => $photo,
1209 'verb' => ACTIVITY_TAG,
1214 $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1216 call_hooks('tagged', $arr);
1218 if((! $community_page) && (! $prvgroup))
1222 // tgroup delivery - setup a second delivery chain
1223 // prevent delivery looping - only proceed
1224 // if the message originated elsewhere and is a top-level post
1226 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1229 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1232 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1233 intval($u[0]['uid'])
1238 // also reset all the privacy bits to the forum default permissions
1240 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1242 $forum_mode = (($prvgroup) ? 2 : 1);
1244 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1245 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1246 intval($forum_mode),
1247 dbesc($c[0]['name']),
1248 dbesc($c[0]['url']),
1249 dbesc($c[0]['thumb']),
1251 dbesc($u[0]['allow_cid']),
1252 dbesc($u[0]['allow_gid']),
1253 dbesc($u[0]['deny_cid']),
1254 dbesc($u[0]['deny_gid']),
1258 proc_run('php','include/notifier.php','tgroup',$item_id);
1264 function tgroup_check($uid,$item) {
1270 // check that the message originated elsewhere and is a top-level post
1272 if(($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri']))
1276 $u = q("select * from user where uid = %d limit 1",
1282 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1283 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1286 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1288 // Diaspora uses their own hardwired link URL in @-tags
1289 // instead of the one we supply with webfinger
1291 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1293 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1295 foreach($matches as $mtch) {
1296 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1298 logger('tgroup_check: mention found: ' . $mtch[2]);
1306 if((! $community_page) && (! $prvgroup))
1320 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1324 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1326 if($contact['duplex'] && $contact['dfrn-id'])
1327 $idtosend = '0:' . $orig_id;
1328 if($contact['duplex'] && $contact['issued-id'])
1329 $idtosend = '1:' . $orig_id;
1331 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1333 $rino_enable = get_config('system','rino_encrypt');
1338 $ssl_val = intval(get_config('system','ssl_policy'));
1342 case SSL_POLICY_FULL:
1343 $ssl_policy = 'full';
1345 case SSL_POLICY_SELFSIGN:
1346 $ssl_policy = 'self';
1348 case SSL_POLICY_NONE:
1350 $ssl_policy = 'none';
1354 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1356 logger('dfrn_deliver: ' . $url);
1358 $xml = fetch_url($url);
1360 $curl_stat = $a->get_curl_code();
1362 return(-1); // timed out
1364 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1369 if(strpos($xml,'<?xml') === false) {
1370 logger('dfrn_deliver: no valid XML returned');
1371 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1375 $res = parse_xml_string($xml);
1377 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1378 return (($res->status) ? $res->status : 3);
1380 $postvars = array();
1381 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1382 $challenge = hex2bin((string) $res->challenge);
1383 $perm = (($res->perm) ? $res->perm : null);
1384 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1385 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1386 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1388 if($owner['page-flags'] == PAGE_PRVGROUP)
1391 $final_dfrn_id = '';
1394 if((($perm == 'rw') && (! intval($contact['writable'])))
1395 || (($perm == 'r') && (intval($contact['writable'])))) {
1396 q("update contact set writable = %d where id = %d limit 1",
1397 intval(($perm == 'rw') ? 1 : 0),
1398 intval($contact['id'])
1400 $contact['writable'] = (string) 1 - intval($contact['writable']);
1404 if(($contact['duplex'] && strlen($contact['pubkey']))
1405 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1406 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1407 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1408 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1411 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1412 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1415 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1417 if(strpos($final_dfrn_id,':') == 1)
1418 $final_dfrn_id = substr($final_dfrn_id,2);
1420 if($final_dfrn_id != $orig_id) {
1421 logger('dfrn_deliver: wrong dfrn_id.');
1422 // did not decode properly - cannot trust this site
1426 $postvars['dfrn_id'] = $idtosend;
1427 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1429 $postvars['dissolve'] = '1';
1432 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1433 $postvars['data'] = $atom;
1434 $postvars['perm'] = 'rw';
1437 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1438 $postvars['perm'] = 'r';
1441 $postvars['ssl_policy'] = $ssl_policy;
1444 $postvars['page'] = $page;
1446 if($rino && $rino_allowed && (! $dissolve)) {
1447 $key = substr(random_string(),0,16);
1448 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1449 $postvars['data'] = $data;
1450 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1453 if($dfrn_version >= 2.1) {
1454 if(($contact['duplex'] && strlen($contact['pubkey']))
1455 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1456 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1458 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1461 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1465 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1466 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1469 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1473 logger('md5 rawkey ' . md5($postvars['key']));
1475 $postvars['key'] = bin2hex($postvars['key']);
1478 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1480 $xml = post_url($contact['notify'],$postvars);
1482 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1484 $curl_stat = $a->get_curl_code();
1485 if((! $curl_stat) || (! strlen($xml)))
1486 return(-1); // timed out
1488 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1491 if(strpos($xml,'<?xml') === false) {
1492 logger('dfrn_deliver: phase 2: no valid XML returned');
1493 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1497 if($contact['term-date'] != '0000-00-00 00:00:00') {
1498 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1499 require_once('include/Contact.php');
1500 unmark_for_death($contact);
1503 $res = parse_xml_string($xml);
1505 return $res->status;
1511 * consume_feed - process atom feed and update anything/everything we might need to update
1513 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1515 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1516 * It is this person's stuff that is going to be updated.
1517 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1518 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1519 * have a contact record.
1520 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1521 * might not) try and subscribe to it.
1522 * $datedir sorts in reverse order
1523 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1524 * imported prior to its children being seen in the stream unless we are certain
1525 * of how the feed is arranged/ordered.
1526 * With $pass = 1, we only pull parent items out of the stream.
1527 * With $pass = 2, we only pull children (comments/likes).
1529 * So running this twice, first with pass 1 and then with pass 2 will do the right
1530 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1531 * model where comments can have sub-threads. That would require some massive sorting
1532 * to get all the feed items into a mostly linear ordering, and might still require
1536 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1538 require_once('library/simplepie/simplepie.inc');
1540 if(! strlen($xml)) {
1541 logger('consume_feed: empty input');
1545 $feed = new SimplePie();
1546 $feed->set_raw_data($xml);
1548 $feed->enable_order_by_date(true);
1550 $feed->enable_order_by_date(false);
1554 logger('consume_feed: Error parsing XML: ' . $feed->error());
1556 $permalink = $feed->get_permalink();
1558 // Check at the feed level for updated contact name and/or photo
1562 $photo_timestamp = '';
1566 $hubs = $feed->get_links('hub');
1567 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1570 $hub = implode(',', $hubs);
1572 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1574 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1576 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1577 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1578 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1579 $new_name = $elems['name'][0]['data'];
1581 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1582 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1583 $photo_url = $elems['link'][0]['attribs']['']['href'];
1586 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1587 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1591 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1592 logger('consume_feed: Updating photo for ' . $contact['name']);
1593 require_once("Photo.php");
1594 $photo_failure = false;
1595 $have_photo = false;
1597 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1598 intval($contact['id']),
1599 intval($contact['uid'])
1602 $resource_id = $r[0]['resource-id'];
1606 $resource_id = photo_new_resource();
1609 $img_str = fetch_url($photo_url,true);
1610 // guess mimetype from headers or filename
1611 $type = guess_image_type($photo_url,true);
1614 $img = new Photo($img_str, $type);
1615 if($img->is_valid()) {
1617 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1618 dbesc($resource_id),
1619 intval($contact['id']),
1620 intval($contact['uid'])
1624 $img->scaleImageSquare(175);
1626 $hash = $resource_id;
1627 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1629 $img->scaleImage(80);
1630 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1632 $img->scaleImage(48);
1633 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1637 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1638 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1639 dbesc(datetime_convert()),
1640 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1641 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1642 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1643 intval($contact['uid']),
1644 intval($contact['id'])
1649 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1650 $r = q("select * from contact where uid = %d and id = %d limit 1",
1651 intval($contact['uid']),
1652 intval($contact['id'])
1655 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1656 dbesc(notags(trim($new_name))),
1657 dbesc(datetime_convert()),
1658 intval($contact['uid']),
1659 intval($contact['id'])
1662 // do our best to update the name on content items
1665 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1666 dbesc(notags(trim($new_name))),
1667 dbesc($r[0]['name']),
1668 dbesc($r[0]['url']),
1669 intval($contact['uid'])
1674 if(strlen($birthday)) {
1675 if(substr($birthday,0,4) != $contact['bdyear']) {
1676 logger('consume_feed: updating birthday: ' . $birthday);
1680 * Add new birthday event for this person
1682 * $bdtext is just a readable placeholder in case the event is shared
1683 * with others. We will replace it during presentation to our $importer
1684 * to contain a sparkle link and perhaps a photo.
1688 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1689 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1692 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1693 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1694 intval($contact['uid']),
1695 intval($contact['id']),
1696 dbesc(datetime_convert()),
1697 dbesc(datetime_convert()),
1698 dbesc(datetime_convert('UTC','UTC', $birthday)),
1699 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1708 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1709 dbesc(substr($birthday,0,4)),
1710 intval($contact['uid']),
1711 intval($contact['id'])
1714 // This function is called twice without reloading the contact
1715 // Make sure we only create one event. This is why &$contact
1716 // is a reference var in this function
1718 $contact['bdyear'] = substr($birthday,0,4);
1723 $community_page = 0;
1724 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1726 $community_page = intval($rawtags[0]['data']);
1728 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1729 q("update contact set forum = %d where id = %d limit 1",
1730 intval($community_page),
1731 intval($contact['id'])
1733 $contact['forum'] = (string) $community_page;
1737 // process any deleted entries
1739 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1740 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1741 foreach($del_entries as $dentry) {
1743 if(isset($dentry['attribs']['']['ref'])) {
1744 $uri = $dentry['attribs']['']['ref'];
1746 if(isset($dentry['attribs']['']['when'])) {
1747 $when = $dentry['attribs']['']['when'];
1748 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1751 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1753 if($deleted && is_array($contact)) {
1754 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1755 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1757 intval($importer['uid']),
1758 intval($contact['id'])
1763 if(! $item['deleted'])
1764 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1766 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1767 $xo = parse_xml_string($item['object'],false);
1768 $xt = parse_xml_string($item['target'],false);
1769 if($xt->type === ACTIVITY_OBJ_NOTE) {
1770 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1772 intval($importer['importer_uid'])
1776 // For tags, the owner cannot remove the tag on the author's copy of the post.
1778 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1779 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1780 $author_copy = (($item['origin']) ? true : false);
1782 if($owner_remove && $author_copy)
1784 if($author_remove || $owner_remove) {
1785 $tags = explode(',',$i[0]['tag']);
1788 foreach($tags as $tag)
1789 if(trim($tag) !== trim($xo->body))
1790 $newtags[] = trim($tag);
1792 q("update item set tag = '%s' where id = %d limit 1",
1793 dbesc(implode(',',$newtags)),
1801 if($item['uri'] == $item['parent-uri']) {
1802 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1803 `body` = '', `title` = ''
1804 WHERE `parent-uri` = '%s' AND `uid` = %d",
1806 dbesc(datetime_convert()),
1807 dbesc($item['uri']),
1808 intval($importer['uid'])
1812 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1813 `body` = '', `title` = ''
1814 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1816 dbesc(datetime_convert()),
1818 intval($importer['uid'])
1820 if($item['last-child']) {
1821 // ensure that last-child is set in case the comment that had it just got wiped.
1822 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1823 dbesc(datetime_convert()),
1824 dbesc($item['parent-uri']),
1825 intval($item['uid'])
1827 // who is the last child now?
1828 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1829 ORDER BY `created` DESC LIMIT 1",
1830 dbesc($item['parent-uri']),
1831 intval($importer['uid'])
1834 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1845 // Now process the feed
1847 if($feed->get_item_quantity()) {
1849 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1851 // in inverse date order
1853 $items = array_reverse($feed->get_items());
1855 $items = $feed->get_items();
1858 foreach($items as $item) {
1861 $item_id = $item->get_id();
1862 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1863 if(isset($rawthread[0]['attribs']['']['ref'])) {
1865 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1868 if(($is_reply) && is_array($contact)) {
1873 // not allowed to post
1875 if($contact['rel'] == CONTACT_IS_FOLLOWER)
1879 // Have we seen it? If not, import it.
1881 $item_id = $item->get_id();
1882 $datarray = get_atom_elements($feed,$item);
1884 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1885 $datarray['author-name'] = $contact['name'];
1886 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1887 $datarray['author-link'] = $contact['url'];
1888 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1889 $datarray['author-avatar'] = $contact['thumb'];
1891 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1892 logger('consume_feed: no author information! ' . print_r($datarray,true));
1896 $force_parent = false;
1897 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1898 if($contact['network'] === NETWORK_OSTATUS)
1899 $force_parent = true;
1900 if(strlen($datarray['title']))
1901 unset($datarray['title']);
1902 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1903 dbesc(datetime_convert()),
1905 intval($importer['uid'])
1907 $datarray['last-child'] = 1;
1911 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1913 intval($importer['uid'])
1916 // Update content if 'updated' changes
1919 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1921 // do not accept (ignore) an earlier edit than one we currently have.
1922 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1925 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1926 dbesc($datarray['title']),
1927 dbesc($datarray['body']),
1928 dbesc($datarray['tag']),
1929 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1931 intval($importer['uid'])
1935 // update last-child if it changes
1937 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1938 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1939 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1940 dbesc(datetime_convert()),
1942 intval($importer['uid'])
1944 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1945 intval($allow[0]['data']),
1946 dbesc(datetime_convert()),
1948 intval($importer['uid'])
1955 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1956 // one way feed - no remote comment ability
1957 $datarray['last-child'] = 0;
1959 $datarray['parent-uri'] = $parent_uri;
1960 $datarray['uid'] = $importer['uid'];
1961 $datarray['contact-id'] = $contact['id'];
1962 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1963 $datarray['type'] = 'activity';
1964 $datarray['gravity'] = GRAVITY_LIKE;
1965 // only one like or dislike per person
1966 $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",
1967 intval($datarray['uid']),
1968 intval($datarray['contact-id']),
1969 dbesc($datarray['verb']),
1977 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1978 $xo = parse_xml_string($datarray['object'],false);
1979 $xt = parse_xml_string($datarray['target'],false);
1981 if($xt->type == ACTIVITY_OBJ_NOTE) {
1982 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1984 intval($importer['importer_uid'])
1989 // extract tag, if not duplicate, add to parent item
1990 if($xo->id && $xo->content) {
1991 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1992 if(! (stristr($r[0]['tag'],$newtag))) {
1993 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1994 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2002 $r = item_store($datarray,$force_parent);
2008 // Head post of a conversation. Have we seen it? If not, import it.
2010 $item_id = $item->get_id();
2012 $datarray = get_atom_elements($feed,$item);
2014 if(is_array($contact)) {
2015 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
2016 $datarray['author-name'] = $contact['name'];
2017 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
2018 $datarray['author-link'] = $contact['url'];
2019 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
2020 $datarray['author-avatar'] = $contact['thumb'];
2023 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
2024 logger('consume_feed: no author information! ' . print_r($datarray,true));
2028 // special handling for events
2030 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2031 $ev = bbtoevent($datarray['body']);
2032 if(x($ev,'desc') && x($ev,'start')) {
2033 $ev['uid'] = $importer['uid'];
2034 $ev['uri'] = $item_id;
2035 $ev['edited'] = $datarray['edited'];
2036 $ev['private'] = $datarray['private'];
2038 if(is_array($contact))
2039 $ev['cid'] = $contact['id'];
2040 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2042 intval($importer['uid'])
2045 $ev['id'] = $r[0]['id'];
2046 $xyz = event_store($ev);
2051 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
2052 if(strlen($datarray['title']))
2053 unset($datarray['title']);
2054 $datarray['last-child'] = 1;
2058 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2060 intval($importer['uid'])
2063 // Update content if 'updated' changes
2066 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2068 // do not accept (ignore) an earlier edit than one we currently have.
2069 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2072 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2073 dbesc($datarray['title']),
2074 dbesc($datarray['body']),
2075 dbesc($datarray['tag']),
2076 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2078 intval($importer['uid'])
2082 // update last-child if it changes
2084 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2085 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2086 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2087 intval($allow[0]['data']),
2088 dbesc(datetime_convert()),
2090 intval($importer['uid'])
2096 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
2097 logger('consume-feed: New follower');
2098 new_follower($importer,$contact,$datarray,$item);
2101 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
2102 lose_follower($importer,$contact,$datarray,$item);
2106 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
2107 logger('consume-feed: New friend request');
2108 new_follower($importer,$contact,$datarray,$item,true);
2111 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
2112 lose_sharer($importer,$contact,$datarray,$item);
2117 if(! is_array($contact))
2121 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2122 // one way feed - no remote comment ability
2123 $datarray['last-child'] = 0;
2125 if($contact['network'] === NETWORK_FEED)
2126 $datarray['private'] = 2;
2128 // This is my contact on another system, but it's really me.
2129 // Turn this into a wall post.
2131 if($contact['remote_self']) {
2132 $datarray['wall'] = 1;
2133 if($contact['network'] === NETWORK_FEED) {
2134 $datarray['private'] = 0;
2138 $datarray['parent-uri'] = $item_id;
2139 $datarray['uid'] = $importer['uid'];
2140 $datarray['contact-id'] = $contact['id'];
2142 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2143 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2144 // but otherwise there's a possible data mixup on the sender's system.
2145 // the tgroup delivery code called from item_store will correct it if it's a forum,
2146 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2147 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2148 $datarray['owner-name'] = $contact['name'];
2149 $datarray['owner-link'] = $contact['url'];
2150 $datarray['owner-avatar'] = $contact['thumb'];
2153 // We've allowed "followers" to reach this point so we can decide if they are
2154 // posting an @-tag delivery, which followers are allowed to do for certain
2155 // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it.
2157 if(($contact['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['uid'],$datarray)))
2161 $r = item_store($datarray);
2169 function local_delivery($importer,$data) {
2173 if($importer['readonly']) {
2174 // We aren't receiving stuff from this person. But we will quietly ignore them
2175 // rather than a blatant "go away" message.
2176 logger('local_delivery: ignoring');
2181 // Consume notification feed. This may differ from consuming a public feed in several ways
2182 // - might contain email or friend suggestions
2183 // - might contain remote followup to our message
2184 // - in which case we need to accept it and then notify other conversants
2185 // - we may need to send various email notifications
2187 $feed = new SimplePie();
2188 $feed->set_raw_data($data);
2189 $feed->enable_order_by_date(false);
2194 logger('local_delivery: Error parsing XML: ' . $feed->error());
2197 // Check at the feed level for updated contact name and/or photo
2201 $photo_timestamp = '';
2205 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
2207 // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
2209 // $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
2212 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
2213 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
2214 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
2215 $new_name = $elems['name'][0]['data'];
2217 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
2218 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
2219 $photo_url = $elems['link'][0]['attribs']['']['href'];
2223 if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
2224 logger('local_delivery: Updating photo for ' . $importer['name']);
2225 require_once("Photo.php");
2226 $photo_failure = false;
2227 $have_photo = false;
2229 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
2230 intval($importer['id']),
2231 intval($importer['importer_uid'])
2234 $resource_id = $r[0]['resource-id'];
2238 $resource_id = photo_new_resource();
2241 $img_str = fetch_url($photo_url,true);
2242 // guess mimetype from headers or filename
2243 $type = guess_image_type($photo_url,true);
2246 $img = new Photo($img_str, $type);
2247 if($img->is_valid()) {
2249 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
2250 dbesc($resource_id),
2251 intval($importer['id']),
2252 intval($importer['importer_uid'])
2256 $img->scaleImageSquare(175);
2258 $hash = $resource_id;
2259 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 4);
2261 $img->scaleImage(80);
2262 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 5);
2264 $img->scaleImage(48);
2265 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 6);
2269 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
2270 WHERE `uid` = %d AND `id` = %d LIMIT 1",
2271 dbesc(datetime_convert()),
2272 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
2273 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
2274 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
2275 intval($importer['importer_uid']),
2276 intval($importer['id'])
2281 if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
2282 $r = q("select * from contact where uid = %d and id = %d limit 1",
2283 intval($importer['importer_uid']),
2284 intval($importer['id'])
2287 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2288 dbesc(notags(trim($new_name))),
2289 dbesc(datetime_convert()),
2290 intval($importer['importer_uid']),
2291 intval($importer['id'])
2294 // do our best to update the name on content items
2297 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
2298 dbesc(notags(trim($new_name))),
2299 dbesc($r[0]['name']),
2300 dbesc($r[0]['url']),
2301 intval($importer['importer_uid'])
2308 // Currently unsupported - needs a lot of work
2309 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2310 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2311 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2313 $newloc['uid'] = $importer['importer_uid'];
2314 $newloc['cid'] = $importer['id'];
2315 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2316 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2317 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2318 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2319 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2320 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2321 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2322 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
2323 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2324 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
2327 // merge with current record, current contents have priority
2328 // update record, set url-updated
2329 // update profile photos
2335 // handle friend suggestion notification
2337 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2338 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2339 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2341 $fsugg['uid'] = $importer['importer_uid'];
2342 $fsugg['cid'] = $importer['id'];
2343 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2344 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2345 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2346 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2347 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2349 // Does our member already have a friend matching this description?
2351 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2352 dbesc($fsugg['name']),
2353 dbesc(normalise_link($fsugg['url'])),
2354 intval($fsugg['uid'])
2359 // Do we already have an fcontact record for this person?
2362 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2363 dbesc($fsugg['url']),
2364 dbesc($fsugg['name']),
2365 dbesc($fsugg['request'])
2370 // OK, we do. Do we already have an introduction for this person ?
2371 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2372 intval($fsugg['uid']),
2379 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2380 dbesc($fsugg['name']),
2381 dbesc($fsugg['url']),
2382 dbesc($fsugg['photo']),
2383 dbesc($fsugg['request'])
2385 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2386 dbesc($fsugg['url']),
2387 dbesc($fsugg['name']),
2388 dbesc($fsugg['request'])
2393 // database record did not get created. Quietly give up.
2398 $hash = random_string();
2400 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2401 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2402 intval($fsugg['uid']),
2404 intval($fsugg['cid']),
2405 dbesc($fsugg['body']),
2407 dbesc(datetime_convert()),
2412 'type' => NOTIFY_SUGGEST,
2413 'notify_flags' => $importer['notify-flags'],
2414 'language' => $importer['language'],
2415 'to_name' => $importer['username'],
2416 'to_email' => $importer['email'],
2417 'uid' => $importer['importer_uid'],
2419 'link' => $a->get_baseurl() . '/notifications/intros',
2420 'source_name' => $importer['name'],
2421 'source_link' => $importer['url'],
2422 'source_photo' => $importer['photo'],
2423 'verb' => ACTIVITY_REQ_FRIEND,
2432 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2433 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2435 logger('local_delivery: private message received');
2438 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2441 $msg['uid'] = $importer['importer_uid'];
2442 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2443 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2444 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2445 $msg['contact-id'] = $importer['id'];
2446 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2447 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2449 $msg['replied'] = 0;
2450 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2451 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2452 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2456 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2457 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2459 // send notifications.
2461 require_once('include/enotify.php');
2463 $notif_params = array(
2464 'type' => NOTIFY_MAIL,
2465 'notify_flags' => $importer['notify-flags'],
2466 'language' => $importer['language'],
2467 'to_name' => $importer['username'],
2468 'to_email' => $importer['email'],
2469 'uid' => $importer['importer_uid'],
2471 'source_name' => $msg['from-name'],
2472 'source_link' => $importer['url'],
2473 'source_photo' => $importer['thumb'],
2474 'verb' => ACTIVITY_POST,
2478 notification($notif_params);
2484 $community_page = 0;
2485 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2487 $community_page = intval($rawtags[0]['data']);
2489 if(intval($importer['forum']) != $community_page) {
2490 q("update contact set forum = %d where id = %d limit 1",
2491 intval($community_page),
2492 intval($importer['id'])
2494 $importer['forum'] = (string) $community_page;
2497 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2499 // process any deleted entries
2501 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2502 if(is_array($del_entries) && count($del_entries)) {
2503 foreach($del_entries as $dentry) {
2505 if(isset($dentry['attribs']['']['ref'])) {
2506 $uri = $dentry['attribs']['']['ref'];
2508 if(isset($dentry['attribs']['']['when'])) {
2509 $when = $dentry['attribs']['']['when'];
2510 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2513 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2517 // check for relayed deletes to our conversation
2520 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2522 intval($importer['importer_uid'])
2525 $parent_uri = $r[0]['parent-uri'];
2526 if($r[0]['id'] != $r[0]['parent'])
2533 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2536 logger('local_delivery: possible community delete');
2539 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2541 // was the top-level post for this reply written by somebody on this site?
2542 // Specifically, the recipient?
2544 $is_a_remote_delete = false;
2546 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2547 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2548 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2549 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2550 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2551 AND `item`.`uid` = %d
2557 intval($importer['importer_uid'])
2560 $is_a_remote_delete = true;
2562 // Does this have the characteristics of a community or private group comment?
2563 // If it's a reply to a wall post on a community/prvgroup page it's a
2564 // valid community comment. Also forum_mode makes it valid for sure.
2565 // If neither, it's not.
2567 if($is_a_remote_delete && $community) {
2568 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2569 $is_a_remote_delete = false;
2570 logger('local_delivery: not a community delete');
2574 if($is_a_remote_delete) {
2575 logger('local_delivery: received remote delete');
2579 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2580 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2582 intval($importer['importer_uid']),
2583 intval($importer['id'])
2589 if($item['deleted'])
2592 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2594 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2595 $xo = parse_xml_string($item['object'],false);
2596 $xt = parse_xml_string($item['target'],false);
2598 if($xt->type === ACTIVITY_OBJ_NOTE) {
2599 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2601 intval($importer['importer_uid'])
2605 // For tags, the owner cannot remove the tag on the author's copy of the post.
2607 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2608 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2609 $author_copy = (($item['origin']) ? true : false);
2611 if($owner_remove && $author_copy)
2613 if($author_remove || $owner_remove) {
2614 $tags = explode(',',$i[0]['tag']);
2617 foreach($tags as $tag)
2618 if(trim($tag) !== trim($xo->body))
2619 $newtags[] = trim($tag);
2621 q("update item set tag = '%s' where id = %d limit 1",
2622 dbesc(implode(',',$newtags)),
2630 if($item['uri'] == $item['parent-uri']) {
2631 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2632 `body` = '', `title` = ''
2633 WHERE `parent-uri` = '%s' AND `uid` = %d",
2635 dbesc(datetime_convert()),
2636 dbesc($item['uri']),
2637 intval($importer['importer_uid'])
2641 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2642 `body` = '', `title` = ''
2643 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2645 dbesc(datetime_convert()),
2647 intval($importer['importer_uid'])
2649 if($item['last-child']) {
2650 // ensure that last-child is set in case the comment that had it just got wiped.
2651 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2652 dbesc(datetime_convert()),
2653 dbesc($item['parent-uri']),
2654 intval($item['uid'])
2656 // who is the last child now?
2657 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2658 ORDER BY `created` DESC LIMIT 1",
2659 dbesc($item['parent-uri']),
2660 intval($importer['importer_uid'])
2663 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2668 // if this is a relayed delete, propagate it to other recipients
2670 if($is_a_remote_delete)
2671 proc_run('php',"include/notifier.php","drop",$item['id']);
2679 foreach($feed->get_items() as $item) {
2682 $item_id = $item->get_id();
2683 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2684 if(isset($rawthread[0]['attribs']['']['ref'])) {
2686 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2692 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2695 logger('local_delivery: possible community reply');
2698 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2700 // was the top-level post for this reply written by somebody on this site?
2701 // Specifically, the recipient?
2703 $is_a_remote_comment = false;
2704 $top_uri = $parent_uri;
2706 $r = q("select `item`.`parent-uri` from `item`
2707 WHERE `item`.`uri` = '%s'
2711 if($r && count($r)) {
2712 $top_uri = $r[0]['parent-uri'];
2714 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2715 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2716 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2717 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2718 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2719 AND `item`.`uid` = %d
2725 intval($importer['importer_uid'])
2728 $is_a_remote_comment = true;
2731 // Does this have the characteristics of a community or private group comment?
2732 // If it's a reply to a wall post on a community/prvgroup page it's a
2733 // valid community comment. Also forum_mode makes it valid for sure.
2734 // If neither, it's not.
2736 if($is_a_remote_comment && $community) {
2737 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2738 $is_a_remote_comment = false;
2739 logger('local_delivery: not a community reply');
2743 if($is_a_remote_comment) {
2744 logger('local_delivery: received remote comment');
2746 // remote reply to our post. Import and then notify everybody else.
2748 $datarray = get_atom_elements($feed,$item);
2750 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2752 intval($importer['importer_uid'])
2755 // Update content if 'updated' changes
2759 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2761 // do not accept (ignore) an earlier edit than one we currently have.
2762 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2765 logger('received updated comment' , LOGGER_DEBUG);
2766 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2767 dbesc($datarray['title']),
2768 dbesc($datarray['body']),
2769 dbesc($datarray['tag']),
2770 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2772 intval($importer['importer_uid'])
2775 proc_run('php',"include/notifier.php","comment-import",$iid);
2784 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2785 intval($importer['importer_uid'])
2789 $datarray['type'] = 'remote-comment';
2790 $datarray['wall'] = 1;
2791 $datarray['parent-uri'] = $parent_uri;
2792 $datarray['uid'] = $importer['importer_uid'];
2793 $datarray['owner-name'] = $own[0]['name'];
2794 $datarray['owner-link'] = $own[0]['url'];
2795 $datarray['owner-avatar'] = $own[0]['thumb'];
2796 $datarray['contact-id'] = $importer['id'];
2798 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2800 $datarray['type'] = 'activity';
2801 $datarray['gravity'] = GRAVITY_LIKE;
2802 $datarray['last-child'] = 0;
2803 // only one like or dislike per person
2804 $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",
2805 intval($datarray['uid']),
2806 intval($datarray['contact-id']),
2807 dbesc($datarray['verb']),
2808 dbesc($datarray['parent-uri']),
2809 dbesc($datarray['parent-uri'])
2816 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2818 $xo = parse_xml_string($datarray['object'],false);
2819 $xt = parse_xml_string($datarray['target'],false);
2821 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2823 // fetch the parent item
2825 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2827 intval($importer['importer_uid'])
2832 // extract tag, if not duplicate, and this user allows tags, add to parent item
2834 if($xo->id && $xo->content) {
2835 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2836 if(! (stristr($tagp[0]['tag'],$newtag))) {
2837 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2838 intval($importer['importer_uid'])
2840 if(count($i) && ! intval($i[0]['blocktags'])) {
2841 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2842 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2843 intval($tagp[0]['id']),
2844 dbesc(datetime_convert())
2853 $posted_id = item_store($datarray);
2857 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2859 intval($importer['importer_uid'])
2862 $parent = $r[0]['parent'];
2863 $parent_uri = $r[0]['parent-uri'];
2867 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2868 dbesc(datetime_convert()),
2869 intval($importer['importer_uid']),
2870 intval($r[0]['parent'])
2873 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2874 dbesc(datetime_convert()),
2875 intval($importer['importer_uid']),
2880 if($posted_id && $parent) {
2882 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2884 if((! $is_like) && (! $importer['self'])) {
2886 require_once('include/enotify.php');
2889 'type' => NOTIFY_COMMENT,
2890 'notify_flags' => $importer['notify-flags'],
2891 'language' => $importer['language'],
2892 'to_name' => $importer['username'],
2893 'to_email' => $importer['email'],
2894 'uid' => $importer['importer_uid'],
2895 'item' => $datarray,
2896 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2897 'source_name' => stripslashes($datarray['author-name']),
2898 'source_link' => $datarray['author-link'],
2899 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2900 ? $importer['thumb'] : $datarray['author-avatar']),
2901 'verb' => ACTIVITY_POST,
2903 'parent' => $parent,
2904 'parent_uri' => $parent_uri,
2916 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2918 $item_id = $item->get_id();
2919 $datarray = get_atom_elements($feed,$item);
2921 if($importer['rel'] == CONTACT_IS_FOLLOWER)
2924 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2926 intval($importer['importer_uid'])
2929 // Update content if 'updated' changes
2932 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2934 // do not accept (ignore) an earlier edit than one we currently have.
2935 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2938 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2939 dbesc($datarray['title']),
2940 dbesc($datarray['body']),
2941 dbesc($datarray['tag']),
2942 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2944 intval($importer['importer_uid'])
2948 // update last-child if it changes
2950 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2951 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2952 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2953 dbesc(datetime_convert()),
2955 intval($importer['importer_uid'])
2957 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2958 intval($allow[0]['data']),
2959 dbesc(datetime_convert()),
2961 intval($importer['importer_uid'])
2967 $datarray['parent-uri'] = $parent_uri;
2968 $datarray['uid'] = $importer['importer_uid'];
2969 $datarray['contact-id'] = $importer['id'];
2970 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2971 $datarray['type'] = 'activity';
2972 $datarray['gravity'] = GRAVITY_LIKE;
2973 // only one like or dislike per person
2974 $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",
2975 intval($datarray['uid']),
2976 intval($datarray['contact-id']),
2977 dbesc($datarray['verb']),
2986 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2988 $xo = parse_xml_string($datarray['object'],false);
2989 $xt = parse_xml_string($datarray['target'],false);
2991 if($xt->type == ACTIVITY_OBJ_NOTE) {
2992 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2994 intval($importer['importer_uid'])
2999 // extract tag, if not duplicate, add to parent item
3001 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
3002 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
3003 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
3011 $posted_id = item_store($datarray);
3013 // find out if our user is involved in this conversation and wants to be notified.
3015 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
3017 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
3019 intval($importer['importer_uid'])
3022 if(count($myconv)) {
3023 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
3025 // first make sure this isn't our own post coming back to us from a wall-to-wall event
3026 if(! link_compare($datarray['author-link'],$importer_url)) {
3029 foreach($myconv as $conv) {
3031 // now if we find a match, it means we're in this conversation
3033 if(! link_compare($conv['author-link'],$importer_url))
3036 require_once('include/enotify.php');
3038 $conv_parent = $conv['parent'];
3041 'type' => NOTIFY_COMMENT,
3042 'notify_flags' => $importer['notify-flags'],
3043 'language' => $importer['language'],
3044 'to_name' => $importer['username'],
3045 'to_email' => $importer['email'],
3046 'uid' => $importer['importer_uid'],
3047 'item' => $datarray,
3048 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3049 'source_name' => stripslashes($datarray['author-name']),
3050 'source_link' => $datarray['author-link'],
3051 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3052 ? $importer['thumb'] : $datarray['author-avatar']),
3053 'verb' => ACTIVITY_POST,
3055 'parent' => $conv_parent,
3056 'parent_uri' => $parent_uri
3060 // only send one notification
3072 // Head post of a conversation. Have we seen it? If not, import it.
3075 $item_id = $item->get_id();
3076 $datarray = get_atom_elements($feed,$item);
3078 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
3079 $ev = bbtoevent($datarray['body']);
3080 if(x($ev,'desc') && x($ev,'start')) {
3081 $ev['cid'] = $importer['id'];
3082 $ev['uid'] = $importer['uid'];
3083 $ev['uri'] = $item_id;
3084 $ev['edited'] = $datarray['edited'];
3085 $ev['private'] = $datarray['private'];
3087 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3089 intval($importer['uid'])
3092 $ev['id'] = $r[0]['id'];
3093 $xyz = event_store($ev);
3098 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3100 intval($importer['importer_uid'])
3103 // Update content if 'updated' changes
3106 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
3108 // do not accept (ignore) an earlier edit than one we currently have.
3109 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3112 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3113 dbesc($datarray['title']),
3114 dbesc($datarray['body']),
3115 dbesc($datarray['tag']),
3116 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3118 intval($importer['importer_uid'])
3122 // update last-child if it changes
3124 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3125 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
3126 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3127 intval($allow[0]['data']),
3128 dbesc(datetime_convert()),
3130 intval($importer['importer_uid'])
3136 // This is my contact on another system, but it's really me.
3137 // Turn this into a wall post.
3139 if($importer['remote_self'])
3140 $datarray['wall'] = 1;
3142 $datarray['parent-uri'] = $item_id;
3143 $datarray['uid'] = $importer['importer_uid'];
3144 $datarray['contact-id'] = $importer['id'];
3147 if(! link_compare($datarray['owner-link'],$importer['url'])) {
3148 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
3149 // but otherwise there's a possible data mixup on the sender's system.
3150 // the tgroup delivery code called from item_store will correct it if it's a forum,
3151 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
3152 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
3153 $datarray['owner-name'] = $importer['senderName'];
3154 $datarray['owner-link'] = $importer['url'];
3155 $datarray['owner-avatar'] = $importer['thumb'];
3158 if(($importer['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['importer_uid'],$datarray)))
3161 $posted_id = item_store($datarray);
3163 if(stristr($datarray['verb'],ACTIVITY_POKE)) {
3164 $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
3167 $xo = parse_xml_string($datarray['object'],false);
3169 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
3171 // somebody was poked/prodded. Was it me?
3173 $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
3175 foreach($links->link as $l) {
3176 $atts = $l->attributes();
3177 switch($atts['rel']) {
3179 $Blink = $atts['href'];
3185 if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
3187 // send a notification
3188 require_once('include/enotify.php');
3191 'type' => NOTIFY_POKE,
3192 'notify_flags' => $importer['notify-flags'],
3193 'language' => $importer['language'],
3194 'to_name' => $importer['username'],
3195 'to_email' => $importer['email'],
3196 'uid' => $importer['importer_uid'],
3197 'item' => $datarray,
3198 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3199 'source_name' => stripslashes($datarray['author-name']),
3200 'source_link' => $datarray['author-link'],
3201 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3202 ? $importer['thumb'] : $datarray['author-avatar']),
3203 'verb' => $datarray['verb'],
3204 'otype' => 'person',
3205 'activity' => $verb,
3222 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
3223 $url = notags(trim($datarray['author-link']));
3224 $name = notags(trim($datarray['author-name']));
3225 $photo = notags(trim($datarray['author-avatar']));
3227 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
3228 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
3229 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
3231 if(is_array($contact)) {
3232 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
3233 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
3234 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
3235 intval(CONTACT_IS_FRIEND),
3236 intval($contact['id']),
3237 intval($importer['uid'])
3240 // send email notification to owner?
3244 // create contact record
3246 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
3247 `blocked`, `readonly`, `pending`, `writable` )
3248 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
3249 intval($importer['uid']),
3250 dbesc(datetime_convert()),
3252 dbesc(normalise_link($url)),
3256 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
3257 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
3259 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
3260 intval($importer['uid']),
3264 $contact_record = $r[0];
3266 // create notification
3267 $hash = random_string();
3269 if(is_array($contact_record)) {
3270 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
3271 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
3272 intval($importer['uid']),
3273 intval($contact_record['id']),
3275 dbesc(datetime_convert())
3278 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3279 intval($importer['uid'])
3284 if(intval($r[0]['def_gid'])) {
3285 require_once('include/group.php');
3286 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
3289 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
3290 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
3291 $email = replace_macros($email_tpl, array(
3292 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
3294 '$myname' => $r[0]['username'],
3295 '$siteurl' => $a->get_baseurl(),
3296 '$sitename' => $a->config['sitename']
3298 $res = mail($r[0]['email'],
3299 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
3301 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
3302 . 'Content-type: text/plain; charset=UTF-8' . "\n"
3303 . 'Content-transfer-encoding: 8bit' );
3310 function lose_follower($importer,$contact,$datarray,$item) {
3312 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
3313 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3314 intval(CONTACT_IS_SHARING),
3315 intval($contact['id'])
3319 contact_remove($contact['id']);
3323 function lose_sharer($importer,$contact,$datarray,$item) {
3325 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3326 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3327 intval(CONTACT_IS_FOLLOWER),
3328 intval($contact['id'])
3332 contact_remove($contact['id']);
3337 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3341 if(is_array($importer)) {
3342 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3343 intval($importer['uid'])
3347 // Diaspora has different message-ids in feeds than they do
3348 // through the direct Diaspora protocol. If we try and use
3349 // the feed, we'll get duplicates. So don't.
3351 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3354 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3356 // Use a single verify token, even if multiple hubs
3358 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3360 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3362 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
3364 if(! strlen($contact['hub-verify'])) {
3365 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3366 dbesc($verify_token),
3367 intval($contact['id'])
3371 post_url($url,$params);
3373 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3380 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3384 $name = xmlify($name);
3385 $uri = xmlify($uri);
3388 $photo = xmlify($photo);
3392 $o .= "<name>$name</name>\r\n";
3393 $o .= "<uri>$uri</uri>\r\n";
3394 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3395 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3397 call_hooks('atom_author', $o);
3399 $o .= "</$tag>\r\n";
3403 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3407 if(! $item['parent'])
3410 if($item['deleted'])
3411 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3414 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3415 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3417 $body = $item['body'];
3419 $o = "\r\n\r\n<entry>\r\n";
3421 if(is_array($author))
3422 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3424 $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']));
3425 if(strlen($item['owner-name']))
3426 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3428 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
3429 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3430 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3433 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3434 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3435 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3436 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3437 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3438 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3439 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3441 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3443 if($item['location']) {
3444 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3445 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3449 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3451 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3452 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3455 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3456 if($item['bookmark'])
3457 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3460 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3463 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3465 if($item['signed_text']) {
3466 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3467 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3470 $verb = construct_verb($item);
3471 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3472 $actobj = construct_activity_object($item);
3475 $actarg = construct_activity_target($item);
3479 $tags = item_getfeedtags($item);
3481 foreach($tags as $t) {
3482 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3486 $o .= item_getfeedattach($item);
3488 $mentioned = get_mentions($item);
3492 call_hooks('atom_entry', $o);
3494 $o .= '</entry>' . "\r\n";
3499 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3502 logger('fix_private_photos', LOGGER_DEBUG);
3503 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3508 $img_start = strpos($orig_body, '[img');
3509 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3510 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3511 while( ($img_st_close !== false) && ($img_len !== false) ) {
3513 $img_st_close++; // make it point to AFTER the closing bracket
3514 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3516 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3519 if(stristr($image , $site . '/photo/')) {
3520 // Only embed locally hosted photos
3522 $i = basename($image);
3523 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3524 $x = strpos($i,'-');
3527 $res = substr($i,$x+1);
3528 $i = substr($i,0,$x);
3529 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3536 // Check to see if we should replace this photo link with an embedded image
3537 // 1. No need to do so if the photo is public
3538 // 2. If there's a contact-id provided, see if they're in the access list
3539 // for the photo. If so, embed it.
3540 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3541 // permissions, regardless of order but first check to see if they're an exact
3542 // match to save some processing overhead.
3544 if(has_permissions($r[0])) {
3546 $recips = enumerate_permissions($r[0]);
3547 if(in_array($cid, $recips)) {
3552 if(compare_permissions($item,$r[0]))
3557 $data = $r[0]['data'];
3558 $type = $r[0]['type'];
3560 // If a custom width and height were specified, apply before embedding
3561 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3562 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3564 $width = intval($match[1]);
3565 $height = intval($match[2]);
3567 $ph = new Photo($data, $type);
3568 if($ph->is_valid()) {
3569 $ph->scaleImage(max($width, $height));
3570 $data = $ph->imageString();
3571 $type = $ph->getType();
3575 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3576 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3577 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3583 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3584 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3585 if($orig_body === false)
3588 $img_start = strpos($orig_body, '[img');
3589 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3590 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3593 $new_body = $new_body . $orig_body;
3599 function has_permissions($obj) {
3600 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3605 function compare_permissions($obj1,$obj2) {
3606 // first part is easy. Check that these are exactly the same.
3607 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3608 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3609 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3610 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3613 // This is harder. Parse all the permissions and compare the resulting set.
3615 $recipients1 = enumerate_permissions($obj1);
3616 $recipients2 = enumerate_permissions($obj2);
3619 if($recipients1 == $recipients2)
3624 // returns an array of contact-ids that are allowed to see this object
3626 function enumerate_permissions($obj) {
3627 require_once('include/group.php');
3628 $allow_people = expand_acl($obj['allow_cid']);
3629 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3630 $deny_people = expand_acl($obj['deny_cid']);
3631 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3632 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3633 $deny = array_unique(array_merge($deny_people,$deny_groups));
3634 $recipients = array_diff($recipients,$deny);
3638 function item_getfeedtags($item) {
3641 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3643 for($x = 0; $x < $cnt; $x ++) {
3645 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3649 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3651 for($x = 0; $x < $cnt; $x ++) {
3653 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3659 function item_getfeedattach($item) {
3661 $arr = explode(',',$item['attach']);
3663 foreach($arr as $r) {
3665 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3667 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3668 if(intval($matches[2]))
3669 $ret .= 'length="' . intval($matches[2]) . '" ';
3670 if($matches[4] !== ' ')
3671 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3672 $ret .= ' />' . "\r\n";
3681 function item_expire($uid,$days) {
3683 if((! $uid) || ($days < 1))
3686 // $expire_network_only = save your own wall posts
3687 // and just expire conversations started by others
3689 $expire_network_only = get_pconfig($uid,'expire','network_only');
3690 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3692 $r = q("SELECT * FROM `item`
3694 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3705 $expire_items = get_pconfig($uid, 'expire','items');
3706 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3708 $expire_notes = get_pconfig($uid, 'expire','notes');
3709 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3711 $expire_starred = get_pconfig($uid, 'expire','starred');
3712 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3714 $expire_photos = get_pconfig($uid, 'expire','photos');
3715 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3717 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3719 foreach($r as $item) {
3721 // don't expire filed items
3723 if(strpos($item['file'],'[') !== false)
3726 // Only expire posts, not photos and photo comments
3728 if($expire_photos==0 && strlen($item['resource-id']))
3730 if($expire_starred==0 && intval($item['starred']))
3732 if($expire_notes==0 && $item['type']=='note')
3734 if($expire_items==0 && $item['type']!='note')
3737 drop_item($item['id'],false);
3740 proc_run('php',"include/notifier.php","expire","$uid");
3745 function drop_items($items) {
3748 if(! local_user() && ! remote_user())
3752 foreach($items as $item) {
3753 $owner = drop_item($item,false);
3754 if($owner && ! $uid)
3759 // multiple threads may have been deleted, send an expire notification
3762 proc_run('php',"include/notifier.php","expire","$uid");
3766 function drop_item($id,$interactive = true) {
3770 // locate item to be deleted
3772 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3779 notice( t('Item not found.') . EOL);
3780 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3785 $owner = $item['uid'];
3789 // check if logged in user is either the author or owner of this item
3791 if(is_array($_SESSION['remote'])) {
3792 foreach($_SESSION['remote'] as $visitor) {
3793 if($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
3794 $cid = $visitor['cid'];
3801 if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
3803 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
3806 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3807 dbesc(datetime_convert()),
3808 dbesc(datetime_convert()),
3812 // clean up categories and tags so they don't end up as orphans
3815 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3817 foreach($matches as $mtch) {
3818 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3824 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3826 foreach($matches as $mtch) {
3827 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3831 // If item is a link to a photo resource, nuke all the associated photos
3832 // (visitors will not have photo resources)
3833 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3834 // generate a resource-id and therefore aren't intimately linked to the item.
3836 if(strlen($item['resource-id'])) {
3837 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3838 dbesc($item['resource-id']),
3839 intval($item['uid'])
3841 // ignore the result
3844 // If item is a link to an event, nuke the event record.
3846 if(intval($item['event-id'])) {
3847 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3848 intval($item['event-id']),
3849 intval($item['uid'])
3851 // ignore the result
3854 // clean up item_id and sign meta-data tables
3856 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3857 intval($item['id']),
3858 intval($item['uid'])
3861 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3862 intval($item['id']),
3863 intval($item['uid'])
3866 // If it's the parent of a comment thread, kill all the kids
3868 if($item['uri'] == $item['parent-uri']) {
3869 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3870 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3871 dbesc(datetime_convert()),
3872 dbesc(datetime_convert()),
3873 dbesc($item['parent-uri']),
3874 intval($item['uid'])
3876 // ignore the result
3879 // ensure that last-child is set in case the comment that had it just got wiped.
3880 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3881 dbesc(datetime_convert()),
3882 dbesc($item['parent-uri']),
3883 intval($item['uid'])
3885 // who is the last child now?
3886 $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",
3887 dbesc($item['parent-uri']),
3888 intval($item['uid'])
3891 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3896 // Add a relayable_retraction signature for Diaspora.
3897 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
3899 $drop_id = intval($item['id']);
3901 // send the notification upstream/downstream as the case may be
3906 proc_run('php',"include/notifier.php","drop","$drop_id");
3907 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3913 notice( t('Permission denied.') . EOL);
3914 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3921 function first_post_date($uid,$wall = false) {
3922 $r = q("select id, created from item
3923 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3925 order by created asc limit 1",
3927 intval($wall ? 1 : 0)
3930 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3931 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3936 function posted_dates($uid,$wall) {
3937 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3939 $dthen = first_post_date($uid,$wall);
3943 // If it's near the end of a long month, backup to the 28th so that in
3944 // consecutive loops we'll always get a whole month difference.
3946 if(intval(substr($dnow,8)) > 28)
3947 $dnow = substr($dnow,0,8) . '28';
3948 if(intval(substr($dthen,8)) > 28)
3949 $dnow = substr($dthen,0,8) . '28';
3952 // Starting with the current month, get the first and last days of every
3953 // month down to and including the month of the first post
3954 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
3955 $dstart = substr($dnow,0,8) . '01';
3956 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3957 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3958 $end_month = datetime_convert('','',$dend,'Y-m-d');
3959 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3960 $ret[] = array($str,$end_month,$start_month);
3961 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3967 function posted_date_widget($url,$uid,$wall) {
3970 // For former Facebook folks that left because of "timeline"
3972 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3975 $ret = posted_dates($uid,$wall);
3979 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3980 '$title' => t('Archives'),
3981 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3988 function store_diaspora_retract_sig($item, $user, $baseurl) {
3989 // Note that we can't add a target_author_signature
3990 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3991 // the comment, that means we're the home of the post, and Diaspora will only
3992 // check the parent_author_signature of retractions that it doesn't have to relay further
3994 // I don't think this function gets called for an "unlike," but I'll check anyway
3996 $enabled = intval(get_config('system','diaspora_enabled'));
3998 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
4002 logger('drop_item: storing diaspora retraction signature');
4004 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
4006 if(local_user() == $item['uid']) {
4008 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
4009 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
4012 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
4013 $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
4016 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
4017 // only handles DFRN deletes
4018 $handle_baseurl_start = strpos($r['url'],'://') + 3;
4019 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
4020 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
4026 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
4027 intval($item['id']),
4028 dbesc($signed_text),