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 = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
382 $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
384 $body = strip_tags($body);
386 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
387 $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
389 if (strlen($title) < strlen($body))
390 $body = substr($body, 0, strlen($title));
392 if (($title != $body) and (substr($title, -3) == "...")) {
393 $pos = strrpos($title, "...");
395 $title = substr($title, 0, $pos);
396 $body = substr($body, 0, $pos);
400 return($title == $body);
405 function get_atom_elements($feed,$item) {
407 require_once('library/HTMLPurifier.auto.php');
408 require_once('include/html2bbcode.php');
410 $best_photo = array();
414 $author = $item->get_author();
416 $res['author-name'] = unxmlify($author->get_name());
417 $res['author-link'] = unxmlify($author->get_link());
420 $res['author-name'] = unxmlify($feed->get_title());
421 $res['author-link'] = unxmlify($feed->get_permalink());
423 $res['uri'] = unxmlify($item->get_id());
424 $res['title'] = unxmlify($item->get_title());
425 $res['body'] = unxmlify($item->get_content());
426 $res['plink'] = unxmlify($item->get_link(0));
428 // removing the content of the title if its identically to the body
429 // This helps with auto generated titles e.g. from tumblr
430 if (title_is_body($res["title"], $res["body"]))
434 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
438 // look for a photo. We should check media size and find the best one,
439 // but for now let's just find any author photo
441 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
443 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
444 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
445 foreach($base as $link) {
446 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
447 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
448 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
453 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
455 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
456 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
457 if($base && count($base)) {
458 foreach($base as $link) {
459 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
460 $res['author-link'] = unxmlify($link['attribs']['']['href']);
461 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
462 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
463 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
469 // No photo/profile-link on the item - look at the feed level
471 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
472 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
473 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
474 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
475 foreach($base as $link) {
476 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
477 $res['author-link'] = unxmlify($link['attribs']['']['href']);
478 if(! $res['author-avatar']) {
479 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
480 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
485 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
487 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
488 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
490 if($base && count($base)) {
491 foreach($base as $link) {
492 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
493 $res['author-link'] = unxmlify($link['attribs']['']['href']);
494 if(! (x($res,'author-avatar'))) {
495 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
496 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
503 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
504 if($apps && $apps[0]['attribs']['']['source']) {
505 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
506 if($res['app'] === 'web')
507 $res['app'] = 'OStatus';
510 // base64 encoded json structure representing Diaspora signature
512 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
514 $res['dsprsig'] = unxmlify($dsig[0]['data']);
517 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
519 $res['guid'] = unxmlify($dguid[0]['data']);
521 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
523 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
527 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
530 $have_real_body = false;
532 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
534 $have_real_body = true;
535 $res['body'] = $rawenv[0]['data'];
536 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
537 // make sure nobody is trying to sneak some html tags by us
538 $res['body'] = notags(base64url_decode($res['body']));
542 $res['body'] = limit_body_size($res['body']);
544 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
545 // the content type. Our own network only emits text normally, though it might have been converted to
546 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
547 // have to assume it is all html and needs to be purified.
549 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
550 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
551 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
554 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
556 $res['body'] = reltoabs($res['body'],$base_url);
558 $res['body'] = html2bb_video($res['body']);
560 $res['body'] = oembed_html2bbcode($res['body']);
562 $config = HTMLPurifier_Config::createDefault();
563 $config->set('Cache.DefinitionImpl', null);
565 // we shouldn't need a whitelist, because the bbcode converter
566 // will strip out any unsupported tags.
568 $purifier = new HTMLPurifier($config);
569 $res['body'] = $purifier->purify($res['body']);
571 $res['body'] = @html2bbcode($res['body']);
575 elseif(! $have_real_body) {
577 // it's not one of our messages and it has no tags
578 // so it's probably just text. We'll escape it just to be safe.
580 $res['body'] = escape_tags($res['body']);
583 // this tag is obsolete but we keep it for really old sites
585 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
586 if($allow && $allow[0]['data'] == 1)
587 $res['last-child'] = 1;
589 $res['last-child'] = 0;
591 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
592 if($private && intval($private[0]['data']) > 0)
593 $res['private'] = intval($private[0]['data']);
597 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
598 if($extid && $extid[0]['data'])
599 $res['extid'] = $extid[0]['data'];
601 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
603 $res['location'] = unxmlify($rawlocation[0]['data']);
606 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
608 $res['created'] = unxmlify($rawcreated[0]['data']);
611 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
613 $res['edited'] = unxmlify($rawedited[0]['data']);
615 if((x($res,'edited')) && (! (x($res,'created'))))
616 $res['created'] = $res['edited'];
618 if(! $res['created'])
619 $res['created'] = $item->get_date('c');
622 $res['edited'] = $item->get_date('c');
625 // Disallow time travelling posts
627 $d1 = strtotime($res['created']);
628 $d2 = strtotime($res['edited']);
629 $d3 = strtotime('now');
632 $res['created'] = datetime_convert();
634 $res['edited'] = datetime_convert();
636 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
637 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
638 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
639 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
640 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
641 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
642 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
643 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
644 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
646 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
647 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
649 foreach($base as $link) {
650 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
651 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
652 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
657 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
659 $res['coord'] = unxmlify($rawgeo[0]['data']);
662 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
664 // select between supported verbs
667 $res['verb'] = unxmlify($rawverb[0]['data']);
670 // translate OStatus unfollow to activity streams if it happened to get selected
672 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
673 $res['verb'] = ACTIVITY_UNFOLLOW;
675 $cats = $item->get_categories();
678 foreach($cats as $cat) {
679 $term = $cat->get_term();
681 $term = $cat->get_label();
682 $scheme = $cat->get_scheme();
683 if($scheme && $term && stristr($scheme,'X-DFRN:'))
684 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
686 $tag_arr[] = notags(trim($term));
688 $res['tag'] = implode(',', $tag_arr);
691 $attach = $item->get_enclosures();
694 foreach($attach as $att) {
695 $len = intval($att->get_length());
696 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
697 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
698 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
699 if(strpos($type,';'))
700 $type = substr($type,0,strpos($type,';'));
701 if((! $link) || (strpos($link,'http') !== 0))
707 $type = 'application/octet-stream';
709 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
711 $res['attach'] = implode(',', $att_arr);
714 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
717 $res['object'] = '<object>' . "\n";
718 $child = $rawobj[0]['child'];
719 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
720 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
721 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
723 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
724 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
725 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
726 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
727 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
728 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
729 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
730 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
732 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
733 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
734 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
735 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
737 $body = html2bb_video($body);
739 $config = HTMLPurifier_Config::createDefault();
740 $config->set('Cache.DefinitionImpl', null);
742 $purifier = new HTMLPurifier($config);
743 $body = $purifier->purify($body);
744 $body = html2bbcode($body);
747 $res['object'] .= '<content>' . $body . '</content>' . "\n";
750 $res['object'] .= '</object>' . "\n";
753 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
756 $res['target'] = '<target>' . "\n";
757 $child = $rawobj[0]['child'];
758 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
759 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
761 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
762 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
763 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
764 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
765 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
766 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
767 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
768 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
770 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
771 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
772 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
773 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
775 $body = html2bb_video($body);
777 $config = HTMLPurifier_Config::createDefault();
778 $config->set('Cache.DefinitionImpl', null);
780 $purifier = new HTMLPurifier($config);
781 $body = $purifier->purify($body);
782 $body = html2bbcode($body);
785 $res['target'] .= '<content>' . $body . '</content>' . "\n";
788 $res['target'] .= '</target>' . "\n";
791 // This is some experimental stuff. By now retweets are shown with "RT:"
792 // But: There is data so that the message could be shown similar to native retweets
793 // There is some better way to parse this array - but it didn't worked for me.
794 $child = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://activitystrea.ms/spec/1.0/"][object][0]["child"];
795 if (is_array($child)) {
796 logger('get_atom_elements: Looking for status.net repeated message');
798 $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
799 $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
800 $uri = $author["uri"][0]["data"];
801 $name = $author["name"][0]["data"];
802 $avatar = @array_shift($author["link"][2]["attribs"]);
803 $avatar = $avatar["href"];
805 if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
806 logger('get_atom_elements: fixing sender of repeated message');
808 $res["owner-name"] = $res["author-name"];
809 $res["owner-link"] = $res["author-link"];
810 $res["owner-avatar"] = $res["author-avatar"];
812 $res["author-name"] = $name;
813 $res["author-link"] = $uri;
814 $res["author-avatar"] = $avatar;
816 $res["body"] = html2bbcode($message);
820 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
822 call_hooks('parse_atom', $arr);
824 //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
825 //if (strpos($res["body"], "RT @") !== false) {
826 // $debugfile = tempnam("/home/ike/log", "item-res2-");
827 // file_put_contents($debugfile, serialize($arr));
833 function encode_rel_links($links) {
835 if(! ((is_array($links)) && (count($links))))
837 foreach($links as $link) {
839 if($link['attribs']['']['rel'])
840 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
841 if($link['attribs']['']['type'])
842 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
843 if($link['attribs']['']['href'])
844 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
845 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
846 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
847 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
848 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
856 function item_store($arr,$force_parent = false) {
858 // If a Diaspora signature structure was passed in, pull it out of the
859 // item array and set it aside for later storage.
862 if(x($arr,'dsprsig')) {
863 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
864 unset($arr['dsprsig']);
867 if(x($arr, 'gravity'))
868 $arr['gravity'] = intval($arr['gravity']);
869 elseif($arr['parent-uri'] === $arr['uri'])
871 elseif(activity_match($arr['verb'],ACTIVITY_POST))
874 $arr['gravity'] = 6; // extensible catchall
877 $arr['type'] = 'remote';
879 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
881 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
882 $arr['body'] = strip_tags($arr['body']);
885 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
886 require_once('Text/LanguageDetect.php');
887 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
888 $l = new Text_LanguageDetect;
889 $lng = $l->detectConfidence($naked_body);
890 $arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
893 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
894 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
895 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
896 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
897 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
898 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
899 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
900 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
901 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
902 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
903 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
904 $arr['commented'] = datetime_convert();
905 $arr['received'] = datetime_convert();
906 $arr['changed'] = datetime_convert();
907 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
908 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
909 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
910 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
911 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
913 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
914 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
915 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
916 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
917 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
918 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
919 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
920 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
921 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
922 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
923 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
924 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
925 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
926 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
927 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
928 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
929 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
930 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
931 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
933 if($arr['parent-uri'] === $arr['uri']) {
936 $allow_cid = $arr['allow_cid'];
937 $allow_gid = $arr['allow_gid'];
938 $deny_cid = $arr['deny_cid'];
939 $deny_gid = $arr['deny_gid'];
943 // find the parent and snarf the item id and ACL's
944 // and anything else we need to inherit
946 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
947 dbesc($arr['parent-uri']),
953 // is the new message multi-level threaded?
954 // even though we don't support it now, preserve the info
955 // and re-attach to the conversation parent.
957 if($r[0]['uri'] != $r[0]['parent-uri']) {
958 $arr['thr-parent'] = $arr['parent-uri'];
959 $arr['parent-uri'] = $r[0]['parent-uri'];
960 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
961 ORDER BY `id` ASC LIMIT 1",
962 dbesc($r[0]['parent-uri']),
963 dbesc($r[0]['parent-uri']),
970 $parent_id = $r[0]['id'];
971 $parent_deleted = $r[0]['deleted'];
972 $allow_cid = $r[0]['allow_cid'];
973 $allow_gid = $r[0]['allow_gid'];
974 $deny_cid = $r[0]['deny_cid'];
975 $deny_gid = $r[0]['deny_gid'];
976 $arr['wall'] = $r[0]['wall'];
978 // if the parent is private, force privacy for the entire conversation
979 // This differs from the above settings as it subtly allows comments from
980 // email correspondents to be private even if the overall thread is not.
983 $arr['private'] = $r[0]['private'];
985 // Edge case. We host a public forum that was originally posted to privately.
986 // The original author commented, but as this is a comment, the permissions
987 // weren't fixed up so it will still show the comment as private unless we fix it here.
989 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
994 // Allow one to see reply tweets from status.net even when
995 // we don't have or can't see the original post.
998 logger('item_store: $force_parent=true, reply converted to top-level post.');
1000 $arr['thr-parent'] = $arr['parent-uri'];
1001 $arr['parent-uri'] = $arr['uri'];
1002 $arr['gravity'] = 0;
1005 logger('item_store: item parent was not found - ignoring item');
1009 $parent_deleted = 0;
1013 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1017 if($r && count($r)) {
1018 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
1022 call_hooks('post_remote',$arr);
1024 if(x($arr,'cancel')) {
1025 logger('item_store: post cancelled by plugin.');
1031 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
1033 $r = dbq("INSERT INTO `item` (`"
1034 . implode("`, `", array_keys($arr))
1036 . implode("', '", array_values($arr))
1039 // find the item we just created
1041 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
1042 $arr['uri'], // already dbesc'd
1047 $current_post = $r[0]['id'];
1048 logger('item_store: created item ' . $current_post);
1051 logger('item_store: could not locate created item');
1055 logger('item_store: duplicated post occurred. Removing duplicates.');
1056 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
1058 intval($arr['uid']),
1059 intval($current_post)
1063 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
1064 $parent_id = $current_post;
1066 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1069 $private = $arr['private'];
1071 // Set parent id - and also make sure to inherit the parent's ACL's.
1073 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1074 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1081 intval($parent_deleted),
1082 intval($current_post)
1085 $arr['id'] = $current_post;
1086 $arr['parent'] = $parent_id;
1087 $arr['allow_cid'] = $allow_cid;
1088 $arr['allow_gid'] = $allow_gid;
1089 $arr['deny_cid'] = $deny_cid;
1090 $arr['deny_gid'] = $deny_gid;
1091 $arr['private'] = $private;
1092 $arr['deleted'] = $parent_deleted;
1093 call_hooks('post_remote_end',$arr);
1095 // update the commented timestamp on the parent
1097 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1098 dbesc(datetime_convert()),
1099 dbesc(datetime_convert()),
1104 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1105 intval($current_post),
1106 dbesc($dsprsig->signed_text),
1107 dbesc($dsprsig->signature),
1108 dbesc($dsprsig->signer)
1114 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1117 if($arr['last-child']) {
1118 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1120 intval($arr['uid']),
1121 intval($current_post)
1125 tag_deliver($arr['uid'],$current_post);
1127 return $current_post;
1130 function get_item_contact($item,$contacts) {
1131 if(! count($contacts) || (! is_array($item)))
1133 foreach($contacts as $contact) {
1134 if($contact['id'] == $item['contact-id']) {
1136 break; // NOTREACHED
1143 function tag_deliver($uid,$item_id) {
1145 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1151 $u = q("select * from user where uid = %d limit 1",
1157 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1158 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1161 $i = q("select * from item where id = %d and uid = %d limit 1",
1170 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1172 // Diaspora uses their own hardwired link URL in @-tags
1173 // instead of the one we supply with webfinger
1175 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1177 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1179 foreach($matches as $mtch) {
1180 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1182 logger('tag_deliver: mention found: ' . $mtch[2]);
1190 // send a notification
1192 require_once('include/enotify.php');
1194 'type' => NOTIFY_TAGSELF,
1195 'notify_flags' => $u[0]['notify-flags'],
1196 'language' => $u[0]['language'],
1197 'to_name' => $u[0]['username'],
1198 'to_email' => $u[0]['email'],
1199 'uid' => $u[0]['uid'],
1201 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1202 'source_name' => $item['author-name'],
1203 'source_link' => $item['author-link'],
1204 'source_photo' => $item['author-avatar'],
1205 'verb' => ACTIVITY_TAG,
1209 if((! $community_page) && (! $prvgroup))
1213 // tgroup delivery - setup a second delivery chain
1214 // prevent delivery looping - only proceed
1215 // if the message originated elsewhere and is a top-level post
1217 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1220 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1223 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1224 intval($u[0]['uid'])
1229 // also reset all the privacy bits to the forum default permissions
1231 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1233 $forum_mode = (($prvgroup) ? 2 : 1);
1235 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1236 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1237 intval($forum_mode),
1238 dbesc($c[0]['name']),
1239 dbesc($c[0]['url']),
1240 dbesc($c[0]['thumb']),
1242 dbesc($u[0]['allow_cid']),
1243 dbesc($u[0]['allow_gid']),
1244 dbesc($u[0]['deny_cid']),
1245 dbesc($u[0]['deny_gid']),
1249 proc_run('php','include/notifier.php','tgroup',$item_id);
1258 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1262 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1264 if($contact['duplex'] && $contact['dfrn-id'])
1265 $idtosend = '0:' . $orig_id;
1266 if($contact['duplex'] && $contact['issued-id'])
1267 $idtosend = '1:' . $orig_id;
1269 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1271 $rino_enable = get_config('system','rino_encrypt');
1276 $ssl_val = intval(get_config('system','ssl_policy'));
1280 case SSL_POLICY_FULL:
1281 $ssl_policy = 'full';
1283 case SSL_POLICY_SELFSIGN:
1284 $ssl_policy = 'self';
1286 case SSL_POLICY_NONE:
1288 $ssl_policy = 'none';
1292 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1294 logger('dfrn_deliver: ' . $url);
1296 $xml = fetch_url($url);
1298 $curl_stat = $a->get_curl_code();
1300 return(-1); // timed out
1302 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1307 if(strpos($xml,'<?xml') === false) {
1308 logger('dfrn_deliver: no valid XML returned');
1309 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1313 $res = parse_xml_string($xml);
1315 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1316 return (($res->status) ? $res->status : 3);
1318 $postvars = array();
1319 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1320 $challenge = hex2bin((string) $res->challenge);
1321 $perm = (($res->perm) ? $res->perm : null);
1322 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1323 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1324 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1326 if($owner['page-flags'] == PAGE_PRVGROUP)
1329 $final_dfrn_id = '';
1332 if((($perm == 'rw') && (! intval($contact['writable'])))
1333 || (($perm == 'r') && (intval($contact['writable'])))) {
1334 q("update contact set writable = %d where id = %d limit 1",
1335 intval(($perm == 'rw') ? 1 : 0),
1336 intval($contact['id'])
1338 $contact['writable'] = (string) 1 - intval($contact['writable']);
1342 if(($contact['duplex'] && strlen($contact['pubkey']))
1343 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1344 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1345 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1346 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1349 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1350 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1353 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1355 if(strpos($final_dfrn_id,':') == 1)
1356 $final_dfrn_id = substr($final_dfrn_id,2);
1358 if($final_dfrn_id != $orig_id) {
1359 logger('dfrn_deliver: wrong dfrn_id.');
1360 // did not decode properly - cannot trust this site
1364 $postvars['dfrn_id'] = $idtosend;
1365 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1367 $postvars['dissolve'] = '1';
1370 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1371 $postvars['data'] = $atom;
1372 $postvars['perm'] = 'rw';
1375 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1376 $postvars['perm'] = 'r';
1379 $postvars['ssl_policy'] = $ssl_policy;
1382 $postvars['page'] = $page;
1384 if($rino && $rino_allowed && (! $dissolve)) {
1385 $key = substr(random_string(),0,16);
1386 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1387 $postvars['data'] = $data;
1388 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1391 if($dfrn_version >= 2.1) {
1392 if(($contact['duplex'] && strlen($contact['pubkey']))
1393 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1394 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1396 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1399 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1403 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1404 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1407 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1411 logger('md5 rawkey ' . md5($postvars['key']));
1413 $postvars['key'] = bin2hex($postvars['key']);
1416 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1418 $xml = post_url($contact['notify'],$postvars);
1420 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1422 $curl_stat = $a->get_curl_code();
1423 if((! $curl_stat) || (! strlen($xml)))
1424 return(-1); // timed out
1426 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1429 if(strpos($xml,'<?xml') === false) {
1430 logger('dfrn_deliver: phase 2: no valid XML returned');
1431 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1435 if($contact['term-date'] != '0000-00-00 00:00:00') {
1436 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1437 require_once('include/Contact.php');
1438 unmark_for_death($contact);
1441 $res = parse_xml_string($xml);
1443 return $res->status;
1449 * consume_feed - process atom feed and update anything/everything we might need to update
1451 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1453 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1454 * It is this person's stuff that is going to be updated.
1455 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1456 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1457 * have a contact record.
1458 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1459 * might not) try and subscribe to it.
1460 * $datedir sorts in reverse order
1461 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1462 * imported prior to its children being seen in the stream unless we are certain
1463 * of how the feed is arranged/ordered.
1464 * With $pass = 1, we only pull parent items out of the stream.
1465 * With $pass = 2, we only pull children (comments/likes).
1467 * So running this twice, first with pass 1 and then with pass 2 will do the right
1468 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1469 * model where comments can have sub-threads. That would require some massive sorting
1470 * to get all the feed items into a mostly linear ordering, and might still require
1474 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1476 require_once('library/simplepie/simplepie.inc');
1478 if(! strlen($xml)) {
1479 logger('consume_feed: empty input');
1483 $feed = new SimplePie();
1484 $feed->set_raw_data($xml);
1486 $feed->enable_order_by_date(true);
1488 $feed->enable_order_by_date(false);
1492 logger('consume_feed: Error parsing XML: ' . $feed->error());
1494 $permalink = $feed->get_permalink();
1496 // Check at the feed level for updated contact name and/or photo
1500 $photo_timestamp = '';
1504 $hubs = $feed->get_links('hub');
1505 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1508 $hub = implode(',', $hubs);
1510 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1512 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1514 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1515 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1516 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1517 $new_name = $elems['name'][0]['data'];
1519 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1520 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1521 $photo_url = $elems['link'][0]['attribs']['']['href'];
1524 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1525 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1529 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1530 logger('consume_feed: Updating photo for ' . $contact['name']);
1531 require_once("Photo.php");
1532 $photo_failure = false;
1533 $have_photo = false;
1535 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1536 intval($contact['id']),
1537 intval($contact['uid'])
1540 $resource_id = $r[0]['resource-id'];
1544 $resource_id = photo_new_resource();
1547 $img_str = fetch_url($photo_url,true);
1548 // guess mimetype from headers or filename
1549 $type = guess_image_type($photo_url,true);
1552 $img = new Photo($img_str, $type);
1553 if($img->is_valid()) {
1555 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1556 dbesc($resource_id),
1557 intval($contact['id']),
1558 intval($contact['uid'])
1562 $img->scaleImageSquare(175);
1564 $hash = $resource_id;
1565 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1567 $img->scaleImage(80);
1568 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1570 $img->scaleImage(48);
1571 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1575 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1576 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1577 dbesc(datetime_convert()),
1578 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1579 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1580 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1581 intval($contact['uid']),
1582 intval($contact['id'])
1587 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1588 $r = q("select * from contact where uid = %d and id = %d limit 1",
1589 intval($contact['uid']),
1590 intval($contact['id'])
1593 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1594 dbesc(notags(trim($new_name))),
1595 dbesc(datetime_convert()),
1596 intval($contact['uid']),
1597 intval($contact['id'])
1600 // do our best to update the name on content items
1603 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1604 dbesc(notags(trim($new_name))),
1605 dbesc($r[0]['name']),
1606 dbesc($r[0]['url']),
1607 intval($contact['uid'])
1612 if(strlen($birthday)) {
1613 if(substr($birthday,0,4) != $contact['bdyear']) {
1614 logger('consume_feed: updating birthday: ' . $birthday);
1618 * Add new birthday event for this person
1620 * $bdtext is just a readable placeholder in case the event is shared
1621 * with others. We will replace it during presentation to our $importer
1622 * to contain a sparkle link and perhaps a photo.
1626 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1627 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1630 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1631 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1632 intval($contact['uid']),
1633 intval($contact['id']),
1634 dbesc(datetime_convert()),
1635 dbesc(datetime_convert()),
1636 dbesc(datetime_convert('UTC','UTC', $birthday)),
1637 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1646 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1647 dbesc(substr($birthday,0,4)),
1648 intval($contact['uid']),
1649 intval($contact['id'])
1652 // This function is called twice without reloading the contact
1653 // Make sure we only create one event. This is why &$contact
1654 // is a reference var in this function
1656 $contact['bdyear'] = substr($birthday,0,4);
1661 $community_page = 0;
1662 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1664 $community_page = intval($rawtags[0]['data']);
1666 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1667 q("update contact set forum = %d where id = %d limit 1",
1668 intval($community_page),
1669 intval($contact['id'])
1671 $contact['forum'] = (string) $community_page;
1675 // process any deleted entries
1677 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1678 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1679 foreach($del_entries as $dentry) {
1681 if(isset($dentry['attribs']['']['ref'])) {
1682 $uri = $dentry['attribs']['']['ref'];
1684 if(isset($dentry['attribs']['']['when'])) {
1685 $when = $dentry['attribs']['']['when'];
1686 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1689 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1691 if($deleted && is_array($contact)) {
1692 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1693 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1695 intval($importer['uid']),
1696 intval($contact['id'])
1701 if(! $item['deleted'])
1702 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1704 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1705 $xo = parse_xml_string($item['object'],false);
1706 $xt = parse_xml_string($item['target'],false);
1707 if($xt->type === ACTIVITY_OBJ_NOTE) {
1708 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1710 intval($importer['importer_uid'])
1714 // For tags, the owner cannot remove the tag on the author's copy of the post.
1716 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1717 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1718 $author_copy = (($item['origin']) ? true : false);
1720 if($owner_remove && $author_copy)
1722 if($author_remove || $owner_remove) {
1723 $tags = explode(',',$i[0]['tag']);
1726 foreach($tags as $tag)
1727 if(trim($tag) !== trim($xo->body))
1728 $newtags[] = trim($tag);
1730 q("update item set tag = '%s' where id = %d limit 1",
1731 dbesc(implode(',',$newtags)),
1739 if($item['uri'] == $item['parent-uri']) {
1740 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1741 `body` = '', `title` = ''
1742 WHERE `parent-uri` = '%s' AND `uid` = %d",
1744 dbesc(datetime_convert()),
1745 dbesc($item['uri']),
1746 intval($importer['uid'])
1750 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1751 `body` = '', `title` = ''
1752 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1754 dbesc(datetime_convert()),
1756 intval($importer['uid'])
1758 if($item['last-child']) {
1759 // ensure that last-child is set in case the comment that had it just got wiped.
1760 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1761 dbesc(datetime_convert()),
1762 dbesc($item['parent-uri']),
1763 intval($item['uid'])
1765 // who is the last child now?
1766 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1767 ORDER BY `created` DESC LIMIT 1",
1768 dbesc($item['parent-uri']),
1769 intval($importer['uid'])
1772 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1783 // Now process the feed
1785 if($feed->get_item_quantity()) {
1787 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1789 // in inverse date order
1791 $items = array_reverse($feed->get_items());
1793 $items = $feed->get_items();
1796 foreach($items as $item) {
1799 $item_id = $item->get_id();
1800 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1801 if(isset($rawthread[0]['attribs']['']['ref'])) {
1803 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1806 if(($is_reply) && is_array($contact)) {
1811 // Have we seen it? If not, import it.
1813 $item_id = $item->get_id();
1814 $datarray = get_atom_elements($feed,$item);
1816 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1817 $datarray['author-name'] = $contact['name'];
1818 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1819 $datarray['author-link'] = $contact['url'];
1820 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1821 $datarray['author-avatar'] = $contact['thumb'];
1823 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1824 logger('consume_feed: no author information! ' . print_r($datarray,true));
1828 $force_parent = false;
1829 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1830 if($contact['network'] === NETWORK_OSTATUS)
1831 $force_parent = true;
1832 if(strlen($datarray['title']))
1833 unset($datarray['title']);
1834 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1835 dbesc(datetime_convert()),
1837 intval($importer['uid'])
1839 $datarray['last-child'] = 1;
1843 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1845 intval($importer['uid'])
1848 // Update content if 'updated' changes
1851 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1853 // do not accept (ignore) an earlier edit than one we currently have.
1854 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1857 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1858 dbesc($datarray['title']),
1859 dbesc($datarray['body']),
1860 dbesc($datarray['tag']),
1861 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1863 intval($importer['uid'])
1867 // update last-child if it changes
1869 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1870 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1871 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1872 dbesc(datetime_convert()),
1874 intval($importer['uid'])
1876 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1877 intval($allow[0]['data']),
1878 dbesc(datetime_convert()),
1880 intval($importer['uid'])
1887 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1888 // one way feed - no remote comment ability
1889 $datarray['last-child'] = 0;
1891 $datarray['parent-uri'] = $parent_uri;
1892 $datarray['uid'] = $importer['uid'];
1893 $datarray['contact-id'] = $contact['id'];
1894 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1895 $datarray['type'] = 'activity';
1896 $datarray['gravity'] = GRAVITY_LIKE;
1897 // only one like or dislike per person
1898 $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",
1899 intval($datarray['uid']),
1900 intval($datarray['contact-id']),
1901 dbesc($datarray['verb']),
1909 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1910 $xo = parse_xml_string($datarray['object'],false);
1911 $xt = parse_xml_string($datarray['target'],false);
1913 if($xt->type == ACTIVITY_OBJ_NOTE) {
1914 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1916 intval($importer['importer_uid'])
1921 // extract tag, if not duplicate, add to parent item
1922 if($xo->id && $xo->content) {
1923 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1924 if(! (stristr($r[0]['tag'],$newtag))) {
1925 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1926 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1934 $r = item_store($datarray,$force_parent);
1940 // Head post of a conversation. Have we seen it? If not, import it.
1942 $item_id = $item->get_id();
1944 $datarray = get_atom_elements($feed,$item);
1946 if(is_array($contact)) {
1947 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1948 $datarray['author-name'] = $contact['name'];
1949 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1950 $datarray['author-link'] = $contact['url'];
1951 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1952 $datarray['author-avatar'] = $contact['thumb'];
1955 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1956 logger('consume_feed: no author information! ' . print_r($datarray,true));
1960 // special handling for events
1962 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1963 $ev = bbtoevent($datarray['body']);
1964 if(x($ev,'desc') && x($ev,'start')) {
1965 $ev['uid'] = $importer['uid'];
1966 $ev['uri'] = $item_id;
1967 $ev['edited'] = $datarray['edited'];
1968 $ev['private'] = $datarray['private'];
1970 if(is_array($contact))
1971 $ev['cid'] = $contact['id'];
1972 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1974 intval($importer['uid'])
1977 $ev['id'] = $r[0]['id'];
1978 $xyz = event_store($ev);
1983 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1984 if(strlen($datarray['title']))
1985 unset($datarray['title']);
1986 $datarray['last-child'] = 1;
1990 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1992 intval($importer['uid'])
1995 // Update content if 'updated' changes
1998 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2000 // do not accept (ignore) an earlier edit than one we currently have.
2001 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2004 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2005 dbesc($datarray['title']),
2006 dbesc($datarray['body']),
2007 dbesc($datarray['tag']),
2008 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2010 intval($importer['uid'])
2014 // update last-child if it changes
2016 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2017 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2018 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2019 intval($allow[0]['data']),
2020 dbesc(datetime_convert()),
2022 intval($importer['uid'])
2028 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
2029 logger('consume-feed: New follower');
2030 new_follower($importer,$contact,$datarray,$item);
2033 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
2034 lose_follower($importer,$contact,$datarray,$item);
2038 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
2039 logger('consume-feed: New friend request');
2040 new_follower($importer,$contact,$datarray,$item,true);
2043 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
2044 lose_sharer($importer,$contact,$datarray,$item);
2049 if(! is_array($contact))
2053 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2054 // one way feed - no remote comment ability
2055 $datarray['last-child'] = 0;
2057 if($contact['network'] === NETWORK_FEED)
2058 $datarray['private'] = 2;
2060 // This is my contact on another system, but it's really me.
2061 // Turn this into a wall post.
2063 if($contact['remote_self']) {
2064 $datarray['wall'] = 1;
2065 if($contact['network'] === NETWORK_FEED) {
2066 $datarray['private'] = 0;
2070 $datarray['parent-uri'] = $item_id;
2071 $datarray['uid'] = $importer['uid'];
2072 $datarray['contact-id'] = $contact['id'];
2074 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2075 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2076 // but otherwise there's a possible data mixup on the sender's system.
2077 // the tgroup delivery code called from item_store will correct it if it's a forum,
2078 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2079 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2080 $datarray['owner-name'] = $contact['name'];
2081 $datarray['owner-link'] = $contact['url'];
2082 $datarray['owner-avatar'] = $contact['thumb'];
2085 $r = item_store($datarray);
2093 function local_delivery($importer,$data) {
2097 if($importer['readonly']) {
2098 // We aren't receiving stuff from this person. But we will quietly ignore them
2099 // rather than a blatant "go away" message.
2100 logger('local_delivery: ignoring');
2105 // Consume notification feed. This may differ from consuming a public feed in several ways
2106 // - might contain email or friend suggestions
2107 // - might contain remote followup to our message
2108 // - in which case we need to accept it and then notify other conversants
2109 // - we may need to send various email notifications
2111 $feed = new SimplePie();
2112 $feed->set_raw_data($data);
2113 $feed->enable_order_by_date(false);
2118 logger('local_delivery: Error parsing XML: ' . $feed->error());
2121 // Check at the feed level for updated contact name and/or photo
2125 $photo_timestamp = '';
2129 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
2131 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
2133 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
2134 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
2135 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
2136 $new_name = $elems['name'][0]['data'];
2138 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
2139 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
2140 $photo_url = $elems['link'][0]['attribs']['']['href'];
2144 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
2145 logger('local_delivery: Updating photo for ' . $importer['name']);
2146 require_once("Photo.php");
2147 $photo_failure = false;
2148 $have_photo = false;
2150 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
2151 intval($importer['id']),
2152 intval($importer['importer_uid'])
2155 $resource_id = $r[0]['resource-id'];
2159 $resource_id = photo_new_resource();
2162 $img_str = fetch_url($photo_url,true);
2163 // guess mimetype from headers or filename
2164 $type = guess_image_type($photo_url,true);
2167 $img = new Photo($img_str, $type);
2168 if($img->is_valid()) {
2170 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
2171 dbesc($resource_id),
2172 intval($importer['id']),
2173 intval($importer['importer_uid'])
2177 $img->scaleImageSquare(175);
2179 $hash = $resource_id;
2180 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 4);
2182 $img->scaleImage(80);
2183 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 5);
2185 $img->scaleImage(48);
2186 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 6);
2190 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
2191 WHERE `uid` = %d AND `id` = %d LIMIT 1",
2192 dbesc(datetime_convert()),
2193 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
2194 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
2195 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
2196 intval($importer['importer_uid']),
2197 intval($importer['id'])
2202 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
2203 $r = q("select * from contact where uid = %d and id = %d limit 1",
2204 intval($importer['importer_uid']),
2205 intval($importer['id'])
2208 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2209 dbesc(notags(trim($new_name))),
2210 dbesc(datetime_convert()),
2211 intval($importer['importer_uid']),
2212 intval($importer['id'])
2215 // do our best to update the name on content items
2218 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
2219 dbesc(notags(trim($new_name))),
2220 dbesc($r[0]['name']),
2221 dbesc($r[0]['url']),
2222 intval($importer['importer_uid'])
2229 // Currently unsupported - needs a lot of work
2230 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2231 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2232 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2234 $newloc['uid'] = $importer['importer_uid'];
2235 $newloc['cid'] = $importer['id'];
2236 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2237 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2238 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2239 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2240 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2241 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2242 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2243 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
2244 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2245 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
2248 // merge with current record, current contents have priority
2249 // update record, set url-updated
2250 // update profile photos
2256 // handle friend suggestion notification
2258 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2259 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2260 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2262 $fsugg['uid'] = $importer['importer_uid'];
2263 $fsugg['cid'] = $importer['id'];
2264 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2265 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2266 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2267 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2268 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2270 // Does our member already have a friend matching this description?
2272 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2273 dbesc($fsugg['name']),
2274 dbesc(normalise_link($fsugg['url'])),
2275 intval($fsugg['uid'])
2280 // Do we already have an fcontact record for this person?
2283 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2284 dbesc($fsugg['url']),
2285 dbesc($fsugg['name']),
2286 dbesc($fsugg['request'])
2291 // OK, we do. Do we already have an introduction for this person ?
2292 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2293 intval($fsugg['uid']),
2300 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2301 dbesc($fsugg['name']),
2302 dbesc($fsugg['url']),
2303 dbesc($fsugg['photo']),
2304 dbesc($fsugg['request'])
2306 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2307 dbesc($fsugg['url']),
2308 dbesc($fsugg['name']),
2309 dbesc($fsugg['request'])
2314 // database record did not get created. Quietly give up.
2319 $hash = random_string();
2321 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2322 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2323 intval($fsugg['uid']),
2325 intval($fsugg['cid']),
2326 dbesc($fsugg['body']),
2328 dbesc(datetime_convert()),
2333 'type' => NOTIFY_SUGGEST,
2334 'notify_flags' => $importer['notify-flags'],
2335 'language' => $importer['language'],
2336 'to_name' => $importer['username'],
2337 'to_email' => $importer['email'],
2338 'uid' => $importer['importer_uid'],
2340 'link' => $a->get_baseurl() . '/notifications/intros',
2341 'source_name' => $importer['name'],
2342 'source_link' => $importer['url'],
2343 'source_photo' => $importer['photo'],
2344 'verb' => ACTIVITY_REQ_FRIEND,
2353 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2354 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2356 logger('local_delivery: private message received');
2359 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2362 $msg['uid'] = $importer['importer_uid'];
2363 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2364 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2365 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2366 $msg['contact-id'] = $importer['id'];
2367 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2368 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2370 $msg['replied'] = 0;
2371 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2372 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2373 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2377 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2378 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2380 // send notifications.
2382 require_once('include/enotify.php');
2384 $notif_params = array(
2385 'type' => NOTIFY_MAIL,
2386 'notify_flags' => $importer['notify-flags'],
2387 'language' => $importer['language'],
2388 'to_name' => $importer['username'],
2389 'to_email' => $importer['email'],
2390 'uid' => $importer['importer_uid'],
2392 'source_name' => $msg['from-name'],
2393 'source_link' => $importer['url'],
2394 'source_photo' => $importer['thumb'],
2395 'verb' => ACTIVITY_POST,
2399 notification($notif_params);
2405 $community_page = 0;
2406 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2408 $community_page = intval($rawtags[0]['data']);
2410 if(intval($importer['forum']) != $community_page) {
2411 q("update contact set forum = %d where id = %d limit 1",
2412 intval($community_page),
2413 intval($importer['id'])
2415 $importer['forum'] = (string) $community_page;
2418 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2420 // process any deleted entries
2422 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2423 if(is_array($del_entries) && count($del_entries)) {
2424 foreach($del_entries as $dentry) {
2426 if(isset($dentry['attribs']['']['ref'])) {
2427 $uri = $dentry['attribs']['']['ref'];
2429 if(isset($dentry['attribs']['']['when'])) {
2430 $when = $dentry['attribs']['']['when'];
2431 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2434 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2438 // check for relayed deletes to our conversation
2441 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2443 intval($importer['importer_uid'])
2446 $parent_uri = $r[0]['parent-uri'];
2447 if($r[0]['id'] != $r[0]['parent'])
2454 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2457 logger('local_delivery: possible community delete');
2460 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2462 // was the top-level post for this reply written by somebody on this site?
2463 // Specifically, the recipient?
2465 $is_a_remote_delete = false;
2467 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2468 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2469 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2470 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2471 AND `item`.`uid` = %d
2477 intval($importer['importer_uid'])
2480 $is_a_remote_delete = true;
2482 // Does this have the characteristics of a community or private group comment?
2483 // If it's a reply to a wall post on a community/prvgroup page it's a
2484 // valid community comment. Also forum_mode makes it valid for sure.
2485 // If neither, it's not.
2487 if($is_a_remote_delete && $community) {
2488 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2489 $is_a_remote_delete = false;
2490 logger('local_delivery: not a community delete');
2494 if($is_a_remote_delete) {
2495 logger('local_delivery: received remote delete');
2499 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2500 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2502 intval($importer['importer_uid']),
2503 intval($importer['id'])
2509 if($item['deleted'])
2512 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2514 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2515 $xo = parse_xml_string($item['object'],false);
2516 $xt = parse_xml_string($item['target'],false);
2518 if($xt->type === ACTIVITY_OBJ_NOTE) {
2519 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2521 intval($importer['importer_uid'])
2525 // For tags, the owner cannot remove the tag on the author's copy of the post.
2527 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2528 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2529 $author_copy = (($item['origin']) ? true : false);
2531 if($owner_remove && $author_copy)
2533 if($author_remove || $owner_remove) {
2534 $tags = explode(',',$i[0]['tag']);
2537 foreach($tags as $tag)
2538 if(trim($tag) !== trim($xo->body))
2539 $newtags[] = trim($tag);
2541 q("update item set tag = '%s' where id = %d limit 1",
2542 dbesc(implode(',',$newtags)),
2550 if($item['uri'] == $item['parent-uri']) {
2551 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2552 `body` = '', `title` = ''
2553 WHERE `parent-uri` = '%s' AND `uid` = %d",
2555 dbesc(datetime_convert()),
2556 dbesc($item['uri']),
2557 intval($importer['importer_uid'])
2561 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2562 `body` = '', `title` = ''
2563 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2565 dbesc(datetime_convert()),
2567 intval($importer['importer_uid'])
2569 if($item['last-child']) {
2570 // ensure that last-child is set in case the comment that had it just got wiped.
2571 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2572 dbesc(datetime_convert()),
2573 dbesc($item['parent-uri']),
2574 intval($item['uid'])
2576 // who is the last child now?
2577 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2578 ORDER BY `created` DESC LIMIT 1",
2579 dbesc($item['parent-uri']),
2580 intval($importer['importer_uid'])
2583 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2588 // if this is a relayed delete, propagate it to other recipients
2590 if($is_a_remote_delete)
2591 proc_run('php',"include/notifier.php","drop",$item['id']);
2599 foreach($feed->get_items() as $item) {
2602 $item_id = $item->get_id();
2603 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2604 if(isset($rawthread[0]['attribs']['']['ref'])) {
2606 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2612 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2615 logger('local_delivery: possible community reply');
2618 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2620 // was the top-level post for this reply written by somebody on this site?
2621 // Specifically, the recipient?
2623 $is_a_remote_comment = false;
2625 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2626 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2627 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2628 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2629 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2630 AND `item`.`uid` = %d
2636 intval($importer['importer_uid'])
2639 $is_a_remote_comment = true;
2641 // Does this have the characteristics of a community or private group comment?
2642 // If it's a reply to a wall post on a community/prvgroup page it's a
2643 // valid community comment. Also forum_mode makes it valid for sure.
2644 // If neither, it's not.
2646 if($is_a_remote_comment && $community) {
2647 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2648 $is_a_remote_comment = false;
2649 logger('local_delivery: not a community reply');
2653 if($is_a_remote_comment) {
2654 logger('local_delivery: received remote comment');
2656 // remote reply to our post. Import and then notify everybody else.
2658 $datarray = get_atom_elements($feed,$item);
2660 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2662 intval($importer['importer_uid'])
2665 // Update content if 'updated' changes
2669 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2671 // do not accept (ignore) an earlier edit than one we currently have.
2672 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2675 logger('received updated comment' , LOGGER_DEBUG);
2676 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2677 dbesc($datarray['title']),
2678 dbesc($datarray['body']),
2679 dbesc($datarray['tag']),
2680 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2682 intval($importer['importer_uid'])
2685 proc_run('php',"include/notifier.php","comment-import",$iid);
2693 // TODO: make this next part work against both delivery threads of a community post
2695 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2696 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2697 // they won't know what to do so don't report an error. Just quietly die.
2701 // our user with $importer['importer_uid'] is the owner
2703 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2704 intval($importer['importer_uid'])
2708 $datarray['type'] = 'remote-comment';
2709 $datarray['wall'] = 1;
2710 $datarray['parent-uri'] = $parent_uri;
2711 $datarray['uid'] = $importer['importer_uid'];
2712 $datarray['owner-name'] = $own[0]['name'];
2713 $datarray['owner-link'] = $own[0]['url'];
2714 $datarray['owner-avatar'] = $own[0]['thumb'];
2715 $datarray['contact-id'] = $importer['id'];
2717 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2719 $datarray['type'] = 'activity';
2720 $datarray['gravity'] = GRAVITY_LIKE;
2721 $datarray['last-child'] = 0;
2722 // only one like or dislike per person
2723 $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",
2724 intval($datarray['uid']),
2725 intval($datarray['contact-id']),
2726 dbesc($datarray['verb']),
2727 dbesc($datarray['parent-uri']),
2728 dbesc($datarray['parent-uri'])
2735 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2737 $xo = parse_xml_string($datarray['object'],false);
2738 $xt = parse_xml_string($datarray['target'],false);
2740 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2742 // fetch the parent item
2744 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2746 intval($importer['importer_uid'])
2751 // extract tag, if not duplicate, and this user allows tags, add to parent item
2753 if($xo->id && $xo->content) {
2754 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2755 if(! (stristr($tagp[0]['tag'],$newtag))) {
2756 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2757 intval($importer['importer_uid'])
2759 if(count($i) && ! intval($i[0]['blocktags'])) {
2760 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2761 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2762 intval($tagp[0]['id']),
2763 dbesc(datetime_convert())
2772 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2773 // if(! stristr($datarray['tag'],$newtag)) {
2774 // if(strlen($datarray['tag']))
2775 // $datarray['tag'] .= ',';
2776 // $datarray['tag'] .= $newtag;
2781 $posted_id = item_store($datarray);
2785 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2787 intval($importer['importer_uid'])
2790 $parent = $r[0]['parent'];
2793 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2794 dbesc(datetime_convert()),
2795 intval($importer['importer_uid']),
2796 intval($r[0]['parent'])
2799 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2800 dbesc(datetime_convert()),
2801 intval($importer['importer_uid']),
2806 if($posted_id && $parent) {
2808 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2810 if((! $is_like) && (! $importer['self'])) {
2812 require_once('include/enotify.php');
2815 'type' => NOTIFY_COMMENT,
2816 'notify_flags' => $importer['notify-flags'],
2817 'language' => $importer['language'],
2818 'to_name' => $importer['username'],
2819 'to_email' => $importer['email'],
2820 'uid' => $importer['importer_uid'],
2821 'item' => $datarray,
2822 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2823 'source_name' => stripslashes($datarray['author-name']),
2824 'source_link' => $datarray['author-link'],
2825 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2826 ? $importer['thumb'] : $datarray['author-avatar']),
2827 'verb' => ACTIVITY_POST,
2829 'parent' => $parent,
2842 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2844 $item_id = $item->get_id();
2845 $datarray = get_atom_elements($feed,$item);
2847 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2849 intval($importer['importer_uid'])
2852 // Update content if 'updated' changes
2855 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2857 // do not accept (ignore) an earlier edit than one we currently have.
2858 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2861 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2862 dbesc($datarray['title']),
2863 dbesc($datarray['body']),
2864 dbesc($datarray['tag']),
2865 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2867 intval($importer['importer_uid'])
2871 // update last-child if it changes
2873 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2874 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2875 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2876 dbesc(datetime_convert()),
2878 intval($importer['importer_uid'])
2880 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2881 intval($allow[0]['data']),
2882 dbesc(datetime_convert()),
2884 intval($importer['importer_uid'])
2890 $datarray['parent-uri'] = $parent_uri;
2891 $datarray['uid'] = $importer['importer_uid'];
2892 $datarray['contact-id'] = $importer['id'];
2893 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2894 $datarray['type'] = 'activity';
2895 $datarray['gravity'] = GRAVITY_LIKE;
2896 // only one like or dislike per person
2897 $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",
2898 intval($datarray['uid']),
2899 intval($datarray['contact-id']),
2900 dbesc($datarray['verb']),
2909 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2911 $xo = parse_xml_string($datarray['object'],false);
2912 $xt = parse_xml_string($datarray['target'],false);
2914 if($xt->type == ACTIVITY_OBJ_NOTE) {
2915 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2917 intval($importer['importer_uid'])
2922 // extract tag, if not duplicate, add to parent item
2924 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2925 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2926 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2934 $posted_id = item_store($datarray);
2936 // find out if our user is involved in this conversation and wants to be notified.
2938 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2940 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2942 intval($importer['importer_uid'])
2945 if(count($myconv)) {
2946 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2948 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2949 if(! link_compare($datarray['author-link'],$importer_url)) {
2952 foreach($myconv as $conv) {
2954 // now if we find a match, it means we're in this conversation
2956 if(! link_compare($conv['author-link'],$importer_url))
2959 require_once('include/enotify.php');
2961 $conv_parent = $conv['parent'];
2964 'type' => NOTIFY_COMMENT,
2965 'notify_flags' => $importer['notify-flags'],
2966 'language' => $importer['language'],
2967 'to_name' => $importer['username'],
2968 'to_email' => $importer['email'],
2969 'uid' => $importer['importer_uid'],
2970 'item' => $datarray,
2971 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2972 'source_name' => stripslashes($datarray['author-name']),
2973 'source_link' => $datarray['author-link'],
2974 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2975 ? $importer['thumb'] : $datarray['author-avatar']),
2976 'verb' => ACTIVITY_POST,
2978 'parent' => $conv_parent,
2982 // only send one notification
2994 // Head post of a conversation. Have we seen it? If not, import it.
2997 $item_id = $item->get_id();
2998 $datarray = get_atom_elements($feed,$item);
3000 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
3001 $ev = bbtoevent($datarray['body']);
3002 if(x($ev,'desc') && x($ev,'start')) {
3003 $ev['cid'] = $importer['id'];
3004 $ev['uid'] = $importer['uid'];
3005 $ev['uri'] = $item_id;
3006 $ev['edited'] = $datarray['edited'];
3007 $ev['private'] = $datarray['private'];
3009 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3011 intval($importer['uid'])
3014 $ev['id'] = $r[0]['id'];
3015 $xyz = event_store($ev);
3020 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3022 intval($importer['importer_uid'])
3025 // Update content if 'updated' changes
3028 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
3030 // do not accept (ignore) an earlier edit than one we currently have.
3031 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3034 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3035 dbesc($datarray['title']),
3036 dbesc($datarray['body']),
3037 dbesc($datarray['tag']),
3038 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3040 intval($importer['importer_uid'])
3044 // update last-child if it changes
3046 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3047 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
3048 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3049 intval($allow[0]['data']),
3050 dbesc(datetime_convert()),
3052 intval($importer['importer_uid'])
3058 // This is my contact on another system, but it's really me.
3059 // Turn this into a wall post.
3061 if($importer['remote_self'])
3062 $datarray['wall'] = 1;
3064 $datarray['parent-uri'] = $item_id;
3065 $datarray['uid'] = $importer['importer_uid'];
3066 $datarray['contact-id'] = $importer['id'];
3068 if(! link_compare($datarray['owner-link'],$contact['url'])) {
3069 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
3070 // but otherwise there's a possible data mixup on the sender's system.
3071 // the tgroup delivery code called from item_store will correct it if it's a forum,
3072 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
3073 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
3074 $datarray['owner-name'] = $importer['senderName'];
3075 $datarray['owner-link'] = $importer['url'];
3076 $datarray['owner-avatar'] = $importer['thumb'];
3079 $posted_id = item_store($datarray);
3081 if(stristr($datarray['verb'],ACTIVITY_POKE)) {
3082 $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
3085 $xo = parse_xml_string($datarray['object'],false);
3087 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
3089 // somebody was poked/prodded. Was it me?
3091 $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
3093 foreach($links->link as $l) {
3094 $atts = $l->attributes();
3095 switch($atts['rel']) {
3097 $Blink = $atts['href'];
3103 if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
3105 // send a notification
3106 require_once('include/enotify.php');
3109 'type' => NOTIFY_POKE,
3110 'notify_flags' => $importer['notify-flags'],
3111 'language' => $importer['language'],
3112 'to_name' => $importer['username'],
3113 'to_email' => $importer['email'],
3114 'uid' => $importer['importer_uid'],
3115 'item' => $datarray,
3116 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3117 'source_name' => stripslashes($datarray['author-name']),
3118 'source_link' => $datarray['author-link'],
3119 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3120 ? $importer['thumb'] : $datarray['author-avatar']),
3121 'verb' => $datarray['verb'],
3122 'otype' => 'person',
3123 'activity' => $verb,
3140 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
3141 $url = notags(trim($datarray['author-link']));
3142 $name = notags(trim($datarray['author-name']));
3143 $photo = notags(trim($datarray['author-avatar']));
3145 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
3146 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
3147 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
3149 if(is_array($contact)) {
3150 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
3151 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
3152 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
3153 intval(CONTACT_IS_FRIEND),
3154 intval($contact['id']),
3155 intval($importer['uid'])
3158 // send email notification to owner?
3162 // create contact record
3164 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
3165 `blocked`, `readonly`, `pending`, `writable` )
3166 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
3167 intval($importer['uid']),
3168 dbesc(datetime_convert()),
3170 dbesc(normalise_link($url)),
3174 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
3175 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
3177 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
3178 intval($importer['uid']),
3182 $contact_record = $r[0];
3184 // create notification
3185 $hash = random_string();
3187 if(is_array($contact_record)) {
3188 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
3189 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
3190 intval($importer['uid']),
3191 intval($contact_record['id']),
3193 dbesc(datetime_convert())
3196 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3197 intval($importer['uid'])
3202 if(intval($r[0]['def_gid'])) {
3203 require_once('include/group.php');
3204 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
3207 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
3208 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
3209 $email = replace_macros($email_tpl, array(
3210 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
3212 '$myname' => $r[0]['username'],
3213 '$siteurl' => $a->get_baseurl(),
3214 '$sitename' => $a->config['sitename']
3216 $res = mail($r[0]['email'],
3217 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
3219 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
3220 . 'Content-type: text/plain; charset=UTF-8' . "\n"
3221 . 'Content-transfer-encoding: 8bit' );
3228 function lose_follower($importer,$contact,$datarray,$item) {
3230 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
3231 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3232 intval(CONTACT_IS_SHARING),
3233 intval($contact['id'])
3237 contact_remove($contact['id']);
3241 function lose_sharer($importer,$contact,$datarray,$item) {
3243 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3244 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3245 intval(CONTACT_IS_FOLLOWER),
3246 intval($contact['id'])
3250 contact_remove($contact['id']);
3255 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3259 if(is_array($importer)) {
3260 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3261 intval($importer['uid'])
3265 // Diaspora has different message-ids in feeds than they do
3266 // through the direct Diaspora protocol. If we try and use
3267 // the feed, we'll get duplicates. So don't.
3269 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3272 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3274 // Use a single verify token, even if multiple hubs
3276 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3278 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3280 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
3282 if(! strlen($contact['hub-verify'])) {
3283 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3284 dbesc($verify_token),
3285 intval($contact['id'])
3289 post_url($url,$params);
3291 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3298 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3302 $name = xmlify($name);
3303 $uri = xmlify($uri);
3306 $photo = xmlify($photo);
3310 $o .= "<name>$name</name>\r\n";
3311 $o .= "<uri>$uri</uri>\r\n";
3312 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3313 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3315 call_hooks('atom_author', $o);
3317 $o .= "</$tag>\r\n";
3321 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3325 if(! $item['parent'])
3328 if($item['deleted'])
3329 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3332 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3333 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3335 $body = $item['body'];
3338 $o = "\r\n\r\n<entry>\r\n";
3340 if(is_array($author))
3341 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3343 $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']));
3344 if(strlen($item['owner-name']))
3345 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3347 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || ($item['thr-parent'])) {
3348 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3349 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3352 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3353 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3354 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3355 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3356 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3357 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3358 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3360 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3362 if($item['location']) {
3363 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3364 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3368 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3370 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3371 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3374 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3375 if($item['bookmark'])
3376 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3379 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3382 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3384 if($item['signed_text']) {
3385 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3386 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3389 $verb = construct_verb($item);
3390 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3391 $actobj = construct_activity_object($item);
3394 $actarg = construct_activity_target($item);
3398 $tags = item_getfeedtags($item);
3400 foreach($tags as $t) {
3401 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3405 $o .= item_getfeedattach($item);
3407 $mentioned = get_mentions($item);
3411 call_hooks('atom_entry', $o);
3413 $o .= '</entry>' . "\r\n";
3418 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3421 logger('fix_private_photos', LOGGER_DEBUG);
3422 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3427 $img_start = strpos($orig_body, '[img');
3428 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3429 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3430 while( ($img_st_close !== false) && ($img_len !== false) ) {
3432 $img_st_close++; // make it point to AFTER the closing bracket
3433 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3435 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3438 if(stristr($image , $site . '/photo/')) {
3439 // Only embed locally hosted photos
3441 $i = basename($image);
3442 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3443 $x = strpos($i,'-');
3446 $res = substr($i,$x+1);
3447 $i = substr($i,0,$x);
3448 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3455 // Check to see if we should replace this photo link with an embedded image
3456 // 1. No need to do so if the photo is public
3457 // 2. If there's a contact-id provided, see if they're in the access list
3458 // for the photo. If so, embed it.
3459 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3460 // permissions, regardless of order but first check to see if they're an exact
3461 // match to save some processing overhead.
3463 if(has_permissions($r[0])) {
3465 $recips = enumerate_permissions($r[0]);
3466 if(in_array($cid, $recips)) {
3471 if(compare_permissions($item,$r[0]))
3476 $data = $r[0]['data'];
3477 $type = $r[0]['type'];
3479 // If a custom width and height were specified, apply before embedding
3480 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3481 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3483 $width = intval($match[1]);
3484 $height = intval($match[2]);
3486 $ph = new Photo($data, $type);
3487 if($ph->is_valid()) {
3488 $ph->scaleImage(max($width, $height));
3489 $data = $ph->imageString();
3490 $type = $ph->getType();
3494 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3495 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3496 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3502 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3503 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3504 if($orig_body === false)
3507 $img_start = strpos($orig_body, '[img');
3508 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3509 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3512 $new_body = $new_body . $orig_body;
3518 function has_permissions($obj) {
3519 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3524 function compare_permissions($obj1,$obj2) {
3525 // first part is easy. Check that these are exactly the same.
3526 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3527 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3528 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3529 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3532 // This is harder. Parse all the permissions and compare the resulting set.
3534 $recipients1 = enumerate_permissions($obj1);
3535 $recipients2 = enumerate_permissions($obj2);
3538 if($recipients1 == $recipients2)
3543 // returns an array of contact-ids that are allowed to see this object
3545 function enumerate_permissions($obj) {
3546 require_once('include/group.php');
3547 $allow_people = expand_acl($obj['allow_cid']);
3548 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3549 $deny_people = expand_acl($obj['deny_cid']);
3550 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3551 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3552 $deny = array_unique(array_merge($deny_people,$deny_groups));
3553 $recipients = array_diff($recipients,$deny);
3557 function item_getfeedtags($item) {
3560 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3562 for($x = 0; $x < $cnt; $x ++) {
3564 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3568 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3570 for($x = 0; $x < $cnt; $x ++) {
3572 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3578 function item_getfeedattach($item) {
3580 $arr = explode(',',$item['attach']);
3582 foreach($arr as $r) {
3584 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3586 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3587 if(intval($matches[2]))
3588 $ret .= 'length="' . intval($matches[2]) . '" ';
3589 if($matches[4] !== ' ')
3590 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3591 $ret .= ' />' . "\r\n";
3600 function item_expire($uid,$days) {
3602 if((! $uid) || ($days < 1))
3605 // $expire_network_only = save your own wall posts
3606 // and just expire conversations started by others
3608 $expire_network_only = get_pconfig($uid,'expire','network_only');
3609 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3611 $r = q("SELECT * FROM `item`
3613 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3624 $expire_items = get_pconfig($uid, 'expire','items');
3625 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3627 $expire_notes = get_pconfig($uid, 'expire','notes');
3628 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3630 $expire_starred = get_pconfig($uid, 'expire','starred');
3631 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3633 $expire_photos = get_pconfig($uid, 'expire','photos');
3634 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3636 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3638 foreach($r as $item) {
3640 // don't expire filed items
3642 if(strpos($item['file'],'[') !== false)
3645 // Only expire posts, not photos and photo comments
3647 if($expire_photos==0 && strlen($item['resource-id']))
3649 if($expire_starred==0 && intval($item['starred']))
3651 if($expire_notes==0 && $item['type']=='note')
3653 if($expire_items==0 && $item['type']!='note')
3656 drop_item($item['id'],false);
3659 proc_run('php',"include/notifier.php","expire","$uid");
3664 function drop_items($items) {
3667 if(! local_user() && ! remote_user())
3671 foreach($items as $item) {
3672 $owner = drop_item($item,false);
3673 if($owner && ! $uid)
3678 // multiple threads may have been deleted, send an expire notification
3681 proc_run('php',"include/notifier.php","expire","$uid");
3685 function drop_item($id,$interactive = true) {
3689 // locate item to be deleted
3691 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3698 notice( t('Item not found.') . EOL);
3699 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3704 $owner = $item['uid'];
3706 // check if logged in user is either the author or owner of this item
3708 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3712 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3713 dbesc(datetime_convert()),
3714 dbesc(datetime_convert()),
3718 // clean up categories and tags so they don't end up as orphans
3721 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3723 foreach($matches as $mtch) {
3724 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3730 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3732 foreach($matches as $mtch) {
3733 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3737 // If item is a link to a photo resource, nuke all the associated photos
3738 // (visitors will not have photo resources)
3739 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3740 // generate a resource-id and therefore aren't intimately linked to the item.
3742 if(strlen($item['resource-id'])) {
3743 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3744 dbesc($item['resource-id']),
3745 intval($item['uid'])
3747 // ignore the result
3750 // If item is a link to an event, nuke the event record.
3752 if(intval($item['event-id'])) {
3753 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3754 intval($item['event-id']),
3755 intval($item['uid'])
3757 // ignore the result
3760 // clean up item_id and sign meta-data tables
3762 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3763 intval($item['id']),
3764 intval($item['uid'])
3767 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3768 intval($item['id']),
3769 intval($item['uid'])
3772 // If it's the parent of a comment thread, kill all the kids
3774 if($item['uri'] == $item['parent-uri']) {
3775 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3776 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3777 dbesc(datetime_convert()),
3778 dbesc(datetime_convert()),
3779 dbesc($item['parent-uri']),
3780 intval($item['uid'])
3782 // ignore the result
3785 // ensure that last-child is set in case the comment that had it just got wiped.
3786 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3787 dbesc(datetime_convert()),
3788 dbesc($item['parent-uri']),
3789 intval($item['uid'])
3791 // who is the last child now?
3792 $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",
3793 dbesc($item['parent-uri']),
3794 intval($item['uid'])
3797 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3802 // Add a relayable_retraction signature for Diaspora.
3803 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
3805 $drop_id = intval($item['id']);
3807 // send the notification upstream/downstream as the case may be
3812 proc_run('php',"include/notifier.php","drop","$drop_id");
3813 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3819 notice( t('Permission denied.') . EOL);
3820 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3827 function first_post_date($uid,$wall = false) {
3828 $r = q("select id, created from item
3829 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3831 order by created asc limit 1",
3833 intval($wall ? 1 : 0)
3836 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3837 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3842 function posted_dates($uid,$wall) {
3843 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3845 $dthen = first_post_date($uid,$wall);
3849 // If it's near the end of a long month, backup to the 28th so that in
3850 // consecutive loops we'll always get a whole month difference.
3852 if(intval(substr($dnow,8)) > 28)
3853 $dnow = substr($dnow,0,8) . '28';
3854 if(intval(substr($dthen,8)) > 28)
3855 $dnow = substr($dthen,0,8) . '28';
3858 // Starting with the current month, get the first and last days of every
3859 // month down to and including the month of the first post
3860 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
3861 $dstart = substr($dnow,0,8) . '01';
3862 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3863 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3864 $end_month = datetime_convert('','',$dend,'Y-m-d');
3865 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3866 $ret[] = array($str,$end_month,$start_month);
3867 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3873 function posted_date_widget($url,$uid,$wall) {
3876 // For former Facebook folks that left because of "timeline"
3878 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3881 $ret = posted_dates($uid,$wall);
3885 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3886 '$title' => t('Archives'),
3887 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3894 function store_diaspora_retract_sig($item, $user, $baseurl) {
3895 // Note that we can't add a target_author_signature
3896 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3897 // the comment, that means we're the home of the post, and Diaspora will only
3898 // check the parent_author_signature of retractions that it doesn't have to relay further
3900 // I don't think this function gets called for an "unlike," but I'll check anyway
3902 $enabled = intval(get_config('system','diaspora_enabled'));
3904 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
3908 logger('drop_item: storing diaspora retraction signature');
3910 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3912 if(local_user() == $item['uid']) {
3914 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
3915 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
3918 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3919 $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
3922 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3923 // only handles DFRN deletes
3924 $handle_baseurl_start = strpos($r['url'],'://') + 3;
3925 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3926 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3932 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3933 intval($item['id']),
3934 dbesc($signed_text),