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']);
584 // this tag is obsolete but we keep it for really old sites
586 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
587 if($allow && $allow[0]['data'] == 1)
588 $res['last-child'] = 1;
590 $res['last-child'] = 0;
592 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
593 if($private && intval($private[0]['data']) > 0)
594 $res['private'] = intval($private[0]['data']);
598 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
599 if($extid && $extid[0]['data'])
600 $res['extid'] = $extid[0]['data'];
602 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
604 $res['location'] = unxmlify($rawlocation[0]['data']);
607 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
609 $res['created'] = unxmlify($rawcreated[0]['data']);
612 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
614 $res['edited'] = unxmlify($rawedited[0]['data']);
616 if((x($res,'edited')) && (! (x($res,'created'))))
617 $res['created'] = $res['edited'];
619 if(! $res['created'])
620 $res['created'] = $item->get_date('c');
623 $res['edited'] = $item->get_date('c');
626 // Disallow time travelling posts
628 $d1 = strtotime($res['created']);
629 $d2 = strtotime($res['edited']);
630 $d3 = strtotime('now');
633 $res['created'] = datetime_convert();
635 $res['edited'] = datetime_convert();
637 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
638 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
639 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
640 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
641 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
642 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
643 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
644 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
645 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
647 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
648 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
650 foreach($base as $link) {
651 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
652 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
653 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
658 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
660 $res['coord'] = unxmlify($rawgeo[0]['data']);
663 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
665 // select between supported verbs
668 $res['verb'] = unxmlify($rawverb[0]['data']);
671 // translate OStatus unfollow to activity streams if it happened to get selected
673 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
674 $res['verb'] = ACTIVITY_UNFOLLOW;
676 $cats = $item->get_categories();
679 foreach($cats as $cat) {
680 $term = $cat->get_term();
682 $term = $cat->get_label();
683 $scheme = $cat->get_scheme();
684 if($scheme && $term && stristr($scheme,'X-DFRN:'))
685 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
687 $tag_arr[] = notags(trim($term));
689 $res['tag'] = implode(',', $tag_arr);
692 $attach = $item->get_enclosures();
695 foreach($attach as $att) {
696 $len = intval($att->get_length());
697 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
698 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
699 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
700 if(strpos($type,';'))
701 $type = substr($type,0,strpos($type,';'));
702 if((! $link) || (strpos($link,'http') !== 0))
708 $type = 'application/octet-stream';
710 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
712 $res['attach'] = implode(',', $att_arr);
715 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
718 $res['object'] = '<object>' . "\n";
719 $child = $rawobj[0]['child'];
720 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
721 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
722 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
724 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
725 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
726 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
727 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
728 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
729 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
730 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
731 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
733 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
734 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
735 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
736 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
738 $body = html2bb_video($body);
740 $config = HTMLPurifier_Config::createDefault();
741 $config->set('Cache.DefinitionImpl', null);
743 $purifier = new HTMLPurifier($config);
744 $body = $purifier->purify($body);
745 $body = html2bbcode($body);
748 $res['object'] .= '<content>' . $body . '</content>' . "\n";
751 $res['object'] .= '</object>' . "\n";
754 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
757 $res['target'] = '<target>' . "\n";
758 $child = $rawobj[0]['child'];
759 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
760 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
762 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
763 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
764 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
765 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
766 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
767 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
768 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
769 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
771 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
772 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
773 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
774 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
776 $body = html2bb_video($body);
778 $config = HTMLPurifier_Config::createDefault();
779 $config->set('Cache.DefinitionImpl', null);
781 $purifier = new HTMLPurifier($config);
782 $body = $purifier->purify($body);
783 $body = html2bbcode($body);
786 $res['target'] .= '<content>' . $body . '</content>' . "\n";
789 $res['target'] .= '</target>' . "\n";
792 // This is some experimental stuff. By now retweets are shown with "RT:"
793 // But: There is data so that the message could be shown similar to native retweets
794 // There is some better way to parse this array - but it didn't worked for me.
795 $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"];
796 if (is_array($child)) {
797 logger('get_atom_elements: Looking for status.net repeated message');
799 $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
800 $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
801 $uri = $author["uri"][0]["data"];
802 $name = $author["name"][0]["data"];
803 $avatar = @array_shift($author["link"][2]["attribs"]);
804 $avatar = $avatar["href"];
806 if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
807 logger('get_atom_elements: fixing sender of repeated message');
809 $res["owner-name"] = $res["author-name"];
810 $res["owner-link"] = $res["author-link"];
811 $res["owner-avatar"] = $res["author-avatar"];
813 $res["author-name"] = $name;
814 $res["author-link"] = $uri;
815 $res["author-avatar"] = $avatar;
817 $res["body"] = html2bbcode($message);
821 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
823 call_hooks('parse_atom', $arr);
825 //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
826 //if (strpos($res["body"], "RT @") !== false) {
827 // $debugfile = tempnam("/home/ike/log", "item-res2-");
828 // file_put_contents($debugfile, serialize($arr));
834 function encode_rel_links($links) {
836 if(! ((is_array($links)) && (count($links))))
838 foreach($links as $link) {
840 if($link['attribs']['']['rel'])
841 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
842 if($link['attribs']['']['type'])
843 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
844 if($link['attribs']['']['href'])
845 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
846 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
847 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
848 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
849 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
857 function item_store($arr,$force_parent = false) {
859 // If a Diaspora signature structure was passed in, pull it out of the
860 // item array and set it aside for later storage.
863 if(x($arr,'dsprsig')) {
864 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
865 unset($arr['dsprsig']);
868 if(x($arr, 'gravity'))
869 $arr['gravity'] = intval($arr['gravity']);
870 elseif($arr['parent-uri'] === $arr['uri'])
872 elseif(activity_match($arr['verb'],ACTIVITY_POST))
875 $arr['gravity'] = 6; // extensible catchall
878 $arr['type'] = 'remote';
880 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
882 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
883 $arr['body'] = strip_tags($arr['body']);
886 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
887 require_once('Text/LanguageDetect.php');
888 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
889 $l = new Text_LanguageDetect;
890 $lng = $l->detectConfidence($naked_body);
891 $arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
894 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
895 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
896 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
897 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
898 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
899 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
900 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
901 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
902 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
903 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
904 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
905 $arr['commented'] = datetime_convert();
906 $arr['received'] = datetime_convert();
907 $arr['changed'] = datetime_convert();
908 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
909 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
910 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
911 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
912 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
914 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
915 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
916 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
917 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
918 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
919 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
920 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
921 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
922 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
923 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
924 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
925 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
926 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
927 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
928 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
929 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
930 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
931 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
932 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
935 $arr['thr-parent'] = $arr['parent-uri'];
936 if($arr['parent-uri'] === $arr['uri']) {
939 $allow_cid = $arr['allow_cid'];
940 $allow_gid = $arr['allow_gid'];
941 $deny_cid = $arr['deny_cid'];
942 $deny_gid = $arr['deny_gid'];
946 // find the parent and snarf the item id and ACL's
947 // and anything else we need to inherit
949 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
950 dbesc($arr['parent-uri']),
956 // is the new message multi-level threaded?
957 // even though we don't support it now, preserve the info
958 // and re-attach to the conversation parent.
960 if($r[0]['uri'] != $r[0]['parent-uri']) {
961 $arr['parent-uri'] = $r[0]['parent-uri'];
962 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
963 ORDER BY `id` ASC LIMIT 1",
964 dbesc($r[0]['parent-uri']),
965 dbesc($r[0]['parent-uri']),
972 $parent_id = $r[0]['id'];
973 $parent_deleted = $r[0]['deleted'];
974 $allow_cid = $r[0]['allow_cid'];
975 $allow_gid = $r[0]['allow_gid'];
976 $deny_cid = $r[0]['deny_cid'];
977 $deny_gid = $r[0]['deny_gid'];
978 $arr['wall'] = $r[0]['wall'];
980 // if the parent is private, force privacy for the entire conversation
981 // This differs from the above settings as it subtly allows comments from
982 // email correspondents to be private even if the overall thread is not.
985 $arr['private'] = $r[0]['private'];
987 // Edge case. We host a public forum that was originally posted to privately.
988 // The original author commented, but as this is a comment, the permissions
989 // weren't fixed up so it will still show the comment as private unless we fix it here.
991 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
996 // Allow one to see reply tweets from status.net even when
997 // we don't have or can't see the original post.
1000 logger('item_store: $force_parent=true, reply converted to top-level post.');
1002 $arr['parent-uri'] = $arr['uri'];
1003 $arr['gravity'] = 0;
1006 logger('item_store: item parent was not found - ignoring item');
1010 $parent_deleted = 0;
1014 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1018 if($r && count($r)) {
1019 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
1023 call_hooks('post_remote',$arr);
1025 if(x($arr,'cancel')) {
1026 logger('item_store: post cancelled by plugin.');
1032 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
1034 $r = dbq("INSERT INTO `item` (`"
1035 . implode("`, `", array_keys($arr))
1037 . implode("', '", array_values($arr))
1040 // find the item we just created
1042 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
1043 $arr['uri'], // already dbesc'd
1048 $current_post = $r[0]['id'];
1049 logger('item_store: created item ' . $current_post);
1052 logger('item_store: could not locate created item');
1056 logger('item_store: duplicated post occurred. Removing duplicates.');
1057 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
1059 intval($arr['uid']),
1060 intval($current_post)
1064 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
1065 $parent_id = $current_post;
1067 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1070 $private = $arr['private'];
1072 // Set parent id - and also make sure to inherit the parent's ACL's.
1074 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1075 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1082 intval($parent_deleted),
1083 intval($current_post)
1086 $arr['id'] = $current_post;
1087 $arr['parent'] = $parent_id;
1088 $arr['allow_cid'] = $allow_cid;
1089 $arr['allow_gid'] = $allow_gid;
1090 $arr['deny_cid'] = $deny_cid;
1091 $arr['deny_gid'] = $deny_gid;
1092 $arr['private'] = $private;
1093 $arr['deleted'] = $parent_deleted;
1094 call_hooks('post_remote_end',$arr);
1096 // update the commented timestamp on the parent
1098 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1099 dbesc(datetime_convert()),
1100 dbesc(datetime_convert()),
1105 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1106 intval($current_post),
1107 dbesc($dsprsig->signed_text),
1108 dbesc($dsprsig->signature),
1109 dbesc($dsprsig->signer)
1115 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1118 if($arr['last-child']) {
1119 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1121 intval($arr['uid']),
1122 intval($current_post)
1126 tag_deliver($arr['uid'],$current_post);
1128 return $current_post;
1131 function get_item_contact($item,$contacts) {
1132 if(! count($contacts) || (! is_array($item)))
1134 foreach($contacts as $contact) {
1135 if($contact['id'] == $item['contact-id']) {
1137 break; // NOTREACHED
1144 function tag_deliver($uid,$item_id) {
1146 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1152 $u = q("select * from user where uid = %d limit 1",
1158 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1159 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1162 $i = q("select * from item where id = %d and uid = %d limit 1",
1171 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1173 // Diaspora uses their own hardwired link URL in @-tags
1174 // instead of the one we supply with webfinger
1176 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1178 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1180 foreach($matches as $mtch) {
1181 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1183 logger('tag_deliver: mention found: ' . $mtch[2]);
1191 // send a notification
1193 require_once('include/enotify.php');
1195 'type' => NOTIFY_TAGSELF,
1196 'notify_flags' => $u[0]['notify-flags'],
1197 'language' => $u[0]['language'],
1198 'to_name' => $u[0]['username'],
1199 'to_email' => $u[0]['email'],
1200 'uid' => $u[0]['uid'],
1202 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1203 'source_name' => $item['author-name'],
1204 'source_link' => $item['author-link'],
1205 'source_photo' => $item['author-avatar'],
1206 'verb' => ACTIVITY_TAG,
1210 if((! $community_page) && (! $prvgroup))
1214 // tgroup delivery - setup a second delivery chain
1215 // prevent delivery looping - only proceed
1216 // if the message originated elsewhere and is a top-level post
1218 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1221 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1224 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1225 intval($u[0]['uid'])
1230 // also reset all the privacy bits to the forum default permissions
1232 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1234 $forum_mode = (($prvgroup) ? 2 : 1);
1236 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1237 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1238 intval($forum_mode),
1239 dbesc($c[0]['name']),
1240 dbesc($c[0]['url']),
1241 dbesc($c[0]['thumb']),
1243 dbesc($u[0]['allow_cid']),
1244 dbesc($u[0]['allow_gid']),
1245 dbesc($u[0]['deny_cid']),
1246 dbesc($u[0]['deny_gid']),
1250 proc_run('php','include/notifier.php','tgroup',$item_id);
1259 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1263 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1265 if($contact['duplex'] && $contact['dfrn-id'])
1266 $idtosend = '0:' . $orig_id;
1267 if($contact['duplex'] && $contact['issued-id'])
1268 $idtosend = '1:' . $orig_id;
1270 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1272 $rino_enable = get_config('system','rino_encrypt');
1277 $ssl_val = intval(get_config('system','ssl_policy'));
1281 case SSL_POLICY_FULL:
1282 $ssl_policy = 'full';
1284 case SSL_POLICY_SELFSIGN:
1285 $ssl_policy = 'self';
1287 case SSL_POLICY_NONE:
1289 $ssl_policy = 'none';
1293 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1295 logger('dfrn_deliver: ' . $url);
1297 $xml = fetch_url($url);
1299 $curl_stat = $a->get_curl_code();
1301 return(-1); // timed out
1303 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1308 if(strpos($xml,'<?xml') === false) {
1309 logger('dfrn_deliver: no valid XML returned');
1310 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1314 $res = parse_xml_string($xml);
1316 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1317 return (($res->status) ? $res->status : 3);
1319 $postvars = array();
1320 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1321 $challenge = hex2bin((string) $res->challenge);
1322 $perm = (($res->perm) ? $res->perm : null);
1323 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1324 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1325 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1327 if($owner['page-flags'] == PAGE_PRVGROUP)
1330 $final_dfrn_id = '';
1333 if((($perm == 'rw') && (! intval($contact['writable'])))
1334 || (($perm == 'r') && (intval($contact['writable'])))) {
1335 q("update contact set writable = %d where id = %d limit 1",
1336 intval(($perm == 'rw') ? 1 : 0),
1337 intval($contact['id'])
1339 $contact['writable'] = (string) 1 - intval($contact['writable']);
1343 if(($contact['duplex'] && strlen($contact['pubkey']))
1344 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1345 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1346 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1347 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1350 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1351 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1354 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1356 if(strpos($final_dfrn_id,':') == 1)
1357 $final_dfrn_id = substr($final_dfrn_id,2);
1359 if($final_dfrn_id != $orig_id) {
1360 logger('dfrn_deliver: wrong dfrn_id.');
1361 // did not decode properly - cannot trust this site
1365 $postvars['dfrn_id'] = $idtosend;
1366 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1368 $postvars['dissolve'] = '1';
1371 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1372 $postvars['data'] = $atom;
1373 $postvars['perm'] = 'rw';
1376 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1377 $postvars['perm'] = 'r';
1380 $postvars['ssl_policy'] = $ssl_policy;
1383 $postvars['page'] = $page;
1385 if($rino && $rino_allowed && (! $dissolve)) {
1386 $key = substr(random_string(),0,16);
1387 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1388 $postvars['data'] = $data;
1389 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1392 if($dfrn_version >= 2.1) {
1393 if(($contact['duplex'] && strlen($contact['pubkey']))
1394 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1395 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1397 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1400 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1404 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1405 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1408 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1412 logger('md5 rawkey ' . md5($postvars['key']));
1414 $postvars['key'] = bin2hex($postvars['key']);
1417 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1419 $xml = post_url($contact['notify'],$postvars);
1421 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1423 $curl_stat = $a->get_curl_code();
1424 if((! $curl_stat) || (! strlen($xml)))
1425 return(-1); // timed out
1427 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1430 if(strpos($xml,'<?xml') === false) {
1431 logger('dfrn_deliver: phase 2: no valid XML returned');
1432 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1436 if($contact['term-date'] != '0000-00-00 00:00:00') {
1437 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1438 require_once('include/Contact.php');
1439 unmark_for_death($contact);
1442 $res = parse_xml_string($xml);
1444 return $res->status;
1450 * consume_feed - process atom feed and update anything/everything we might need to update
1452 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1454 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1455 * It is this person's stuff that is going to be updated.
1456 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1457 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1458 * have a contact record.
1459 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1460 * might not) try and subscribe to it.
1461 * $datedir sorts in reverse order
1462 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1463 * imported prior to its children being seen in the stream unless we are certain
1464 * of how the feed is arranged/ordered.
1465 * With $pass = 1, we only pull parent items out of the stream.
1466 * With $pass = 2, we only pull children (comments/likes).
1468 * So running this twice, first with pass 1 and then with pass 2 will do the right
1469 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1470 * model where comments can have sub-threads. That would require some massive sorting
1471 * to get all the feed items into a mostly linear ordering, and might still require
1475 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1477 require_once('library/simplepie/simplepie.inc');
1479 if(! strlen($xml)) {
1480 logger('consume_feed: empty input');
1484 $feed = new SimplePie();
1485 $feed->set_raw_data($xml);
1487 $feed->enable_order_by_date(true);
1489 $feed->enable_order_by_date(false);
1493 logger('consume_feed: Error parsing XML: ' . $feed->error());
1495 $permalink = $feed->get_permalink();
1497 // Check at the feed level for updated contact name and/or photo
1501 $photo_timestamp = '';
1505 $hubs = $feed->get_links('hub');
1506 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1509 $hub = implode(',', $hubs);
1511 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1513 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1515 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1516 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1517 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1518 $new_name = $elems['name'][0]['data'];
1520 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1521 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1522 $photo_url = $elems['link'][0]['attribs']['']['href'];
1525 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1526 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1530 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1531 logger('consume_feed: Updating photo for ' . $contact['name']);
1532 require_once("Photo.php");
1533 $photo_failure = false;
1534 $have_photo = false;
1536 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1537 intval($contact['id']),
1538 intval($contact['uid'])
1541 $resource_id = $r[0]['resource-id'];
1545 $resource_id = photo_new_resource();
1548 $img_str = fetch_url($photo_url,true);
1549 // guess mimetype from headers or filename
1550 $type = guess_image_type($photo_url,true);
1553 $img = new Photo($img_str, $type);
1554 if($img->is_valid()) {
1556 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1557 dbesc($resource_id),
1558 intval($contact['id']),
1559 intval($contact['uid'])
1563 $img->scaleImageSquare(175);
1565 $hash = $resource_id;
1566 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1568 $img->scaleImage(80);
1569 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1571 $img->scaleImage(48);
1572 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1576 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1577 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1578 dbesc(datetime_convert()),
1579 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1580 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1581 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1582 intval($contact['uid']),
1583 intval($contact['id'])
1588 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1589 $r = q("select * from contact where uid = %d and id = %d limit 1",
1590 intval($contact['uid']),
1591 intval($contact['id'])
1594 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1595 dbesc(notags(trim($new_name))),
1596 dbesc(datetime_convert()),
1597 intval($contact['uid']),
1598 intval($contact['id'])
1601 // do our best to update the name on content items
1604 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1605 dbesc(notags(trim($new_name))),
1606 dbesc($r[0]['name']),
1607 dbesc($r[0]['url']),
1608 intval($contact['uid'])
1613 if(strlen($birthday)) {
1614 if(substr($birthday,0,4) != $contact['bdyear']) {
1615 logger('consume_feed: updating birthday: ' . $birthday);
1619 * Add new birthday event for this person
1621 * $bdtext is just a readable placeholder in case the event is shared
1622 * with others. We will replace it during presentation to our $importer
1623 * to contain a sparkle link and perhaps a photo.
1627 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1628 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1631 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1632 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1633 intval($contact['uid']),
1634 intval($contact['id']),
1635 dbesc(datetime_convert()),
1636 dbesc(datetime_convert()),
1637 dbesc(datetime_convert('UTC','UTC', $birthday)),
1638 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1647 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1648 dbesc(substr($birthday,0,4)),
1649 intval($contact['uid']),
1650 intval($contact['id'])
1653 // This function is called twice without reloading the contact
1654 // Make sure we only create one event. This is why &$contact
1655 // is a reference var in this function
1657 $contact['bdyear'] = substr($birthday,0,4);
1662 $community_page = 0;
1663 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1665 $community_page = intval($rawtags[0]['data']);
1667 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1668 q("update contact set forum = %d where id = %d limit 1",
1669 intval($community_page),
1670 intval($contact['id'])
1672 $contact['forum'] = (string) $community_page;
1676 // process any deleted entries
1678 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1679 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1680 foreach($del_entries as $dentry) {
1682 if(isset($dentry['attribs']['']['ref'])) {
1683 $uri = $dentry['attribs']['']['ref'];
1685 if(isset($dentry['attribs']['']['when'])) {
1686 $when = $dentry['attribs']['']['when'];
1687 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1690 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1692 if($deleted && is_array($contact)) {
1693 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1694 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1696 intval($importer['uid']),
1697 intval($contact['id'])
1702 if(! $item['deleted'])
1703 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1705 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1706 $xo = parse_xml_string($item['object'],false);
1707 $xt = parse_xml_string($item['target'],false);
1708 if($xt->type === ACTIVITY_OBJ_NOTE) {
1709 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1711 intval($importer['importer_uid'])
1715 // For tags, the owner cannot remove the tag on the author's copy of the post.
1717 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1718 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1719 $author_copy = (($item['origin']) ? true : false);
1721 if($owner_remove && $author_copy)
1723 if($author_remove || $owner_remove) {
1724 $tags = explode(',',$i[0]['tag']);
1727 foreach($tags as $tag)
1728 if(trim($tag) !== trim($xo->body))
1729 $newtags[] = trim($tag);
1731 q("update item set tag = '%s' where id = %d limit 1",
1732 dbesc(implode(',',$newtags)),
1740 if($item['uri'] == $item['parent-uri']) {
1741 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1742 `body` = '', `title` = ''
1743 WHERE `parent-uri` = '%s' AND `uid` = %d",
1745 dbesc(datetime_convert()),
1746 dbesc($item['uri']),
1747 intval($importer['uid'])
1751 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1752 `body` = '', `title` = ''
1753 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1755 dbesc(datetime_convert()),
1757 intval($importer['uid'])
1759 if($item['last-child']) {
1760 // ensure that last-child is set in case the comment that had it just got wiped.
1761 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1762 dbesc(datetime_convert()),
1763 dbesc($item['parent-uri']),
1764 intval($item['uid'])
1766 // who is the last child now?
1767 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1768 ORDER BY `created` DESC LIMIT 1",
1769 dbesc($item['parent-uri']),
1770 intval($importer['uid'])
1773 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1784 // Now process the feed
1786 if($feed->get_item_quantity()) {
1788 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1790 // in inverse date order
1792 $items = array_reverse($feed->get_items());
1794 $items = $feed->get_items();
1797 foreach($items as $item) {
1800 $item_id = $item->get_id();
1801 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1802 if(isset($rawthread[0]['attribs']['']['ref'])) {
1804 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1807 if(($is_reply) && is_array($contact)) {
1812 // Have we seen it? If not, import it.
1814 $item_id = $item->get_id();
1815 $datarray = get_atom_elements($feed,$item);
1817 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1818 $datarray['author-name'] = $contact['name'];
1819 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1820 $datarray['author-link'] = $contact['url'];
1821 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1822 $datarray['author-avatar'] = $contact['thumb'];
1824 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1825 logger('consume_feed: no author information! ' . print_r($datarray,true));
1829 $force_parent = false;
1830 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1831 if($contact['network'] === NETWORK_OSTATUS)
1832 $force_parent = true;
1833 if(strlen($datarray['title']))
1834 unset($datarray['title']);
1835 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1836 dbesc(datetime_convert()),
1838 intval($importer['uid'])
1840 $datarray['last-child'] = 1;
1844 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1846 intval($importer['uid'])
1849 // Update content if 'updated' changes
1852 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1854 // do not accept (ignore) an earlier edit than one we currently have.
1855 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1858 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1859 dbesc($datarray['title']),
1860 dbesc($datarray['body']),
1861 dbesc($datarray['tag']),
1862 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1864 intval($importer['uid'])
1868 // update last-child if it changes
1870 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1871 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1872 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1873 dbesc(datetime_convert()),
1875 intval($importer['uid'])
1877 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1878 intval($allow[0]['data']),
1879 dbesc(datetime_convert()),
1881 intval($importer['uid'])
1888 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1889 // one way feed - no remote comment ability
1890 $datarray['last-child'] = 0;
1892 $datarray['parent-uri'] = $parent_uri;
1893 $datarray['uid'] = $importer['uid'];
1894 $datarray['contact-id'] = $contact['id'];
1895 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1896 $datarray['type'] = 'activity';
1897 $datarray['gravity'] = GRAVITY_LIKE;
1898 // only one like or dislike per person
1899 $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",
1900 intval($datarray['uid']),
1901 intval($datarray['contact-id']),
1902 dbesc($datarray['verb']),
1910 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1911 $xo = parse_xml_string($datarray['object'],false);
1912 $xt = parse_xml_string($datarray['target'],false);
1914 if($xt->type == ACTIVITY_OBJ_NOTE) {
1915 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1917 intval($importer['importer_uid'])
1922 // extract tag, if not duplicate, add to parent item
1923 if($xo->id && $xo->content) {
1924 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1925 if(! (stristr($r[0]['tag'],$newtag))) {
1926 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1927 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1935 $r = item_store($datarray,$force_parent);
1941 // Head post of a conversation. Have we seen it? If not, import it.
1943 $item_id = $item->get_id();
1945 $datarray = get_atom_elements($feed,$item);
1947 if(is_array($contact)) {
1948 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1949 $datarray['author-name'] = $contact['name'];
1950 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1951 $datarray['author-link'] = $contact['url'];
1952 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1953 $datarray['author-avatar'] = $contact['thumb'];
1956 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1957 logger('consume_feed: no author information! ' . print_r($datarray,true));
1961 // special handling for events
1963 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1964 $ev = bbtoevent($datarray['body']);
1965 if(x($ev,'desc') && x($ev,'start')) {
1966 $ev['uid'] = $importer['uid'];
1967 $ev['uri'] = $item_id;
1968 $ev['edited'] = $datarray['edited'];
1969 $ev['private'] = $datarray['private'];
1971 if(is_array($contact))
1972 $ev['cid'] = $contact['id'];
1973 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1975 intval($importer['uid'])
1978 $ev['id'] = $r[0]['id'];
1979 $xyz = event_store($ev);
1984 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1985 if(strlen($datarray['title']))
1986 unset($datarray['title']);
1987 $datarray['last-child'] = 1;
1991 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1993 intval($importer['uid'])
1996 // Update content if 'updated' changes
1999 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2001 // do not accept (ignore) an earlier edit than one we currently have.
2002 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2005 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2006 dbesc($datarray['title']),
2007 dbesc($datarray['body']),
2008 dbesc($datarray['tag']),
2009 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2011 intval($importer['uid'])
2015 // update last-child if it changes
2017 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2018 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2019 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2020 intval($allow[0]['data']),
2021 dbesc(datetime_convert()),
2023 intval($importer['uid'])
2029 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
2030 logger('consume-feed: New follower');
2031 new_follower($importer,$contact,$datarray,$item);
2034 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
2035 lose_follower($importer,$contact,$datarray,$item);
2039 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
2040 logger('consume-feed: New friend request');
2041 new_follower($importer,$contact,$datarray,$item,true);
2044 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
2045 lose_sharer($importer,$contact,$datarray,$item);
2050 if(! is_array($contact))
2054 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2055 // one way feed - no remote comment ability
2056 $datarray['last-child'] = 0;
2058 if($contact['network'] === NETWORK_FEED)
2059 $datarray['private'] = 2;
2061 // This is my contact on another system, but it's really me.
2062 // Turn this into a wall post.
2064 if($contact['remote_self']) {
2065 $datarray['wall'] = 1;
2066 if($contact['network'] === NETWORK_FEED) {
2067 $datarray['private'] = 0;
2071 $datarray['parent-uri'] = $item_id;
2072 $datarray['uid'] = $importer['uid'];
2073 $datarray['contact-id'] = $contact['id'];
2075 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2076 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2077 // but otherwise there's a possible data mixup on the sender's system.
2078 // the tgroup delivery code called from item_store will correct it if it's a forum,
2079 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2080 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2081 $datarray['owner-name'] = $contact['name'];
2082 $datarray['owner-link'] = $contact['url'];
2083 $datarray['owner-avatar'] = $contact['thumb'];
2086 $r = item_store($datarray);
2094 function local_delivery($importer,$data) {
2098 if($importer['readonly']) {
2099 // We aren't receiving stuff from this person. But we will quietly ignore them
2100 // rather than a blatant "go away" message.
2101 logger('local_delivery: ignoring');
2106 // Consume notification feed. This may differ from consuming a public feed in several ways
2107 // - might contain email or friend suggestions
2108 // - might contain remote followup to our message
2109 // - in which case we need to accept it and then notify other conversants
2110 // - we may need to send various email notifications
2112 $feed = new SimplePie();
2113 $feed->set_raw_data($data);
2114 $feed->enable_order_by_date(false);
2119 logger('local_delivery: Error parsing XML: ' . $feed->error());
2122 // Check at the feed level for updated contact name and/or photo
2126 $photo_timestamp = '';
2130 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
2132 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
2134 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
2135 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
2136 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
2137 $new_name = $elems['name'][0]['data'];
2139 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
2140 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
2141 $photo_url = $elems['link'][0]['attribs']['']['href'];
2145 if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
2146 logger('local_delivery: Updating photo for ' . $importer['name']);
2147 require_once("Photo.php");
2148 $photo_failure = false;
2149 $have_photo = false;
2151 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
2152 intval($importer['id']),
2153 intval($importer['importer_uid'])
2156 $resource_id = $r[0]['resource-id'];
2160 $resource_id = photo_new_resource();
2163 $img_str = fetch_url($photo_url,true);
2164 // guess mimetype from headers or filename
2165 $type = guess_image_type($photo_url,true);
2168 $img = new Photo($img_str, $type);
2169 if($img->is_valid()) {
2171 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
2172 dbesc($resource_id),
2173 intval($importer['id']),
2174 intval($importer['importer_uid'])
2178 $img->scaleImageSquare(175);
2180 $hash = $resource_id;
2181 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 4);
2183 $img->scaleImage(80);
2184 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 5);
2186 $img->scaleImage(48);
2187 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 6);
2191 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
2192 WHERE `uid` = %d AND `id` = %d LIMIT 1",
2193 dbesc(datetime_convert()),
2194 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
2195 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
2196 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
2197 intval($importer['importer_uid']),
2198 intval($importer['id'])
2203 if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
2204 $r = q("select * from contact where uid = %d and id = %d limit 1",
2205 intval($importer['importer_uid']),
2206 intval($importer['id'])
2209 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2210 dbesc(notags(trim($new_name))),
2211 dbesc(datetime_convert()),
2212 intval($importer['importer_uid']),
2213 intval($importer['id'])
2216 // do our best to update the name on content items
2219 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
2220 dbesc(notags(trim($new_name))),
2221 dbesc($r[0]['name']),
2222 dbesc($r[0]['url']),
2223 intval($importer['importer_uid'])
2230 // Currently unsupported - needs a lot of work
2231 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2232 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2233 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2235 $newloc['uid'] = $importer['importer_uid'];
2236 $newloc['cid'] = $importer['id'];
2237 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2238 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2239 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2240 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2241 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2242 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2243 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2244 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
2245 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2246 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
2249 // merge with current record, current contents have priority
2250 // update record, set url-updated
2251 // update profile photos
2257 // handle friend suggestion notification
2259 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2260 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2261 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2263 $fsugg['uid'] = $importer['importer_uid'];
2264 $fsugg['cid'] = $importer['id'];
2265 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2266 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2267 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2268 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2269 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2271 // Does our member already have a friend matching this description?
2273 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2274 dbesc($fsugg['name']),
2275 dbesc(normalise_link($fsugg['url'])),
2276 intval($fsugg['uid'])
2281 // Do we already have an fcontact record for this person?
2284 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2285 dbesc($fsugg['url']),
2286 dbesc($fsugg['name']),
2287 dbesc($fsugg['request'])
2292 // OK, we do. Do we already have an introduction for this person ?
2293 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2294 intval($fsugg['uid']),
2301 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2302 dbesc($fsugg['name']),
2303 dbesc($fsugg['url']),
2304 dbesc($fsugg['photo']),
2305 dbesc($fsugg['request'])
2307 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2308 dbesc($fsugg['url']),
2309 dbesc($fsugg['name']),
2310 dbesc($fsugg['request'])
2315 // database record did not get created. Quietly give up.
2320 $hash = random_string();
2322 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2323 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2324 intval($fsugg['uid']),
2326 intval($fsugg['cid']),
2327 dbesc($fsugg['body']),
2329 dbesc(datetime_convert()),
2334 'type' => NOTIFY_SUGGEST,
2335 'notify_flags' => $importer['notify-flags'],
2336 'language' => $importer['language'],
2337 'to_name' => $importer['username'],
2338 'to_email' => $importer['email'],
2339 'uid' => $importer['importer_uid'],
2341 'link' => $a->get_baseurl() . '/notifications/intros',
2342 'source_name' => $importer['name'],
2343 'source_link' => $importer['url'],
2344 'source_photo' => $importer['photo'],
2345 'verb' => ACTIVITY_REQ_FRIEND,
2354 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2355 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2357 logger('local_delivery: private message received');
2360 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2363 $msg['uid'] = $importer['importer_uid'];
2364 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2365 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2366 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2367 $msg['contact-id'] = $importer['id'];
2368 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2369 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2371 $msg['replied'] = 0;
2372 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2373 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2374 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2378 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2379 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2381 // send notifications.
2383 require_once('include/enotify.php');
2385 $notif_params = array(
2386 'type' => NOTIFY_MAIL,
2387 'notify_flags' => $importer['notify-flags'],
2388 'language' => $importer['language'],
2389 'to_name' => $importer['username'],
2390 'to_email' => $importer['email'],
2391 'uid' => $importer['importer_uid'],
2393 'source_name' => $msg['from-name'],
2394 'source_link' => $importer['url'],
2395 'source_photo' => $importer['thumb'],
2396 'verb' => ACTIVITY_POST,
2400 notification($notif_params);
2406 $community_page = 0;
2407 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2409 $community_page = intval($rawtags[0]['data']);
2411 if(intval($importer['forum']) != $community_page) {
2412 q("update contact set forum = %d where id = %d limit 1",
2413 intval($community_page),
2414 intval($importer['id'])
2416 $importer['forum'] = (string) $community_page;
2419 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2421 // process any deleted entries
2423 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2424 if(is_array($del_entries) && count($del_entries)) {
2425 foreach($del_entries as $dentry) {
2427 if(isset($dentry['attribs']['']['ref'])) {
2428 $uri = $dentry['attribs']['']['ref'];
2430 if(isset($dentry['attribs']['']['when'])) {
2431 $when = $dentry['attribs']['']['when'];
2432 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2435 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2439 // check for relayed deletes to our conversation
2442 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2444 intval($importer['importer_uid'])
2447 $parent_uri = $r[0]['parent-uri'];
2448 if($r[0]['id'] != $r[0]['parent'])
2455 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2458 logger('local_delivery: possible community delete');
2461 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2463 // was the top-level post for this reply written by somebody on this site?
2464 // Specifically, the recipient?
2466 $is_a_remote_delete = false;
2468 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2469 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2470 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2471 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2472 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2473 AND `item`.`uid` = %d
2479 intval($importer['importer_uid'])
2482 $is_a_remote_delete = true;
2484 // Does this have the characteristics of a community or private group comment?
2485 // If it's a reply to a wall post on a community/prvgroup page it's a
2486 // valid community comment. Also forum_mode makes it valid for sure.
2487 // If neither, it's not.
2489 if($is_a_remote_delete && $community) {
2490 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2491 $is_a_remote_delete = false;
2492 logger('local_delivery: not a community delete');
2496 if($is_a_remote_delete) {
2497 logger('local_delivery: received remote delete');
2501 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2502 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2504 intval($importer['importer_uid']),
2505 intval($importer['id'])
2511 if($item['deleted'])
2514 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2516 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2517 $xo = parse_xml_string($item['object'],false);
2518 $xt = parse_xml_string($item['target'],false);
2520 if($xt->type === ACTIVITY_OBJ_NOTE) {
2521 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2523 intval($importer['importer_uid'])
2527 // For tags, the owner cannot remove the tag on the author's copy of the post.
2529 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2530 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2531 $author_copy = (($item['origin']) ? true : false);
2533 if($owner_remove && $author_copy)
2535 if($author_remove || $owner_remove) {
2536 $tags = explode(',',$i[0]['tag']);
2539 foreach($tags as $tag)
2540 if(trim($tag) !== trim($xo->body))
2541 $newtags[] = trim($tag);
2543 q("update item set tag = '%s' where id = %d limit 1",
2544 dbesc(implode(',',$newtags)),
2552 if($item['uri'] == $item['parent-uri']) {
2553 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2554 `body` = '', `title` = ''
2555 WHERE `parent-uri` = '%s' AND `uid` = %d",
2557 dbesc(datetime_convert()),
2558 dbesc($item['uri']),
2559 intval($importer['importer_uid'])
2563 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2564 `body` = '', `title` = ''
2565 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2567 dbesc(datetime_convert()),
2569 intval($importer['importer_uid'])
2571 if($item['last-child']) {
2572 // ensure that last-child is set in case the comment that had it just got wiped.
2573 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2574 dbesc(datetime_convert()),
2575 dbesc($item['parent-uri']),
2576 intval($item['uid'])
2578 // who is the last child now?
2579 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2580 ORDER BY `created` DESC LIMIT 1",
2581 dbesc($item['parent-uri']),
2582 intval($importer['importer_uid'])
2585 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2590 // if this is a relayed delete, propagate it to other recipients
2592 if($is_a_remote_delete)
2593 proc_run('php',"include/notifier.php","drop",$item['id']);
2601 foreach($feed->get_items() as $item) {
2604 $item_id = $item->get_id();
2605 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2606 if(isset($rawthread[0]['attribs']['']['ref'])) {
2608 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2614 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2617 logger('local_delivery: possible community reply');
2620 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2622 // was the top-level post for this reply written by somebody on this site?
2623 // Specifically, the recipient?
2625 $is_a_remote_comment = false;
2627 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2628 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2629 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2630 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2631 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2632 AND `item`.`uid` = %d
2638 intval($importer['importer_uid'])
2641 $is_a_remote_comment = true;
2643 // Does this have the characteristics of a community or private group comment?
2644 // If it's a reply to a wall post on a community/prvgroup page it's a
2645 // valid community comment. Also forum_mode makes it valid for sure.
2646 // If neither, it's not.
2648 if($is_a_remote_comment && $community) {
2649 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2650 $is_a_remote_comment = false;
2651 logger('local_delivery: not a community reply');
2655 if($is_a_remote_comment) {
2656 logger('local_delivery: received remote comment');
2658 // remote reply to our post. Import and then notify everybody else.
2660 $datarray = get_atom_elements($feed,$item);
2662 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2664 intval($importer['importer_uid'])
2667 // Update content if 'updated' changes
2671 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2673 // do not accept (ignore) an earlier edit than one we currently have.
2674 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2677 logger('received updated comment' , LOGGER_DEBUG);
2678 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2679 dbesc($datarray['title']),
2680 dbesc($datarray['body']),
2681 dbesc($datarray['tag']),
2682 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2684 intval($importer['importer_uid'])
2687 proc_run('php',"include/notifier.php","comment-import",$iid);
2695 // TODO: make this next part work against both delivery threads of a community post
2697 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2698 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2699 // they won't know what to do so don't report an error. Just quietly die.
2703 // our user with $importer['importer_uid'] is the owner
2705 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2706 intval($importer['importer_uid'])
2710 $datarray['type'] = 'remote-comment';
2711 $datarray['wall'] = 1;
2712 $datarray['parent-uri'] = $parent_uri;
2713 $datarray['uid'] = $importer['importer_uid'];
2714 $datarray['owner-name'] = $own[0]['name'];
2715 $datarray['owner-link'] = $own[0]['url'];
2716 $datarray['owner-avatar'] = $own[0]['thumb'];
2717 $datarray['contact-id'] = $importer['id'];
2719 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2721 $datarray['type'] = 'activity';
2722 $datarray['gravity'] = GRAVITY_LIKE;
2723 $datarray['last-child'] = 0;
2724 // only one like or dislike per person
2725 $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",
2726 intval($datarray['uid']),
2727 intval($datarray['contact-id']),
2728 dbesc($datarray['verb']),
2729 dbesc($datarray['parent-uri']),
2730 dbesc($datarray['parent-uri'])
2737 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2739 $xo = parse_xml_string($datarray['object'],false);
2740 $xt = parse_xml_string($datarray['target'],false);
2742 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2744 // fetch the parent item
2746 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2748 intval($importer['importer_uid'])
2753 // extract tag, if not duplicate, and this user allows tags, add to parent item
2755 if($xo->id && $xo->content) {
2756 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2757 if(! (stristr($tagp[0]['tag'],$newtag))) {
2758 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2759 intval($importer['importer_uid'])
2761 if(count($i) && ! intval($i[0]['blocktags'])) {
2762 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2763 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2764 intval($tagp[0]['id']),
2765 dbesc(datetime_convert())
2774 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2775 // if(! stristr($datarray['tag'],$newtag)) {
2776 // if(strlen($datarray['tag']))
2777 // $datarray['tag'] .= ',';
2778 // $datarray['tag'] .= $newtag;
2783 $posted_id = item_store($datarray);
2787 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2789 intval($importer['importer_uid'])
2792 $parent = $r[0]['parent'];
2793 $parent_uri = $r[0]['parent-uri'];
2797 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2798 dbesc(datetime_convert()),
2799 intval($importer['importer_uid']),
2800 intval($r[0]['parent'])
2803 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2804 dbesc(datetime_convert()),
2805 intval($importer['importer_uid']),
2810 if($posted_id && $parent) {
2812 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2814 if((! $is_like) && (! $importer['self'])) {
2816 require_once('include/enotify.php');
2819 'type' => NOTIFY_COMMENT,
2820 'notify_flags' => $importer['notify-flags'],
2821 'language' => $importer['language'],
2822 'to_name' => $importer['username'],
2823 'to_email' => $importer['email'],
2824 'uid' => $importer['importer_uid'],
2825 'item' => $datarray,
2826 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2827 'source_name' => stripslashes($datarray['author-name']),
2828 'source_link' => $datarray['author-link'],
2829 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2830 ? $importer['thumb'] : $datarray['author-avatar']),
2831 'verb' => ACTIVITY_POST,
2833 'parent' => $parent,
2834 'parent_uri' => $parent_uri,
2846 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2848 $item_id = $item->get_id();
2849 $datarray = get_atom_elements($feed,$item);
2851 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2853 intval($importer['importer_uid'])
2856 // Update content if 'updated' changes
2859 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2861 // do not accept (ignore) an earlier edit than one we currently have.
2862 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2865 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2866 dbesc($datarray['title']),
2867 dbesc($datarray['body']),
2868 dbesc($datarray['tag']),
2869 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2871 intval($importer['importer_uid'])
2875 // update last-child if it changes
2877 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2878 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2879 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2880 dbesc(datetime_convert()),
2882 intval($importer['importer_uid'])
2884 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2885 intval($allow[0]['data']),
2886 dbesc(datetime_convert()),
2888 intval($importer['importer_uid'])
2894 $datarray['parent-uri'] = $parent_uri;
2895 $datarray['uid'] = $importer['importer_uid'];
2896 $datarray['contact-id'] = $importer['id'];
2897 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2898 $datarray['type'] = 'activity';
2899 $datarray['gravity'] = GRAVITY_LIKE;
2900 // only one like or dislike per person
2901 $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",
2902 intval($datarray['uid']),
2903 intval($datarray['contact-id']),
2904 dbesc($datarray['verb']),
2913 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2915 $xo = parse_xml_string($datarray['object'],false);
2916 $xt = parse_xml_string($datarray['target'],false);
2918 if($xt->type == ACTIVITY_OBJ_NOTE) {
2919 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2921 intval($importer['importer_uid'])
2926 // extract tag, if not duplicate, add to parent item
2928 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2929 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2930 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2938 $posted_id = item_store($datarray);
2940 // find out if our user is involved in this conversation and wants to be notified.
2942 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2944 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2946 intval($importer['importer_uid'])
2949 if(count($myconv)) {
2950 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2952 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2953 if(! link_compare($datarray['author-link'],$importer_url)) {
2956 foreach($myconv as $conv) {
2958 // now if we find a match, it means we're in this conversation
2960 if(! link_compare($conv['author-link'],$importer_url))
2963 require_once('include/enotify.php');
2965 $conv_parent = $conv['parent'];
2968 'type' => NOTIFY_COMMENT,
2969 'notify_flags' => $importer['notify-flags'],
2970 'language' => $importer['language'],
2971 'to_name' => $importer['username'],
2972 'to_email' => $importer['email'],
2973 'uid' => $importer['importer_uid'],
2974 'item' => $datarray,
2975 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2976 'source_name' => stripslashes($datarray['author-name']),
2977 'source_link' => $datarray['author-link'],
2978 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2979 ? $importer['thumb'] : $datarray['author-avatar']),
2980 'verb' => ACTIVITY_POST,
2982 'parent' => $conv_parent,
2983 'parent_uri' => $parent_uri
2987 // only send one notification
2999 // Head post of a conversation. Have we seen it? If not, import it.
3002 $item_id = $item->get_id();
3003 $datarray = get_atom_elements($feed,$item);
3005 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
3006 $ev = bbtoevent($datarray['body']);
3007 if(x($ev,'desc') && x($ev,'start')) {
3008 $ev['cid'] = $importer['id'];
3009 $ev['uid'] = $importer['uid'];
3010 $ev['uri'] = $item_id;
3011 $ev['edited'] = $datarray['edited'];
3012 $ev['private'] = $datarray['private'];
3014 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3016 intval($importer['uid'])
3019 $ev['id'] = $r[0]['id'];
3020 $xyz = event_store($ev);
3025 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3027 intval($importer['importer_uid'])
3030 // Update content if 'updated' changes
3033 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
3035 // do not accept (ignore) an earlier edit than one we currently have.
3036 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3039 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3040 dbesc($datarray['title']),
3041 dbesc($datarray['body']),
3042 dbesc($datarray['tag']),
3043 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3045 intval($importer['importer_uid'])
3049 // update last-child if it changes
3051 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3052 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
3053 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3054 intval($allow[0]['data']),
3055 dbesc(datetime_convert()),
3057 intval($importer['importer_uid'])
3063 // This is my contact on another system, but it's really me.
3064 // Turn this into a wall post.
3066 if($importer['remote_self'])
3067 $datarray['wall'] = 1;
3069 $datarray['parent-uri'] = $item_id;
3070 $datarray['uid'] = $importer['importer_uid'];
3071 $datarray['contact-id'] = $importer['id'];
3074 if(! link_compare($datarray['owner-link'],$importer['url'])) {
3075 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
3076 // but otherwise there's a possible data mixup on the sender's system.
3077 // the tgroup delivery code called from item_store will correct it if it's a forum,
3078 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
3079 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
3080 $datarray['owner-name'] = $importer['senderName'];
3081 $datarray['owner-link'] = $importer['url'];
3082 $datarray['owner-avatar'] = $importer['thumb'];
3085 $posted_id = item_store($datarray);
3087 if(stristr($datarray['verb'],ACTIVITY_POKE)) {
3088 $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
3091 $xo = parse_xml_string($datarray['object'],false);
3093 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
3095 // somebody was poked/prodded. Was it me?
3097 $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
3099 foreach($links->link as $l) {
3100 $atts = $l->attributes();
3101 switch($atts['rel']) {
3103 $Blink = $atts['href'];
3109 if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
3111 // send a notification
3112 require_once('include/enotify.php');
3115 'type' => NOTIFY_POKE,
3116 'notify_flags' => $importer['notify-flags'],
3117 'language' => $importer['language'],
3118 'to_name' => $importer['username'],
3119 'to_email' => $importer['email'],
3120 'uid' => $importer['importer_uid'],
3121 'item' => $datarray,
3122 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3123 'source_name' => stripslashes($datarray['author-name']),
3124 'source_link' => $datarray['author-link'],
3125 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3126 ? $importer['thumb'] : $datarray['author-avatar']),
3127 'verb' => $datarray['verb'],
3128 'otype' => 'person',
3129 'activity' => $verb,
3146 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
3147 $url = notags(trim($datarray['author-link']));
3148 $name = notags(trim($datarray['author-name']));
3149 $photo = notags(trim($datarray['author-avatar']));
3151 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
3152 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
3153 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
3155 if(is_array($contact)) {
3156 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
3157 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
3158 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
3159 intval(CONTACT_IS_FRIEND),
3160 intval($contact['id']),
3161 intval($importer['uid'])
3164 // send email notification to owner?
3168 // create contact record
3170 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
3171 `blocked`, `readonly`, `pending`, `writable` )
3172 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
3173 intval($importer['uid']),
3174 dbesc(datetime_convert()),
3176 dbesc(normalise_link($url)),
3180 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
3181 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
3183 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
3184 intval($importer['uid']),
3188 $contact_record = $r[0];
3190 // create notification
3191 $hash = random_string();
3193 if(is_array($contact_record)) {
3194 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
3195 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
3196 intval($importer['uid']),
3197 intval($contact_record['id']),
3199 dbesc(datetime_convert())
3202 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3203 intval($importer['uid'])
3208 if(intval($r[0]['def_gid'])) {
3209 require_once('include/group.php');
3210 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
3213 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
3214 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
3215 $email = replace_macros($email_tpl, array(
3216 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
3218 '$myname' => $r[0]['username'],
3219 '$siteurl' => $a->get_baseurl(),
3220 '$sitename' => $a->config['sitename']
3222 $res = mail($r[0]['email'],
3223 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
3225 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
3226 . 'Content-type: text/plain; charset=UTF-8' . "\n"
3227 . 'Content-transfer-encoding: 8bit' );
3234 function lose_follower($importer,$contact,$datarray,$item) {
3236 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
3237 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3238 intval(CONTACT_IS_SHARING),
3239 intval($contact['id'])
3243 contact_remove($contact['id']);
3247 function lose_sharer($importer,$contact,$datarray,$item) {
3249 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3250 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3251 intval(CONTACT_IS_FOLLOWER),
3252 intval($contact['id'])
3256 contact_remove($contact['id']);
3261 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3265 if(is_array($importer)) {
3266 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3267 intval($importer['uid'])
3271 // Diaspora has different message-ids in feeds than they do
3272 // through the direct Diaspora protocol. If we try and use
3273 // the feed, we'll get duplicates. So don't.
3275 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3278 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3280 // Use a single verify token, even if multiple hubs
3282 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3284 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3286 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
3288 if(! strlen($contact['hub-verify'])) {
3289 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3290 dbesc($verify_token),
3291 intval($contact['id'])
3295 post_url($url,$params);
3297 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3304 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3308 $name = xmlify($name);
3309 $uri = xmlify($uri);
3312 $photo = xmlify($photo);
3316 $o .= "<name>$name</name>\r\n";
3317 $o .= "<uri>$uri</uri>\r\n";
3318 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3319 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3321 call_hooks('atom_author', $o);
3323 $o .= "</$tag>\r\n";
3327 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3331 if(! $item['parent'])
3334 if($item['deleted'])
3335 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3338 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3339 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3341 $body = $item['body'];
3343 $o = "\r\n\r\n<entry>\r\n";
3345 if(is_array($author))
3346 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3348 $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']));
3349 if(strlen($item['owner-name']))
3350 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3352 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
3353 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3354 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3357 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3358 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3359 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3360 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3361 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3362 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3363 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3365 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3367 if($item['location']) {
3368 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3369 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3373 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3375 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3376 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3379 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3380 if($item['bookmark'])
3381 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3384 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3387 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3389 if($item['signed_text']) {
3390 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3391 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3394 $verb = construct_verb($item);
3395 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3396 $actobj = construct_activity_object($item);
3399 $actarg = construct_activity_target($item);
3403 $tags = item_getfeedtags($item);
3405 foreach($tags as $t) {
3406 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3410 $o .= item_getfeedattach($item);
3412 $mentioned = get_mentions($item);
3416 call_hooks('atom_entry', $o);
3418 $o .= '</entry>' . "\r\n";
3423 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3426 logger('fix_private_photos', LOGGER_DEBUG);
3427 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3432 $img_start = strpos($orig_body, '[img');
3433 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3434 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3435 while( ($img_st_close !== false) && ($img_len !== false) ) {
3437 $img_st_close++; // make it point to AFTER the closing bracket
3438 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3440 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3443 if(stristr($image , $site . '/photo/')) {
3444 // Only embed locally hosted photos
3446 $i = basename($image);
3447 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3448 $x = strpos($i,'-');
3451 $res = substr($i,$x+1);
3452 $i = substr($i,0,$x);
3453 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3460 // Check to see if we should replace this photo link with an embedded image
3461 // 1. No need to do so if the photo is public
3462 // 2. If there's a contact-id provided, see if they're in the access list
3463 // for the photo. If so, embed it.
3464 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3465 // permissions, regardless of order but first check to see if they're an exact
3466 // match to save some processing overhead.
3468 if(has_permissions($r[0])) {
3470 $recips = enumerate_permissions($r[0]);
3471 if(in_array($cid, $recips)) {
3476 if(compare_permissions($item,$r[0]))
3481 $data = $r[0]['data'];
3482 $type = $r[0]['type'];
3484 // If a custom width and height were specified, apply before embedding
3485 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3486 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3488 $width = intval($match[1]);
3489 $height = intval($match[2]);
3491 $ph = new Photo($data, $type);
3492 if($ph->is_valid()) {
3493 $ph->scaleImage(max($width, $height));
3494 $data = $ph->imageString();
3495 $type = $ph->getType();
3499 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3500 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3501 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3507 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3508 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3509 if($orig_body === false)
3512 $img_start = strpos($orig_body, '[img');
3513 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3514 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3517 $new_body = $new_body . $orig_body;
3523 function has_permissions($obj) {
3524 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3529 function compare_permissions($obj1,$obj2) {
3530 // first part is easy. Check that these are exactly the same.
3531 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3532 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3533 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3534 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3537 // This is harder. Parse all the permissions and compare the resulting set.
3539 $recipients1 = enumerate_permissions($obj1);
3540 $recipients2 = enumerate_permissions($obj2);
3543 if($recipients1 == $recipients2)
3548 // returns an array of contact-ids that are allowed to see this object
3550 function enumerate_permissions($obj) {
3551 require_once('include/group.php');
3552 $allow_people = expand_acl($obj['allow_cid']);
3553 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3554 $deny_people = expand_acl($obj['deny_cid']);
3555 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3556 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3557 $deny = array_unique(array_merge($deny_people,$deny_groups));
3558 $recipients = array_diff($recipients,$deny);
3562 function item_getfeedtags($item) {
3565 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3567 for($x = 0; $x < $cnt; $x ++) {
3569 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3573 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3575 for($x = 0; $x < $cnt; $x ++) {
3577 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3583 function item_getfeedattach($item) {
3585 $arr = explode(',',$item['attach']);
3587 foreach($arr as $r) {
3589 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3591 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3592 if(intval($matches[2]))
3593 $ret .= 'length="' . intval($matches[2]) . '" ';
3594 if($matches[4] !== ' ')
3595 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3596 $ret .= ' />' . "\r\n";
3605 function item_expire($uid,$days) {
3607 if((! $uid) || ($days < 1))
3610 // $expire_network_only = save your own wall posts
3611 // and just expire conversations started by others
3613 $expire_network_only = get_pconfig($uid,'expire','network_only');
3614 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3616 $r = q("SELECT * FROM `item`
3618 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3629 $expire_items = get_pconfig($uid, 'expire','items');
3630 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3632 $expire_notes = get_pconfig($uid, 'expire','notes');
3633 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3635 $expire_starred = get_pconfig($uid, 'expire','starred');
3636 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3638 $expire_photos = get_pconfig($uid, 'expire','photos');
3639 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3641 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3643 foreach($r as $item) {
3645 // don't expire filed items
3647 if(strpos($item['file'],'[') !== false)
3650 // Only expire posts, not photos and photo comments
3652 if($expire_photos==0 && strlen($item['resource-id']))
3654 if($expire_starred==0 && intval($item['starred']))
3656 if($expire_notes==0 && $item['type']=='note')
3658 if($expire_items==0 && $item['type']!='note')
3661 drop_item($item['id'],false);
3664 proc_run('php',"include/notifier.php","expire","$uid");
3669 function drop_items($items) {
3672 if(! local_user() && ! remote_user())
3676 foreach($items as $item) {
3677 $owner = drop_item($item,false);
3678 if($owner && ! $uid)
3683 // multiple threads may have been deleted, send an expire notification
3686 proc_run('php',"include/notifier.php","expire","$uid");
3690 function drop_item($id,$interactive = true) {
3694 // locate item to be deleted
3696 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3703 notice( t('Item not found.') . EOL);
3704 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3709 $owner = $item['uid'];
3711 // check if logged in user is either the author or owner of this item
3713 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id']) || (! $interactive)) {
3715 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
3718 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3719 dbesc(datetime_convert()),
3720 dbesc(datetime_convert()),
3724 // clean up categories and tags so they don't end up as orphans
3727 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3729 foreach($matches as $mtch) {
3730 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3736 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3738 foreach($matches as $mtch) {
3739 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3743 // If item is a link to a photo resource, nuke all the associated photos
3744 // (visitors will not have photo resources)
3745 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3746 // generate a resource-id and therefore aren't intimately linked to the item.
3748 if(strlen($item['resource-id'])) {
3749 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3750 dbesc($item['resource-id']),
3751 intval($item['uid'])
3753 // ignore the result
3756 // If item is a link to an event, nuke the event record.
3758 if(intval($item['event-id'])) {
3759 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3760 intval($item['event-id']),
3761 intval($item['uid'])
3763 // ignore the result
3766 // clean up item_id and sign meta-data tables
3768 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3769 intval($item['id']),
3770 intval($item['uid'])
3773 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3774 intval($item['id']),
3775 intval($item['uid'])
3778 // If it's the parent of a comment thread, kill all the kids
3780 if($item['uri'] == $item['parent-uri']) {
3781 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3782 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3783 dbesc(datetime_convert()),
3784 dbesc(datetime_convert()),
3785 dbesc($item['parent-uri']),
3786 intval($item['uid'])
3788 // ignore the result
3791 // ensure that last-child is set in case the comment that had it just got wiped.
3792 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3793 dbesc(datetime_convert()),
3794 dbesc($item['parent-uri']),
3795 intval($item['uid'])
3797 // who is the last child now?
3798 $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",
3799 dbesc($item['parent-uri']),
3800 intval($item['uid'])
3803 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3808 // Add a relayable_retraction signature for Diaspora.
3809 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
3811 $drop_id = intval($item['id']);
3813 // send the notification upstream/downstream as the case may be
3818 proc_run('php',"include/notifier.php","drop","$drop_id");
3819 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3825 notice( t('Permission denied.') . EOL);
3826 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3833 function first_post_date($uid,$wall = false) {
3834 $r = q("select id, created from item
3835 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3837 order by created asc limit 1",
3839 intval($wall ? 1 : 0)
3842 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3843 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3848 function posted_dates($uid,$wall) {
3849 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3851 $dthen = first_post_date($uid,$wall);
3855 // If it's near the end of a long month, backup to the 28th so that in
3856 // consecutive loops we'll always get a whole month difference.
3858 if(intval(substr($dnow,8)) > 28)
3859 $dnow = substr($dnow,0,8) . '28';
3860 if(intval(substr($dthen,8)) > 28)
3861 $dnow = substr($dthen,0,8) . '28';
3864 // Starting with the current month, get the first and last days of every
3865 // month down to and including the month of the first post
3866 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
3867 $dstart = substr($dnow,0,8) . '01';
3868 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3869 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3870 $end_month = datetime_convert('','',$dend,'Y-m-d');
3871 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3872 $ret[] = array($str,$end_month,$start_month);
3873 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3879 function posted_date_widget($url,$uid,$wall) {
3882 // For former Facebook folks that left because of "timeline"
3884 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3887 $ret = posted_dates($uid,$wall);
3891 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3892 '$title' => t('Archives'),
3893 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3900 function store_diaspora_retract_sig($item, $user, $baseurl) {
3901 // Note that we can't add a target_author_signature
3902 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3903 // the comment, that means we're the home of the post, and Diaspora will only
3904 // check the parent_author_signature of retractions that it doesn't have to relay further
3906 // I don't think this function gets called for an "unlike," but I'll check anyway
3908 $enabled = intval(get_config('system','diaspora_enabled'));
3910 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
3914 logger('drop_item: storing diaspora retraction signature');
3916 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3918 if(local_user() == $item['uid']) {
3920 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
3921 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
3924 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3925 $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
3928 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3929 // only handles DFRN deletes
3930 $handle_baseurl_start = strpos($r['url'],'://') + 3;
3931 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3932 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3938 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3939 intval($item['id']),
3940 dbesc($signed_text),