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));
310 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
314 // look for a photo. We should check media size and find the best one,
315 // but for now let's just find any author photo
317 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
319 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
320 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
321 foreach($base as $link) {
322 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
323 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
324 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
329 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
331 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
332 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
333 if($base && count($base)) {
334 foreach($base as $link) {
335 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
336 $res['author-link'] = unxmlify($link['attribs']['']['href']);
337 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
338 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
339 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
345 // No photo/profile-link on the item - look at the feed level
347 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
348 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
349 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
350 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
351 foreach($base as $link) {
352 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
353 $res['author-link'] = unxmlify($link['attribs']['']['href']);
354 if(! $res['author-avatar']) {
355 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
356 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
361 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
363 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
364 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
366 if($base && count($base)) {
367 foreach($base as $link) {
368 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
369 $res['author-link'] = unxmlify($link['attribs']['']['href']);
370 if(! (x($res,'author-avatar'))) {
371 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
372 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
379 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
380 if($apps && $apps[0]['attribs']['']['source']) {
381 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
382 if($res['app'] === 'web')
383 $res['app'] = 'OStatus';
386 // base64 encoded json structure representing Diaspora signature
388 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
390 $res['dsprsig'] = unxmlify($dsig[0]['data']);
393 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
395 $res['guid'] = unxmlify($dguid[0]['data']);
397 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
399 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
403 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
406 $have_real_body = false;
408 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
410 $have_real_body = true;
411 $res['body'] = $rawenv[0]['data'];
412 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
413 // make sure nobody is trying to sneak some html tags by us
414 $res['body'] = notags(base64url_decode($res['body']));
417 $maxlen = get_max_import_size();
418 if($maxlen && (strlen($res['body']) > $maxlen))
419 $res['body'] = substr($res['body'],0, $maxlen);
421 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
422 // the content type. Our own network only emits text normally, though it might have been converted to
423 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
424 // have to assume it is all html and needs to be purified.
426 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
427 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
428 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
431 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
433 $res['body'] = reltoabs($res['body'],$base_url);
435 $res['body'] = html2bb_video($res['body']);
437 $res['body'] = oembed_html2bbcode($res['body']);
439 $config = HTMLPurifier_Config::createDefault();
440 $config->set('Cache.DefinitionImpl', null);
442 // we shouldn't need a whitelist, because the bbcode converter
443 // will strip out any unsupported tags.
445 $purifier = new HTMLPurifier($config);
446 $res['body'] = $purifier->purify($res['body']);
448 $res['body'] = @html2bbcode($res['body']);
452 elseif(! $have_real_body) {
454 // it's not one of our messages and it has no tags
455 // so it's probably just text. We'll escape it just to be safe.
457 $res['body'] = escape_tags($res['body']);
460 // this tag is obsolete but we keep it for really old sites
462 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
463 if($allow && $allow[0]['data'] == 1)
464 $res['last-child'] = 1;
466 $res['last-child'] = 0;
468 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
469 if($private && $private[0]['data'] == 1)
474 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
475 if($extid && $extid[0]['data'])
476 $res['extid'] = $extid[0]['data'];
478 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
480 $res['location'] = unxmlify($rawlocation[0]['data']);
483 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
485 $res['created'] = unxmlify($rawcreated[0]['data']);
488 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
490 $res['edited'] = unxmlify($rawedited[0]['data']);
492 if((x($res,'edited')) && (! (x($res,'created'))))
493 $res['created'] = $res['edited'];
495 if(! $res['created'])
496 $res['created'] = $item->get_date('c');
499 $res['edited'] = $item->get_date('c');
502 // Disallow time travelling posts
504 $d1 = strtotime($res['created']);
505 $d2 = strtotime($res['edited']);
506 $d3 = strtotime('now');
509 $res['created'] = datetime_convert();
511 $res['edited'] = datetime_convert();
513 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
514 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
515 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
516 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
517 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
518 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
519 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
520 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
521 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
523 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
524 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
526 foreach($base as $link) {
527 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
528 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
529 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
534 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
536 $res['coord'] = unxmlify($rawgeo[0]['data']);
539 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
541 // select between supported verbs
544 $res['verb'] = unxmlify($rawverb[0]['data']);
547 // translate OStatus unfollow to activity streams if it happened to get selected
549 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
550 $res['verb'] = ACTIVITY_UNFOLLOW;
552 $cats = $item->get_categories();
555 foreach($cats as $cat) {
556 $term = $cat->get_term();
558 $term = $cat->get_label();
559 $scheme = $cat->get_scheme();
560 if($scheme && $term && stristr($scheme,'X-DFRN:'))
561 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
563 $tag_arr[] = notags(trim($term));
565 $res['tag'] = implode(',', $tag_arr);
568 $attach = $item->get_enclosures();
571 foreach($attach as $att) {
572 $len = intval($att->get_length());
573 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
574 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
575 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
576 if(strpos($type,';'))
577 $type = substr($type,0,strpos($type,';'));
578 if((! $link) || (strpos($link,'http') !== 0))
584 $type = 'application/octet-stream';
586 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
588 $res['attach'] = implode(',', $att_arr);
591 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
594 $res['object'] = '<object>' . "\n";
595 $child = $rawobj[0]['child'];
596 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
597 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
598 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
600 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
601 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
602 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
603 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
604 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
605 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
606 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
607 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
609 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
610 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
611 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
612 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
614 $body = html2bb_video($body);
616 $config = HTMLPurifier_Config::createDefault();
617 $config->set('Cache.DefinitionImpl', null);
619 $purifier = new HTMLPurifier($config);
620 $body = $purifier->purify($body);
621 $body = html2bbcode($body);
624 $res['object'] .= '<content>' . $body . '</content>' . "\n";
627 $res['object'] .= '</object>' . "\n";
630 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
633 $res['target'] = '<target>' . "\n";
634 $child = $rawobj[0]['child'];
635 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
636 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
638 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
639 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
640 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
641 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
642 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
643 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
644 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
645 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
647 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
648 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
649 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
650 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
652 $body = html2bb_video($body);
654 $config = HTMLPurifier_Config::createDefault();
655 $config->set('Cache.DefinitionImpl', null);
657 $purifier = new HTMLPurifier($config);
658 $body = $purifier->purify($body);
659 $body = html2bbcode($body);
662 $res['target'] .= '<content>' . $body . '</content>' . "\n";
665 $res['target'] .= '</target>' . "\n";
668 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
670 call_hooks('parse_atom', $arr);
675 function encode_rel_links($links) {
677 if(! ((is_array($links)) && (count($links))))
679 foreach($links as $link) {
681 if($link['attribs']['']['rel'])
682 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
683 if($link['attribs']['']['type'])
684 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
685 if($link['attribs']['']['href'])
686 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
687 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
688 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
689 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
690 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
698 function item_store($arr,$force_parent = false) {
700 // If a Diaspora signature structure was passed in, pull it out of the
701 // item array and set it aside for later storage.
704 if(x($arr,'dsprsig')) {
705 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
706 unset($arr['dsprsig']);
709 if(x($arr, 'gravity'))
710 $arr['gravity'] = intval($arr['gravity']);
711 elseif($arr['parent-uri'] === $arr['uri'])
713 elseif(activity_match($arr['verb'],ACTIVITY_POST))
716 $arr['gravity'] = 6; // extensible catchall
719 $arr['type'] = 'remote';
721 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
723 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
724 $arr['body'] = strip_tags($arr['body']);
727 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
728 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
729 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
730 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
731 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
732 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
733 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
734 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
735 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
736 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
737 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
738 $arr['commented'] = datetime_convert();
739 $arr['received'] = datetime_convert();
740 $arr['changed'] = datetime_convert();
741 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
742 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
743 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
744 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
745 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
747 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
748 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
749 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
750 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
751 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
752 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
753 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
754 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
755 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
756 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
757 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
758 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
759 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
760 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
761 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
762 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
763 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
764 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
765 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
767 if($arr['parent-uri'] === $arr['uri']) {
770 $allow_cid = $arr['allow_cid'];
771 $allow_gid = $arr['allow_gid'];
772 $deny_cid = $arr['deny_cid'];
773 $deny_gid = $arr['deny_gid'];
777 // find the parent and snarf the item id and ACL's
778 // and anything else we need to inherit
780 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
781 dbesc($arr['parent-uri']),
787 // is the new message multi-level threaded?
788 // even though we don't support it now, preserve the info
789 // and re-attach to the conversation parent.
791 if($r[0]['uri'] != $r[0]['parent-uri']) {
792 $arr['thr-parent'] = $arr['parent-uri'];
793 $arr['parent-uri'] = $r[0]['parent-uri'];
794 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
795 ORDER BY `id` ASC LIMIT 1",
796 dbesc($r[0]['parent-uri']),
797 dbesc($r[0]['parent-uri']),
804 $parent_id = $r[0]['id'];
805 $parent_deleted = $r[0]['deleted'];
806 $allow_cid = $r[0]['allow_cid'];
807 $allow_gid = $r[0]['allow_gid'];
808 $deny_cid = $r[0]['deny_cid'];
809 $deny_gid = $r[0]['deny_gid'];
810 $arr['wall'] = $r[0]['wall'];
812 // if the parent is private, force privacy for the entire conversation
813 // This differs from the above settings as it subtly allows comments from
814 // email correspondents to be private even if the overall thread is not.
819 // Edge case. We host a public forum that was originally posted to privately.
820 // The original author commented, but as this is a comment, the permissions
821 // weren't fixed up so it will still show the comment as private unless we fix it here.
823 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
828 // Allow one to see reply tweets from status.net even when
829 // we don't have or can't see the original post.
832 logger('item_store: $force_parent=true, reply converted to top-level post.');
834 $arr['thr-parent'] = $arr['parent-uri'];
835 $arr['parent-uri'] = $arr['uri'];
839 logger('item_store: item parent was not found - ignoring item');
847 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
851 if($r && count($r)) {
852 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
856 call_hooks('post_remote',$arr);
858 if(x($arr,'cancel')) {
859 logger('item_store: post cancelled by plugin.');
865 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
867 $r = dbq("INSERT INTO `item` (`"
868 . implode("`, `", array_keys($arr))
870 . implode("', '", array_values($arr))
873 // find the item we just created
875 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
876 $arr['uri'], // already dbesc'd
881 $current_post = $r[0]['id'];
882 logger('item_store: created item ' . $current_post);
885 logger('item_store: could not locate created item');
889 logger('item_store: duplicated post occurred. Removing duplicates.');
890 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
893 intval($current_post)
897 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
898 $parent_id = $current_post;
900 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
903 $private = $arr['private'];
905 // Set parent id - and also make sure to inherit the parent's ACL's.
907 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
908 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
915 intval($parent_deleted),
916 intval($current_post)
919 $arr['id'] = $current_post;
920 $arr['parent'] = $parent_id;
921 $arr['allow_cid'] = $allow_cid;
922 $arr['allow_gid'] = $allow_gid;
923 $arr['deny_cid'] = $deny_cid;
924 $arr['deny_gid'] = $deny_gid;
925 $arr['private'] = $private;
926 $arr['deleted'] = $parent_deleted;
927 call_hooks('post_remote_end',$arr);
929 // update the commented timestamp on the parent
931 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
932 dbesc(datetime_convert()),
933 dbesc(datetime_convert()),
938 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
939 intval($current_post),
940 dbesc($dsprsig->signed_text),
941 dbesc($dsprsig->signature),
942 dbesc($dsprsig->signer)
948 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
951 if($arr['last-child']) {
952 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
955 intval($current_post)
959 tag_deliver($arr['uid'],$current_post);
961 return $current_post;
964 function get_item_contact($item,$contacts) {
965 if(! count($contacts) || (! is_array($item)))
967 foreach($contacts as $contact) {
968 if($contact['id'] == $item['contact-id']) {
977 function tag_deliver($uid,$item_id) {
979 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
985 $u = q("select * from user where uid = %d limit 1",
991 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
992 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
995 $i = q("select * from item where id = %d and uid = %d limit 1",
1004 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1006 // Diaspora uses their own hardwired link URL in @-tags
1007 // instead of the one we supply with webfinger
1009 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1011 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1013 foreach($matches as $mtch) {
1014 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1016 logger('tag_deliver: mention found: ' . $mtch[2]);
1024 // send a notification
1026 require_once('include/enotify.php');
1028 'type' => NOTIFY_TAGSELF,
1029 'notify_flags' => $u[0]['notify-flags'],
1030 'language' => $u[0]['language'],
1031 'to_name' => $u[0]['username'],
1032 'to_email' => $u[0]['email'],
1033 'uid' => $u[0]['uid'],
1035 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1036 'source_name' => $item['author-name'],
1037 'source_link' => $item['author-link'],
1038 'source_photo' => $item['author-avatar'],
1039 'verb' => ACTIVITY_TAG,
1043 if((! $community_page) && (! $prvgroup))
1047 // tgroup delivery - setup a second delivery chain
1048 // prevent delivery looping - only proceed
1049 // if the message originated elsewhere and is a top-level post
1051 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1054 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1057 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1058 intval($u[0]['uid'])
1063 // also reset all the privacy bits to the forum default permissions
1065 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1067 $forum_mode = (($prvgroup) ? 2 : 1);
1069 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1070 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1071 intval($forum_mode),
1072 dbesc($c[0]['name']),
1073 dbesc($c[0]['url']),
1074 dbesc($c[0]['thumb']),
1076 dbesc($u[0]['allow_cid']),
1077 dbesc($u[0]['allow_gid']),
1078 dbesc($u[0]['deny_cid']),
1079 dbesc($u[0]['deny_gid']),
1083 proc_run('php','include/notifier.php','tgroup',$item_id);
1092 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1096 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1098 if($contact['duplex'] && $contact['dfrn-id'])
1099 $idtosend = '0:' . $orig_id;
1100 if($contact['duplex'] && $contact['issued-id'])
1101 $idtosend = '1:' . $orig_id;
1103 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1105 $rino_enable = get_config('system','rino_encrypt');
1110 $ssl_val = intval(get_config('system','ssl_policy'));
1114 case SSL_POLICY_FULL:
1115 $ssl_policy = 'full';
1117 case SSL_POLICY_SELFSIGN:
1118 $ssl_policy = 'self';
1120 case SSL_POLICY_NONE:
1122 $ssl_policy = 'none';
1126 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1128 logger('dfrn_deliver: ' . $url);
1130 $xml = fetch_url($url);
1132 $curl_stat = $a->get_curl_code();
1134 return(-1); // timed out
1136 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1141 if(strpos($xml,'<?xml') === false) {
1142 logger('dfrn_deliver: no valid XML returned');
1143 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1147 $res = parse_xml_string($xml);
1149 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1150 return (($res->status) ? $res->status : 3);
1152 $postvars = array();
1153 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1154 $challenge = hex2bin((string) $res->challenge);
1155 $perm = (($res->perm) ? $res->perm : null);
1156 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1157 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1158 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1160 if($owner['page-flags'] == PAGE_PRVGROUP)
1163 $final_dfrn_id = '';
1166 if((($perm == 'rw') && (! intval($contact['writable'])))
1167 || (($perm == 'r') && (intval($contact['writable'])))) {
1168 q("update contact set writable = %d where id = %d limit 1",
1169 intval(($perm == 'rw') ? 1 : 0),
1170 intval($contact['id'])
1172 $contact['writable'] = (string) 1 - intval($contact['writable']);
1176 if(($contact['duplex'] && strlen($contact['pubkey']))
1177 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1178 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1179 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1180 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1183 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1184 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1187 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1189 if(strpos($final_dfrn_id,':') == 1)
1190 $final_dfrn_id = substr($final_dfrn_id,2);
1192 if($final_dfrn_id != $orig_id) {
1193 logger('dfrn_deliver: wrong dfrn_id.');
1194 // did not decode properly - cannot trust this site
1198 $postvars['dfrn_id'] = $idtosend;
1199 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1201 $postvars['dissolve'] = '1';
1204 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1205 $postvars['data'] = $atom;
1206 $postvars['perm'] = 'rw';
1209 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1210 $postvars['perm'] = 'r';
1213 $postvars['ssl_policy'] = $ssl_policy;
1216 $postvars['page'] = $page;
1218 if($rino && $rino_allowed && (! $dissolve)) {
1219 $key = substr(random_string(),0,16);
1220 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1221 $postvars['data'] = $data;
1222 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1225 if($dfrn_version >= 2.1) {
1226 if(($contact['duplex'] && strlen($contact['pubkey']))
1227 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1228 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1230 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1233 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1237 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1238 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1241 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1245 logger('md5 rawkey ' . md5($postvars['key']));
1247 $postvars['key'] = bin2hex($postvars['key']);
1250 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1252 $xml = post_url($contact['notify'],$postvars);
1254 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1256 $curl_stat = $a->get_curl_code();
1257 if((! $curl_stat) || (! strlen($xml)))
1258 return(-1); // timed out
1260 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1263 if(strpos($xml,'<?xml') === false) {
1264 logger('dfrn_deliver: phase 2: no valid XML returned');
1265 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1269 if($contact['term-date'] != '0000-00-00 00:00:00') {
1270 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1271 require_once('include/Contact.php');
1272 unmark_for_death($contact);
1275 $res = parse_xml_string($xml);
1277 return $res->status;
1283 * consume_feed - process atom feed and update anything/everything we might need to update
1285 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1287 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1288 * It is this person's stuff that is going to be updated.
1289 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1290 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1291 * have a contact record.
1292 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1293 * might not) try and subscribe to it.
1294 * $datedir sorts in reverse order
1295 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1296 * imported prior to its children being seen in the stream unless we are certain
1297 * of how the feed is arranged/ordered.
1298 * With $pass = 1, we only pull parent items out of the stream.
1299 * With $pass = 2, we only pull children (comments/likes).
1301 * So running this twice, first with pass 1 and then with pass 2 will do the right
1302 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1303 * model where comments can have sub-threads. That would require some massive sorting
1304 * to get all the feed items into a mostly linear ordering, and might still require
1308 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1310 require_once('library/simplepie/simplepie.inc');
1312 if(! strlen($xml)) {
1313 logger('consume_feed: empty input');
1317 $feed = new SimplePie();
1318 $feed->set_raw_data($xml);
1320 $feed->enable_order_by_date(true);
1322 $feed->enable_order_by_date(false);
1326 logger('consume_feed: Error parsing XML: ' . $feed->error());
1328 $permalink = $feed->get_permalink();
1330 // Check at the feed level for updated contact name and/or photo
1334 $photo_timestamp = '';
1338 $hubs = $feed->get_links('hub');
1339 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1342 $hub = implode(',', $hubs);
1344 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1346 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1348 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1349 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1350 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1351 $new_name = $elems['name'][0]['data'];
1353 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1354 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1355 $photo_url = $elems['link'][0]['attribs']['']['href'];
1358 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1359 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1363 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1364 logger('consume_feed: Updating photo for ' . $contact['name']);
1365 require_once("Photo.php");
1366 $photo_failure = false;
1367 $have_photo = false;
1369 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1370 intval($contact['id']),
1371 intval($contact['uid'])
1374 $resource_id = $r[0]['resource-id'];
1378 $resource_id = photo_new_resource();
1381 $img_str = fetch_url($photo_url,true);
1382 // guess mimetype from headers or filename
1383 $type = guess_image_type($photo_url,true);
1386 $img = new Photo($img_str, $type);
1387 if($img->is_valid()) {
1389 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1390 dbesc($resource_id),
1391 intval($contact['id']),
1392 intval($contact['uid'])
1396 $img->scaleImageSquare(175);
1398 $hash = $resource_id;
1399 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1401 $img->scaleImage(80);
1402 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1404 $img->scaleImage(48);
1405 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1409 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1410 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1411 dbesc(datetime_convert()),
1412 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1413 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1414 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1415 intval($contact['uid']),
1416 intval($contact['id'])
1421 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1422 $r = q("select * from contact where uid = %d and id = %d limit 1",
1423 intval($contact['uid']),
1424 intval($contact['id'])
1427 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1428 dbesc(notags(trim($new_name))),
1429 dbesc(datetime_convert()),
1430 intval($contact['uid']),
1431 intval($contact['id'])
1434 // do our best to update the name on content items
1437 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1438 dbesc(notags(trim($new_name))),
1439 dbesc($r[0]['name']),
1440 dbesc($r[0]['url']),
1441 intval($contact['uid'])
1446 if(strlen($birthday)) {
1447 if(substr($birthday,0,4) != $contact['bdyear']) {
1448 logger('consume_feed: updating birthday: ' . $birthday);
1452 * Add new birthday event for this person
1454 * $bdtext is just a readable placeholder in case the event is shared
1455 * with others. We will replace it during presentation to our $importer
1456 * to contain a sparkle link and perhaps a photo.
1460 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1463 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1464 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1465 intval($contact['uid']),
1466 intval($contact['id']),
1467 dbesc(datetime_convert()),
1468 dbesc(datetime_convert()),
1469 dbesc(datetime_convert('UTC','UTC', $birthday)),
1470 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1478 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1479 dbesc(substr($birthday,0,4)),
1480 intval($contact['uid']),
1481 intval($contact['id'])
1484 // This function is called twice without reloading the contact
1485 // Make sure we only create one event. This is why &$contact
1486 // is a reference var in this function
1488 $contact['bdyear'] = substr($birthday,0,4);
1493 $community_page = 0;
1494 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1496 $community_page = intval($rawtags[0]['data']);
1498 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1499 q("update contact set forum = %d where id = %d limit 1",
1500 intval($community_page),
1501 intval($contact['id'])
1503 $contact['forum'] = (string) $community_page;
1507 // process any deleted entries
1509 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1510 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1511 foreach($del_entries as $dentry) {
1513 if(isset($dentry['attribs']['']['ref'])) {
1514 $uri = $dentry['attribs']['']['ref'];
1516 if(isset($dentry['attribs']['']['when'])) {
1517 $when = $dentry['attribs']['']['when'];
1518 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1521 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1523 if($deleted && is_array($contact)) {
1524 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1525 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1527 intval($importer['uid']),
1528 intval($contact['id'])
1533 if(! $item['deleted'])
1534 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1536 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1537 $xo = parse_xml_string($item['object'],false);
1538 $xt = parse_xml_string($item['target'],false);
1539 if($xt->type === ACTIVITY_OBJ_NOTE) {
1540 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1542 intval($importer['importer_uid'])
1546 // For tags, the owner cannot remove the tag on the author's copy of the post.
1548 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1549 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1550 $author_copy = (($item['origin']) ? true : false);
1552 if($owner_remove && $author_copy)
1554 if($author_remove || $owner_remove) {
1555 $tags = explode(',',$i[0]['tag']);
1558 foreach($tags as $tag)
1559 if(trim($tag) !== trim($xo->body))
1560 $newtags[] = trim($tag);
1562 q("update item set tag = '%s' where id = %d limit 1",
1563 dbesc(implode(',',$newtags)),
1571 if($item['uri'] == $item['parent-uri']) {
1572 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1573 `body` = '', `title` = ''
1574 WHERE `parent-uri` = '%s' AND `uid` = %d",
1576 dbesc(datetime_convert()),
1577 dbesc($item['uri']),
1578 intval($importer['uid'])
1582 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1583 `body` = '', `title` = ''
1584 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1586 dbesc(datetime_convert()),
1588 intval($importer['uid'])
1590 if($item['last-child']) {
1591 // ensure that last-child is set in case the comment that had it just got wiped.
1592 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1593 dbesc(datetime_convert()),
1594 dbesc($item['parent-uri']),
1595 intval($item['uid'])
1597 // who is the last child now?
1598 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1599 ORDER BY `created` DESC LIMIT 1",
1600 dbesc($item['parent-uri']),
1601 intval($importer['uid'])
1604 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1615 // Now process the feed
1617 if($feed->get_item_quantity()) {
1619 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1621 // in inverse date order
1623 $items = array_reverse($feed->get_items());
1625 $items = $feed->get_items();
1628 foreach($items as $item) {
1631 $item_id = $item->get_id();
1632 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1633 if(isset($rawthread[0]['attribs']['']['ref'])) {
1635 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1638 if(($is_reply) && is_array($contact)) {
1643 // Have we seen it? If not, import it.
1645 $item_id = $item->get_id();
1646 $datarray = get_atom_elements($feed,$item);
1649 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1650 $datarray['author-name'] = $contact['name'];
1651 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1652 $datarray['author-link'] = $contact['url'];
1653 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1654 $datarray['author-avatar'] = $contact['thumb'];
1656 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1657 logger('consume_feed: no author information! ' . print_r($datarray,true));
1661 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1663 intval($importer['uid'])
1666 // Update content if 'updated' changes
1669 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1671 // do not accept (ignore) an earlier edit than one we currently have.
1672 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1675 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1676 dbesc($datarray['title']),
1677 dbesc($datarray['body']),
1678 dbesc($datarray['tag']),
1679 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1681 intval($importer['uid'])
1685 // update last-child if it changes
1687 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1688 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1689 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1690 dbesc(datetime_convert()),
1692 intval($importer['uid'])
1694 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1695 intval($allow[0]['data']),
1696 dbesc(datetime_convert()),
1698 intval($importer['uid'])
1704 $force_parent = false;
1705 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1706 if($contact['network'] === NETWORK_OSTATUS)
1707 $force_parent = true;
1708 if(strlen($datarray['title']))
1709 unset($datarray['title']);
1710 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1711 dbesc(datetime_convert()),
1713 intval($importer['uid'])
1715 $datarray['last-child'] = 1;
1718 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1719 // one way feed - no remote comment ability
1720 $datarray['last-child'] = 0;
1722 $datarray['parent-uri'] = $parent_uri;
1723 $datarray['uid'] = $importer['uid'];
1724 $datarray['contact-id'] = $contact['id'];
1725 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1726 $datarray['type'] = 'activity';
1727 $datarray['gravity'] = GRAVITY_LIKE;
1728 // only one like or dislike per person
1729 $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",
1730 intval($datarray['uid']),
1731 intval($datarray['contact-id']),
1732 dbesc($datarray['verb']),
1740 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1741 $xo = parse_xml_string($datarray['object'],false);
1742 $xt = parse_xml_string($datarray['target'],false);
1744 if($xt->type == ACTIVITY_OBJ_NOTE) {
1745 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1747 intval($importer['importer_uid'])
1752 // extract tag, if not duplicate, add to parent item
1753 if($xo->id && $xo->content) {
1754 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1755 if(! (stristr($r[0]['tag'],$newtag))) {
1756 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1757 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1765 $r = item_store($datarray,$force_parent);
1771 // Head post of a conversation. Have we seen it? If not, import it.
1773 $item_id = $item->get_id();
1775 $datarray = get_atom_elements($feed,$item);
1777 if(is_array($contact)) {
1778 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1779 $datarray['author-name'] = $contact['name'];
1780 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1781 $datarray['author-link'] = $contact['url'];
1782 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1783 $datarray['author-avatar'] = $contact['thumb'];
1786 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1787 logger('consume_feed: no author information! ' . print_r($datarray,true));
1791 // special handling for events
1793 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1794 $ev = bbtoevent($datarray['body']);
1795 if(x($ev,'desc') && x($ev,'start')) {
1796 $ev['uid'] = $importer['uid'];
1797 $ev['uri'] = $item_id;
1798 $ev['edited'] = $datarray['edited'];
1799 $ev['private'] = $datarray['private'];
1801 if(is_array($contact))
1802 $ev['cid'] = $contact['id'];
1803 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1805 intval($importer['uid'])
1808 $ev['id'] = $r[0]['id'];
1809 $xyz = event_store($ev);
1814 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1816 intval($importer['uid'])
1819 // Update content if 'updated' changes
1822 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1824 // do not accept (ignore) an earlier edit than one we currently have.
1825 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1828 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1829 dbesc($datarray['title']),
1830 dbesc($datarray['body']),
1831 dbesc($datarray['tag']),
1832 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1834 intval($importer['uid'])
1838 // update last-child if it changes
1840 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1841 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1842 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1843 intval($allow[0]['data']),
1844 dbesc(datetime_convert()),
1846 intval($importer['uid'])
1852 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1853 logger('consume-feed: New follower');
1854 new_follower($importer,$contact,$datarray,$item);
1857 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1858 lose_follower($importer,$contact,$datarray,$item);
1862 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1863 logger('consume-feed: New friend request');
1864 new_follower($importer,$contact,$datarray,$item,true);
1867 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1868 lose_sharer($importer,$contact,$datarray,$item);
1873 if(! is_array($contact))
1876 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1877 if(strlen($datarray['title']))
1878 unset($datarray['title']);
1879 $datarray['last-child'] = 1;
1882 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1883 // one way feed - no remote comment ability
1884 $datarray['last-child'] = 0;
1886 if($contact['network'] === NETWORK_FEED)
1887 $datarray['private'] = 1;
1889 // This is my contact on another system, but it's really me.
1890 // Turn this into a wall post.
1892 if($contact['remote_self'])
1893 $datarray['wall'] = 1;
1895 $datarray['parent-uri'] = $item_id;
1896 $datarray['uid'] = $importer['uid'];
1897 $datarray['contact-id'] = $contact['id'];
1899 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1900 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1901 // but otherwise there's a possible data mixup on the sender's system.
1902 // the tgroup delivery code called from item_store will correct it if it's a forum,
1903 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1904 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1905 $datarray['owner-name'] = $contact['name'];
1906 $datarray['owner-link'] = $contact['url'];
1907 $datarray['owner-avatar'] = $contact['thumb'];
1910 $r = item_store($datarray);
1918 function local_delivery($importer,$data) {
1922 if($importer['readonly']) {
1923 // We aren't receiving stuff from this person. But we will quietly ignore them
1924 // rather than a blatant "go away" message.
1925 logger('local_delivery: ignoring');
1930 // Consume notification feed. This may differ from consuming a public feed in several ways
1931 // - might contain email or friend suggestions
1932 // - might contain remote followup to our message
1933 // - in which case we need to accept it and then notify other conversants
1934 // - we may need to send various email notifications
1936 $feed = new SimplePie();
1937 $feed->set_raw_data($data);
1938 $feed->enable_order_by_date(false);
1942 // Currently unsupported - needs a lot of work
1943 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1944 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1945 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1947 $newloc['uid'] = $importer['importer_uid'];
1948 $newloc['cid'] = $importer['id'];
1949 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1950 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1951 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1952 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1953 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1954 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1955 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1956 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1957 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1958 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1961 // merge with current record, current contents have priority
1962 // update record, set url-updated
1963 // update profile photos
1969 // handle friend suggestion notification
1971 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1972 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1973 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1975 $fsugg['uid'] = $importer['importer_uid'];
1976 $fsugg['cid'] = $importer['id'];
1977 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1978 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1979 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1980 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1981 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1983 // Does our member already have a friend matching this description?
1985 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1986 dbesc($fsugg['name']),
1987 dbesc(normalise_link($fsugg['url'])),
1988 intval($fsugg['uid'])
1993 // Do we already have an fcontact record for this person?
1996 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1997 dbesc($fsugg['url']),
1998 dbesc($fsugg['name']),
1999 dbesc($fsugg['request'])
2004 // OK, we do. Do we already have an introduction for this person ?
2005 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2006 intval($fsugg['uid']),
2013 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2014 dbesc($fsugg['name']),
2015 dbesc($fsugg['url']),
2016 dbesc($fsugg['photo']),
2017 dbesc($fsugg['request'])
2019 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2020 dbesc($fsugg['url']),
2021 dbesc($fsugg['name']),
2022 dbesc($fsugg['request'])
2027 // database record did not get created. Quietly give up.
2032 $hash = random_string();
2034 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2035 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2036 intval($fsugg['uid']),
2038 intval($fsugg['cid']),
2039 dbesc($fsugg['body']),
2041 dbesc(datetime_convert()),
2046 'type' => NOTIFY_SUGGEST,
2047 'notify_flags' => $importer['notify-flags'],
2048 'language' => $importer['language'],
2049 'to_name' => $importer['username'],
2050 'to_email' => $importer['email'],
2051 'uid' => $importer['importer_uid'],
2053 'link' => $a->get_baseurl() . '/notifications/intros',
2054 'source_name' => $importer['name'],
2055 'source_link' => $importer['url'],
2056 'source_photo' => $importer['photo'],
2057 'verb' => ACTIVITY_REQ_FRIEND,
2066 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2067 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2069 logger('local_delivery: private message received');
2072 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2075 $msg['uid'] = $importer['importer_uid'];
2076 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2077 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2078 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2079 $msg['contact-id'] = $importer['id'];
2080 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2081 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2083 $msg['replied'] = 0;
2084 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2085 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2086 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2090 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2091 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2093 // send notifications.
2095 require_once('include/enotify.php');
2097 $notif_params = array(
2098 'type' => NOTIFY_MAIL,
2099 'notify_flags' => $importer['notify-flags'],
2100 'language' => $importer['language'],
2101 'to_name' => $importer['username'],
2102 'to_email' => $importer['email'],
2103 'uid' => $importer['importer_uid'],
2105 'source_name' => $msg['from-name'],
2106 'source_link' => $importer['url'],
2107 'source_photo' => $importer['thumb'],
2108 'verb' => ACTIVITY_POST,
2112 notification($notif_params);
2118 $community_page = 0;
2119 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2121 $community_page = intval($rawtags[0]['data']);
2123 if(intval($importer['forum']) != $community_page) {
2124 q("update contact set forum = %d where id = %d limit 1",
2125 intval($community_page),
2126 intval($importer['id'])
2128 $importer['forum'] = (string) $community_page;
2131 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2133 // process any deleted entries
2135 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2136 if(is_array($del_entries) && count($del_entries)) {
2137 foreach($del_entries as $dentry) {
2139 if(isset($dentry['attribs']['']['ref'])) {
2140 $uri = $dentry['attribs']['']['ref'];
2142 if(isset($dentry['attribs']['']['when'])) {
2143 $when = $dentry['attribs']['']['when'];
2144 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2147 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2153 $r = q("select * from item where uri = '%s' and id = parent limit 1",
2157 $parent_uri = $r[0]['parent-uri'];
2158 if($r[0]['parent-uri'] != $uri && $r[0]['thr-parent'] != $uri)
2166 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2169 logger('local_delivery: possible community delete');
2172 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2174 // was the top-level post for this reply written by somebody on this site?
2175 // Specifically, the recipient?
2177 $is_a_remote_delete = false;
2179 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2180 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2181 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2182 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2183 AND `item`.`uid` = %d
2189 intval($importer['importer_uid'])
2192 $is_a_remote_delete = true;
2194 // Does this have the characteristics of a community or private group comment?
2195 // If it's a reply to a wall post on a community/prvgroup page it's a
2196 // valid community comment. Also forum_mode makes it valid for sure.
2197 // If neither, it's not.
2199 if($is_a_remote_delete && $community) {
2200 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2201 $is_a_remote_delete = false;
2202 logger('local_delivery: not a community delete');
2206 if($is_a_remote_delete) {
2207 logger('local_delivery: received remote delete');
2211 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2212 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2214 intval($importer['importer_uid']),
2215 intval($importer['id'])
2221 if($item['deleted'])
2224 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2226 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2227 $xo = parse_xml_string($item['object'],false);
2228 $xt = parse_xml_string($item['target'],false);
2230 if($xt->type === ACTIVITY_OBJ_NOTE) {
2231 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2233 intval($importer['importer_uid'])
2237 // For tags, the owner cannot remove the tag on the author's copy of the post.
2239 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2240 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2241 $author_copy = (($item['origin']) ? true : false);
2243 if($owner_remove && $author_copy)
2245 if($author_remove || $owner_remove) {
2246 $tags = explode(',',$i[0]['tag']);
2249 foreach($tags as $tag)
2250 if(trim($tag) !== trim($xo->body))
2251 $newtags[] = trim($tag);
2253 q("update item set tag = '%s' where id = %d limit 1",
2254 dbesc(implode(',',$newtags)),
2262 if($item['uri'] == $item['parent-uri']) {
2263 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2264 WHERE `parent-uri` = '%s' AND `uid` = %d",
2266 dbesc(datetime_convert()),
2267 dbesc($item['uri']),
2268 intval($importer['importer_uid'])
2272 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2273 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2275 dbesc(datetime_convert()),
2277 intval($importer['importer_uid'])
2279 if($item['last-child']) {
2280 // ensure that last-child is set in case the comment that had it just got wiped.
2281 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2282 dbesc(datetime_convert()),
2283 dbesc($item['parent-uri']),
2284 intval($item['uid'])
2286 // who is the last child now?
2287 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2288 ORDER BY `created` DESC LIMIT 1",
2289 dbesc($item['parent-uri']),
2290 intval($importer['importer_uid'])
2293 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2298 if($is_a_remote_delete)
2299 proc_run('php',"include/notifier.php","delete",$item['id']);
2307 foreach($feed->get_items() as $item) {
2310 $item_id = $item->get_id();
2311 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2312 if(isset($rawthread[0]['attribs']['']['ref'])) {
2314 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2320 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2323 logger('local_delivery: possible community reply');
2326 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2328 // was the top-level post for this reply written by somebody on this site?
2329 // Specifically, the recipient?
2331 $is_a_remote_comment = false;
2333 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2334 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2335 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2336 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2337 AND `item`.`uid` = %d
2343 intval($importer['importer_uid'])
2346 $is_a_remote_comment = true;
2348 // Does this have the characteristics of a community or private group comment?
2349 // If it's a reply to a wall post on a community/prvgroup page it's a
2350 // valid community comment. Also forum_mode makes it valid for sure.
2351 // If neither, it's not.
2353 if($is_a_remote_comment && $community) {
2354 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2355 $is_a_remote_comment = false;
2356 logger('local_delivery: not a community reply');
2360 if($is_a_remote_comment) {
2361 logger('local_delivery: received remote comment');
2363 // remote reply to our post. Import and then notify everybody else.
2365 $datarray = get_atom_elements($feed,$item);
2367 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2369 intval($importer['importer_uid'])
2372 // Update content if 'updated' changes
2376 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2378 // do not accept (ignore) an earlier edit than one we currently have.
2379 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2382 logger('received updated comment' , LOGGER_DEBUG);
2383 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2384 dbesc($datarray['title']),
2385 dbesc($datarray['body']),
2386 dbesc($datarray['tag']),
2387 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2389 intval($importer['importer_uid'])
2392 proc_run('php',"include/notifier.php","comment-import",$iid);
2400 // TODO: make this next part work against both delivery threads of a community post
2402 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2403 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2404 // they won't know what to do so don't report an error. Just quietly die.
2408 // our user with $importer['importer_uid'] is the owner
2410 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2411 intval($importer['importer_uid'])
2415 $datarray['type'] = 'remote-comment';
2416 $datarray['wall'] = 1;
2417 $datarray['parent-uri'] = $parent_uri;
2418 $datarray['uid'] = $importer['importer_uid'];
2419 $datarray['owner-name'] = $own[0]['name'];
2420 $datarray['owner-link'] = $own[0]['url'];
2421 $datarray['owner-avatar'] = $own[0]['thumb'];
2422 $datarray['contact-id'] = $importer['id'];
2424 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2426 $datarray['type'] = 'activity';
2427 $datarray['gravity'] = GRAVITY_LIKE;
2428 $datarray['last-child'] = 0;
2429 // only one like or dislike per person
2430 $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",
2431 intval($datarray['uid']),
2432 intval($datarray['contact-id']),
2433 dbesc($datarray['verb']),
2434 dbesc($datarray['parent-uri']),
2435 dbesc($datarray['parent-uri'])
2442 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2444 $xo = parse_xml_string($datarray['object'],false);
2445 $xt = parse_xml_string($datarray['target'],false);
2447 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2449 // fetch the parent item
2451 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2453 intval($importer['importer_uid'])
2458 // extract tag, if not duplicate, and this user allows tags, add to parent item
2460 if($xo->id && $xo->content) {
2461 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2462 if(! (stristr($tagp[0]['tag'],$newtag))) {
2463 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2464 intval($importer['importer_uid'])
2466 if(count($i) && ! intval($i[0]['blocktags'])) {
2467 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2468 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2469 intval($tagp[0]['id']),
2470 dbesc(datetime_convert())
2479 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2480 // if(! stristr($datarray['tag'],$newtag)) {
2481 // if(strlen($datarray['tag']))
2482 // $datarray['tag'] .= ',';
2483 // $datarray['tag'] .= $newtag;
2488 $posted_id = item_store($datarray);
2492 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2494 intval($importer['importer_uid'])
2497 $parent = $r[0]['parent'];
2500 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2501 dbesc(datetime_convert()),
2502 intval($importer['importer_uid']),
2503 intval($r[0]['parent'])
2506 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2507 dbesc(datetime_convert()),
2508 intval($importer['importer_uid']),
2513 if($posted_id && $parent) {
2515 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2517 if((! $is_like) && (! $importer['self'])) {
2519 require_once('include/enotify.php');
2522 'type' => NOTIFY_COMMENT,
2523 'notify_flags' => $importer['notify-flags'],
2524 'language' => $importer['language'],
2525 'to_name' => $importer['username'],
2526 'to_email' => $importer['email'],
2527 'uid' => $importer['importer_uid'],
2528 'item' => $datarray,
2529 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2530 'source_name' => stripslashes($datarray['author-name']),
2531 'source_link' => $datarray['author-link'],
2532 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2533 ? $importer['thumb'] : $datarray['author-avatar']),
2534 'verb' => ACTIVITY_POST,
2536 'parent' => $parent,
2549 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2551 $item_id = $item->get_id();
2552 $datarray = get_atom_elements($feed,$item);
2554 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2556 intval($importer['importer_uid'])
2559 // Update content if 'updated' changes
2562 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2564 // do not accept (ignore) an earlier edit than one we currently have.
2565 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2568 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2569 dbesc($datarray['title']),
2570 dbesc($datarray['body']),
2571 dbesc($datarray['tag']),
2572 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2574 intval($importer['importer_uid'])
2578 // update last-child if it changes
2580 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2581 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2582 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2583 dbesc(datetime_convert()),
2585 intval($importer['importer_uid'])
2587 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2588 intval($allow[0]['data']),
2589 dbesc(datetime_convert()),
2591 intval($importer['importer_uid'])
2597 $datarray['parent-uri'] = $parent_uri;
2598 $datarray['uid'] = $importer['importer_uid'];
2599 $datarray['contact-id'] = $importer['id'];
2600 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2601 $datarray['type'] = 'activity';
2602 $datarray['gravity'] = GRAVITY_LIKE;
2603 // only one like or dislike per person
2604 $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",
2605 intval($datarray['uid']),
2606 intval($datarray['contact-id']),
2607 dbesc($datarray['verb']),
2616 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2618 $xo = parse_xml_string($datarray['object'],false);
2619 $xt = parse_xml_string($datarray['target'],false);
2621 if($xt->type == ACTIVITY_OBJ_NOTE) {
2622 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2624 intval($importer['importer_uid'])
2629 // extract tag, if not duplicate, add to parent item
2631 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2632 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2633 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2641 $posted_id = item_store($datarray);
2643 // find out if our user is involved in this conversation and wants to be notified.
2645 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2647 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2649 intval($importer['importer_uid'])
2652 if(count($myconv)) {
2653 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2655 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2656 if(! link_compare($datarray['author-link'],$importer_url)) {
2659 foreach($myconv as $conv) {
2661 // now if we find a match, it means we're in this conversation
2663 if(! link_compare($conv['author-link'],$importer_url))
2666 require_once('include/enotify.php');
2668 $conv_parent = $conv['parent'];
2671 'type' => NOTIFY_COMMENT,
2672 'notify_flags' => $importer['notify-flags'],
2673 'language' => $importer['language'],
2674 'to_name' => $importer['username'],
2675 'to_email' => $importer['email'],
2676 'uid' => $importer['importer_uid'],
2677 'item' => $datarray,
2678 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2679 'source_name' => stripslashes($datarray['author-name']),
2680 'source_link' => $datarray['author-link'],
2681 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2682 ? $importer['thumb'] : $datarray['author-avatar']),
2683 'verb' => ACTIVITY_POST,
2685 'parent' => $conv_parent,
2689 // only send one notification
2701 // Head post of a conversation. Have we seen it? If not, import it.
2704 $item_id = $item->get_id();
2705 $datarray = get_atom_elements($feed,$item);
2707 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2708 $ev = bbtoevent($datarray['body']);
2709 if(x($ev,'desc') && x($ev,'start')) {
2710 $ev['cid'] = $importer['id'];
2711 $ev['uid'] = $importer['uid'];
2712 $ev['uri'] = $item_id;
2713 $ev['edited'] = $datarray['edited'];
2714 $ev['private'] = $datarray['private'];
2716 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2718 intval($importer['uid'])
2721 $ev['id'] = $r[0]['id'];
2722 $xyz = event_store($ev);
2727 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2729 intval($importer['importer_uid'])
2732 // Update content if 'updated' changes
2735 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2737 // do not accept (ignore) an earlier edit than one we currently have.
2738 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2741 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2742 dbesc($datarray['title']),
2743 dbesc($datarray['body']),
2744 dbesc($datarray['tag']),
2745 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2747 intval($importer['importer_uid'])
2751 // update last-child if it changes
2753 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2754 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2755 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2756 intval($allow[0]['data']),
2757 dbesc(datetime_convert()),
2759 intval($importer['importer_uid'])
2765 // This is my contact on another system, but it's really me.
2766 // Turn this into a wall post.
2768 if($importer['remote_self'])
2769 $datarray['wall'] = 1;
2771 $datarray['parent-uri'] = $item_id;
2772 $datarray['uid'] = $importer['importer_uid'];
2773 $datarray['contact-id'] = $importer['id'];
2775 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2776 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2777 // but otherwise there's a possible data mixup on the sender's system.
2778 // the tgroup delivery code called from item_store will correct it if it's a forum,
2779 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2780 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2781 $datarray['owner-name'] = $importer['senderName'];
2782 $datarray['owner-link'] = $importer['url'];
2783 $datarray['owner-avatar'] = $importer['thumb'];
2786 $r = item_store($datarray);
2797 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2798 $url = notags(trim($datarray['author-link']));
2799 $name = notags(trim($datarray['author-name']));
2800 $photo = notags(trim($datarray['author-avatar']));
2802 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2803 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2804 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2806 if(is_array($contact)) {
2807 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2808 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2809 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2810 intval(CONTACT_IS_FRIEND),
2811 intval($contact['id']),
2812 intval($importer['uid'])
2815 // send email notification to owner?
2819 // create contact record
2821 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2822 `blocked`, `readonly`, `pending`, `writable` )
2823 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2824 intval($importer['uid']),
2825 dbesc(datetime_convert()),
2827 dbesc(normalise_link($url)),
2831 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2832 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2834 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2835 intval($importer['uid']),
2839 $contact_record = $r[0];
2841 // create notification
2842 $hash = random_string();
2844 if(is_array($contact_record)) {
2845 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2846 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2847 intval($importer['uid']),
2848 intval($contact_record['id']),
2850 dbesc(datetime_convert())
2853 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2854 intval($importer['uid'])
2859 if(intval($r[0]['def_gid'])) {
2860 require_once('include/group.php');
2861 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2864 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2865 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2866 $email = replace_macros($email_tpl, array(
2867 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2869 '$myname' => $r[0]['username'],
2870 '$siteurl' => $a->get_baseurl(),
2871 '$sitename' => $a->config['sitename']
2873 $res = mail($r[0]['email'],
2874 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2876 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2877 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2878 . 'Content-transfer-encoding: 8bit' );
2885 function lose_follower($importer,$contact,$datarray,$item) {
2887 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2888 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2889 intval(CONTACT_IS_SHARING),
2890 intval($contact['id'])
2894 contact_remove($contact['id']);
2898 function lose_sharer($importer,$contact,$datarray,$item) {
2900 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2901 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2902 intval(CONTACT_IS_FOLLOWER),
2903 intval($contact['id'])
2907 contact_remove($contact['id']);
2912 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2916 if(is_array($importer)) {
2917 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2918 intval($importer['uid'])
2922 // Diaspora has different message-ids in feeds than they do
2923 // through the direct Diaspora protocol. If we try and use
2924 // the feed, we'll get duplicates. So don't.
2926 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2929 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2931 // Use a single verify token, even if multiple hubs
2933 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2935 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2937 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2939 if(! strlen($contact['hub-verify'])) {
2940 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2941 dbesc($verify_token),
2942 intval($contact['id'])
2946 post_url($url,$params);
2948 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
2955 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2959 $name = xmlify($name);
2960 $uri = xmlify($uri);
2963 $photo = xmlify($photo);
2967 $o .= "<name>$name</name>\r\n";
2968 $o .= "<uri>$uri</uri>\r\n";
2969 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2970 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2972 call_hooks('atom_author', $o);
2974 $o .= "</$tag>\r\n";
2978 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
2982 if(! $item['parent'])
2985 if($item['deleted'])
2986 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2989 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2990 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
2992 $body = $item['body'];
2995 $o = "\r\n\r\n<entry>\r\n";
2997 if(is_array($author))
2998 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3000 $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']));
3001 if(strlen($item['owner-name']))
3002 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3004 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || ($item['thr-parent'])) {
3005 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3006 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3009 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3010 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3011 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3012 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3013 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3014 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3015 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3017 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3019 if($item['location']) {
3020 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3021 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3025 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3027 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3028 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
3031 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3032 if($item['bookmark'])
3033 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3036 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3039 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3041 if($item['signed_text']) {
3042 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3043 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3046 $verb = construct_verb($item);
3047 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3048 $actobj = construct_activity_object($item);
3051 $actarg = construct_activity_target($item);
3055 $tags = item_getfeedtags($item);
3057 foreach($tags as $t) {
3058 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3062 $o .= item_getfeedattach($item);
3064 $mentioned = get_mentions($item);
3068 call_hooks('atom_entry', $o);
3070 $o .= '</entry>' . "\r\n";
3075 function fix_private_photos($s,$uid, $item = null, $cid = 0) {
3078 logger('fix_private_photos', LOGGER_DEBUG);
3079 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3081 if(preg_match("/\[img(.*?)\](.*?)\[\/img\]/is",$s,$matches)) {
3082 $image = $matches[2];
3083 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3084 if(stristr($image , $site . '/photo/')) {
3086 $i = basename($image);
3087 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3088 $x = strpos($i,'-');
3090 $res = substr($i,$x+1);
3091 $i = substr($i,0,$x);
3092 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3099 // Check to see if we should replace this photo link with an embedded image
3100 // 1. No need to do so if the photo is public
3101 // 2. If there's a contact-id provided, see if they're in the access list
3102 // for the photo. If so, embed it.
3103 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3104 // permissions, regardless of order but first check to see if they're an exact
3105 // match to save some processing overhead.
3107 // Currently we only embed one private photo per message so as not to hit import
3108 // size limits at the receiving end.
3110 // To embed multiples, we would need to parse out the embedded photos on message
3111 // receipt and limit size based only on the text component. Would also need to
3112 // ignore all photos during bbcode translation and item localisation, as these
3113 // will hit internal regex backtrace limits.
3115 if(has_permissions($r[0])) {
3117 $recips = enumerate_permissions($r[0]);
3118 if(in_array($cid, $recips)) {
3123 if(compare_permissions($item,$r[0]))
3128 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3129 $s = str_replace($image, 'data:' . $r[0]['type'] . ';base64,' . base64_encode($r[0]['data']), $s);
3130 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
3140 function has_permissions($obj) {
3141 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3146 function compare_permissions($obj1,$obj2) {
3147 // first part is easy. Check that these are exactly the same.
3148 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3149 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3150 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3151 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3154 // This is harder. Parse all the permissions and compare the resulting set.
3156 $recipients1 = enumerate_permissions($obj1);
3157 $recipients2 = enumerate_permissions($obj2);
3160 if($recipients1 == $recipients2)
3165 // returns an array of contact-ids that are allowed to see this object
3167 function enumerate_permissions($obj) {
3168 require_once('include/group.php');
3169 $allow_people = expand_acl($obj['allow_cid']);
3170 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3171 $deny_people = expand_acl($obj['deny_cid']);
3172 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3173 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3174 $deny = array_unique(array_merge($deny_people,$deny_groups));
3175 $recipients = array_diff($recipients,$deny);
3179 function item_getfeedtags($item) {
3182 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3184 for($x = 0; $x < $cnt; $x ++) {
3186 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3190 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3192 for($x = 0; $x < $cnt; $x ++) {
3194 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3200 function item_getfeedattach($item) {
3202 $arr = explode(',',$item['attach']);
3204 foreach($arr as $r) {
3206 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3208 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3209 if(intval($matches[2]))
3210 $ret .= 'length="' . intval($matches[2]) . '" ';
3211 if($matches[4] !== ' ')
3212 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3213 $ret .= ' />' . "\r\n";
3222 function item_expire($uid,$days) {
3224 if((! $uid) || ($days < 1))
3227 // $expire_network_only = save your own wall posts
3228 // and just expire conversations started by others
3230 $expire_network_only = get_pconfig($uid,'expire','network_only');
3231 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3233 $r = q("SELECT * FROM `item`
3235 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3246 $expire_items = get_pconfig($uid, 'expire','items');
3247 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3249 $expire_notes = get_pconfig($uid, 'expire','notes');
3250 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3252 $expire_starred = get_pconfig($uid, 'expire','starred');
3253 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3255 $expire_photos = get_pconfig($uid, 'expire','photos');
3256 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3258 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3260 foreach($r as $item) {
3262 // don't expire filed items
3264 if(strpos($item['file'],'[') !== false)
3267 // Only expire posts, not photos and photo comments
3269 if($expire_photos==0 && strlen($item['resource-id']))
3271 if($expire_starred==0 && intval($item['starred']))
3273 if($expire_notes==0 && $item['type']=='note')
3275 if($expire_items==0 && $item['type']!='note')
3278 drop_item($item['id'],false);
3281 proc_run('php',"include/notifier.php","expire","$uid");
3286 function drop_items($items) {
3289 if(! local_user() && ! remote_user())
3293 foreach($items as $item) {
3294 $owner = drop_item($item,false);
3295 if($owner && ! $uid)
3300 // multiple threads may have been deleted, send an expire notification
3303 proc_run('php',"include/notifier.php","expire","$uid");
3307 function drop_item($id,$interactive = true) {
3311 // locate item to be deleted
3313 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3320 notice( t('Item not found.') . EOL);
3321 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3326 $owner = $item['uid'];
3328 // check if logged in user is either the author or owner of this item
3330 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3334 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3335 dbesc(datetime_convert()),
3336 dbesc(datetime_convert()),
3340 // clean up categories and tags so they don't end up as orphans
3343 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3345 foreach($matches as $mtch) {
3346 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3352 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3354 foreach($matches as $mtch) {
3355 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3359 // If item is a link to a photo resource, nuke all the associated photos
3360 // (visitors will not have photo resources)
3361 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3362 // generate a resource-id and therefore aren't intimately linked to the item.
3364 if(strlen($item['resource-id'])) {
3365 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3366 dbesc($item['resource-id']),
3367 intval($item['uid'])
3369 // ignore the result
3372 // If item is a link to an event, nuke the event record.
3374 if(intval($item['event-id'])) {
3375 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3376 intval($item['event-id']),
3377 intval($item['uid'])
3379 // ignore the result
3382 // clean up item_id and sign meta-data tables
3384 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3385 intval($item['id']),
3386 intval($item['uid'])
3389 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3390 intval($item['id']),
3391 intval($item['uid'])
3394 // If it's the parent of a comment thread, kill all the kids
3396 if($item['uri'] == $item['parent-uri']) {
3397 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3398 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3399 dbesc(datetime_convert()),
3400 dbesc(datetime_convert()),
3401 dbesc($item['parent-uri']),
3402 intval($item['uid'])
3404 // ignore the result
3407 // ensure that last-child is set in case the comment that had it just got wiped.
3408 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3409 dbesc(datetime_convert()),
3410 dbesc($item['parent-uri']),
3411 intval($item['uid'])
3413 // who is the last child now?
3414 $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",
3415 dbesc($item['parent-uri']),
3416 intval($item['uid'])
3419 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3424 // Add a relayable_retraction signature for Diaspora. Note that we can't add a target_author_signature
3425 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3426 // the comment, that means we're the home of the post, and Diaspora will only
3427 // check the parent_author_signature of retractions that it doesn't have to relay further
3429 // I don't think this function gets called for an "unlike," but I'll check anyway
3430 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3432 if(local_user() == $item['uid']) {
3434 $handle = $a->user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
3435 $authorsig = base64_encode(rsa_sign($signed_text,$a->user['prvkey'],'sha256'));
3438 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3442 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3443 // only handles DFRN deletes
3444 $handle_baseurl_start = strpos($r['url'],'://') + 3;
3445 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3446 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3452 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3453 intval($item['id']),
3454 dbesc($signed_text),
3459 $drop_id = intval($item['id']);
3461 // send the notification upstream/downstream as the case may be
3466 proc_run('php',"include/notifier.php","drop","$drop_id");
3467 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3473 notice( t('Permission denied.') . EOL);
3474 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3481 function first_post_date($uid,$wall = false) {
3482 $r = q("select id, created from item
3483 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
3485 order by created asc limit 1",
3487 intval($wall ? 1 : 0)
3490 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
3491 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
3496 function posted_dates($uid,$wall) {
3497 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
3499 $dthen = first_post_date($uid,$wall);
3503 // If it's near the end of a long month, backup to the 28th so that in
3504 // consecutive loops we'll always get a whole month difference.
3506 if(intval(substr($dnow,8)) > 28)
3507 $dnow = substr($dnow,0,8) . '28';
3508 if(intval(substr($dthen,8)) > 28)
3509 $dnow = substr($dthen,0,8) . '28';
3512 while($dnow >= $dthen) {
3513 $dstart = substr($dnow,0,8) . '01';
3514 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
3515 $start_month = datetime_convert('','',$dstart,'Y-m-d');
3516 $end_month = datetime_convert('','',$dend,'Y-m-d');
3517 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
3518 $ret[] = array($str,$end_month,$start_month);
3519 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
3525 function posted_date_widget($url,$uid,$wall) {
3528 // For former Facebook folks that left because of "timeline"
3530 if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
3533 $ret = posted_dates($uid,$wall);
3537 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
3538 '$title' => t('Archives'),
3539 '$size' => ((count($ret) > 6) ? 6 : count($ret)),