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";
286 function get_atom_elements($feed,$item) {
288 require_once('library/HTMLPurifier.auto.php');
289 require_once('include/html2bbcode.php');
291 $best_photo = array();
295 $author = $item->get_author();
297 $res['author-name'] = unxmlify($author->get_name());
298 $res['author-link'] = unxmlify($author->get_link());
301 $res['author-name'] = unxmlify($feed->get_title());
302 $res['author-link'] = unxmlify($feed->get_permalink());
304 $res['uri'] = unxmlify($item->get_id());
305 $res['title'] = unxmlify($item->get_title());
306 $res['body'] = unxmlify($item->get_content());
307 $res['plink'] = unxmlify($item->get_link(0));
309 //$debugfile = tempnam("/home/ike/log", "item-res-");
310 //file_put_contents($debugfile, serialize($res));
313 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
317 // look for a photo. We should check media size and find the best one,
318 // but for now let's just find any author photo
320 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
322 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
323 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
324 foreach($base as $link) {
325 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
326 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
327 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
332 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
334 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
335 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
336 if($base && count($base)) {
337 foreach($base as $link) {
338 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
339 $res['author-link'] = unxmlify($link['attribs']['']['href']);
340 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
341 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
342 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
348 // No photo/profile-link on the item - look at the feed level
350 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
351 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
352 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
353 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
354 foreach($base as $link) {
355 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
356 $res['author-link'] = unxmlify($link['attribs']['']['href']);
357 if(! $res['author-avatar']) {
358 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
359 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
364 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
366 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
367 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
369 if($base && count($base)) {
370 foreach($base as $link) {
371 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
372 $res['author-link'] = unxmlify($link['attribs']['']['href']);
373 if(! (x($res,'author-avatar'))) {
374 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
375 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
382 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
383 if($apps && $apps[0]['attribs']['']['source']) {
384 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
385 if($res['app'] === 'web')
386 $res['app'] = 'OStatus';
389 // base64 encoded json structure representing Diaspora signature
391 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
393 $res['dsprsig'] = unxmlify($dsig[0]['data']);
396 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
398 $res['guid'] = unxmlify($dguid[0]['data']);
400 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
402 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
406 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
409 $have_real_body = false;
411 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
413 $have_real_body = true;
414 $res['body'] = $rawenv[0]['data'];
415 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
416 // make sure nobody is trying to sneak some html tags by us
417 $res['body'] = notags(base64url_decode($res['body']));
420 $maxlen = get_max_import_size();
421 if($maxlen && (strlen($res['body']) > $maxlen))
422 $res['body'] = substr($res['body'],0, $maxlen);
424 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
425 // the content type. Our own network only emits text normally, though it might have been converted to
426 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
427 // have to assume it is all html and needs to be purified.
429 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
430 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
431 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
434 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
436 $res['body'] = reltoabs($res['body'],$base_url);
438 $res['body'] = html2bb_video($res['body']);
440 $res['body'] = oembed_html2bbcode($res['body']);
442 $config = HTMLPurifier_Config::createDefault();
443 $config->set('Cache.DefinitionImpl', null);
445 // we shouldn't need a whitelist, because the bbcode converter
446 // will strip out any unsupported tags.
448 $purifier = new HTMLPurifier($config);
449 $res['body'] = $purifier->purify($res['body']);
451 $res['body'] = @html2bbcode($res['body']);
455 elseif(! $have_real_body) {
457 // it's not one of our messages and it has no tags
458 // so it's probably just text. We'll escape it just to be safe.
460 $res['body'] = escape_tags($res['body']);
463 // this tag is obsolete but we keep it for really old sites
465 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
466 if($allow && $allow[0]['data'] == 1)
467 $res['last-child'] = 1;
469 $res['last-child'] = 0;
471 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
472 if($private && intval($private[0]['data']) > 0)
473 $res['private'] = intval($private[0]['data']);
477 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
478 if($extid && $extid[0]['data'])
479 $res['extid'] = $extid[0]['data'];
481 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
483 $res['location'] = unxmlify($rawlocation[0]['data']);
486 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
488 $res['created'] = unxmlify($rawcreated[0]['data']);
491 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
493 $res['edited'] = unxmlify($rawedited[0]['data']);
495 if((x($res,'edited')) && (! (x($res,'created'))))
496 $res['created'] = $res['edited'];
498 if(! $res['created'])
499 $res['created'] = $item->get_date('c');
502 $res['edited'] = $item->get_date('c');
505 // Disallow time travelling posts
507 $d1 = strtotime($res['created']);
508 $d2 = strtotime($res['edited']);
509 $d3 = strtotime('now');
512 $res['created'] = datetime_convert();
514 $res['edited'] = datetime_convert();
516 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
517 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
518 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
519 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
520 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
521 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
522 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
523 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
524 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
526 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
527 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
529 foreach($base as $link) {
530 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
531 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
532 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
537 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
539 $res['coord'] = unxmlify($rawgeo[0]['data']);
542 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
544 // select between supported verbs
547 $res['verb'] = unxmlify($rawverb[0]['data']);
550 // translate OStatus unfollow to activity streams if it happened to get selected
552 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
553 $res['verb'] = ACTIVITY_UNFOLLOW;
555 $cats = $item->get_categories();
558 foreach($cats as $cat) {
559 $term = $cat->get_term();
561 $term = $cat->get_label();
562 $scheme = $cat->get_scheme();
563 if($scheme && $term && stristr($scheme,'X-DFRN:'))
564 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
566 $tag_arr[] = notags(trim($term));
568 $res['tag'] = implode(',', $tag_arr);
571 $attach = $item->get_enclosures();
574 foreach($attach as $att) {
575 $len = intval($att->get_length());
576 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
577 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
578 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
579 if(strpos($type,';'))
580 $type = substr($type,0,strpos($type,';'));
581 if((! $link) || (strpos($link,'http') !== 0))
587 $type = 'application/octet-stream';
589 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
591 $res['attach'] = implode(',', $att_arr);
594 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
597 $res['object'] = '<object>' . "\n";
598 $child = $rawobj[0]['child'];
599 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
600 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
601 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
603 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
604 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
605 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
606 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
607 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
608 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
609 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
610 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
612 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
613 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
614 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
615 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
617 $body = html2bb_video($body);
619 $config = HTMLPurifier_Config::createDefault();
620 $config->set('Cache.DefinitionImpl', null);
622 $purifier = new HTMLPurifier($config);
623 $body = $purifier->purify($body);
624 $body = html2bbcode($body);
627 $res['object'] .= '<content>' . $body . '</content>' . "\n";
630 $res['object'] .= '</object>' . "\n";
633 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
636 $res['target'] = '<target>' . "\n";
637 $child = $rawobj[0]['child'];
638 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
639 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
641 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
642 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
643 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
644 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
645 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
646 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
647 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
648 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
650 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
651 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
652 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
653 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
655 $body = html2bb_video($body);
657 $config = HTMLPurifier_Config::createDefault();
658 $config->set('Cache.DefinitionImpl', null);
660 $purifier = new HTMLPurifier($config);
661 $body = $purifier->purify($body);
662 $body = html2bbcode($body);
665 $res['target'] .= '<content>' . $body . '</content>' . "\n";
668 $res['target'] .= '</target>' . "\n";
671 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
673 call_hooks('parse_atom', $arr);
678 function encode_rel_links($links) {
680 if(! ((is_array($links)) && (count($links))))
682 foreach($links as $link) {
684 if($link['attribs']['']['rel'])
685 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
686 if($link['attribs']['']['type'])
687 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
688 if($link['attribs']['']['href'])
689 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
690 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
691 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
692 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
693 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
701 function item_store($arr,$force_parent = false) {
703 // If a Diaspora signature structure was passed in, pull it out of the
704 // item array and set it aside for later storage.
707 if(x($arr,'dsprsig')) {
708 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
709 unset($arr['dsprsig']);
712 if(x($arr, 'gravity'))
713 $arr['gravity'] = intval($arr['gravity']);
714 elseif($arr['parent-uri'] === $arr['uri'])
716 elseif(activity_match($arr['verb'],ACTIVITY_POST))
719 $arr['gravity'] = 6; // extensible catchall
722 $arr['type'] = 'remote';
724 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
726 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
727 $arr['body'] = strip_tags($arr['body']);
730 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
731 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
732 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
733 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
734 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
735 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
736 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
737 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
738 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
739 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
740 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
741 $arr['commented'] = datetime_convert();
742 $arr['received'] = datetime_convert();
743 $arr['changed'] = datetime_convert();
744 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
745 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
746 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
747 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
748 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
750 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
751 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
752 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
753 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
754 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
755 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
756 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
757 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
758 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
759 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
760 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
761 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
762 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
763 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
764 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
765 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
766 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
767 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
768 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
770 if($arr['parent-uri'] === $arr['uri']) {
773 $allow_cid = $arr['allow_cid'];
774 $allow_gid = $arr['allow_gid'];
775 $deny_cid = $arr['deny_cid'];
776 $deny_gid = $arr['deny_gid'];
780 // find the parent and snarf the item id and ACL's
781 // and anything else we need to inherit
783 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
784 dbesc($arr['parent-uri']),
790 // is the new message multi-level threaded?
791 // even though we don't support it now, preserve the info
792 // and re-attach to the conversation parent.
794 if($r[0]['uri'] != $r[0]['parent-uri']) {
795 $arr['thr-parent'] = $arr['parent-uri'];
796 $arr['parent-uri'] = $r[0]['parent-uri'];
797 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
798 ORDER BY `id` ASC LIMIT 1",
799 dbesc($r[0]['parent-uri']),
800 dbesc($r[0]['parent-uri']),
807 $parent_id = $r[0]['id'];
808 $parent_deleted = $r[0]['deleted'];
809 $allow_cid = $r[0]['allow_cid'];
810 $allow_gid = $r[0]['allow_gid'];
811 $deny_cid = $r[0]['deny_cid'];
812 $deny_gid = $r[0]['deny_gid'];
813 $arr['wall'] = $r[0]['wall'];
815 // if the parent is private, force privacy for the entire conversation
816 // This differs from the above settings as it subtly allows comments from
817 // email correspondents to be private even if the overall thread is not.
820 $arr['private'] = $r[0]['private'];
822 // Edge case. We host a public forum that was originally posted to privately.
823 // The original author commented, but as this is a comment, the permissions
824 // weren't fixed up so it will still show the comment as private unless we fix it here.
826 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
831 // Allow one to see reply tweets from status.net even when
832 // we don't have or can't see the original post.
835 logger('item_store: $force_parent=true, reply converted to top-level post.');
837 $arr['thr-parent'] = $arr['parent-uri'];
838 $arr['parent-uri'] = $arr['uri'];
842 logger('item_store: item parent was not found - ignoring item');
850 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
854 if($r && count($r)) {
855 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
859 call_hooks('post_remote',$arr);
861 if(x($arr,'cancel')) {
862 logger('item_store: post cancelled by plugin.');
868 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
870 $r = dbq("INSERT INTO `item` (`"
871 . implode("`, `", array_keys($arr))
873 . implode("', '", array_values($arr))
876 // find the item we just created
878 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
879 $arr['uri'], // already dbesc'd
884 $current_post = $r[0]['id'];
885 logger('item_store: created item ' . $current_post);
888 logger('item_store: could not locate created item');
892 logger('item_store: duplicated post occurred. Removing duplicates.');
893 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
896 intval($current_post)
900 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
901 $parent_id = $current_post;
903 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
906 $private = $arr['private'];
908 // Set parent id - and also make sure to inherit the parent's ACL's.
910 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
911 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
918 intval($parent_deleted),
919 intval($current_post)
922 $arr['id'] = $current_post;
923 $arr['parent'] = $parent_id;
924 $arr['allow_cid'] = $allow_cid;
925 $arr['allow_gid'] = $allow_gid;
926 $arr['deny_cid'] = $deny_cid;
927 $arr['deny_gid'] = $deny_gid;
928 $arr['private'] = $private;
929 $arr['deleted'] = $parent_deleted;
930 call_hooks('post_remote_end',$arr);
932 // update the commented timestamp on the parent
934 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
935 dbesc(datetime_convert()),
936 dbesc(datetime_convert()),
941 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
942 intval($current_post),
943 dbesc($dsprsig->signed_text),
944 dbesc($dsprsig->signature),
945 dbesc($dsprsig->signer)
951 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
954 if($arr['last-child']) {
955 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
958 intval($current_post)
962 tag_deliver($arr['uid'],$current_post);
964 return $current_post;
967 function get_item_contact($item,$contacts) {
968 if(! count($contacts) || (! is_array($item)))
970 foreach($contacts as $contact) {
971 if($contact['id'] == $item['contact-id']) {
980 function tag_deliver($uid,$item_id) {
982 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
988 $u = q("select * from user where uid = %d limit 1",
994 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
995 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
998 $i = q("select * from item where id = %d and uid = %d limit 1",
1007 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1009 // Diaspora uses their own hardwired link URL in @-tags
1010 // instead of the one we supply with webfinger
1012 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1014 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1016 foreach($matches as $mtch) {
1017 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1019 logger('tag_deliver: mention found: ' . $mtch[2]);
1027 // send a notification
1029 require_once('include/enotify.php');
1031 'type' => NOTIFY_TAGSELF,
1032 'notify_flags' => $u[0]['notify-flags'],
1033 'language' => $u[0]['language'],
1034 'to_name' => $u[0]['username'],
1035 'to_email' => $u[0]['email'],
1036 'uid' => $u[0]['uid'],
1038 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1039 'source_name' => $item['author-name'],
1040 'source_link' => $item['author-link'],
1041 'source_photo' => $item['author-avatar'],
1042 'verb' => ACTIVITY_TAG,
1046 if((! $community_page) && (! $prvgroup))
1050 // tgroup delivery - setup a second delivery chain
1051 // prevent delivery looping - only proceed
1052 // if the message originated elsewhere and is a top-level post
1054 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1057 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1060 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1061 intval($u[0]['uid'])
1066 // also reset all the privacy bits to the forum default permissions
1068 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1070 $forum_mode = (($prvgroup) ? 2 : 1);
1072 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1073 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1074 intval($forum_mode),
1075 dbesc($c[0]['name']),
1076 dbesc($c[0]['url']),
1077 dbesc($c[0]['thumb']),
1079 dbesc($u[0]['allow_cid']),
1080 dbesc($u[0]['allow_gid']),
1081 dbesc($u[0]['deny_cid']),
1082 dbesc($u[0]['deny_gid']),
1086 proc_run('php','include/notifier.php','tgroup',$item_id);
1095 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1099 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1101 if($contact['duplex'] && $contact['dfrn-id'])
1102 $idtosend = '0:' . $orig_id;
1103 if($contact['duplex'] && $contact['issued-id'])
1104 $idtosend = '1:' . $orig_id;
1106 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1108 $rino_enable = get_config('system','rino_encrypt');
1113 $ssl_val = intval(get_config('system','ssl_policy'));
1117 case SSL_POLICY_FULL:
1118 $ssl_policy = 'full';
1120 case SSL_POLICY_SELFSIGN:
1121 $ssl_policy = 'self';
1123 case SSL_POLICY_NONE:
1125 $ssl_policy = 'none';
1129 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1131 logger('dfrn_deliver: ' . $url);
1133 $xml = fetch_url($url);
1135 $curl_stat = $a->get_curl_code();
1137 return(-1); // timed out
1139 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1144 if(strpos($xml,'<?xml') === false) {
1145 logger('dfrn_deliver: no valid XML returned');
1146 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1150 $res = parse_xml_string($xml);
1152 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1153 return (($res->status) ? $res->status : 3);
1155 $postvars = array();
1156 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1157 $challenge = hex2bin((string) $res->challenge);
1158 $perm = (($res->perm) ? $res->perm : null);
1159 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1160 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1161 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1163 if($owner['page-flags'] == PAGE_PRVGROUP)
1166 $final_dfrn_id = '';
1169 if((($perm == 'rw') && (! intval($contact['writable'])))
1170 || (($perm == 'r') && (intval($contact['writable'])))) {
1171 q("update contact set writable = %d where id = %d limit 1",
1172 intval(($perm == 'rw') ? 1 : 0),
1173 intval($contact['id'])
1175 $contact['writable'] = (string) 1 - intval($contact['writable']);
1179 if(($contact['duplex'] && strlen($contact['pubkey']))
1180 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1181 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1182 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1183 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1186 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1187 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1190 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1192 if(strpos($final_dfrn_id,':') == 1)
1193 $final_dfrn_id = substr($final_dfrn_id,2);
1195 if($final_dfrn_id != $orig_id) {
1196 logger('dfrn_deliver: wrong dfrn_id.');
1197 // did not decode properly - cannot trust this site
1201 $postvars['dfrn_id'] = $idtosend;
1202 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1204 $postvars['dissolve'] = '1';
1207 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1208 $postvars['data'] = $atom;
1209 $postvars['perm'] = 'rw';
1212 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1213 $postvars['perm'] = 'r';
1216 $postvars['ssl_policy'] = $ssl_policy;
1219 $postvars['page'] = $page;
1221 if($rino && $rino_allowed && (! $dissolve)) {
1222 $key = substr(random_string(),0,16);
1223 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1224 $postvars['data'] = $data;
1225 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1228 if($dfrn_version >= 2.1) {
1229 if(($contact['duplex'] && strlen($contact['pubkey']))
1230 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1231 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1233 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1236 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1240 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1241 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1244 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1248 logger('md5 rawkey ' . md5($postvars['key']));
1250 $postvars['key'] = bin2hex($postvars['key']);
1253 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1255 $xml = post_url($contact['notify'],$postvars);
1257 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1259 $curl_stat = $a->get_curl_code();
1260 if((! $curl_stat) || (! strlen($xml)))
1261 return(-1); // timed out
1263 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1266 if(strpos($xml,'<?xml') === false) {
1267 logger('dfrn_deliver: phase 2: no valid XML returned');
1268 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1272 if($contact['term-date'] != '0000-00-00 00:00:00') {
1273 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1274 require_once('include/Contact.php');
1275 unmark_for_death($contact);
1278 $res = parse_xml_string($xml);
1280 return $res->status;
1286 * consume_feed - process atom feed and update anything/everything we might need to update
1288 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1290 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1291 * It is this person's stuff that is going to be updated.
1292 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1293 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1294 * have a contact record.
1295 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1296 * might not) try and subscribe to it.
1297 * $datedir sorts in reverse order
1298 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1299 * imported prior to its children being seen in the stream unless we are certain
1300 * of how the feed is arranged/ordered.
1301 * With $pass = 1, we only pull parent items out of the stream.
1302 * With $pass = 2, we only pull children (comments/likes).
1304 * So running this twice, first with pass 1 and then with pass 2 will do the right
1305 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1306 * model where comments can have sub-threads. That would require some massive sorting
1307 * to get all the feed items into a mostly linear ordering, and might still require
1311 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1313 require_once('library/simplepie/simplepie.inc');
1315 if(! strlen($xml)) {
1316 logger('consume_feed: empty input');
1320 $feed = new SimplePie();
1321 $feed->set_raw_data($xml);
1323 $feed->enable_order_by_date(true);
1325 $feed->enable_order_by_date(false);
1329 logger('consume_feed: Error parsing XML: ' . $feed->error());
1331 $permalink = $feed->get_permalink();
1333 // Check at the feed level for updated contact name and/or photo
1337 $photo_timestamp = '';
1341 $hubs = $feed->get_links('hub');
1342 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1345 $hub = implode(',', $hubs);
1347 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1349 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1351 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1352 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1353 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1354 $new_name = $elems['name'][0]['data'];
1356 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1357 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1358 $photo_url = $elems['link'][0]['attribs']['']['href'];
1361 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1362 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1366 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1367 logger('consume_feed: Updating photo for ' . $contact['name']);
1368 require_once("Photo.php");
1369 $photo_failure = false;
1370 $have_photo = false;
1372 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1373 intval($contact['id']),
1374 intval($contact['uid'])
1377 $resource_id = $r[0]['resource-id'];
1381 $resource_id = photo_new_resource();
1384 $img_str = fetch_url($photo_url,true);
1385 // guess mimetype from headers or filename
1386 $type = guess_image_type($photo_url,true);
1389 $img = new Photo($img_str, $type);
1390 if($img->is_valid()) {
1392 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1393 dbesc($resource_id),
1394 intval($contact['id']),
1395 intval($contact['uid'])
1399 $img->scaleImageSquare(175);
1401 $hash = $resource_id;
1402 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1404 $img->scaleImage(80);
1405 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1407 $img->scaleImage(48);
1408 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1412 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1413 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1414 dbesc(datetime_convert()),
1415 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1416 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1417 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1418 intval($contact['uid']),
1419 intval($contact['id'])
1424 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1425 $r = q("select * from contact where uid = %d and id = %d limit 1",
1426 intval($contact['uid']),
1427 intval($contact['id'])
1430 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1431 dbesc(notags(trim($new_name))),
1432 dbesc(datetime_convert()),
1433 intval($contact['uid']),
1434 intval($contact['id'])
1437 // do our best to update the name on content items
1440 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1441 dbesc(notags(trim($new_name))),
1442 dbesc($r[0]['name']),
1443 dbesc($r[0]['url']),
1444 intval($contact['uid'])
1449 if(strlen($birthday)) {
1450 if(substr($birthday,0,4) != $contact['bdyear']) {
1451 logger('consume_feed: updating birthday: ' . $birthday);
1455 * Add new birthday event for this person
1457 * $bdtext is just a readable placeholder in case the event is shared
1458 * with others. We will replace it during presentation to our $importer
1459 * to contain a sparkle link and perhaps a photo.
1463 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1464 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1467 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1468 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1469 intval($contact['uid']),
1470 intval($contact['id']),
1471 dbesc(datetime_convert()),
1472 dbesc(datetime_convert()),
1473 dbesc(datetime_convert('UTC','UTC', $birthday)),
1474 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1483 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1484 dbesc(substr($birthday,0,4)),
1485 intval($contact['uid']),
1486 intval($contact['id'])
1489 // This function is called twice without reloading the contact
1490 // Make sure we only create one event. This is why &$contact
1491 // is a reference var in this function
1493 $contact['bdyear'] = substr($birthday,0,4);
1498 $community_page = 0;
1499 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1501 $community_page = intval($rawtags[0]['data']);
1503 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1504 q("update contact set forum = %d where id = %d limit 1",
1505 intval($community_page),
1506 intval($contact['id'])
1508 $contact['forum'] = (string) $community_page;
1512 // process any deleted entries
1514 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1515 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1516 foreach($del_entries as $dentry) {
1518 if(isset($dentry['attribs']['']['ref'])) {
1519 $uri = $dentry['attribs']['']['ref'];
1521 if(isset($dentry['attribs']['']['when'])) {
1522 $when = $dentry['attribs']['']['when'];
1523 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1526 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1528 if($deleted && is_array($contact)) {
1529 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1530 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1532 intval($importer['uid']),
1533 intval($contact['id'])
1538 if(! $item['deleted'])
1539 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1541 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1542 $xo = parse_xml_string($item['object'],false);
1543 $xt = parse_xml_string($item['target'],false);
1544 if($xt->type === ACTIVITY_OBJ_NOTE) {
1545 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1547 intval($importer['importer_uid'])
1551 // For tags, the owner cannot remove the tag on the author's copy of the post.
1553 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1554 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1555 $author_copy = (($item['origin']) ? true : false);
1557 if($owner_remove && $author_copy)
1559 if($author_remove || $owner_remove) {
1560 $tags = explode(',',$i[0]['tag']);
1563 foreach($tags as $tag)
1564 if(trim($tag) !== trim($xo->body))
1565 $newtags[] = trim($tag);
1567 q("update item set tag = '%s' where id = %d limit 1",
1568 dbesc(implode(',',$newtags)),
1576 if($item['uri'] == $item['parent-uri']) {
1577 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1578 `body` = '', `title` = ''
1579 WHERE `parent-uri` = '%s' AND `uid` = %d",
1581 dbesc(datetime_convert()),
1582 dbesc($item['uri']),
1583 intval($importer['uid'])
1587 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1588 `body` = '', `title` = ''
1589 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1591 dbesc(datetime_convert()),
1593 intval($importer['uid'])
1595 if($item['last-child']) {
1596 // ensure that last-child is set in case the comment that had it just got wiped.
1597 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1598 dbesc(datetime_convert()),
1599 dbesc($item['parent-uri']),
1600 intval($item['uid'])
1602 // who is the last child now?
1603 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1604 ORDER BY `created` DESC LIMIT 1",
1605 dbesc($item['parent-uri']),
1606 intval($importer['uid'])
1609 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1620 // Now process the feed
1622 if($feed->get_item_quantity()) {
1624 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1626 // in inverse date order
1628 $items = array_reverse($feed->get_items());
1630 $items = $feed->get_items();
1633 foreach($items as $item) {
1636 $item_id = $item->get_id();
1637 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1638 if(isset($rawthread[0]['attribs']['']['ref'])) {
1640 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1643 if(($is_reply) && is_array($contact)) {
1648 // Have we seen it? If not, import it.
1650 $item_id = $item->get_id();
1651 $datarray = get_atom_elements($feed,$item);
1653 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1654 $datarray['author-name'] = $contact['name'];
1655 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1656 $datarray['author-link'] = $contact['url'];
1657 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1658 $datarray['author-avatar'] = $contact['thumb'];
1660 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1661 logger('consume_feed: no author information! ' . print_r($datarray,true));
1665 $force_parent = false;
1666 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1667 if($contact['network'] === NETWORK_OSTATUS)
1668 $force_parent = true;
1669 if(strlen($datarray['title']))
1670 unset($datarray['title']);
1671 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1672 dbesc(datetime_convert()),
1674 intval($importer['uid'])
1676 $datarray['last-child'] = 1;
1680 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1682 intval($importer['uid'])
1685 // Update content if 'updated' changes
1688 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1690 // do not accept (ignore) an earlier edit than one we currently have.
1691 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1694 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1695 dbesc($datarray['title']),
1696 dbesc($datarray['body']),
1697 dbesc($datarray['tag']),
1698 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1700 intval($importer['uid'])
1704 // update last-child if it changes
1706 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1707 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1708 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1709 dbesc(datetime_convert()),
1711 intval($importer['uid'])
1713 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1714 intval($allow[0]['data']),
1715 dbesc(datetime_convert()),
1717 intval($importer['uid'])
1724 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1725 // one way feed - no remote comment ability
1726 $datarray['last-child'] = 0;
1728 $datarray['parent-uri'] = $parent_uri;
1729 $datarray['uid'] = $importer['uid'];
1730 $datarray['contact-id'] = $contact['id'];
1731 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1732 $datarray['type'] = 'activity';
1733 $datarray['gravity'] = GRAVITY_LIKE;
1734 // only one like or dislike per person
1735 $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",
1736 intval($datarray['uid']),
1737 intval($datarray['contact-id']),
1738 dbesc($datarray['verb']),
1746 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1747 $xo = parse_xml_string($datarray['object'],false);
1748 $xt = parse_xml_string($datarray['target'],false);
1750 if($xt->type == ACTIVITY_OBJ_NOTE) {
1751 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1753 intval($importer['importer_uid'])
1758 // extract tag, if not duplicate, add to parent item
1759 if($xo->id && $xo->content) {
1760 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1761 if(! (stristr($r[0]['tag'],$newtag))) {
1762 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1763 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1771 $r = item_store($datarray,$force_parent);
1777 // Head post of a conversation. Have we seen it? If not, import it.
1779 $item_id = $item->get_id();
1781 $datarray = get_atom_elements($feed,$item);
1783 if(is_array($contact)) {
1784 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1785 $datarray['author-name'] = $contact['name'];
1786 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1787 $datarray['author-link'] = $contact['url'];
1788 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1789 $datarray['author-avatar'] = $contact['thumb'];
1792 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1793 logger('consume_feed: no author information! ' . print_r($datarray,true));
1797 // special handling for events
1799 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1800 $ev = bbtoevent($datarray['body']);
1801 if(x($ev,'desc') && x($ev,'start')) {
1802 $ev['uid'] = $importer['uid'];
1803 $ev['uri'] = $item_id;
1804 $ev['edited'] = $datarray['edited'];
1805 $ev['private'] = $datarray['private'];
1807 if(is_array($contact))
1808 $ev['cid'] = $contact['id'];
1809 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1811 intval($importer['uid'])
1814 $ev['id'] = $r[0]['id'];
1815 $xyz = event_store($ev);
1820 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1821 if(strlen($datarray['title']))
1822 unset($datarray['title']);
1823 $datarray['last-child'] = 1;
1827 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1829 intval($importer['uid'])
1832 // Update content if 'updated' changes
1835 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1837 // do not accept (ignore) an earlier edit than one we currently have.
1838 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1841 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1842 dbesc($datarray['title']),
1843 dbesc($datarray['body']),
1844 dbesc($datarray['tag']),
1845 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1847 intval($importer['uid'])
1851 // update last-child if it changes
1853 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1854 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1855 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1856 intval($allow[0]['data']),
1857 dbesc(datetime_convert()),
1859 intval($importer['uid'])
1865 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1866 logger('consume-feed: New follower');
1867 new_follower($importer,$contact,$datarray,$item);
1870 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1871 lose_follower($importer,$contact,$datarray,$item);
1875 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1876 logger('consume-feed: New friend request');
1877 new_follower($importer,$contact,$datarray,$item,true);
1880 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1881 lose_sharer($importer,$contact,$datarray,$item);
1886 if(! is_array($contact))
1890 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1891 // one way feed - no remote comment ability
1892 $datarray['last-child'] = 0;
1894 if($contact['network'] === NETWORK_FEED)
1895 $datarray['private'] = 2;
1897 // This is my contact on another system, but it's really me.
1898 // Turn this into a wall post.
1900 if($contact['remote_self']) {
1901 $datarray['wall'] = 1;
1902 if($contact['network'] === NETWORK_FEED) {
1903 $datarray['private'] = 0;
1907 $datarray['parent-uri'] = $item_id;
1908 $datarray['uid'] = $importer['uid'];
1909 $datarray['contact-id'] = $contact['id'];
1911 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1912 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1913 // but otherwise there's a possible data mixup on the sender's system.
1914 // the tgroup delivery code called from item_store will correct it if it's a forum,
1915 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1916 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1917 $datarray['owner-name'] = $contact['name'];
1918 $datarray['owner-link'] = $contact['url'];
1919 $datarray['owner-avatar'] = $contact['thumb'];
1922 $r = item_store($datarray);
1930 function local_delivery($importer,$data) {
1934 if($importer['readonly']) {
1935 // We aren't receiving stuff from this person. But we will quietly ignore them
1936 // rather than a blatant "go away" message.
1937 logger('local_delivery: ignoring');
1942 // Consume notification feed. This may differ from consuming a public feed in several ways
1943 // - might contain email or friend suggestions
1944 // - might contain remote followup to our message
1945 // - in which case we need to accept it and then notify other conversants
1946 // - we may need to send various email notifications
1948 $feed = new SimplePie();
1949 $feed->set_raw_data($data);
1950 $feed->enable_order_by_date(false);
1954 // Currently unsupported - needs a lot of work
1955 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1956 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1957 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1959 $newloc['uid'] = $importer['importer_uid'];
1960 $newloc['cid'] = $importer['id'];
1961 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1962 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1963 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1964 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1965 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1966 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1967 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1968 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1969 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1970 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1973 // merge with current record, current contents have priority
1974 // update record, set url-updated
1975 // update profile photos
1981 // handle friend suggestion notification
1983 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1984 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1985 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1987 $fsugg['uid'] = $importer['importer_uid'];
1988 $fsugg['cid'] = $importer['id'];
1989 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1990 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1991 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1992 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1993 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1995 // Does our member already have a friend matching this description?
1997 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1998 dbesc($fsugg['name']),
1999 dbesc(normalise_link($fsugg['url'])),
2000 intval($fsugg['uid'])
2005 // Do we already have an fcontact record for this person?
2008 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2009 dbesc($fsugg['url']),
2010 dbesc($fsugg['name']),
2011 dbesc($fsugg['request'])
2016 // OK, we do. Do we already have an introduction for this person ?
2017 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2018 intval($fsugg['uid']),
2025 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2026 dbesc($fsugg['name']),
2027 dbesc($fsugg['url']),
2028 dbesc($fsugg['photo']),
2029 dbesc($fsugg['request'])
2031 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2032 dbesc($fsugg['url']),
2033 dbesc($fsugg['name']),
2034 dbesc($fsugg['request'])
2039 // database record did not get created. Quietly give up.
2044 $hash = random_string();
2046 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2047 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2048 intval($fsugg['uid']),
2050 intval($fsugg['cid']),
2051 dbesc($fsugg['body']),
2053 dbesc(datetime_convert()),
2058 'type' => NOTIFY_SUGGEST,
2059 'notify_flags' => $importer['notify-flags'],
2060 'language' => $importer['language'],
2061 'to_name' => $importer['username'],
2062 'to_email' => $importer['email'],
2063 'uid' => $importer['importer_uid'],
2065 'link' => $a->get_baseurl() . '/notifications/intros',
2066 'source_name' => $importer['name'],
2067 'source_link' => $importer['url'],
2068 'source_photo' => $importer['photo'],
2069 'verb' => ACTIVITY_REQ_FRIEND,
2078 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2079 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2081 logger('local_delivery: private message received');
2084 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2087 $msg['uid'] = $importer['importer_uid'];
2088 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2089 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2090 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2091 $msg['contact-id'] = $importer['id'];
2092 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2093 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2095 $msg['replied'] = 0;
2096 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2097 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2098 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2102 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2103 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2105 // send notifications.
2107 require_once('include/enotify.php');
2109 $notif_params = array(
2110 'type' => NOTIFY_MAIL,
2111 'notify_flags' => $importer['notify-flags'],
2112 'language' => $importer['language'],
2113 'to_name' => $importer['username'],
2114 'to_email' => $importer['email'],
2115 'uid' => $importer['importer_uid'],
2117 'source_name' => $msg['from-name'],
2118 'source_link' => $importer['url'],
2119 'source_photo' => $importer['thumb'],
2120 'verb' => ACTIVITY_POST,
2124 notification($notif_params);
2130 $community_page = 0;
2131 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2133 $community_page = intval($rawtags[0]['data']);
2135 if(intval($importer['forum']) != $community_page) {
2136 q("update contact set forum = %d where id = %d limit 1",
2137 intval($community_page),
2138 intval($importer['id'])
2140 $importer['forum'] = (string) $community_page;
2143 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2145 // process any deleted entries
2147 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2148 if(is_array($del_entries) && count($del_entries)) {
2149 foreach($del_entries as $dentry) {
2151 if(isset($dentry['attribs']['']['ref'])) {
2152 $uri = $dentry['attribs']['']['ref'];
2154 if(isset($dentry['attribs']['']['when'])) {
2155 $when = $dentry['attribs']['']['when'];
2156 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2159 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2163 // check for relayed deletes to our conversation
2166 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2168 intval($importer['importer_uid'])
2171 $parent_uri = $r[0]['parent-uri'];
2172 if($r[0]['id'] != $r[0]['parent'])
2179 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2182 logger('local_delivery: possible community delete');
2185 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2187 // was the top-level post for this reply written by somebody on this site?
2188 // Specifically, the recipient?
2190 $is_a_remote_delete = false;
2192 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2193 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2194 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2195 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2196 AND `item`.`uid` = %d
2202 intval($importer['importer_uid'])
2205 $is_a_remote_delete = true;
2207 // Does this have the characteristics of a community or private group comment?
2208 // If it's a reply to a wall post on a community/prvgroup page it's a
2209 // valid community comment. Also forum_mode makes it valid for sure.
2210 // If neither, it's not.
2212 if($is_a_remote_delete && $community) {
2213 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2214 $is_a_remote_delete = false;
2215 logger('local_delivery: not a community delete');
2219 if($is_a_remote_delete) {
2220 logger('local_delivery: received remote delete');
2224 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2225 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2227 intval($importer['importer_uid']),
2228 intval($importer['id'])
2234 if($item['deleted'])
2237 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2239 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2240 $xo = parse_xml_string($item['object'],false);
2241 $xt = parse_xml_string($item['target'],false);
2243 if($xt->type === ACTIVITY_OBJ_NOTE) {
2244 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2246 intval($importer['importer_uid'])
2250 // For tags, the owner cannot remove the tag on the author's copy of the post.
2252 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2253 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2254 $author_copy = (($item['origin']) ? true : false);
2256 if($owner_remove && $author_copy)
2258 if($author_remove || $owner_remove) {
2259 $tags = explode(',',$i[0]['tag']);
2262 foreach($tags as $tag)
2263 if(trim($tag) !== trim($xo->body))
2264 $newtags[] = trim($tag);
2266 q("update item set tag = '%s' where id = %d limit 1",
2267 dbesc(implode(',',$newtags)),
2275 if($item['uri'] == $item['parent-uri']) {
2276 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2277 WHERE `parent-uri` = '%s' AND `uid` = %d",
2279 dbesc(datetime_convert()),
2280 dbesc($item['uri']),
2281 intval($importer['importer_uid'])
2285 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2286 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2288 dbesc(datetime_convert()),
2290 intval($importer['importer_uid'])
2292 if($item['last-child']) {
2293 // ensure that last-child is set in case the comment that had it just got wiped.
2294 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2295 dbesc(datetime_convert()),
2296 dbesc($item['parent-uri']),
2297 intval($item['uid'])
2299 // who is the last child now?
2300 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2301 ORDER BY `created` DESC LIMIT 1",
2302 dbesc($item['parent-uri']),
2303 intval($importer['importer_uid'])
2306 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2311 // if this is a relayed delete, propagate it to other recipients
2313 if($is_a_remote_delete)
2314 proc_run('php',"include/notifier.php","drop",$item['id']);
2322 foreach($feed->get_items() as $item) {
2325 $item_id = $item->get_id();
2326 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2327 if(isset($rawthread[0]['attribs']['']['ref'])) {
2329 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2335 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2338 logger('local_delivery: possible community reply');
2341 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2343 // was the top-level post for this reply written by somebody on this site?
2344 // Specifically, the recipient?
2346 $is_a_remote_comment = false;
2348 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2349 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2350 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2351 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2352 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2353 AND `item`.`uid` = %d
2359 intval($importer['importer_uid'])
2362 $is_a_remote_comment = true;
2364 // Does this have the characteristics of a community or private group comment?
2365 // If it's a reply to a wall post on a community/prvgroup page it's a
2366 // valid community comment. Also forum_mode makes it valid for sure.
2367 // If neither, it's not.
2369 if($is_a_remote_comment && $community) {
2370 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2371 $is_a_remote_comment = false;
2372 logger('local_delivery: not a community reply');
2376 if($is_a_remote_comment) {
2377 logger('local_delivery: received remote comment');
2379 // remote reply to our post. Import and then notify everybody else.
2381 $datarray = get_atom_elements($feed,$item);
2383 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2385 intval($importer['importer_uid'])
2388 // Update content if 'updated' changes
2392 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2394 // do not accept (ignore) an earlier edit than one we currently have.
2395 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2398 logger('received updated comment' , LOGGER_DEBUG);
2399 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2400 dbesc($datarray['title']),
2401 dbesc($datarray['body']),
2402 dbesc($datarray['tag']),
2403 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2405 intval($importer['importer_uid'])
2408 proc_run('php',"include/notifier.php","comment-import",$iid);
2416 // TODO: make this next part work against both delivery threads of a community post
2418 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2419 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2420 // they won't know what to do so don't report an error. Just quietly die.
2424 // our user with $importer['importer_uid'] is the owner
2426 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2427 intval($importer['importer_uid'])
2431 $datarray['type'] = 'remote-comment';
2432 $datarray['wall'] = 1;
2433 $datarray['parent-uri'] = $parent_uri;
2434 $datarray['uid'] = $importer['importer_uid'];
2435 $datarray['owner-name'] = $own[0]['name'];
2436 $datarray['owner-link'] = $own[0]['url'];
2437 $datarray['owner-avatar'] = $own[0]['thumb'];
2438 $datarray['contact-id'] = $importer['id'];
2440 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2442 $datarray['type'] = 'activity';
2443 $datarray['gravity'] = GRAVITY_LIKE;
2444 $datarray['last-child'] = 0;
2445 // only one like or dislike per person
2446 $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",
2447 intval($datarray['uid']),
2448 intval($datarray['contact-id']),
2449 dbesc($datarray['verb']),
2450 dbesc($datarray['parent-uri']),
2451 dbesc($datarray['parent-uri'])
2458 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2460 $xo = parse_xml_string($datarray['object'],false);
2461 $xt = parse_xml_string($datarray['target'],false);
2463 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2465 // fetch the parent item
2467 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2469 intval($importer['importer_uid'])
2474 // extract tag, if not duplicate, and this user allows tags, add to parent item
2476 if($xo->id && $xo->content) {
2477 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2478 if(! (stristr($tagp[0]['tag'],$newtag))) {
2479 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2480 intval($importer['importer_uid'])
2482 if(count($i) && ! intval($i[0]['blocktags'])) {
2483 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2484 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2485 intval($tagp[0]['id']),
2486 dbesc(datetime_convert())
2495 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2496 // if(! stristr($datarray['tag'],$newtag)) {
2497 // if(strlen($datarray['tag']))
2498 // $datarray['tag'] .= ',';
2499 // $datarray['tag'] .= $newtag;
2504 $posted_id = item_store($datarray);
2508 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2510 intval($importer['importer_uid'])
2513 $parent = $r[0]['parent'];
2516 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2517 dbesc(datetime_convert()),
2518 intval($importer['importer_uid']),
2519 intval($r[0]['parent'])
2522 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2523 dbesc(datetime_convert()),
2524 intval($importer['importer_uid']),
2529 if($posted_id && $parent) {
2531 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2533 if((! $is_like) && (! $importer['self'])) {
2535 require_once('include/enotify.php');
2538 'type' => NOTIFY_COMMENT,
2539 'notify_flags' => $importer['notify-flags'],
2540 'language' => $importer['language'],
2541 'to_name' => $importer['username'],
2542 'to_email' => $importer['email'],
2543 'uid' => $importer['importer_uid'],
2544 'item' => $datarray,
2545 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2546 'source_name' => stripslashes($datarray['author-name']),
2547 'source_link' => $datarray['author-link'],
2548 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2549 ? $importer['thumb'] : $datarray['author-avatar']),
2550 'verb' => ACTIVITY_POST,
2552 'parent' => $parent,
2565 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2567 $item_id = $item->get_id();
2568 $datarray = get_atom_elements($feed,$item);
2570 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2572 intval($importer['importer_uid'])
2575 // Update content if 'updated' changes
2578 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2580 // do not accept (ignore) an earlier edit than one we currently have.
2581 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2584 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2585 dbesc($datarray['title']),
2586 dbesc($datarray['body']),
2587 dbesc($datarray['tag']),
2588 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2590 intval($importer['importer_uid'])
2594 // update last-child if it changes
2596 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2597 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2598 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2599 dbesc(datetime_convert()),
2601 intval($importer['importer_uid'])
2603 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2604 intval($allow[0]['data']),
2605 dbesc(datetime_convert()),
2607 intval($importer['importer_uid'])
2613 $datarray['parent-uri'] = $parent_uri;
2614 $datarray['uid'] = $importer['importer_uid'];
2615 $datarray['contact-id'] = $importer['id'];
2616 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2617 $datarray['type'] = 'activity';
2618 $datarray['gravity'] = GRAVITY_LIKE;
2619 // only one like or dislike per person
2620 $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",
2621 intval($datarray['uid']),
2622 intval($datarray['contact-id']),
2623 dbesc($datarray['verb']),
2632 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2634 $xo = parse_xml_string($datarray['object'],false);
2635 $xt = parse_xml_string($datarray['target'],false);
2637 if($xt->type == ACTIVITY_OBJ_NOTE) {
2638 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2640 intval($importer['importer_uid'])
2645 // extract tag, if not duplicate, add to parent item
2647 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2648 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2649 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2657 $posted_id = item_store($datarray);
2659 // find out if our user is involved in this conversation and wants to be notified.
2661 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2663 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2665 intval($importer['importer_uid'])
2668 if(count($myconv)) {
2669 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2671 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2672 if(! link_compare($datarray['author-link'],$importer_url)) {
2675 foreach($myconv as $conv) {
2677 // now if we find a match, it means we're in this conversation
2679 if(! link_compare($conv['author-link'],$importer_url))
2682 require_once('include/enotify.php');
2684 $conv_parent = $conv['parent'];
2687 'type' => NOTIFY_COMMENT,
2688 'notify_flags' => $importer['notify-flags'],
2689 'language' => $importer['language'],
2690 'to_name' => $importer['username'],
2691 'to_email' => $importer['email'],
2692 'uid' => $importer['importer_uid'],
2693 'item' => $datarray,
2694 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2695 'source_name' => stripslashes($datarray['author-name']),
2696 'source_link' => $datarray['author-link'],
2697 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2698 ? $importer['thumb'] : $datarray['author-avatar']),
2699 'verb' => ACTIVITY_POST,
2701 'parent' => $conv_parent,
2705 // only send one notification
2717 // Head post of a conversation. Have we seen it? If not, import it.
2720 $item_id = $item->get_id();
2721 $datarray = get_atom_elements($feed,$item);
2723 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2724 $ev = bbtoevent($datarray['body']);
2725 if(x($ev,'desc') && x($ev,'start')) {
2726 $ev['cid'] = $importer['id'];
2727 $ev['uid'] = $importer['uid'];
2728 $ev['uri'] = $item_id;
2729 $ev['edited'] = $datarray['edited'];
2730 $ev['private'] = $datarray['private'];
2732 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2734 intval($importer['uid'])
2737 $ev['id'] = $r[0]['id'];
2738 $xyz = event_store($ev);
2743 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2745 intval($importer['importer_uid'])
2748 // Update content if 'updated' changes
2751 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2753 // do not accept (ignore) an earlier edit than one we currently have.
2754 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2757 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2758 dbesc($datarray['title']),
2759 dbesc($datarray['body']),
2760 dbesc($datarray['tag']),
2761 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2763 intval($importer['importer_uid'])
2767 // update last-child if it changes
2769 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2770 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2771 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2772 intval($allow[0]['data']),
2773 dbesc(datetime_convert()),
2775 intval($importer['importer_uid'])
2781 // This is my contact on another system, but it's really me.
2782 // Turn this into a wall post.
2784 if($importer['remote_self'])
2785 $datarray['wall'] = 1;
2787 $datarray['parent-uri'] = $item_id;
2788 $datarray['uid'] = $importer['importer_uid'];
2789 $datarray['contact-id'] = $importer['id'];
2791 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2792 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2793 // but otherwise there's a possible data mixup on the sender's system.
2794 // the tgroup delivery code called from item_store will correct it if it's a forum,
2795 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2796 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2797 $datarray['owner-name'] = $importer['senderName'];
2798 $datarray['owner-link'] = $importer['url'];
2799 $datarray['owner-avatar'] = $importer['thumb'];
2802 $r = item_store($datarray);
2813 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2814 $url = notags(trim($datarray['author-link']));
2815 $name = notags(trim($datarray['author-name']));
2816 $photo = notags(trim($datarray['author-avatar']));
2818 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2819 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2820 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2822 if(is_array($contact)) {
2823 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2824 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2825 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2826 intval(CONTACT_IS_FRIEND),
2827 intval($contact['id']),
2828 intval($importer['uid'])
2831 // send email notification to owner?
2835 // create contact record
2837 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2838 `blocked`, `readonly`, `pending`, `writable` )
2839 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2840 intval($importer['uid']),
2841 dbesc(datetime_convert()),
2843 dbesc(normalise_link($url)),
2847 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2848 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2850 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2851 intval($importer['uid']),
2855 $contact_record = $r[0];
2857 // create notification
2858 $hash = random_string();
2860 if(is_array($contact_record)) {
2861 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2862 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2863 intval($importer['uid']),
2864 intval($contact_record['id']),
2866 dbesc(datetime_convert())
2869 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2870 intval($importer['uid'])
2875 if(intval($r[0]['def_gid'])) {
2876 require_once('include/group.php');
2877 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2880 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2881 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2882 $email = replace_macros($email_tpl, array(
2883 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2885 '$myname' => $r[0]['username'],
2886 '$siteurl' => $a->get_baseurl(),
2887 '$sitename' => $a->config['sitename']
2889 $res = mail($r[0]['email'],
2890 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2892 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2893 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2894 . 'Content-transfer-encoding: 8bit' );
2901 function lose_follower($importer,$contact,$datarray,$item) {
2903 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2904 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2905 intval(CONTACT_IS_SHARING),
2906 intval($contact['id'])
2910 contact_remove($contact['id']);
2914 function lose_sharer($importer,$contact,$datarray,$item) {
2916 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2917 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2918 intval(CONTACT_IS_FOLLOWER),
2919 intval($contact['id'])
2923 contact_remove($contact['id']);
2928 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2932 if(is_array($importer)) {
2933 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2934 intval($importer['uid'])
2938 // Diaspora has different message-ids in feeds than they do
2939 // through the direct Diaspora protocol. If we try and use
2940 // the feed, we'll get duplicates. So don't.
2942 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2945 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2947 // Use a single verify token, even if multiple hubs
2949 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2951 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2953 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2955 if(! strlen($contact['hub-verify'])) {
2956 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2957 dbesc($verify_token),
2958 intval($contact['id'])
2962 post_url($url,$params);
2964 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
2971 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2975 $name = xmlify($name);
2976 $uri = xmlify($uri);
2979 $photo = xmlify($photo);
2983 $o .= "<name>$name</name>\r\n";
2984 $o .= "<uri>$uri</uri>\r\n";
2985 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2986 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2988 call_hooks('atom_author', $o);
2990 $o .= "</$tag>\r\n";
2994 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
2998 if(! $item['parent'])
3001 if($item['deleted'])
3002 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3005 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3006 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3008 $body = $item['body'];
3011 $o = "\r\n\r\n<entry>\r\n";
3013 if(is_array($author))
3014 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3016 $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']));
3017 if(strlen($item['owner-name']))
3018 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3020 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || ($item['thr-parent'])) {
3021 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3022 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3025 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3026 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3027 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3028 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3029 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3030 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3031 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3033 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3035 if($item['location']) {
3036 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3037 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3041 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3043 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3044 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3047 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3048 if($item['bookmark'])
3049 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3052 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3055 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3057 if($item['signed_text']) {
3058 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3059 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3062 $verb = construct_verb($item);
3063 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3064 $actobj = construct_activity_object($item);
3067 $actarg = construct_activity_target($item);
3071 $tags = item_getfeedtags($item);
3073 foreach($tags as $t) {
3074 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3078 $o .= item_getfeedattach($item);
3080 $mentioned = get_mentions($item);
3084 call_hooks('atom_entry', $o);
3086 $o .= '</entry>' . "\r\n";
3091 function fix_private_photos($s,$uid, $item = null, $cid = 0) {
3094 logger('fix_private_photos', LOGGER_DEBUG);
3095 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3097 if(preg_match("/\[img(.*?)\](.*?)\[\/img\]/is",$s,$matches)) {
3098 $image = $matches[2];
3099 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3100 if(stristr($image , $site . '/photo/')) {
3102 $i = basename($image);
3103 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3104 $x = strpos($i,'-');
3106 $res = substr($i,$x+1);
3107 $i = substr($i,0,$x);
3108 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3115 // Check to see if we should replace this photo link with an embedded image
3116 // 1. No need to do so if the photo is public
3117 // 2. If there's a contact-id provided, see if they're in the access list
3118 // for the photo. If so, embed it.
3119 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3120 // permissions, regardless of order but first check to see if they're an exact
3121 // match to save some processing overhead.
3123 // Currently we only embed one private photo per message so as not to hit import
3124 // size limits at the receiving end.
3126 // To embed multiples, we would need to parse out the embedded photos on message
3127 // receipt and limit size based only on the text component. Would also need to
3128 // ignore all photos during bbcode translation and item localisation, as these
3129 // will hit internal regex backtrace limits.
3131 if(has_permissions($r[0])) {
3133 $recips = enumerate_permissions($r[0]);
3134 if(in_array($cid, $recips)) {
3139 if(compare_permissions($item,$r[0]))
3144 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3145 $s = str_replace($image, 'data:' . $r[0]['type'] . ';base64,' . base64_encode($r[0]['data']), $s);
3146 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
3156 function has_permissions($obj) {
3157 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3162 function compare_permissions($obj1,$obj2) {
3163 // first part is easy. Check that these are exactly the same.
3164 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3165 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3166 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3167 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3170 // This is harder. Parse all the permissions and compare the resulting set.
3172 $recipients1 = enumerate_permissions($obj1);
3173 $recipients2 = enumerate_permissions($obj2);
3176 if($recipients1 == $recipients2)
3181 // returns an array of contact-ids that are allowed to see this object
3183 function enumerate_permissions($obj) {
3184 require_once('include/group.php');
3185 $allow_people = expand_acl($obj['allow_cid']);
3186 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3187 $deny_people = expand_acl($obj['deny_cid']);
3188 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3189 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3190 $deny = array_unique(array_merge($deny_people,$deny_groups));
3191 $recipients = array_diff($recipients,$deny);
3195 function item_getfeedtags($item) {
3198 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3200 for($x = 0; $x < $cnt; $x ++) {
3202 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3206 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3208 for($x = 0; $x < $cnt; $x ++) {
3210 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3216 function item_getfeedattach($item) {
3218 $arr = explode(',',$item['attach']);
3220 foreach($arr as $r) {
3222 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3224 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3225 if(intval($matches[2]))
3226 $ret .= 'length="' . intval($matches[2]) . '" ';
3227 if($matches[4] !== ' ')
3228 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3229 $ret .= ' />' . "\r\n";
3238 function item_expire($uid,$days) {
3240 if((! $uid) || ($days < 1))
3243 // $expire_network_only = save your own wall posts
3244 // and just expire conversations started by others
3246 $expire_network_only = get_pconfig($uid,'expire','network_only');
3247 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3249 $r = q("SELECT * FROM `item`
3251 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3262 $expire_items = get_pconfig($uid, 'expire','items');
3263 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3265 $expire_notes = get_pconfig($uid, 'expire','notes');
3266 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3268 $expire_starred = get_pconfig($uid, 'expire','starred');
3269 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3271 $expire_photos = get_pconfig($uid, 'expire','photos');
3272 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3274 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3276 foreach($r as $item) {
3278 // don't expire filed items
3280 if(strpos($item['file'],'[') !== false)
3283 // Only expire posts, not photos and photo comments
3285 if($expire_photos==0 && strlen($item['resource-id']))
3287 if($expire_starred==0 && intval($item['starred']))
3289 if($expire_notes==0 && $item['type']=='note')
3291 if($expire_items==0 && $item['type']!='note')
3294 drop_item($item['id'],false);
3297 proc_run('php',"include/notifier.php","expire","$uid");
3302 function drop_items($items) {
3305 if(! local_user() && ! remote_user())
3309 foreach($items as $item) {
3310 $owner = drop_item($item,false);
3311 if($owner && ! $uid)
3316 // multiple threads may have been deleted, send an expire notification
3319 proc_run('php',"include/notifier.php","expire","$uid");
3323 function drop_item($id,$interactive = true) {
3327 // locate item to be deleted
3329 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3336 notice( t('Item not found.') . EOL);
3337 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3342 $owner = $item['uid'];
3344 // check if logged in user is either the author or owner of this item
3346 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3350 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3351 dbesc(datetime_convert()),
3352 dbesc(datetime_convert()),
3356 // clean up categories and tags so they don't end up as orphans
3359 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3361 foreach($matches as $mtch) {
3362 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3368 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3370 foreach($matches as $mtch) {
3371 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3375 // If item is a link to a photo resource, nuke all the associated photos
3376 // (visitors will not have photo resources)
3377 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3378 // generate a resource-id and therefore aren't intimately linked to the item.
3380 if(strlen($item['resource-id'])) {
3381 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3382 dbesc($item['resource-id']),
3383 intval($item['uid'])
3385 // ignore the result
3388 // If item is a link to an event, nuke the event record.
3390 if(intval($item['event-id'])) {
3391 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3392 intval($item['event-id']),
3393 intval($item['uid'])
3395 // ignore the result
3398 // clean up item_id and sign meta-data tables
3400 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3401 intval($item['id']),
3402 intval($item['uid'])
3405 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3406 intval($item['id']),
3407 intval($item['uid'])
3410 // If it's the parent of a comment thread, kill all the kids
3412 if($item['uri'] == $item['parent-uri']) {
3413 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3414 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3415 dbesc(datetime_convert()),
3416 dbesc(datetime_convert()),
3417 dbesc($item['parent-uri']),
3418 intval($item['uid'])
3420 // ignore the result
3423 // ensure that last-child is set in case the comment that had it just got wiped.
3424 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3425 dbesc(datetime_convert()),
3426 dbesc($item['parent-uri']),
3427 intval($item['uid'])
3429 // who is the last child now?
3430 $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",
3431 dbesc($item['parent-uri']),
3432 intval($item['uid'])
3435 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3440 // Add a relayable_retraction signature for Diaspora.
3441 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
3443 $drop_id = intval($item['id']);
3445 // send the notification upstream/downstream as the case may be
3450 proc_run('php',"include/notifier.php","drop","$drop_id");
3451 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3457 notice( t('Permission denied.') . EOL);
3458 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3465 function first_post_date($uid,$wall = false) {
3466 $r = q("select id, created from item
3467 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3469 order by created asc limit 1",
3471 intval($wall ? 1 : 0)
3474 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3475 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3480 function posted_dates($uid,$wall) {
3481 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3483 $dthen = first_post_date($uid,$wall);
3487 // If it's near the end of a long month, backup to the 28th so that in
3488 // consecutive loops we'll always get a whole month difference.
3490 if(intval(substr($dnow,8)) > 28)
3491 $dnow = substr($dnow,0,8) . '28';
3492 if(intval(substr($dthen,8)) > 28)
3493 $dnow = substr($dthen,0,8) . '28';
3496 while($dnow >= $dthen) {
3497 $dstart = substr($dnow,0,8) . '01';
3498 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3499 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3500 $end_month = datetime_convert('','',$dend,'Y-m-d');
3501 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3502 $ret[] = array($str,$end_month,$start_month);
3503 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3509 function posted_date_widget($url,$uid,$wall) {
3512 // For former Facebook folks that left because of "timeline"
3514 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3517 $ret = posted_dates($uid,$wall);
3521 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3522 '$title' => t('Archives'),
3523 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
3530 function store_diaspora_retract_sig($item, $user, $baseurl) {
3531 // Note that we can't add a target_author_signature
3532 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3533 // the comment, that means we're the home of the post, and Diaspora will only
3534 // check the parent_author_signature of retractions that it doesn't have to relay further
3536 // I don't think this function gets called for an "unlike," but I'll check anyway
3538 $enabled = intval(get_config('system','diaspora_enabled'));
3540 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
3544 logger('drop_item: storing diaspora retraction signature');
3546 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3548 if(local_user() == $item['uid']) {
3550 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
3551 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
3554 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3558 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3559 // only handles DFRN deletes
3560 $handle_baseurl_start = strpos($r['url'],'://') + 3;
3561 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3562 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3568 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3569 intval($item['id']),
3570 dbesc($signed_text),