3 require_once('bbcode.php');
4 require_once('oembed.php');
5 require_once('include/salmon.php');
7 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
9 // default permissions - anonymous user
11 if(! strlen($owner_nick))
14 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
16 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
17 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
18 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
26 $owner_id = $owner['user_uid'];
27 $owner_nick = $owner['nickname'];
29 $birthday = feed_birthday($owner_id,$owner['timezone']);
31 if(strlen($dfrn_id)) {
36 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
40 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
41 $my_id = '1:' . $dfrn_id;
44 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
45 $my_id = '0:' . $dfrn_id;
52 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
60 $groups = init_groups_visitor($contact['id']);
63 for($x = 0; $x < count($groups); $x ++)
64 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
65 $gs = implode('|', $groups);
68 $gs = '<<>>' ; // Impossible to match
70 $sql_extra = sprintf("
71 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
72 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
73 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
74 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
76 intval($contact['id']),
77 intval($contact['id']),
83 if($dfrn_id === '' || $dfrn_id === '*')
88 if(! strlen($last_update))
89 $last_update = 'now -30 days';
91 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
93 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
94 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
95 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
96 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
97 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
98 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
99 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0
100 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
101 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
103 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
110 // Will check further below if this actually returned results.
111 // We will provide an empty feed if that is the case.
115 $feed_template = get_markup_template('atom_feed.tpl');
119 $hubxml = feed_hublinks();
121 $salmon = feed_salmonlinks($owner_nick);
123 $atom .= replace_macros($feed_template, array(
124 '$version' => xmlify(FRIENDIKA_VERSION),
125 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
126 '$feed_title' => xmlify($owner['name']),
127 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
129 '$salmon' => $salmon,
130 '$name' => xmlify($owner['name']),
131 '$profile_page' => xmlify($owner['url']),
132 '$photo' => xmlify($owner['photo']),
133 '$thumb' => xmlify($owner['thumb']),
134 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
135 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
136 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
137 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
140 call_hooks('atom_feed', $atom);
142 if(! count($items)) {
144 call_hooks('atom_feed_end', $atom);
146 $atom .= '</feed>' . "\r\n";
150 foreach($items as $item) {
152 // public feeds get html, our own nodes use bbcode
154 if($dfrn_id === '') {
161 $atom .= atom_entry($item,$type,null,$owner,true);
164 call_hooks('atom_feed_end', $atom);
166 $atom .= '</feed>' . "\r\n";
172 function construct_verb($item) {
174 return $item['verb'];
175 return ACTIVITY_POST;
178 function construct_activity_object($item) {
180 if($item['object']) {
181 $o = '<as:object>' . "\r\n";
182 $r = parse_xml_string($item['object'],false);
188 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
190 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
192 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
194 if(substr($r->link,0,1) === '<') {
195 // patch up some facebook "like" activity objects that got stored incorrectly
196 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
197 // we can probably remove this hack here and in the following function in a few months time.
198 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
199 $r->link = str_replace('&','&', $r->link);
200 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
204 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
207 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
208 $o .= '</as:object>' . "\r\n";
215 function construct_activity_target($item) {
217 if($item['target']) {
218 $o = '<as:target>' . "\r\n";
219 $r = parse_xml_string($item['target'],false);
223 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
225 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
227 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
229 if(substr($r->link,0,1) === '<') {
230 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
231 $r->link = str_replace('&','&', $r->link);
232 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
236 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
239 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
240 $o .= '</as:target>' . "\r\n";
250 function get_atom_elements($feed,$item) {
252 require_once('library/HTMLPurifier.auto.php');
253 require_once('include/html2bbcode.php');
255 $best_photo = array();
259 $author = $item->get_author();
261 $res['author-name'] = unxmlify($author->get_name());
262 $res['author-link'] = unxmlify($author->get_link());
265 $res['author-name'] = unxmlify($feed->get_title());
266 $res['author-link'] = unxmlify($feed->get_permalink());
268 $res['uri'] = unxmlify($item->get_id());
269 $res['title'] = unxmlify($item->get_title());
270 $res['body'] = unxmlify($item->get_content());
271 $res['plink'] = unxmlify($item->get_link(0));
273 // look for a photo. We should check media size and find the best one,
274 // but for now let's just find any author photo
276 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
278 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
279 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
280 foreach($base as $link) {
281 if(! $res['author-avatar']) {
282 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
283 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
288 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
290 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
291 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
292 if($base && count($base)) {
293 foreach($base as $link) {
294 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
295 $res['author-link'] = unxmlify($link['attribs']['']['href']);
296 if(! $res['author-avatar']) {
297 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
298 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
304 // No photo/profile-link on the item - look at the feed level
306 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
307 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
308 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
309 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
310 foreach($base as $link) {
311 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
312 $res['author-link'] = unxmlify($link['attribs']['']['href']);
313 if(! $res['author-avatar']) {
314 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
315 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
320 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
322 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
323 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
325 if($base && count($base)) {
326 foreach($base as $link) {
327 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
328 $res['author-link'] = unxmlify($link['attribs']['']['href']);
329 if(! (x($res,'author-avatar'))) {
330 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
331 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
338 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
339 if($apps && $apps[0]['attribs']['']['source']) {
340 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
341 if($res['app'] === 'web')
342 $res['app'] = 'OStatus';
346 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
349 $have_real_body = false;
351 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
353 $have_real_body = true;
354 $res['body'] = $rawenv[0]['data'];
355 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
356 // make sure nobody is trying to sneak some html tags by us
357 $res['body'] = notags(base64url_decode($res['body']));
360 $maxlen = get_max_import_size();
361 if($maxlen && (strlen($res['body']) > $maxlen))
362 $res['body'] = substr($res['body'],0, $maxlen);
364 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
365 // the content type. Our own network only emits text normally, though it might have been converted to
366 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
367 // have to assume it is all html and needs to be purified.
369 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
370 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
371 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
374 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
376 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
377 '[youtube]$1[/youtube]', $res['body']);
379 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
380 '[youtube]$1[/youtube]', $res['body']);
382 $res['body'] = oembed_html2bbcode($res['body']);
384 $config = HTMLPurifier_Config::createDefault();
385 $config->set('Cache.DefinitionImpl', null);
387 // we shouldn't need a whitelist, because the bbcode converter
388 // will strip out any unsupported tags.
389 // $config->set('HTML.Allowed', 'p,b,a[href],i');
391 $purifier = new HTMLPurifier($config);
392 $res['body'] = $purifier->purify($res['body']);
394 $res['body'] = html2bbcode($res['body']);
397 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
398 if($allow && $allow[0]['data'] == 1)
399 $res['last-child'] = 1;
401 $res['last-child'] = 0;
403 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
404 if($private && $private[0]['data'] == 1)
409 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
410 if($extid && $extid[0]['data'])
411 $res['extid'] = $extid[0]['data'];
413 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
415 $res['location'] = unxmlify($rawlocation[0]['data']);
418 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
420 $res['created'] = unxmlify($rawcreated[0]['data']);
423 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
425 $res['edited'] = unxmlify($rawedited[0]['data']);
427 if((x($res,'edited')) && (! (x($res,'created'))))
428 $res['created'] = $res['edited'];
430 if(! $res['created'])
431 $res['created'] = $item->get_date('c');
434 $res['edited'] = $item->get_date('c');
437 // Disallow time travelling posts
439 $d1 = strtotime($res['created']);
440 $d2 = strtotime($res['edited']);
441 $d3 = strtotime('now');
444 $res['created'] = datetime_convert();
446 $res['edited'] = datetime_convert();
448 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
449 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
450 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
451 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
452 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
453 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
454 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
455 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
456 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
458 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
459 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
461 foreach($base as $link) {
462 if(! $res['owner-avatar']) {
463 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
464 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
469 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
471 $res['coord'] = unxmlify($rawgeo[0]['data']);
474 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
476 // select between supported verbs
479 $res['verb'] = unxmlify($rawverb[0]['data']);
482 // translate OStatus unfollow to activity streams if it happened to get selected
484 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
485 $res['verb'] = ACTIVITY_UNFOLLOW;
487 $cats = $item->get_categories();
490 foreach($cats as $cat) {
491 $term = $cat->get_term();
493 $term = $cat->get_label();
494 $scheme = $cat->get_scheme();
495 if($scheme && $term && stristr($scheme,'X-DFRN:'))
496 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
498 $tag_arr[] = notags(trim($term));
500 $res['tag'] = implode(',', $tag_arr);
503 $attach = $item->get_enclosures();
506 foreach($attach as $att) {
507 $len = intval($att->get_length());
508 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
509 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
510 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
511 if(strpos($type,';'))
512 $type = substr($type,0,strpos($type,';'));
513 if((! $link) || (strpos($link,'http') !== 0))
519 $type = 'application/octet-stream';
521 $att_arr[] = '[attach]href="' . $link . '" size="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
523 $res['attach'] = implode(',', $att_arr);
526 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
529 $res['object'] = '<object>' . "\n";
530 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
531 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
532 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
534 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
535 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
536 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
537 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
538 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
539 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
540 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
541 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
543 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
544 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
545 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
546 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
548 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
549 '[youtube]$1[/youtube]', $body);
551 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
552 '[youtube]$1[/youtube]', $res['body']);
555 $config = HTMLPurifier_Config::createDefault();
556 $config->set('Cache.DefinitionImpl', null);
558 $purifier = new HTMLPurifier($config);
559 $body = $purifier->purify($body);
560 $body = html2bbcode($body);
563 $res['object'] .= '<content>' . $body . '</content>' . "\n";
566 $res['object'] .= '</object>' . "\n";
569 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
572 $res['target'] = '<target>' . "\n";
573 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
574 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
576 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
577 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
579 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
580 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
581 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
582 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
583 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
584 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
586 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
587 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
588 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
589 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
591 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
592 '[youtube]$1[/youtube]', $body);
594 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
595 '[youtube]$1[/youtube]', $res['body']);
597 $config = HTMLPurifier_Config::createDefault();
598 $config->set('Cache.DefinitionImpl', null);
600 $purifier = new HTMLPurifier($config);
601 $body = $purifier->purify($body);
602 $body = html2bbcode($body);
605 $res['target'] .= '<content>' . $body . '</content>' . "\n";
608 $res['target'] .= '</target>' . "\n";
611 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
613 call_hooks('parse_atom', $arr);
618 function encode_rel_links($links) {
620 if(! ((is_array($links)) && (count($links))))
622 foreach($links as $link) {
624 if($link['attribs']['']['rel'])
625 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
626 if($link['attribs']['']['type'])
627 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
628 if($link['attribs']['']['href'])
629 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
630 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
631 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
632 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
633 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
639 function item_store($arr,$force_parent = false) {
642 $arr['gravity'] = intval($arr['gravity']);
643 elseif($arr['parent-uri'] == $arr['uri'])
645 elseif(activity_match($arr['verb'],ACTIVITY_POST))
648 $arr['gravity'] = 6; // extensible catchall
651 $arr['type'] = 'remote';
653 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
655 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
656 $arr['body'] = strip_tags($arr['body']);
659 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
660 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
661 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
662 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
663 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
664 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
665 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
666 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
667 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
668 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
669 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
670 $arr['received'] = datetime_convert();
671 $arr['changed'] = datetime_convert();
672 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
673 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
674 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
675 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
676 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
678 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
679 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
680 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
681 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
682 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
683 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
684 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
685 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
686 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
687 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
688 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
689 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
690 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
691 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
692 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
693 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
695 if($arr['parent-uri'] === $arr['uri']) {
697 $allow_cid = $arr['allow_cid'];
698 $allow_gid = $arr['allow_gid'];
699 $deny_cid = $arr['deny_cid'];
700 $deny_gid = $arr['deny_gid'];
704 // find the parent and snarf the item id and ACL's
705 // and anything else we need to inherit
707 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
708 dbesc($arr['parent-uri']),
714 // is the new message multi-level threaded?
715 // even though we don't support it now, preserve the info
716 // and re-attach to the conversation parent.
718 if($r[0]['uri'] != $r[0]['parent-uri']) {
719 $arr['thr-parent'] = $arr['parent-uri'];
720 $arr['parent-uri'] = $r[0]['parent-uri'];
723 $parent_id = $r[0]['id'];
724 $parent_deleted = $r[0]['deleted'];
725 $allow_cid = $r[0]['allow_cid'];
726 $allow_gid = $r[0]['allow_gid'];
727 $deny_cid = $r[0]['deny_cid'];
728 $deny_gid = $r[0]['deny_gid'];
729 $arr['wall'] = $r[0]['wall'];
733 // Allow one to see reply tweets from status.net even when
734 // we don't have or can't see the original post.
737 logger('item_store: $force_parent=true, reply converted to top-level post.');
739 $arr['thr-parent'] = $arr['parent-uri'];
740 $arr['parent-uri'] = $arr['uri'];
744 logger('item_store: item parent was not found - ignoring item');
750 call_hooks('post_remote',$arr);
754 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
756 $r = dbq("INSERT INTO `item` (`"
757 . implode("`, `", array_keys($arr))
759 . implode("', '", array_values($arr))
762 // find the item we just created
764 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
765 $arr['uri'], // already dbesc'd
769 // This is not good, but perhaps we encountered a rare race/cache condition, so back off and try again.
771 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
772 $arr['uri'], // already dbesc'd
778 $current_post = $r[0]['id'];
779 logger('item_store: created item ' . $current_post);
782 logger('item_store: could not locate created item');
786 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
787 $parent_id = $current_post;
789 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
792 $private = $arr['private'];
794 // Set parent id - and also make sure to inherit the parent's ACL's.
796 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
797 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
804 intval($parent_deleted),
805 intval($current_post)
809 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
812 if($arr['last-child']) {
813 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
816 intval($current_post)
820 return $current_post;
823 function get_item_contact($item,$contacts) {
824 if(! count($contacts) || (! is_array($item)))
826 foreach($contacts as $contact) {
827 if($contact['id'] == $item['contact-id']) {
836 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
840 if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
843 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
845 if($contact['duplex'] && $contact['dfrn-id'])
846 $idtosend = '0:' . $orig_id;
847 if($contact['duplex'] && $contact['issued-id'])
848 $idtosend = '1:' . $orig_id;
850 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
852 $rino_enable = get_config('system','rino_encrypt');
857 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
859 logger('dfrn_deliver: ' . $url);
861 $xml = fetch_url($url);
863 $curl_stat = $a->get_curl_code();
865 return(-1); // timed out
867 logger('dfrn_deliver: ' . $xml);
872 if(strpos($xml,'<?xml') === false) {
873 logger('dfrn_deliver: no valid XML returned');
874 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
878 $res = parse_xml_string($xml);
880 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
881 return (($res->status) ? $res->status : 3);
884 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
885 $challenge = hex2bin((string) $res->challenge);
886 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
887 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
892 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
893 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
894 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
897 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
898 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
901 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
903 if(strpos($final_dfrn_id,':') == 1)
904 $final_dfrn_id = substr($final_dfrn_id,2);
906 if($final_dfrn_id != $orig_id) {
907 logger('dfrn_deliver: wrong dfrn_id.');
908 // did not decode properly - cannot trust this site
912 $postvars['dfrn_id'] = $idtosend;
913 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
915 $postvars['dissolve'] = '1';
918 if((($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
919 $postvars['data'] = $atom;
920 $postvars['perm'] = 'rw';
923 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
924 $postvars['perm'] = 'r';
927 if($rino && $rino_allowed && (! $dissolve)) {
928 $key = substr(random_string(),0,16);
929 $data = bin2hex(aes_encrypt($postvars['data'],$key));
930 $postvars['data'] = $data;
931 logger('rino: sent key = ' . $key);
934 if($dfrn_version >= 2.1) {
935 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
936 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
939 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
943 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
944 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
947 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
951 logger('md5 rawkey ' . md5($postvars['key']));
953 $postvars['key'] = bin2hex($postvars['key']);
956 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
958 $xml = post_url($contact['notify'],$postvars);
960 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
962 $curl_stat = $a->get_curl_code();
963 if((! $curl_stat) || (! strlen($xml)))
964 return(-1); // timed out
966 if(strpos($xml,'<?xml') === false) {
967 logger('dfrn_deliver: phase 2: no valid XML returned');
968 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
972 $res = parse_xml_string($xml);
980 * consume_feed - process atom feed and update anything/everything we might need to update
982 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
984 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
985 * It is this person's stuff that is going to be updated.
986 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
987 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
988 * have a contact record.
989 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
990 * might not) try and subscribe to it.
994 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
996 require_once('library/simplepie/simplepie.inc');
998 $feed = new SimplePie();
999 $feed->set_raw_data($xml);
1001 $feed->enable_order_by_date(true);
1003 $feed->enable_order_by_date(false);
1007 logger('consume_feed: Error parsing XML: ' . $feed->error());
1009 $permalink = $feed->get_permalink();
1011 // Check at the feed level for updated contact name and/or photo
1015 $photo_timestamp = '';
1019 $hubs = $feed->get_links('hub');
1022 $hub = implode(',', $hubs);
1024 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1026 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1027 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1028 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1029 $new_name = $elems['name'][0]['data'];
1031 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1032 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1033 $photo_url = $elems['link'][0]['attribs']['']['href'];
1036 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1037 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1041 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1042 logger('consume_feed: Updating photo for ' . $contact['name']);
1043 require_once("Photo.php");
1044 $photo_failure = false;
1045 $have_photo = false;
1047 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1048 intval($contact['id']),
1049 intval($contact['uid'])
1052 $resource_id = $r[0]['resource-id'];
1056 $resource_id = photo_new_resource();
1059 $img_str = fetch_url($photo_url,true);
1060 $img = new Photo($img_str);
1061 if($img->is_valid()) {
1063 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1064 dbesc($resource_id),
1065 intval($contact['id']),
1066 intval($contact['uid'])
1070 $img->scaleImageSquare(175);
1072 $hash = $resource_id;
1073 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1075 $img->scaleImage(80);
1076 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1078 $img->scaleImage(48);
1079 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1083 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1084 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1085 dbesc(datetime_convert()),
1086 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1087 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1088 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1089 intval($contact['uid']),
1090 intval($contact['id'])
1095 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1096 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1097 dbesc(notags(trim($new_name))),
1098 dbesc(datetime_convert()),
1099 intval($contact['uid']),
1100 intval($contact['id'])
1104 if(strlen($birthday)) {
1105 if(substr($birthday,0,4) != $contact['bdyear']) {
1106 logger('consume_feed: updating birthday: ' . $birthday);
1110 * Add new birthday event for this person
1112 * $bdtext is just a readable placeholder in case the event is shared
1113 * with others. We will replace it during presentation to our $importer
1114 * to contain a sparkle link and perhaps a photo.
1118 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1121 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1122 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1123 intval($contact['uid']),
1124 intval($contact['id']),
1125 dbesc(datetime_convert()),
1126 dbesc(datetime_convert()),
1127 dbesc(datetime_convert('UTC','UTC', $birthday)),
1128 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1136 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1137 dbesc(substr($birthday,0,4)),
1138 intval($contact['uid']),
1139 intval($contact['id'])
1142 // This function is called twice without reloading the contact
1143 // Make sure we only create one event. This is why &$contact
1144 // is a reference var in this function
1146 $contact['bdyear'] = substr($birthday,0,4);
1152 // process any deleted entries
1154 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1155 if(is_array($del_entries) && count($del_entries)) {
1156 foreach($del_entries as $dentry) {
1158 if(isset($dentry['attribs']['']['ref'])) {
1159 $uri = $dentry['attribs']['']['ref'];
1161 if(isset($dentry['attribs']['']['when'])) {
1162 $when = $dentry['attribs']['']['when'];
1163 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1166 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1168 if($deleted && is_array($contact)) {
1169 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1171 intval($importer['uid']),
1172 intval($contact['id'])
1177 if(! $item['deleted'])
1178 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1180 if($item['uri'] == $item['parent-uri']) {
1181 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1182 `body` = '', `title` = ''
1183 WHERE `parent-uri` = '%s' AND `uid` = %d",
1185 dbesc(datetime_convert()),
1186 dbesc($item['uri']),
1187 intval($importer['uid'])
1191 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1192 `body` = '', `title` = ''
1193 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1195 dbesc(datetime_convert()),
1197 intval($importer['uid'])
1199 if($item['last-child']) {
1200 // ensure that last-child is set in case the comment that had it just got wiped.
1201 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1202 dbesc(datetime_convert()),
1203 dbesc($item['parent-uri']),
1204 intval($item['uid'])
1206 // who is the last child now?
1207 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1208 ORDER BY `created` DESC LIMIT 1",
1209 dbesc($item['parent-uri']),
1210 intval($importer['uid'])
1213 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1224 // Now process the feed
1226 if($feed->get_item_quantity()) {
1228 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1230 // in inverse date order
1232 $items = array_reverse($feed->get_items());
1234 $items = $feed->get_items();
1237 foreach($items as $item) {
1240 $item_id = $item->get_id();
1241 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1242 if(isset($rawthread[0]['attribs']['']['ref'])) {
1244 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1247 if(($is_reply) && is_array($contact)) {
1249 // Have we seen it? If not, import it.
1251 $item_id = $item->get_id();
1252 $datarray = get_atom_elements($feed,$item);
1254 if(! x($datarray,'author-name'))
1255 $datarray['author-name'] = $contact['name'];
1256 if(! x($datarray,'author-link'))
1257 $datarray['author-link'] = $contact['url'];
1258 if(! x($datarray,'author-avatar'))
1259 $datarray['author-avatar'] = $contact['thumb'];
1262 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1264 intval($importer['uid'])
1267 // Update content if 'updated' changes
1270 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1271 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1272 dbesc($datarray['body']),
1273 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1275 intval($importer['uid'])
1279 // update last-child if it changes
1281 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1282 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1283 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1284 dbesc(datetime_convert()),
1286 intval($importer['uid'])
1288 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1289 intval($allow[0]['data']),
1290 dbesc(datetime_convert()),
1292 intval($importer['uid'])
1298 $force_parent = false;
1299 if($contact['network'] === 'stat') {
1300 $force_parent = true;
1301 if(strlen($datarray['title']))
1302 unset($datarray['title']);
1303 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1304 dbesc(datetime_convert()),
1306 intval($importer['uid'])
1308 $datarray['last-child'] = 1;
1311 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1312 // one way feed - no remote comment ability
1313 $datarray['last-child'] = 0;
1315 $datarray['parent-uri'] = $parent_uri;
1316 $datarray['uid'] = $importer['uid'];
1317 $datarray['contact-id'] = $contact['id'];
1318 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1319 $datarray['type'] = 'activity';
1320 $datarray['gravity'] = GRAVITY_LIKE;
1323 $r = item_store($datarray,$force_parent);
1329 // Head post of a conversation. Have we seen it? If not, import it.
1331 $item_id = $item->get_id();
1333 $datarray = get_atom_elements($feed,$item);
1335 if(is_array($contact)) {
1336 if(! x($datarray,'author-name'))
1337 $datarray['author-name'] = $contact['name'];
1338 if(! x($datarray,'author-link'))
1339 $datarray['author-link'] = $contact['url'];
1340 if(! x($datarray,'author-avatar'))
1341 $datarray['author-avatar'] = $contact['thumb'];
1344 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1345 $ev = bbtoevent($datarray['body']);
1346 if(x($ev,'desc') && x($ev,'start')) {
1347 $ev['uid'] = $importer['uid'];
1348 $ev['uri'] = $item_id;
1349 $ev['edited'] = $datarray['edited'];
1350 $ev['private'] = $datarray['private'];
1352 if(is_array($contact))
1353 $ev['cid'] = $contact['id'];
1354 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1356 intval($importer['uid'])
1359 $ev['id'] = $r[0]['id'];
1360 $xyz = event_store($ev);
1365 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1367 intval($importer['uid'])
1370 // Update content if 'updated' changes
1373 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1374 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1375 dbesc($datarray['body']),
1376 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1378 intval($importer['uid'])
1382 // update last-child if it changes
1384 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1385 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1386 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1387 intval($allow[0]['data']),
1388 dbesc(datetime_convert()),
1390 intval($importer['uid'])
1396 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1397 logger('consume-feed: New follower');
1398 new_follower($importer,$contact,$datarray,$item);
1401 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1402 lose_follower($importer,$contact,$datarray,$item);
1405 if(! is_array($contact))
1408 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1409 if(strlen($datarray['title']))
1410 unset($datarray['title']);
1411 $datarray['last-child'] = 1;
1414 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1415 // one way feed - no remote comment ability
1416 $datarray['last-child'] = 0;
1419 // This is my contact on another system, but it's really me.
1420 // Turn this into a wall post.
1422 if($contact['remote_self'])
1423 $datarray['wall'] = 1;
1425 $datarray['parent-uri'] = $item_id;
1426 $datarray['uid'] = $importer['uid'];
1427 $datarray['contact-id'] = $contact['id'];
1428 $r = item_store($datarray);
1436 function new_follower($importer,$contact,$datarray,$item) {
1437 $url = notags(trim($datarray['author-link']));
1438 $name = notags(trim($datarray['author-name']));
1439 $photo = notags(trim($datarray['author-avatar']));
1441 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1442 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1443 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1445 if(is_array($contact)) {
1446 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1447 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1449 intval($contact['id']),
1450 intval($importer['uid'])
1454 // send email notification to owner?
1458 // create contact record
1460 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`,
1461 `blocked`, `readonly`, `pending`, `writable` )
1462 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
1463 intval($importer['uid']),
1464 dbesc(datetime_convert()),
1472 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1473 intval($importer['uid']),
1478 $contact_record = $r[0];
1480 // create notification
1481 $hash = random_string();
1483 if(is_array($contact_record)) {
1484 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1485 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1486 intval($importer['uid']),
1487 intval($contact_record['id']),
1489 dbesc(datetime_convert())
1492 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1493 intval($importer['uid'])
1497 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1498 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1499 $email = replace_macros($email_tpl, array(
1500 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1502 '$myname' => $r[0]['username'],
1503 '$siteurl' => $a->get_baseurl(),
1504 '$sitename' => $a->config['sitename']
1506 $res = mail($r[0]['email'],
1507 t("You have a new follower at ") . $a->config['sitename'],
1509 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1510 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1511 . 'Content-transfer-encoding: 8bit' );
1518 function lose_follower($importer,$contact,$datarray,$item) {
1520 if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1521 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1523 intval($contact['id'])
1527 contact_remove($contact['id']);
1532 function subscribe_to_hub($url,$importer,$contact) {
1534 if(is_array($importer)) {
1535 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1536 intval($importer['uid'])
1542 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1544 // Use a single verify token, even if multiple hubs
1546 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1548 $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1550 logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1552 if(! strlen($contact['hub-verify'])) {
1553 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1554 dbesc($verify_token),
1555 intval($contact['id'])
1559 post_url($url,$params);
1565 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1569 $name = xmlify($name);
1570 $uri = xmlify($uri);
1573 $photo = xmlify($photo);
1577 $o .= "<name>$name</name>\r\n";
1578 $o .= "<uri>$uri</uri>\r\n";
1579 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1580 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1582 call_hooks('atom_author', $o);
1584 $o .= "</$tag>\r\n";
1588 function atom_entry($item,$type,$author,$owner,$comment = false) {
1592 if($item['deleted'])
1593 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1596 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1597 $body = fix_private_photos($item['body'],$owner['uid']);
1599 $body = $item['body'];
1602 $o = "\r\n\r\n<entry>\r\n";
1604 if(is_array($author))
1605 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1607 $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']));
1608 if(strlen($item['owner-name']))
1609 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1611 if($item['parent'] != $item['id'])
1612 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1614 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1615 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1616 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1617 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1618 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1619 $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($body) : $body) . '</content>' . "\r\n";
1620 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1622 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1624 if($item['location']) {
1625 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1626 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1630 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1632 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1633 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1636 $o .= '<dfrn:extid>' . $item['extid'] . '</dfrn:extid>' . "\r\n";
1639 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . $item['app'] . '" ></statusnet:notice_info>';
1640 $verb = construct_verb($item);
1641 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1642 $actobj = construct_activity_object($item);
1645 $actarg = construct_activity_target($item);
1649 $tags = item_getfeedtags($item);
1651 foreach($tags as $t) {
1652 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1656 $o .= item_getfeedattach($item);
1658 $mentioned = get_mentions($item);
1662 call_hooks('atom_entry', $o);
1664 $o .= '</entry>' . "\r\n";
1669 function fix_private_photos($s,$uid) {
1671 logger('fix_private_photos');
1673 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
1674 $image = $matches[1];
1675 logger('fix_private_photos: found photo ' . $image);
1676 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1677 $i = basename($image);
1678 $i = str_replace('.jpg','',$i);
1679 $x = strpos($i,'-');
1681 $res = substr($i,$x+1);
1682 $i = substr($i,0,$x);
1683 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1689 logger('replacing photo');
1690 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1693 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1701 function item_getfeedtags($item) {
1704 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1706 for($x = 0; $x < count($matches); $x ++) {
1708 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1712 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1714 for($x = 0; $x < count($matches); $x ++) {
1716 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1722 function item_getfeedattach($item) {
1724 $arr = explode(',',$item['attach']);
1726 foreach($arr as $r) {
1728 $cnt = preg_match('|\[attach\]href=\"(.*?)\" size=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
1730 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1731 if(intval($matches[2]))
1732 $ret .= 'size="' . intval($matches[2]) . '" ';
1733 if($matches[4] !== ' ')
1734 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1735 $ret .= ' />' . "\r\n";
1744 function item_expire($uid,$days) {
1746 if((! $uid) || (! $days))
1749 $r = q("SELECT * FROM `item`
1751 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
1761 logger('expire: # items=' . count($r) );
1763 foreach($r as $item) {
1765 // Only expire posts, not photos and photo comments
1767 if(strlen($item['resource-id']))
1770 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1771 dbesc(datetime_convert()),
1772 dbesc(datetime_convert()),
1778 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1779 dbesc(datetime_convert()),
1780 dbesc(datetime_convert()),
1781 dbesc($item['parent-uri']),
1782 intval($item['uid'])
1787 proc_run('php',"include/notifier.php","expire","$uid");
1792 function drop_items($items) {
1796 foreach($items as $item) {
1797 $owner = drop_item($item,false);
1798 if($owner && ! $uid)
1803 // multiple threads may have been deleted, send an expire notification
1806 proc_run('php',"include/notifier.php","expire","$uid");
1810 function drop_item($id,$interactive = true) {
1814 // locate item to be deleted
1816 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1823 notice( t('Item not found.') . EOL);
1824 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1829 $owner = $item['uid'];
1831 // check if logged in user is either the author or owner of this item
1833 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
1837 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1838 dbesc(datetime_convert()),
1839 dbesc(datetime_convert()),
1843 // If item is a link to a photo resource, nuke all the associated photos
1844 // (visitors will not have photo resources)
1845 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1846 // generate a resource-id and therefore aren't intimately linked to the item.
1848 if(strlen($item['resource-id'])) {
1849 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
1850 dbesc($item['resource-id']),
1851 intval($item['uid'])
1853 // ignore the result
1856 // If item is a link to an event, nuke the event record.
1858 if(intval($item['event-id'])) {
1859 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1860 intval($item['event-id']),
1861 intval($item['uid'])
1863 // ignore the result
1867 // If it's the parent of a comment thread, kill all the kids
1869 if($item['uri'] == $item['parent-uri']) {
1870 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = ''
1871 WHERE `parent-uri` = '%s' AND `uid` = %d ",
1872 dbesc(datetime_convert()),
1873 dbesc(datetime_convert()),
1874 dbesc($item['parent-uri']),
1875 intval($item['uid'])
1877 // ignore the result
1880 // ensure that last-child is set in case the comment that had it just got wiped.
1881 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1882 dbesc(datetime_convert()),
1883 dbesc($item['parent-uri']),
1884 intval($item['uid'])
1886 // who is the last child now?
1887 $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",
1888 dbesc($item['parent-uri']),
1889 intval($item['uid'])
1892 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1897 $drop_id = intval($item['id']);
1899 // send the notification upstream/downstream as the case may be
1904 proc_run('php',"include/notifier.php","drop","$drop_id");
1905 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1911 notice( t('Permission denied.') . EOL);
1912 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);