3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
8 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
11 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
12 $public_feed = (($dfrn_id) ? false : true);
13 $starred = false; // not yet implemented, possible security issues
16 if($public_feed && $a->argc > 2) {
17 for($x = 2; $x < $a->argc; $x++) {
18 if($a->argv[$x] == 'converse')
20 if($a->argv[$x] == 'starred')
22 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
23 $category = $a->argv[$x+1];
29 // default permissions - anonymous user
31 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
33 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
34 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
35 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
43 $owner_id = $owner['user_uid'];
44 $owner_nick = $owner['nickname'];
46 $birthday = feed_birthday($owner_id,$owner['timezone']);
53 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
57 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
58 $my_id = '1:' . $dfrn_id;
61 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
62 $my_id = '0:' . $dfrn_id;
69 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
77 $groups = init_groups_visitor($contact['id']);
80 for($x = 0; $x < count($groups); $x ++)
81 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
82 $gs = implode('|', $groups);
85 $gs = '<<>>' ; // Impossible to match
87 $sql_extra = sprintf("
88 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
89 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
90 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
91 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
93 intval($contact['id']),
94 intval($contact['id']),
105 if(! strlen($last_update))
106 $last_update = 'now -30 days';
108 if(isset($category)) {
109 $sql_extra .= file_tag_file_query('item',$category,'category');
114 $sql_extra .= " AND `contact`.`self` = 1 ";
117 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
119 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
120 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
121 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
122 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
123 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
124 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
125 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
126 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
127 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
128 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
129 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
131 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
138 // Will check further below if this actually returned results.
139 // We will provide an empty feed if that is the case.
143 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
147 $hubxml = feed_hublinks();
149 $salmon = feed_salmonlinks($owner_nick);
151 $atom .= replace_macros($feed_template, array(
152 '$version' => xmlify(FRIENDICA_VERSION),
153 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
154 '$feed_title' => xmlify($owner['name']),
155 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
157 '$salmon' => $salmon,
158 '$name' => xmlify($owner['name']),
159 '$profile_page' => xmlify($owner['url']),
160 '$photo' => xmlify($owner['photo']),
161 '$thumb' => xmlify($owner['thumb']),
162 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
163 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
164 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
165 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
166 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
169 call_hooks('atom_feed', $atom);
171 if(! count($items)) {
173 call_hooks('atom_feed_end', $atom);
175 $atom .= '</feed>' . "\r\n";
179 foreach($items as $item) {
181 // prevent private email from leaking.
182 if($item['network'] === NETWORK_MAIL)
185 // public feeds get html, our own nodes use bbcode
189 // catch any email that's in a public conversation and make sure it doesn't leak
197 $atom .= atom_entry($item,$type,null,$owner,true);
200 call_hooks('atom_feed_end', $atom);
202 $atom .= '</feed>' . "\r\n";
208 function construct_verb($item) {
210 return $item['verb'];
211 return ACTIVITY_POST;
214 function construct_activity_object($item) {
216 if($item['object']) {
217 $o = '<as:object>' . "\r\n";
218 $r = parse_xml_string($item['object'],false);
224 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
226 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
228 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
230 if(substr($r->link,0,1) === '<') {
231 // patch up some facebook "like" activity objects that got stored incorrectly
232 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
233 // we can probably remove this hack here and in the following function in a few months time.
234 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
235 $r->link = str_replace('&','&', $r->link);
236 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
240 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
243 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
244 $o .= '</as:object>' . "\r\n";
251 function construct_activity_target($item) {
253 if($item['target']) {
254 $o = '<as:target>' . "\r\n";
255 $r = parse_xml_string($item['target'],false);
259 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
261 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
263 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
265 if(substr($r->link,0,1) === '<') {
266 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
267 $r->link = str_replace('&','&', $r->link);
268 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
272 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
275 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
276 $o .= '</as:target>' . "\r\n";
283 function title_is_body($title, $body) {
285 $title = strip_tags($title);
286 $title = trim($title);
287 $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
289 $body = strip_tags($body);
291 $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
293 if (strlen($title) < strlen($body))
294 $body = substr($body, 0, strlen($title));
296 if (($title != $body) and (substr($title, -3) == "...")) {
297 $pos = strrpos($title, "...");
299 $title = substr($title, 0, $pos);
300 $body = substr($body, 0, $pos);
304 return($title == $body);
309 function get_atom_elements($feed,$item) {
311 require_once('library/HTMLPurifier.auto.php');
312 require_once('include/html2bbcode.php');
314 $best_photo = array();
318 $author = $item->get_author();
320 $res['author-name'] = unxmlify($author->get_name());
321 $res['author-link'] = unxmlify($author->get_link());
324 $res['author-name'] = unxmlify($feed->get_title());
325 $res['author-link'] = unxmlify($feed->get_permalink());
327 $res['uri'] = unxmlify($item->get_id());
328 $res['title'] = unxmlify($item->get_title());
329 $res['body'] = unxmlify($item->get_content());
330 $res['plink'] = unxmlify($item->get_link(0));
332 // removing the content of the title if its identically to the body
333 // This helps with auto generated titles e.g. from tumblr
334 if (title_is_body($res["title"], $res["body"]))
338 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
342 // look for a photo. We should check media size and find the best one,
343 // but for now let's just find any author photo
345 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
347 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
348 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
349 foreach($base as $link) {
350 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
351 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
352 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
357 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
359 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
360 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
361 if($base && count($base)) {
362 foreach($base as $link) {
363 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
364 $res['author-link'] = unxmlify($link['attribs']['']['href']);
365 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
366 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
367 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
373 // No photo/profile-link on the item - look at the feed level
375 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
376 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
377 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
378 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
379 foreach($base as $link) {
380 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
381 $res['author-link'] = unxmlify($link['attribs']['']['href']);
382 if(! $res['author-avatar']) {
383 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
384 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
389 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
391 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
392 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
394 if($base && count($base)) {
395 foreach($base as $link) {
396 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
397 $res['author-link'] = unxmlify($link['attribs']['']['href']);
398 if(! (x($res,'author-avatar'))) {
399 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
400 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
407 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
408 if($apps && $apps[0]['attribs']['']['source']) {
409 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
410 if($res['app'] === 'web')
411 $res['app'] = 'OStatus';
414 // base64 encoded json structure representing Diaspora signature
416 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
418 $res['dsprsig'] = unxmlify($dsig[0]['data']);
421 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
423 $res['guid'] = unxmlify($dguid[0]['data']);
425 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
427 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
431 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
434 $have_real_body = false;
436 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
438 $have_real_body = true;
439 $res['body'] = $rawenv[0]['data'];
440 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
441 // make sure nobody is trying to sneak some html tags by us
442 $res['body'] = notags(base64url_decode($res['body']));
445 $maxlen = get_max_import_size();
446 if($maxlen && (strlen($res['body']) > $maxlen))
447 $res['body'] = substr($res['body'],0, $maxlen);
449 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
450 // the content type. Our own network only emits text normally, though it might have been converted to
451 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
452 // have to assume it is all html and needs to be purified.
454 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
455 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
456 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
459 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
461 $res['body'] = reltoabs($res['body'],$base_url);
463 $res['body'] = html2bb_video($res['body']);
465 $res['body'] = oembed_html2bbcode($res['body']);
467 $config = HTMLPurifier_Config::createDefault();
468 $config->set('Cache.DefinitionImpl', null);
470 // we shouldn't need a whitelist, because the bbcode converter
471 // will strip out any unsupported tags.
473 $purifier = new HTMLPurifier($config);
474 $res['body'] = $purifier->purify($res['body']);
476 $res['body'] = @html2bbcode($res['body']);
480 elseif(! $have_real_body) {
482 // it's not one of our messages and it has no tags
483 // so it's probably just text. We'll escape it just to be safe.
485 $res['body'] = escape_tags($res['body']);
488 // this tag is obsolete but we keep it for really old sites
490 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
491 if($allow && $allow[0]['data'] == 1)
492 $res['last-child'] = 1;
494 $res['last-child'] = 0;
496 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
497 if($private && intval($private[0]['data']) > 0)
498 $res['private'] = intval($private[0]['data']);
502 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
503 if($extid && $extid[0]['data'])
504 $res['extid'] = $extid[0]['data'];
506 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
508 $res['location'] = unxmlify($rawlocation[0]['data']);
511 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
513 $res['created'] = unxmlify($rawcreated[0]['data']);
516 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
518 $res['edited'] = unxmlify($rawedited[0]['data']);
520 if((x($res,'edited')) && (! (x($res,'created'))))
521 $res['created'] = $res['edited'];
523 if(! $res['created'])
524 $res['created'] = $item->get_date('c');
527 $res['edited'] = $item->get_date('c');
530 // Disallow time travelling posts
532 $d1 = strtotime($res['created']);
533 $d2 = strtotime($res['edited']);
534 $d3 = strtotime('now');
537 $res['created'] = datetime_convert();
539 $res['edited'] = datetime_convert();
541 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
542 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
543 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
544 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
545 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
546 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
547 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
548 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
549 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
551 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
552 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
554 foreach($base as $link) {
555 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
556 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
557 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
562 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
564 $res['coord'] = unxmlify($rawgeo[0]['data']);
567 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
569 // select between supported verbs
572 $res['verb'] = unxmlify($rawverb[0]['data']);
575 // translate OStatus unfollow to activity streams if it happened to get selected
577 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
578 $res['verb'] = ACTIVITY_UNFOLLOW;
580 $cats = $item->get_categories();
583 foreach($cats as $cat) {
584 $term = $cat->get_term();
586 $term = $cat->get_label();
587 $scheme = $cat->get_scheme();
588 if($scheme && $term && stristr($scheme,'X-DFRN:'))
589 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
591 $tag_arr[] = notags(trim($term));
593 $res['tag'] = implode(',', $tag_arr);
596 $attach = $item->get_enclosures();
599 foreach($attach as $att) {
600 $len = intval($att->get_length());
601 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
602 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
603 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
604 if(strpos($type,';'))
605 $type = substr($type,0,strpos($type,';'));
606 if((! $link) || (strpos($link,'http') !== 0))
612 $type = 'application/octet-stream';
614 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
616 $res['attach'] = implode(',', $att_arr);
619 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
622 $res['object'] = '<object>' . "\n";
623 $child = $rawobj[0]['child'];
624 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
625 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
626 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
628 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
629 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
630 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
631 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
632 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
633 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
634 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
635 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
637 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
638 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
639 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
640 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
642 $body = html2bb_video($body);
644 $config = HTMLPurifier_Config::createDefault();
645 $config->set('Cache.DefinitionImpl', null);
647 $purifier = new HTMLPurifier($config);
648 $body = $purifier->purify($body);
649 $body = html2bbcode($body);
652 $res['object'] .= '<content>' . $body . '</content>' . "\n";
655 $res['object'] .= '</object>' . "\n";
658 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
661 $res['target'] = '<target>' . "\n";
662 $child = $rawobj[0]['child'];
663 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
664 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
666 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
667 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
668 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
669 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
670 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
671 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
672 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
673 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
675 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
676 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
677 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
678 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
680 $body = html2bb_video($body);
682 $config = HTMLPurifier_Config::createDefault();
683 $config->set('Cache.DefinitionImpl', null);
685 $purifier = new HTMLPurifier($config);
686 $body = $purifier->purify($body);
687 $body = html2bbcode($body);
690 $res['target'] .= '<content>' . $body . '</content>' . "\n";
693 $res['target'] .= '</target>' . "\n";
696 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
698 call_hooks('parse_atom', $arr);
700 //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
701 if (strpos($res["body"], "RT @") !== false) {
702 $debugfile = tempnam("/home/ike/log", "item-res2-");
703 file_put_contents($debugfile, serialize($arr));
709 function encode_rel_links($links) {
711 if(! ((is_array($links)) && (count($links))))
713 foreach($links as $link) {
715 if($link['attribs']['']['rel'])
716 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
717 if($link['attribs']['']['type'])
718 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
719 if($link['attribs']['']['href'])
720 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
721 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
722 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
723 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
724 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
732 function item_store($arr,$force_parent = false) {
734 // If a Diaspora signature structure was passed in, pull it out of the
735 // item array and set it aside for later storage.
738 if(x($arr,'dsprsig')) {
739 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
740 unset($arr['dsprsig']);
743 if(x($arr, 'gravity'))
744 $arr['gravity'] = intval($arr['gravity']);
745 elseif($arr['parent-uri'] === $arr['uri'])
747 elseif(activity_match($arr['verb'],ACTIVITY_POST))
750 $arr['gravity'] = 6; // extensible catchall
753 $arr['type'] = 'remote';
755 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
757 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
758 $arr['body'] = strip_tags($arr['body']);
761 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
762 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
763 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
764 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
765 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
766 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
767 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
768 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
769 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
770 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
771 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
772 $arr['commented'] = datetime_convert();
773 $arr['received'] = datetime_convert();
774 $arr['changed'] = datetime_convert();
775 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
776 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
777 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
778 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
779 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
781 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
782 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
783 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
784 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
785 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
786 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
787 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
788 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
789 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
790 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
791 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
792 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
793 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
794 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
795 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
796 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
797 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
798 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
799 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
801 if($arr['parent-uri'] === $arr['uri']) {
804 $allow_cid = $arr['allow_cid'];
805 $allow_gid = $arr['allow_gid'];
806 $deny_cid = $arr['deny_cid'];
807 $deny_gid = $arr['deny_gid'];
811 // find the parent and snarf the item id and ACL's
812 // and anything else we need to inherit
814 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
815 dbesc($arr['parent-uri']),
821 // is the new message multi-level threaded?
822 // even though we don't support it now, preserve the info
823 // and re-attach to the conversation parent.
825 if($r[0]['uri'] != $r[0]['parent-uri']) {
826 $arr['thr-parent'] = $arr['parent-uri'];
827 $arr['parent-uri'] = $r[0]['parent-uri'];
828 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
829 ORDER BY `id` ASC LIMIT 1",
830 dbesc($r[0]['parent-uri']),
831 dbesc($r[0]['parent-uri']),
838 $parent_id = $r[0]['id'];
839 $parent_deleted = $r[0]['deleted'];
840 $allow_cid = $r[0]['allow_cid'];
841 $allow_gid = $r[0]['allow_gid'];
842 $deny_cid = $r[0]['deny_cid'];
843 $deny_gid = $r[0]['deny_gid'];
844 $arr['wall'] = $r[0]['wall'];
846 // if the parent is private, force privacy for the entire conversation
847 // This differs from the above settings as it subtly allows comments from
848 // email correspondents to be private even if the overall thread is not.
851 $arr['private'] = $r[0]['private'];
853 // Edge case. We host a public forum that was originally posted to privately.
854 // The original author commented, but as this is a comment, the permissions
855 // weren't fixed up so it will still show the comment as private unless we fix it here.
857 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
862 // Allow one to see reply tweets from status.net even when
863 // we don't have or can't see the original post.
866 logger('item_store: $force_parent=true, reply converted to top-level post.');
868 $arr['thr-parent'] = $arr['parent-uri'];
869 $arr['parent-uri'] = $arr['uri'];
873 logger('item_store: item parent was not found - ignoring item');
881 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
885 if($r && count($r)) {
886 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
890 call_hooks('post_remote',$arr);
892 if(x($arr,'cancel')) {
893 logger('item_store: post cancelled by plugin.');
899 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
901 $r = dbq("INSERT INTO `item` (`"
902 . implode("`, `", array_keys($arr))
904 . implode("', '", array_values($arr))
907 // find the item we just created
909 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
910 $arr['uri'], // already dbesc'd
915 $current_post = $r[0]['id'];
916 logger('item_store: created item ' . $current_post);
919 logger('item_store: could not locate created item');
923 logger('item_store: duplicated post occurred. Removing duplicates.');
924 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
927 intval($current_post)
931 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
932 $parent_id = $current_post;
934 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
937 $private = $arr['private'];
939 // Set parent id - and also make sure to inherit the parent's ACL's.
941 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
942 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
949 intval($parent_deleted),
950 intval($current_post)
953 $arr['id'] = $current_post;
954 $arr['parent'] = $parent_id;
955 $arr['allow_cid'] = $allow_cid;
956 $arr['allow_gid'] = $allow_gid;
957 $arr['deny_cid'] = $deny_cid;
958 $arr['deny_gid'] = $deny_gid;
959 $arr['private'] = $private;
960 $arr['deleted'] = $parent_deleted;
961 call_hooks('post_remote_end',$arr);
963 // update the commented timestamp on the parent
965 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
966 dbesc(datetime_convert()),
967 dbesc(datetime_convert()),
972 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
973 intval($current_post),
974 dbesc($dsprsig->signed_text),
975 dbesc($dsprsig->signature),
976 dbesc($dsprsig->signer)
982 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
985 if($arr['last-child']) {
986 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
989 intval($current_post)
993 tag_deliver($arr['uid'],$current_post);
995 return $current_post;
998 function get_item_contact($item,$contacts) {
999 if(! count($contacts) || (! is_array($item)))
1001 foreach($contacts as $contact) {
1002 if($contact['id'] == $item['contact-id']) {
1004 break; // NOTREACHED
1011 function tag_deliver($uid,$item_id) {
1013 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1019 $u = q("select * from user where uid = %d limit 1",
1025 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1026 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1029 $i = q("select * from item where id = %d and uid = %d limit 1",
1038 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1040 // Diaspora uses their own hardwired link URL in @-tags
1041 // instead of the one we supply with webfinger
1043 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1045 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1047 foreach($matches as $mtch) {
1048 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1050 logger('tag_deliver: mention found: ' . $mtch[2]);
1058 // send a notification
1060 require_once('include/enotify.php');
1062 'type' => NOTIFY_TAGSELF,
1063 'notify_flags' => $u[0]['notify-flags'],
1064 'language' => $u[0]['language'],
1065 'to_name' => $u[0]['username'],
1066 'to_email' => $u[0]['email'],
1067 'uid' => $u[0]['uid'],
1069 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1070 'source_name' => $item['author-name'],
1071 'source_link' => $item['author-link'],
1072 'source_photo' => $item['author-avatar'],
1073 'verb' => ACTIVITY_TAG,
1077 if((! $community_page) && (! $prvgroup))
1081 // tgroup delivery - setup a second delivery chain
1082 // prevent delivery looping - only proceed
1083 // if the message originated elsewhere and is a top-level post
1085 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1088 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1091 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1092 intval($u[0]['uid'])
1097 // also reset all the privacy bits to the forum default permissions
1099 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1101 $forum_mode = (($prvgroup) ? 2 : 1);
1103 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1104 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1105 intval($forum_mode),
1106 dbesc($c[0]['name']),
1107 dbesc($c[0]['url']),
1108 dbesc($c[0]['thumb']),
1110 dbesc($u[0]['allow_cid']),
1111 dbesc($u[0]['allow_gid']),
1112 dbesc($u[0]['deny_cid']),
1113 dbesc($u[0]['deny_gid']),
1117 proc_run('php','include/notifier.php','tgroup',$item_id);
1126 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1130 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1132 if($contact['duplex'] && $contact['dfrn-id'])
1133 $idtosend = '0:' . $orig_id;
1134 if($contact['duplex'] && $contact['issued-id'])
1135 $idtosend = '1:' . $orig_id;
1137 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1139 $rino_enable = get_config('system','rino_encrypt');
1144 $ssl_val = intval(get_config('system','ssl_policy'));
1148 case SSL_POLICY_FULL:
1149 $ssl_policy = 'full';
1151 case SSL_POLICY_SELFSIGN:
1152 $ssl_policy = 'self';
1154 case SSL_POLICY_NONE:
1156 $ssl_policy = 'none';
1160 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1162 logger('dfrn_deliver: ' . $url);
1164 $xml = fetch_url($url);
1166 $curl_stat = $a->get_curl_code();
1168 return(-1); // timed out
1170 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1175 if(strpos($xml,'<?xml') === false) {
1176 logger('dfrn_deliver: no valid XML returned');
1177 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1181 $res = parse_xml_string($xml);
1183 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1184 return (($res->status) ? $res->status : 3);
1186 $postvars = array();
1187 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1188 $challenge = hex2bin((string) $res->challenge);
1189 $perm = (($res->perm) ? $res->perm : null);
1190 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1191 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1192 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1194 if($owner['page-flags'] == PAGE_PRVGROUP)
1197 $final_dfrn_id = '';
1200 if((($perm == 'rw') && (! intval($contact['writable'])))
1201 || (($perm == 'r') && (intval($contact['writable'])))) {
1202 q("update contact set writable = %d where id = %d limit 1",
1203 intval(($perm == 'rw') ? 1 : 0),
1204 intval($contact['id'])
1206 $contact['writable'] = (string) 1 - intval($contact['writable']);
1210 if(($contact['duplex'] && strlen($contact['pubkey']))
1211 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1212 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1213 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1214 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1217 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1218 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1221 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1223 if(strpos($final_dfrn_id,':') == 1)
1224 $final_dfrn_id = substr($final_dfrn_id,2);
1226 if($final_dfrn_id != $orig_id) {
1227 logger('dfrn_deliver: wrong dfrn_id.');
1228 // did not decode properly - cannot trust this site
1232 $postvars['dfrn_id'] = $idtosend;
1233 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1235 $postvars['dissolve'] = '1';
1238 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1239 $postvars['data'] = $atom;
1240 $postvars['perm'] = 'rw';
1243 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1244 $postvars['perm'] = 'r';
1247 $postvars['ssl_policy'] = $ssl_policy;
1250 $postvars['page'] = $page;
1252 if($rino && $rino_allowed && (! $dissolve)) {
1253 $key = substr(random_string(),0,16);
1254 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1255 $postvars['data'] = $data;
1256 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1259 if($dfrn_version >= 2.1) {
1260 if(($contact['duplex'] && strlen($contact['pubkey']))
1261 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1262 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1264 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1267 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1271 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1272 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1275 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1279 logger('md5 rawkey ' . md5($postvars['key']));
1281 $postvars['key'] = bin2hex($postvars['key']);
1284 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1286 $xml = post_url($contact['notify'],$postvars);
1288 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1290 $curl_stat = $a->get_curl_code();
1291 if((! $curl_stat) || (! strlen($xml)))
1292 return(-1); // timed out
1294 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1297 if(strpos($xml,'<?xml') === false) {
1298 logger('dfrn_deliver: phase 2: no valid XML returned');
1299 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1303 if($contact['term-date'] != '0000-00-00 00:00:00') {
1304 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1305 require_once('include/Contact.php');
1306 unmark_for_death($contact);
1309 $res = parse_xml_string($xml);
1311 return $res->status;
1317 * consume_feed - process atom feed and update anything/everything we might need to update
1319 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1321 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1322 * It is this person's stuff that is going to be updated.
1323 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1324 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1325 * have a contact record.
1326 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1327 * might not) try and subscribe to it.
1328 * $datedir sorts in reverse order
1329 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1330 * imported prior to its children being seen in the stream unless we are certain
1331 * of how the feed is arranged/ordered.
1332 * With $pass = 1, we only pull parent items out of the stream.
1333 * With $pass = 2, we only pull children (comments/likes).
1335 * So running this twice, first with pass 1 and then with pass 2 will do the right
1336 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1337 * model where comments can have sub-threads. That would require some massive sorting
1338 * to get all the feed items into a mostly linear ordering, and might still require
1342 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1344 require_once('library/simplepie/simplepie.inc');
1346 if(! strlen($xml)) {
1347 logger('consume_feed: empty input');
1351 $feed = new SimplePie();
1352 $feed->set_raw_data($xml);
1354 $feed->enable_order_by_date(true);
1356 $feed->enable_order_by_date(false);
1360 logger('consume_feed: Error parsing XML: ' . $feed->error());
1362 $permalink = $feed->get_permalink();
1364 // Check at the feed level for updated contact name and/or photo
1368 $photo_timestamp = '';
1372 $hubs = $feed->get_links('hub');
1373 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1376 $hub = implode(',', $hubs);
1378 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1380 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1382 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1383 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1384 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1385 $new_name = $elems['name'][0]['data'];
1387 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1388 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1389 $photo_url = $elems['link'][0]['attribs']['']['href'];
1392 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1393 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1397 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1398 logger('consume_feed: Updating photo for ' . $contact['name']);
1399 require_once("Photo.php");
1400 $photo_failure = false;
1401 $have_photo = false;
1403 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1404 intval($contact['id']),
1405 intval($contact['uid'])
1408 $resource_id = $r[0]['resource-id'];
1412 $resource_id = photo_new_resource();
1415 $img_str = fetch_url($photo_url,true);
1416 // guess mimetype from headers or filename
1417 $type = guess_image_type($photo_url,true);
1420 $img = new Photo($img_str, $type);
1421 if($img->is_valid()) {
1423 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1424 dbesc($resource_id),
1425 intval($contact['id']),
1426 intval($contact['uid'])
1430 $img->scaleImageSquare(175);
1432 $hash = $resource_id;
1433 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1435 $img->scaleImage(80);
1436 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1438 $img->scaleImage(48);
1439 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1443 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1444 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1445 dbesc(datetime_convert()),
1446 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1447 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1448 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1449 intval($contact['uid']),
1450 intval($contact['id'])
1455 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1456 $r = q("select * from contact where uid = %d and id = %d limit 1",
1457 intval($contact['uid']),
1458 intval($contact['id'])
1461 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1462 dbesc(notags(trim($new_name))),
1463 dbesc(datetime_convert()),
1464 intval($contact['uid']),
1465 intval($contact['id'])
1468 // do our best to update the name on content items
1471 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1472 dbesc(notags(trim($new_name))),
1473 dbesc($r[0]['name']),
1474 dbesc($r[0]['url']),
1475 intval($contact['uid'])
1480 if(strlen($birthday)) {
1481 if(substr($birthday,0,4) != $contact['bdyear']) {
1482 logger('consume_feed: updating birthday: ' . $birthday);
1486 * Add new birthday event for this person
1488 * $bdtext is just a readable placeholder in case the event is shared
1489 * with others. We will replace it during presentation to our $importer
1490 * to contain a sparkle link and perhaps a photo.
1494 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1495 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1498 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1499 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1500 intval($contact['uid']),
1501 intval($contact['id']),
1502 dbesc(datetime_convert()),
1503 dbesc(datetime_convert()),
1504 dbesc(datetime_convert('UTC','UTC', $birthday)),
1505 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1514 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1515 dbesc(substr($birthday,0,4)),
1516 intval($contact['uid']),
1517 intval($contact['id'])
1520 // This function is called twice without reloading the contact
1521 // Make sure we only create one event. This is why &$contact
1522 // is a reference var in this function
1524 $contact['bdyear'] = substr($birthday,0,4);
1529 $community_page = 0;
1530 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1532 $community_page = intval($rawtags[0]['data']);
1534 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1535 q("update contact set forum = %d where id = %d limit 1",
1536 intval($community_page),
1537 intval($contact['id'])
1539 $contact['forum'] = (string) $community_page;
1543 // process any deleted entries
1545 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1546 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1547 foreach($del_entries as $dentry) {
1549 if(isset($dentry['attribs']['']['ref'])) {
1550 $uri = $dentry['attribs']['']['ref'];
1552 if(isset($dentry['attribs']['']['when'])) {
1553 $when = $dentry['attribs']['']['when'];
1554 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1557 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1559 if($deleted && is_array($contact)) {
1560 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1561 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1563 intval($importer['uid']),
1564 intval($contact['id'])
1569 if(! $item['deleted'])
1570 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1572 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1573 $xo = parse_xml_string($item['object'],false);
1574 $xt = parse_xml_string($item['target'],false);
1575 if($xt->type === ACTIVITY_OBJ_NOTE) {
1576 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1578 intval($importer['importer_uid'])
1582 // For tags, the owner cannot remove the tag on the author's copy of the post.
1584 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1585 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1586 $author_copy = (($item['origin']) ? true : false);
1588 if($owner_remove && $author_copy)
1590 if($author_remove || $owner_remove) {
1591 $tags = explode(',',$i[0]['tag']);
1594 foreach($tags as $tag)
1595 if(trim($tag) !== trim($xo->body))
1596 $newtags[] = trim($tag);
1598 q("update item set tag = '%s' where id = %d limit 1",
1599 dbesc(implode(',',$newtags)),
1607 if($item['uri'] == $item['parent-uri']) {
1608 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1609 `body` = '', `title` = ''
1610 WHERE `parent-uri` = '%s' AND `uid` = %d",
1612 dbesc(datetime_convert()),
1613 dbesc($item['uri']),
1614 intval($importer['uid'])
1618 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1619 `body` = '', `title` = ''
1620 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1622 dbesc(datetime_convert()),
1624 intval($importer['uid'])
1626 if($item['last-child']) {
1627 // ensure that last-child is set in case the comment that had it just got wiped.
1628 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1629 dbesc(datetime_convert()),
1630 dbesc($item['parent-uri']),
1631 intval($item['uid'])
1633 // who is the last child now?
1634 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1635 ORDER BY `created` DESC LIMIT 1",
1636 dbesc($item['parent-uri']),
1637 intval($importer['uid'])
1640 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1651 // Now process the feed
1653 if($feed->get_item_quantity()) {
1655 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1657 // in inverse date order
1659 $items = array_reverse($feed->get_items());
1661 $items = $feed->get_items();
1664 foreach($items as $item) {
1667 $item_id = $item->get_id();
1668 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1669 if(isset($rawthread[0]['attribs']['']['ref'])) {
1671 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1674 if(($is_reply) && is_array($contact)) {
1679 // Have we seen it? If not, import it.
1681 $item_id = $item->get_id();
1682 $datarray = get_atom_elements($feed,$item);
1684 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1685 $datarray['author-name'] = $contact['name'];
1686 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1687 $datarray['author-link'] = $contact['url'];
1688 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1689 $datarray['author-avatar'] = $contact['thumb'];
1691 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1692 logger('consume_feed: no author information! ' . print_r($datarray,true));
1696 $force_parent = false;
1697 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1698 if($contact['network'] === NETWORK_OSTATUS)
1699 $force_parent = true;
1700 if(strlen($datarray['title']))
1701 unset($datarray['title']);
1702 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1703 dbesc(datetime_convert()),
1705 intval($importer['uid'])
1707 $datarray['last-child'] = 1;
1711 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1713 intval($importer['uid'])
1716 // Update content if 'updated' changes
1719 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1721 // do not accept (ignore) an earlier edit than one we currently have.
1722 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1725 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1726 dbesc($datarray['title']),
1727 dbesc($datarray['body']),
1728 dbesc($datarray['tag']),
1729 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1731 intval($importer['uid'])
1735 // update last-child if it changes
1737 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1738 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1739 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1740 dbesc(datetime_convert()),
1742 intval($importer['uid'])
1744 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1745 intval($allow[0]['data']),
1746 dbesc(datetime_convert()),
1748 intval($importer['uid'])
1755 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1756 // one way feed - no remote comment ability
1757 $datarray['last-child'] = 0;
1759 $datarray['parent-uri'] = $parent_uri;
1760 $datarray['uid'] = $importer['uid'];
1761 $datarray['contact-id'] = $contact['id'];
1762 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1763 $datarray['type'] = 'activity';
1764 $datarray['gravity'] = GRAVITY_LIKE;
1765 // only one like or dislike per person
1766 $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",
1767 intval($datarray['uid']),
1768 intval($datarray['contact-id']),
1769 dbesc($datarray['verb']),
1777 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1778 $xo = parse_xml_string($datarray['object'],false);
1779 $xt = parse_xml_string($datarray['target'],false);
1781 if($xt->type == ACTIVITY_OBJ_NOTE) {
1782 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1784 intval($importer['importer_uid'])
1789 // extract tag, if not duplicate, add to parent item
1790 if($xo->id && $xo->content) {
1791 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1792 if(! (stristr($r[0]['tag'],$newtag))) {
1793 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1794 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1802 $r = item_store($datarray,$force_parent);
1808 // Head post of a conversation. Have we seen it? If not, import it.
1810 $item_id = $item->get_id();
1812 $datarray = get_atom_elements($feed,$item);
1814 if(is_array($contact)) {
1815 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1816 $datarray['author-name'] = $contact['name'];
1817 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1818 $datarray['author-link'] = $contact['url'];
1819 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1820 $datarray['author-avatar'] = $contact['thumb'];
1823 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1824 logger('consume_feed: no author information! ' . print_r($datarray,true));
1828 // special handling for events
1830 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1831 $ev = bbtoevent($datarray['body']);
1832 if(x($ev,'desc') && x($ev,'start')) {
1833 $ev['uid'] = $importer['uid'];
1834 $ev['uri'] = $item_id;
1835 $ev['edited'] = $datarray['edited'];
1836 $ev['private'] = $datarray['private'];
1838 if(is_array($contact))
1839 $ev['cid'] = $contact['id'];
1840 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1842 intval($importer['uid'])
1845 $ev['id'] = $r[0]['id'];
1846 $xyz = event_store($ev);
1851 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1852 if(strlen($datarray['title']))
1853 unset($datarray['title']);
1854 $datarray['last-child'] = 1;
1858 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1860 intval($importer['uid'])
1863 // Update content if 'updated' changes
1866 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1868 // do not accept (ignore) an earlier edit than one we currently have.
1869 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1872 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1873 dbesc($datarray['title']),
1874 dbesc($datarray['body']),
1875 dbesc($datarray['tag']),
1876 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1878 intval($importer['uid'])
1882 // update last-child if it changes
1884 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1885 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1886 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1887 intval($allow[0]['data']),
1888 dbesc(datetime_convert()),
1890 intval($importer['uid'])
1896 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1897 logger('consume-feed: New follower');
1898 new_follower($importer,$contact,$datarray,$item);
1901 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1902 lose_follower($importer,$contact,$datarray,$item);
1906 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1907 logger('consume-feed: New friend request');
1908 new_follower($importer,$contact,$datarray,$item,true);
1911 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1912 lose_sharer($importer,$contact,$datarray,$item);
1917 if(! is_array($contact))
1921 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1922 // one way feed - no remote comment ability
1923 $datarray['last-child'] = 0;
1925 if($contact['network'] === NETWORK_FEED)
1926 $datarray['private'] = 2;
1928 // This is my contact on another system, but it's really me.
1929 // Turn this into a wall post.
1931 if($contact['remote_self']) {
1932 $datarray['wall'] = 1;
1933 if($contact['network'] === NETWORK_FEED) {
1934 $datarray['private'] = 0;
1938 $datarray['parent-uri'] = $item_id;
1939 $datarray['uid'] = $importer['uid'];
1940 $datarray['contact-id'] = $contact['id'];
1942 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1943 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1944 // but otherwise there's a possible data mixup on the sender's system.
1945 // the tgroup delivery code called from item_store will correct it if it's a forum,
1946 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1947 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1948 $datarray['owner-name'] = $contact['name'];
1949 $datarray['owner-link'] = $contact['url'];
1950 $datarray['owner-avatar'] = $contact['thumb'];
1953 $r = item_store($datarray);
1961 function local_delivery($importer,$data) {
1965 if($importer['readonly']) {
1966 // We aren't receiving stuff from this person. But we will quietly ignore them
1967 // rather than a blatant "go away" message.
1968 logger('local_delivery: ignoring');
1973 // Consume notification feed. This may differ from consuming a public feed in several ways
1974 // - might contain email or friend suggestions
1975 // - might contain remote followup to our message
1976 // - in which case we need to accept it and then notify other conversants
1977 // - we may need to send various email notifications
1979 $feed = new SimplePie();
1980 $feed->set_raw_data($data);
1981 $feed->enable_order_by_date(false);
1985 // Currently unsupported - needs a lot of work
1986 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1987 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1988 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1990 $newloc['uid'] = $importer['importer_uid'];
1991 $newloc['cid'] = $importer['id'];
1992 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1993 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1994 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1995 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1996 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1997 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1998 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1999 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
2000 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2001 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
2004 // merge with current record, current contents have priority
2005 // update record, set url-updated
2006 // update profile photos
2012 // handle friend suggestion notification
2014 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2015 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2016 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2018 $fsugg['uid'] = $importer['importer_uid'];
2019 $fsugg['cid'] = $importer['id'];
2020 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2021 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2022 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2023 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2024 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2026 // Does our member already have a friend matching this description?
2028 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2029 dbesc($fsugg['name']),
2030 dbesc(normalise_link($fsugg['url'])),
2031 intval($fsugg['uid'])
2036 // Do we already have an fcontact record for this person?
2039 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2040 dbesc($fsugg['url']),
2041 dbesc($fsugg['name']),
2042 dbesc($fsugg['request'])
2047 // OK, we do. Do we already have an introduction for this person ?
2048 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2049 intval($fsugg['uid']),
2056 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2057 dbesc($fsugg['name']),
2058 dbesc($fsugg['url']),
2059 dbesc($fsugg['photo']),
2060 dbesc($fsugg['request'])
2062 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2063 dbesc($fsugg['url']),
2064 dbesc($fsugg['name']),
2065 dbesc($fsugg['request'])
2070 // database record did not get created. Quietly give up.
2075 $hash = random_string();
2077 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2078 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2079 intval($fsugg['uid']),
2081 intval($fsugg['cid']),
2082 dbesc($fsugg['body']),
2084 dbesc(datetime_convert()),
2089 'type' => NOTIFY_SUGGEST,
2090 'notify_flags' => $importer['notify-flags'],
2091 'language' => $importer['language'],
2092 'to_name' => $importer['username'],
2093 'to_email' => $importer['email'],
2094 'uid' => $importer['importer_uid'],
2096 'link' => $a->get_baseurl() . '/notifications/intros',
2097 'source_name' => $importer['name'],
2098 'source_link' => $importer['url'],
2099 'source_photo' => $importer['photo'],
2100 'verb' => ACTIVITY_REQ_FRIEND,
2109 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2110 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2112 logger('local_delivery: private message received');
2115 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2118 $msg['uid'] = $importer['importer_uid'];
2119 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2120 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2121 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2122 $msg['contact-id'] = $importer['id'];
2123 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2124 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2126 $msg['replied'] = 0;
2127 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2128 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2129 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2133 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2134 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2136 // send notifications.
2138 require_once('include/enotify.php');
2140 $notif_params = array(
2141 'type' => NOTIFY_MAIL,
2142 'notify_flags' => $importer['notify-flags'],
2143 'language' => $importer['language'],
2144 'to_name' => $importer['username'],
2145 'to_email' => $importer['email'],
2146 'uid' => $importer['importer_uid'],
2148 'source_name' => $msg['from-name'],
2149 'source_link' => $importer['url'],
2150 'source_photo' => $importer['thumb'],
2151 'verb' => ACTIVITY_POST,
2155 notification($notif_params);
2161 $community_page = 0;
2162 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2164 $community_page = intval($rawtags[0]['data']);
2166 if(intval($importer['forum']) != $community_page) {
2167 q("update contact set forum = %d where id = %d limit 1",
2168 intval($community_page),
2169 intval($importer['id'])
2171 $importer['forum'] = (string) $community_page;
2174 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2176 // process any deleted entries
2178 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2179 if(is_array($del_entries) && count($del_entries)) {
2180 foreach($del_entries as $dentry) {
2182 if(isset($dentry['attribs']['']['ref'])) {
2183 $uri = $dentry['attribs']['']['ref'];
2185 if(isset($dentry['attribs']['']['when'])) {
2186 $when = $dentry['attribs']['']['when'];
2187 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2190 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2194 // check for relayed deletes to our conversation
2197 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2199 intval($importer['importer_uid'])
2202 $parent_uri = $r[0]['parent-uri'];
2203 if($r[0]['id'] != $r[0]['parent'])
2210 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2213 logger('local_delivery: possible community delete');
2216 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2218 // was the top-level post for this reply written by somebody on this site?
2219 // Specifically, the recipient?
2221 $is_a_remote_delete = false;
2223 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2224 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2225 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2226 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2227 AND `item`.`uid` = %d
2233 intval($importer['importer_uid'])
2236 $is_a_remote_delete = true;
2238 // Does this have the characteristics of a community or private group comment?
2239 // If it's a reply to a wall post on a community/prvgroup page it's a
2240 // valid community comment. Also forum_mode makes it valid for sure.
2241 // If neither, it's not.
2243 if($is_a_remote_delete && $community) {
2244 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2245 $is_a_remote_delete = false;
2246 logger('local_delivery: not a community delete');
2250 if($is_a_remote_delete) {
2251 logger('local_delivery: received remote delete');
2255 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2256 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2258 intval($importer['importer_uid']),
2259 intval($importer['id'])
2265 if($item['deleted'])
2268 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2270 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2271 $xo = parse_xml_string($item['object'],false);
2272 $xt = parse_xml_string($item['target'],false);
2274 if($xt->type === ACTIVITY_OBJ_NOTE) {
2275 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2277 intval($importer['importer_uid'])
2281 // For tags, the owner cannot remove the tag on the author's copy of the post.
2283 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2284 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2285 $author_copy = (($item['origin']) ? true : false);
2287 if($owner_remove && $author_copy)
2289 if($author_remove || $owner_remove) {
2290 $tags = explode(',',$i[0]['tag']);
2293 foreach($tags as $tag)
2294 if(trim($tag) !== trim($xo->body))
2295 $newtags[] = trim($tag);
2297 q("update item set tag = '%s' where id = %d limit 1",
2298 dbesc(implode(',',$newtags)),
2306 if($item['uri'] == $item['parent-uri']) {
2307 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2308 WHERE `parent-uri` = '%s' AND `uid` = %d",
2310 dbesc(datetime_convert()),
2311 dbesc($item['uri']),
2312 intval($importer['importer_uid'])
2316 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2317 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2319 dbesc(datetime_convert()),
2321 intval($importer['importer_uid'])
2323 if($item['last-child']) {
2324 // ensure that last-child is set in case the comment that had it just got wiped.
2325 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2326 dbesc(datetime_convert()),
2327 dbesc($item['parent-uri']),
2328 intval($item['uid'])
2330 // who is the last child now?
2331 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2332 ORDER BY `created` DESC LIMIT 1",
2333 dbesc($item['parent-uri']),
2334 intval($importer['importer_uid'])
2337 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2342 // if this is a relayed delete, propagate it to other recipients
2344 if($is_a_remote_delete)
2345 proc_run('php',"include/notifier.php","drop",$item['id']);
2353 foreach($feed->get_items() as $item) {
2356 $item_id = $item->get_id();
2357 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2358 if(isset($rawthread[0]['attribs']['']['ref'])) {
2360 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2366 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2369 logger('local_delivery: possible community reply');
2372 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2374 // was the top-level post for this reply written by somebody on this site?
2375 // Specifically, the recipient?
2377 $is_a_remote_comment = false;
2379 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2380 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2381 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2382 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2383 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2384 AND `item`.`uid` = %d
2390 intval($importer['importer_uid'])
2393 $is_a_remote_comment = true;
2395 // Does this have the characteristics of a community or private group comment?
2396 // If it's a reply to a wall post on a community/prvgroup page it's a
2397 // valid community comment. Also forum_mode makes it valid for sure.
2398 // If neither, it's not.
2400 if($is_a_remote_comment && $community) {
2401 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2402 $is_a_remote_comment = false;
2403 logger('local_delivery: not a community reply');
2407 if($is_a_remote_comment) {
2408 logger('local_delivery: received remote comment');
2410 // remote reply to our post. Import and then notify everybody else.
2412 $datarray = get_atom_elements($feed,$item);
2414 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2416 intval($importer['importer_uid'])
2419 // Update content if 'updated' changes
2423 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2425 // do not accept (ignore) an earlier edit than one we currently have.
2426 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2429 logger('received updated comment' , LOGGER_DEBUG);
2430 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2431 dbesc($datarray['title']),
2432 dbesc($datarray['body']),
2433 dbesc($datarray['tag']),
2434 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2436 intval($importer['importer_uid'])
2439 proc_run('php',"include/notifier.php","comment-import",$iid);
2447 // TODO: make this next part work against both delivery threads of a community post
2449 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2450 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2451 // they won't know what to do so don't report an error. Just quietly die.
2455 // our user with $importer['importer_uid'] is the owner
2457 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2458 intval($importer['importer_uid'])
2462 $datarray['type'] = 'remote-comment';
2463 $datarray['wall'] = 1;
2464 $datarray['parent-uri'] = $parent_uri;
2465 $datarray['uid'] = $importer['importer_uid'];
2466 $datarray['owner-name'] = $own[0]['name'];
2467 $datarray['owner-link'] = $own[0]['url'];
2468 $datarray['owner-avatar'] = $own[0]['thumb'];
2469 $datarray['contact-id'] = $importer['id'];
2471 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2473 $datarray['type'] = 'activity';
2474 $datarray['gravity'] = GRAVITY_LIKE;
2475 $datarray['last-child'] = 0;
2476 // only one like or dislike per person
2477 $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",
2478 intval($datarray['uid']),
2479 intval($datarray['contact-id']),
2480 dbesc($datarray['verb']),
2481 dbesc($datarray['parent-uri']),
2482 dbesc($datarray['parent-uri'])
2489 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2491 $xo = parse_xml_string($datarray['object'],false);
2492 $xt = parse_xml_string($datarray['target'],false);
2494 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2496 // fetch the parent item
2498 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2500 intval($importer['importer_uid'])
2505 // extract tag, if not duplicate, and this user allows tags, add to parent item
2507 if($xo->id && $xo->content) {
2508 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2509 if(! (stristr($tagp[0]['tag'],$newtag))) {
2510 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2511 intval($importer['importer_uid'])
2513 if(count($i) && ! intval($i[0]['blocktags'])) {
2514 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2515 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2516 intval($tagp[0]['id']),
2517 dbesc(datetime_convert())
2526 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2527 // if(! stristr($datarray['tag'],$newtag)) {
2528 // if(strlen($datarray['tag']))
2529 // $datarray['tag'] .= ',';
2530 // $datarray['tag'] .= $newtag;
2535 $posted_id = item_store($datarray);
2539 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2541 intval($importer['importer_uid'])
2544 $parent = $r[0]['parent'];
2547 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2548 dbesc(datetime_convert()),
2549 intval($importer['importer_uid']),
2550 intval($r[0]['parent'])
2553 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2554 dbesc(datetime_convert()),
2555 intval($importer['importer_uid']),
2560 if($posted_id && $parent) {
2562 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2564 if((! $is_like) && (! $importer['self'])) {
2566 require_once('include/enotify.php');
2569 'type' => NOTIFY_COMMENT,
2570 'notify_flags' => $importer['notify-flags'],
2571 'language' => $importer['language'],
2572 'to_name' => $importer['username'],
2573 'to_email' => $importer['email'],
2574 'uid' => $importer['importer_uid'],
2575 'item' => $datarray,
2576 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2577 'source_name' => stripslashes($datarray['author-name']),
2578 'source_link' => $datarray['author-link'],
2579 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2580 ? $importer['thumb'] : $datarray['author-avatar']),
2581 'verb' => ACTIVITY_POST,
2583 'parent' => $parent,
2596 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2598 $item_id = $item->get_id();
2599 $datarray = get_atom_elements($feed,$item);
2601 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2603 intval($importer['importer_uid'])
2606 // Update content if 'updated' changes
2609 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2611 // do not accept (ignore) an earlier edit than one we currently have.
2612 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2615 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2616 dbesc($datarray['title']),
2617 dbesc($datarray['body']),
2618 dbesc($datarray['tag']),
2619 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2621 intval($importer['importer_uid'])
2625 // update last-child if it changes
2627 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2628 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2629 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2630 dbesc(datetime_convert()),
2632 intval($importer['importer_uid'])
2634 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2635 intval($allow[0]['data']),
2636 dbesc(datetime_convert()),
2638 intval($importer['importer_uid'])
2644 $datarray['parent-uri'] = $parent_uri;
2645 $datarray['uid'] = $importer['importer_uid'];
2646 $datarray['contact-id'] = $importer['id'];
2647 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2648 $datarray['type'] = 'activity';
2649 $datarray['gravity'] = GRAVITY_LIKE;
2650 // only one like or dislike per person
2651 $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",
2652 intval($datarray['uid']),
2653 intval($datarray['contact-id']),
2654 dbesc($datarray['verb']),
2663 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2665 $xo = parse_xml_string($datarray['object'],false);
2666 $xt = parse_xml_string($datarray['target'],false);
2668 if($xt->type == ACTIVITY_OBJ_NOTE) {
2669 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2671 intval($importer['importer_uid'])
2676 // extract tag, if not duplicate, add to parent item
2678 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2679 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2680 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2688 $posted_id = item_store($datarray);
2690 // find out if our user is involved in this conversation and wants to be notified.
2692 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2694 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2696 intval($importer['importer_uid'])
2699 if(count($myconv)) {
2700 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2702 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2703 if(! link_compare($datarray['author-link'],$importer_url)) {
2706 foreach($myconv as $conv) {
2708 // now if we find a match, it means we're in this conversation
2710 if(! link_compare($conv['author-link'],$importer_url))
2713 require_once('include/enotify.php');
2715 $conv_parent = $conv['parent'];
2718 'type' => NOTIFY_COMMENT,
2719 'notify_flags' => $importer['notify-flags'],
2720 'language' => $importer['language'],
2721 'to_name' => $importer['username'],
2722 'to_email' => $importer['email'],
2723 'uid' => $importer['importer_uid'],
2724 'item' => $datarray,
2725 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2726 'source_name' => stripslashes($datarray['author-name']),
2727 'source_link' => $datarray['author-link'],
2728 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2729 ? $importer['thumb'] : $datarray['author-avatar']),
2730 'verb' => ACTIVITY_POST,
2732 'parent' => $conv_parent,
2736 // only send one notification
2748 // Head post of a conversation. Have we seen it? If not, import it.
2751 $item_id = $item->get_id();
2752 $datarray = get_atom_elements($feed,$item);
2754 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2755 $ev = bbtoevent($datarray['body']);
2756 if(x($ev,'desc') && x($ev,'start')) {
2757 $ev['cid'] = $importer['id'];
2758 $ev['uid'] = $importer['uid'];
2759 $ev['uri'] = $item_id;
2760 $ev['edited'] = $datarray['edited'];
2761 $ev['private'] = $datarray['private'];
2763 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2765 intval($importer['uid'])
2768 $ev['id'] = $r[0]['id'];
2769 $xyz = event_store($ev);
2774 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2776 intval($importer['importer_uid'])
2779 // Update content if 'updated' changes
2782 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2784 // do not accept (ignore) an earlier edit than one we currently have.
2785 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2788 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2789 dbesc($datarray['title']),
2790 dbesc($datarray['body']),
2791 dbesc($datarray['tag']),
2792 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2794 intval($importer['importer_uid'])
2798 // update last-child if it changes
2800 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2801 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2802 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2803 intval($allow[0]['data']),
2804 dbesc(datetime_convert()),
2806 intval($importer['importer_uid'])
2812 // This is my contact on another system, but it's really me.
2813 // Turn this into a wall post.
2815 if($importer['remote_self'])
2816 $datarray['wall'] = 1;
2818 $datarray['parent-uri'] = $item_id;
2819 $datarray['uid'] = $importer['importer_uid'];
2820 $datarray['contact-id'] = $importer['id'];
2822 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2823 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2824 // but otherwise there's a possible data mixup on the sender's system.
2825 // the tgroup delivery code called from item_store will correct it if it's a forum,
2826 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2827 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2828 $datarray['owner-name'] = $importer['senderName'];
2829 $datarray['owner-link'] = $importer['url'];
2830 $datarray['owner-avatar'] = $importer['thumb'];
2833 $r = item_store($datarray);
2844 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2845 $url = notags(trim($datarray['author-link']));
2846 $name = notags(trim($datarray['author-name']));
2847 $photo = notags(trim($datarray['author-avatar']));
2849 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2850 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2851 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2853 if(is_array($contact)) {
2854 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2855 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2856 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2857 intval(CONTACT_IS_FRIEND),
2858 intval($contact['id']),
2859 intval($importer['uid'])
2862 // send email notification to owner?
2866 // create contact record
2868 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2869 `blocked`, `readonly`, `pending`, `writable` )
2870 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2871 intval($importer['uid']),
2872 dbesc(datetime_convert()),
2874 dbesc(normalise_link($url)),
2878 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2879 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2881 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2882 intval($importer['uid']),
2886 $contact_record = $r[0];
2888 // create notification
2889 $hash = random_string();
2891 if(is_array($contact_record)) {
2892 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2893 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2894 intval($importer['uid']),
2895 intval($contact_record['id']),
2897 dbesc(datetime_convert())
2900 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2901 intval($importer['uid'])
2906 if(intval($r[0]['def_gid'])) {
2907 require_once('include/group.php');
2908 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2911 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2912 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2913 $email = replace_macros($email_tpl, array(
2914 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2916 '$myname' => $r[0]['username'],
2917 '$siteurl' => $a->get_baseurl(),
2918 '$sitename' => $a->config['sitename']
2920 $res = mail($r[0]['email'],
2921 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2923 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2924 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2925 . 'Content-transfer-encoding: 8bit' );
2932 function lose_follower($importer,$contact,$datarray,$item) {
2934 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2935 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2936 intval(CONTACT_IS_SHARING),
2937 intval($contact['id'])
2941 contact_remove($contact['id']);
2945 function lose_sharer($importer,$contact,$datarray,$item) {
2947 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2948 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2949 intval(CONTACT_IS_FOLLOWER),
2950 intval($contact['id'])
2954 contact_remove($contact['id']);
2959 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2963 if(is_array($importer)) {
2964 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2965 intval($importer['uid'])
2969 // Diaspora has different message-ids in feeds than they do
2970 // through the direct Diaspora protocol. If we try and use
2971 // the feed, we'll get duplicates. So don't.
2973 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2976 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2978 // Use a single verify token, even if multiple hubs
2980 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2982 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2984 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2986 if(! strlen($contact['hub-verify'])) {
2987 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2988 dbesc($verify_token),
2989 intval($contact['id'])
2993 post_url($url,$params);
2995 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3002 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3006 $name = xmlify($name);
3007 $uri = xmlify($uri);
3010 $photo = xmlify($photo);
3014 $o .= "<name>$name</name>\r\n";
3015 $o .= "<uri>$uri</uri>\r\n";
3016 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3017 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3019 call_hooks('atom_author', $o);
3021 $o .= "</$tag>\r\n";
3025 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3029 if(! $item['parent'])
3032 if($item['deleted'])
3033 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3036 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3037 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3039 $body = $item['body'];
3042 $o = "\r\n\r\n<entry>\r\n";
3044 if(is_array($author))
3045 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3047 $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']));
3048 if(strlen($item['owner-name']))
3049 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3051 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || ($item['thr-parent'])) {
3052 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3053 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3056 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3057 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3058 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3059 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3060 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3061 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3062 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3064 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3066 if($item['location']) {
3067 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3068 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3072 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3074 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3075 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3078 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3079 if($item['bookmark'])
3080 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3083 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3086 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3088 if($item['signed_text']) {
3089 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3090 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3093 $verb = construct_verb($item);
3094 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3095 $actobj = construct_activity_object($item);
3098 $actarg = construct_activity_target($item);
3102 $tags = item_getfeedtags($item);
3104 foreach($tags as $t) {
3105 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3109 $o .= item_getfeedattach($item);
3111 $mentioned = get_mentions($item);
3115 call_hooks('atom_entry', $o);
3117 $o .= '</entry>' . "\r\n";
3122 function fix_private_photos($s,$uid, $item = null, $cid = 0) {
3125 logger('fix_private_photos', LOGGER_DEBUG);
3126 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3128 if(preg_match("/\[img(.*?)\](.*?)\[\/img\]/is",$s,$matches)) {
3129 $image = $matches[2];
3130 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3131 if(stristr($image , $site . '/photo/')) {
3133 $i = basename($image);
3134 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3135 $x = strpos($i,'-');
3137 $res = substr($i,$x+1);
3138 $i = substr($i,0,$x);
3139 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3146 // Check to see if we should replace this photo link with an embedded image
3147 // 1. No need to do so if the photo is public
3148 // 2. If there's a contact-id provided, see if they're in the access list
3149 // for the photo. If so, embed it.
3150 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3151 // permissions, regardless of order but first check to see if they're an exact
3152 // match to save some processing overhead.
3154 // Currently we only embed one private photo per message so as not to hit import
3155 // size limits at the receiving end.
3157 // To embed multiples, we would need to parse out the embedded photos on message
3158 // receipt and limit size based only on the text component. Would also need to
3159 // ignore all photos during bbcode translation and item localisation, as these
3160 // will hit internal regex backtrace limits.
3162 if(has_permissions($r[0])) {
3164 $recips = enumerate_permissions($r[0]);
3165 if(in_array($cid, $recips)) {
3170 if(compare_permissions($item,$r[0]))
3175 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3176 $s = str_replace($image, 'data:' . $r[0]['type'] . ';base64,' . base64_encode($r[0]['data']), $s);
3177 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
3187 function has_permissions($obj) {
3188 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3193 function compare_permissions($obj1,$obj2) {
3194 // first part is easy. Check that these are exactly the same.
3195 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3196 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3197 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3198 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3201 // This is harder. Parse all the permissions and compare the resulting set.
3203 $recipients1 = enumerate_permissions($obj1);
3204 $recipients2 = enumerate_permissions($obj2);
3207 if($recipients1 == $recipients2)
3212 // returns an array of contact-ids that are allowed to see this object
3214 function enumerate_permissions($obj) {
3215 require_once('include/group.php');
3216 $allow_people = expand_acl($obj['allow_cid']);
3217 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3218 $deny_people = expand_acl($obj['deny_cid']);
3219 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3220 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3221 $deny = array_unique(array_merge($deny_people,$deny_groups));
3222 $recipients = array_diff($recipients,$deny);
3226 function item_getfeedtags($item) {
3229 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3231 for($x = 0; $x < $cnt; $x ++) {
3233 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3237 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3239 for($x = 0; $x < $cnt; $x ++) {
3241 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3247 function item_getfeedattach($item) {
3249 $arr = explode(',',$item['attach']);
3251 foreach($arr as $r) {
3253 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3255 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3256 if(intval($matches[2]))
3257 $ret .= 'length="' . intval($matches[2]) . '" ';
3258 if($matches[4] !== ' ')
3259 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3260 $ret .= ' />' . "\r\n";
3269 function item_expire($uid,$days) {
3271 if((! $uid) || ($days < 1))
3274 // $expire_network_only = save your own wall posts
3275 // and just expire conversations started by others
3277 $expire_network_only = get_pconfig($uid,'expire','network_only');
3278 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3280 $r = q("SELECT * FROM `item`
3282 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3293 $expire_items = get_pconfig($uid, 'expire','items');
3294 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3296 $expire_notes = get_pconfig($uid, 'expire','notes');
3297 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3299 $expire_starred = get_pconfig($uid, 'expire','starred');
3300 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3302 $expire_photos = get_pconfig($uid, 'expire','photos');
3303 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3305 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3307 foreach($r as $item) {
3309 // don't expire filed items
3311 if(strpos($item['file'],'[') !== false)
3314 // Only expire posts, not photos and photo comments
3316 if($expire_photos==0 && strlen($item['resource-id']))
3318 if($expire_starred==0 && intval($item['starred']))
3320 if($expire_notes==0 && $item['type']=='note')
3322 if($expire_items==0 && $item['type']!='note')
3325 drop_item($item['id'],false);
3328 proc_run('php',"include/notifier.php","expire","$uid");
3333 function drop_items($items) {
3336 if(! local_user() && ! remote_user())
3340 foreach($items as $item) {
3341 $owner = drop_item($item,false);
3342 if($owner && ! $uid)
3347 // multiple threads may have been deleted, send an expire notification
3350 proc_run('php',"include/notifier.php","expire","$uid");
3354 function drop_item($id,$interactive = true) {
3358 // locate item to be deleted
3360 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3367 notice( t('Item not found.') . EOL);
3368 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3373 $owner = $item['uid'];
3375 // check if logged in user is either the author or owner of this item
3377 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3381 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3382 dbesc(datetime_convert()),
3383 dbesc(datetime_convert()),
3387 // clean up categories and tags so they don't end up as orphans
3390 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3392 foreach($matches as $mtch) {
3393 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3399 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3401 foreach($matches as $mtch) {
3402 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3406 // If item is a link to a photo resource, nuke all the associated photos
3407 // (visitors will not have photo resources)
3408 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3409 // generate a resource-id and therefore aren't intimately linked to the item.
3411 if(strlen($item['resource-id'])) {
3412 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3413 dbesc($item['resource-id']),
3414 intval($item['uid'])
3416 // ignore the result
3419 // If item is a link to an event, nuke the event record.
3421 if(intval($item['event-id'])) {
3422 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3423 intval($item['event-id']),
3424 intval($item['uid'])
3426 // ignore the result
3429 // clean up item_id and sign meta-data tables
3431 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3432 intval($item['id']),
3433 intval($item['uid'])
3436 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3437 intval($item['id']),
3438 intval($item['uid'])
3441 // If it's the parent of a comment thread, kill all the kids
3443 if($item['uri'] == $item['parent-uri']) {
3444 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3445 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3446 dbesc(datetime_convert()),
3447 dbesc(datetime_convert()),
3448 dbesc($item['parent-uri']),
3449 intval($item['uid'])
3451 // ignore the result
3454 // ensure that last-child is set in case the comment that had it just got wiped.
3455 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3456 dbesc(datetime_convert()),
3457 dbesc($item['parent-uri']),
3458 intval($item['uid'])
3460 // who is the last child now?
3461 $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",
3462 dbesc($item['parent-uri']),
3463 intval($item['uid'])
3466 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3471 // Add a relayable_retraction signature for Diaspora.
3472 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
3474 $drop_id = intval($item['id']);
3476 // send the notification upstream/downstream as the case may be
3481 proc_run('php',"include/notifier.php","drop","$drop_id");
3482 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3488 notice( t('Permission denied.') . EOL);
3489 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3496 function first_post_date($uid,$wall = false) {
3497 $r = q("select id, created from item
3498 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3500 order by created asc limit 1",
3502 intval($wall ? 1 : 0)
3505 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3506 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3511 function posted_dates($uid,$wall) {
3512 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3514 $dthen = first_post_date($uid,$wall);
3518 // If it's near the end of a long month, backup to the 28th so that in
3519 // consecutive loops we'll always get a whole month difference.
3521 if(intval(substr($dnow,8)) > 28)
3522 $dnow = substr($dnow,0,8) . '28';
3523 if(intval(substr($dthen,8)) > 28)
3524 $dnow = substr($dthen,0,8) . '28';
3527 while($dnow >= $dthen) {
3528 $dstart = substr($dnow,0,8) . '01';
3529 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3530 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3531 $end_month = datetime_convert('','',$dend,'Y-m-d');
3532 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3533 $ret[] = array($str,$end_month,$start_month);
3534 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3540 function posted_date_widget($url,$uid,$wall) {
3543 // For former Facebook folks that left because of "timeline"
3545 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3548 $ret = posted_dates($uid,$wall);
3552 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3553 '$title' => t('Archives'),
3554 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3561 function store_diaspora_retract_sig($item, $user, $baseurl) {
3562 // Note that we can't add a target_author_signature
3563 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3564 // the comment, that means we're the home of the post, and Diaspora will only
3565 // check the parent_author_signature of retractions that it doesn't have to relay further
3567 // I don't think this function gets called for an "unlike," but I'll check anyway
3569 $enabled = intval(get_config('system','diaspora_enabled'));
3571 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
3575 logger('drop_item: storing diaspora retraction signature');
3577 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3579 if(local_user() == $item['uid']) {
3581 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
3582 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
3585 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3589 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3590 // only handles DFRN deletes
3591 $handle_baseurl_start = strpos($r['url'],'://') + 3;
3592 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3593 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3599 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3600 intval($item['id']),
3601 dbesc($signed_text),