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) {
10 // default permissions - anonymous user
12 if(! strlen($owner_nick))
15 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
17 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
18 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
19 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
27 $owner_id = $owner['user_uid'];
28 $owner_nick = $owner['nickname'];
30 $birthday = feed_birthday($owner_id,$owner['timezone']);
32 if(strlen($dfrn_id)) {
37 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
41 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
42 $my_id = '1:' . $dfrn_id;
45 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
46 $my_id = '0:' . $dfrn_id;
53 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
61 $groups = init_groups_visitor($contact['id']);
64 for($x = 0; $x < count($groups); $x ++)
65 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
66 $gs = implode('|', $groups);
69 $gs = '<<>>' ; // Impossible to match
71 $sql_extra = sprintf("
72 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
73 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
74 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
75 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
77 intval($contact['id']),
78 intval($contact['id']),
84 if($dfrn_id === '' || $dfrn_id === '*')
89 if(! strlen($last_update))
90 $last_update = 'now -30 days';
92 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
94 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
95 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
96 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
97 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
98 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
99 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
100 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0
101 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
102 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
104 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
111 // Will check further below if this actually returned results.
112 // We will provide an empty feed if that is the case.
116 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
120 $hubxml = feed_hublinks();
122 $salmon = feed_salmonlinks($owner_nick);
124 $atom .= replace_macros($feed_template, array(
125 '$version' => xmlify(FRIENDIKA_VERSION),
126 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
127 '$feed_title' => xmlify($owner['name']),
128 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
130 '$salmon' => $salmon,
131 '$name' => xmlify($owner['name']),
132 '$profile_page' => xmlify($owner['url']),
133 '$photo' => xmlify($owner['photo']),
134 '$thumb' => xmlify($owner['thumb']),
135 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
136 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
137 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
138 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
141 call_hooks('atom_feed', $atom);
143 if(! count($items)) {
145 call_hooks('atom_feed_end', $atom);
147 $atom .= '</feed>' . "\r\n";
151 foreach($items as $item) {
153 // public feeds get html, our own nodes use bbcode
155 if($dfrn_id === '') {
157 // catch any email that's in a public conversation and make sure it doesn't leak
165 $atom .= atom_entry($item,$type,null,$owner,true);
168 call_hooks('atom_feed_end', $atom);
170 $atom .= '</feed>' . "\r\n";
176 function construct_verb($item) {
178 return $item['verb'];
179 return ACTIVITY_POST;
182 function construct_activity_object($item) {
184 if($item['object']) {
185 $o = '<as:object>' . "\r\n";
186 $r = parse_xml_string($item['object'],false);
192 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
194 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
196 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
198 if(substr($r->link,0,1) === '<') {
199 // patch up some facebook "like" activity objects that got stored incorrectly
200 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
201 // we can probably remove this hack here and in the following function in a few months time.
202 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
203 $r->link = str_replace('&','&', $r->link);
204 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
208 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
211 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
212 $o .= '</as:object>' . "\r\n";
219 function construct_activity_target($item) {
221 if($item['target']) {
222 $o = '<as:target>' . "\r\n";
223 $r = parse_xml_string($item['target'],false);
227 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
229 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
231 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
233 if(substr($r->link,0,1) === '<') {
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:target>' . "\r\n";
254 function get_atom_elements($feed,$item) {
256 require_once('library/HTMLPurifier.auto.php');
257 require_once('include/html2bbcode.php');
259 $best_photo = array();
263 $author = $item->get_author();
265 $res['author-name'] = unxmlify($author->get_name());
266 $res['author-link'] = unxmlify($author->get_link());
269 $res['author-name'] = unxmlify($feed->get_title());
270 $res['author-link'] = unxmlify($feed->get_permalink());
272 $res['uri'] = unxmlify($item->get_id());
273 $res['title'] = unxmlify($item->get_title());
274 $res['body'] = unxmlify($item->get_content());
275 $res['plink'] = unxmlify($item->get_link(0));
277 // look for a photo. We should check media size and find the best one,
278 // but for now let's just find any author photo
280 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
282 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
283 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
284 foreach($base as $link) {
285 if(! $res['author-avatar']) {
286 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
287 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
292 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
294 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
295 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
296 if($base && count($base)) {
297 foreach($base as $link) {
298 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
299 $res['author-link'] = unxmlify($link['attribs']['']['href']);
300 if(! $res['author-avatar']) {
301 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
302 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
308 // No photo/profile-link on the item - look at the feed level
310 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
311 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
312 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
313 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
314 foreach($base as $link) {
315 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
316 $res['author-link'] = unxmlify($link['attribs']['']['href']);
317 if(! $res['author-avatar']) {
318 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
319 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
324 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
326 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
327 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
329 if($base && count($base)) {
330 foreach($base as $link) {
331 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
332 $res['author-link'] = unxmlify($link['attribs']['']['href']);
333 if(! (x($res,'author-avatar'))) {
334 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
335 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
342 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
343 if($apps && $apps[0]['attribs']['']['source']) {
344 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
345 if($res['app'] === 'web')
346 $res['app'] = 'OStatus';
350 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
353 $have_real_body = false;
355 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
357 $have_real_body = true;
358 $res['body'] = $rawenv[0]['data'];
359 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
360 // make sure nobody is trying to sneak some html tags by us
361 $res['body'] = notags(base64url_decode($res['body']));
364 $maxlen = get_max_import_size();
365 if($maxlen && (strlen($res['body']) > $maxlen))
366 $res['body'] = substr($res['body'],0, $maxlen);
368 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
369 // the content type. Our own network only emits text normally, though it might have been converted to
370 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
371 // have to assume it is all html and needs to be purified.
373 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
374 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
375 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
378 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
380 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
381 '[youtube]$1[/youtube]', $res['body']);
383 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
384 '[youtube]$1[/youtube]', $res['body']);
386 $res['body'] = oembed_html2bbcode($res['body']);
388 $config = HTMLPurifier_Config::createDefault();
389 $config->set('Cache.DefinitionImpl', null);
391 // we shouldn't need a whitelist, because the bbcode converter
392 // will strip out any unsupported tags.
393 // $config->set('HTML.Allowed', 'p,b,a[href],i');
395 $purifier = new HTMLPurifier($config);
396 $res['body'] = $purifier->purify($res['body']);
398 $res['body'] = html2bbcode($res['body']);
401 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
402 if($allow && $allow[0]['data'] == 1)
403 $res['last-child'] = 1;
405 $res['last-child'] = 0;
407 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
408 if($private && $private[0]['data'] == 1)
413 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
414 if($extid && $extid[0]['data'])
415 $res['extid'] = $extid[0]['data'];
417 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
419 $res['location'] = unxmlify($rawlocation[0]['data']);
422 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
424 $res['created'] = unxmlify($rawcreated[0]['data']);
427 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
429 $res['edited'] = unxmlify($rawedited[0]['data']);
431 if((x($res,'edited')) && (! (x($res,'created'))))
432 $res['created'] = $res['edited'];
434 if(! $res['created'])
435 $res['created'] = $item->get_date('c');
438 $res['edited'] = $item->get_date('c');
441 // Disallow time travelling posts
443 $d1 = strtotime($res['created']);
444 $d2 = strtotime($res['edited']);
445 $d3 = strtotime('now');
448 $res['created'] = datetime_convert();
450 $res['edited'] = datetime_convert();
452 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
453 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
454 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
455 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
456 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
457 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
458 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
459 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
460 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
462 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
463 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
465 foreach($base as $link) {
466 if(! $res['owner-avatar']) {
467 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
468 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
473 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
475 $res['coord'] = unxmlify($rawgeo[0]['data']);
478 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
480 // select between supported verbs
483 $res['verb'] = unxmlify($rawverb[0]['data']);
486 // translate OStatus unfollow to activity streams if it happened to get selected
488 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
489 $res['verb'] = ACTIVITY_UNFOLLOW;
491 $cats = $item->get_categories();
494 foreach($cats as $cat) {
495 $term = $cat->get_term();
497 $term = $cat->get_label();
498 $scheme = $cat->get_scheme();
499 if($scheme && $term && stristr($scheme,'X-DFRN:'))
500 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
502 $tag_arr[] = notags(trim($term));
504 $res['tag'] = implode(',', $tag_arr);
507 $attach = $item->get_enclosures();
510 foreach($attach as $att) {
511 $len = intval($att->get_length());
512 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
513 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
514 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
515 if(strpos($type,';'))
516 $type = substr($type,0,strpos($type,';'));
517 if((! $link) || (strpos($link,'http') !== 0))
523 $type = 'application/octet-stream';
525 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
527 $res['attach'] = implode(',', $att_arr);
530 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
533 $res['object'] = '<object>' . "\n";
534 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
535 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
536 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
538 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
539 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
540 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
541 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
542 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
543 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
544 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
545 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
547 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
548 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
549 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
550 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
552 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
553 '[youtube]$1[/youtube]', $body);
555 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
556 '[youtube]$1[/youtube]', $res['body']);
559 $config = HTMLPurifier_Config::createDefault();
560 $config->set('Cache.DefinitionImpl', null);
562 $purifier = new HTMLPurifier($config);
563 $body = $purifier->purify($body);
564 $body = html2bbcode($body);
567 $res['object'] .= '<content>' . $body . '</content>' . "\n";
570 $res['object'] .= '</object>' . "\n";
573 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
576 $res['target'] = '<target>' . "\n";
577 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
578 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
580 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
581 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
583 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
584 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
585 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
586 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
587 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
588 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
590 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
591 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
592 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
593 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
595 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
596 '[youtube]$1[/youtube]', $body);
598 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
599 '[youtube]$1[/youtube]', $res['body']);
601 $config = HTMLPurifier_Config::createDefault();
602 $config->set('Cache.DefinitionImpl', null);
604 $purifier = new HTMLPurifier($config);
605 $body = $purifier->purify($body);
606 $body = html2bbcode($body);
609 $res['target'] .= '<content>' . $body . '</content>' . "\n";
612 $res['target'] .= '</target>' . "\n";
615 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
617 call_hooks('parse_atom', $arr);
622 function encode_rel_links($links) {
624 if(! ((is_array($links)) && (count($links))))
626 foreach($links as $link) {
628 if($link['attribs']['']['rel'])
629 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
630 if($link['attribs']['']['type'])
631 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
632 if($link['attribs']['']['href'])
633 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
634 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
635 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
636 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
637 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
643 function item_store($arr,$force_parent = false) {
646 $arr['gravity'] = intval($arr['gravity']);
647 elseif($arr['parent-uri'] == $arr['uri'])
649 elseif(activity_match($arr['verb'],ACTIVITY_POST))
652 $arr['gravity'] = 6; // extensible catchall
655 $arr['type'] = 'remote';
657 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
659 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
660 $arr['body'] = strip_tags($arr['body']);
663 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
664 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
665 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
666 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
667 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
668 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
669 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
670 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
671 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
672 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
673 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
674 $arr['received'] = datetime_convert();
675 $arr['changed'] = datetime_convert();
676 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
677 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
678 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
679 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
680 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
682 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
683 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
684 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
685 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
686 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
687 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
688 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
689 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
690 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
691 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
692 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
693 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
694 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
695 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
696 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
697 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
698 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
700 if($arr['parent-uri'] === $arr['uri']) {
702 $allow_cid = $arr['allow_cid'];
703 $allow_gid = $arr['allow_gid'];
704 $deny_cid = $arr['deny_cid'];
705 $deny_gid = $arr['deny_gid'];
709 // find the parent and snarf the item id and ACL's
710 // and anything else we need to inherit
712 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
713 dbesc($arr['parent-uri']),
719 // is the new message multi-level threaded?
720 // even though we don't support it now, preserve the info
721 // and re-attach to the conversation parent.
723 if($r[0]['uri'] != $r[0]['parent-uri']) {
724 $arr['thr-parent'] = $arr['parent-uri'];
725 $arr['parent-uri'] = $r[0]['parent-uri'];
726 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
727 dbesc($r[0]['parent-uri']),
728 dbesc($r[0]['parent-uri']),
735 $parent_id = $r[0]['id'];
736 $parent_deleted = $r[0]['deleted'];
737 $allow_cid = $r[0]['allow_cid'];
738 $allow_gid = $r[0]['allow_gid'];
739 $deny_cid = $r[0]['deny_cid'];
740 $deny_gid = $r[0]['deny_gid'];
741 $arr['wall'] = $r[0]['wall'];
745 // Allow one to see reply tweets from status.net even when
746 // we don't have or can't see the original post.
749 logger('item_store: $force_parent=true, reply converted to top-level post.');
751 $arr['thr-parent'] = $arr['parent-uri'];
752 $arr['parent-uri'] = $arr['uri'];
756 logger('item_store: item parent was not found - ignoring item');
763 call_hooks('post_remote',$arr);
767 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
769 $r = dbq("INSERT INTO `item` (`"
770 . implode("`, `", array_keys($arr))
772 . implode("', '", array_values($arr))
775 // find the item we just created
777 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
778 $arr['uri'], // already dbesc'd
782 // This is not good, but perhaps we encountered a rare race/cache condition, so back off and try again.
784 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
785 $arr['uri'], // already dbesc'd
791 $current_post = $r[0]['id'];
792 logger('item_store: created item ' . $current_post);
795 logger('item_store: could not locate created item');
799 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
800 $parent_id = $current_post;
802 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
805 $private = $arr['private'];
807 // Set parent id - and also make sure to inherit the parent's ACL's.
809 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
810 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
817 intval($parent_deleted),
818 intval($current_post)
822 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
825 if($arr['last-child']) {
826 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
829 intval($current_post)
833 return $current_post;
836 function get_item_contact($item,$contacts) {
837 if(! count($contacts) || (! is_array($item)))
839 foreach($contacts as $contact) {
840 if($contact['id'] == $item['contact-id']) {
849 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
853 if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
856 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
858 if($contact['duplex'] && $contact['dfrn-id'])
859 $idtosend = '0:' . $orig_id;
860 if($contact['duplex'] && $contact['issued-id'])
861 $idtosend = '1:' . $orig_id;
863 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
865 $rino_enable = get_config('system','rino_encrypt');
870 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
872 logger('dfrn_deliver: ' . $url);
874 $xml = fetch_url($url);
876 $curl_stat = $a->get_curl_code();
878 return(-1); // timed out
880 logger('dfrn_deliver: ' . $xml);
885 if(strpos($xml,'<?xml') === false) {
886 logger('dfrn_deliver: no valid XML returned');
887 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
891 $res = parse_xml_string($xml);
893 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
894 return (($res->status) ? $res->status : 3);
897 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
898 $challenge = hex2bin((string) $res->challenge);
899 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
900 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
905 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
906 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
907 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
910 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
911 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
914 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
916 if(strpos($final_dfrn_id,':') == 1)
917 $final_dfrn_id = substr($final_dfrn_id,2);
919 if($final_dfrn_id != $orig_id) {
920 logger('dfrn_deliver: wrong dfrn_id.');
921 // did not decode properly - cannot trust this site
925 $postvars['dfrn_id'] = $idtosend;
926 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
928 $postvars['dissolve'] = '1';
931 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
932 $postvars['data'] = $atom;
933 $postvars['perm'] = 'rw';
936 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
937 $postvars['perm'] = 'r';
940 if($rino && $rino_allowed && (! $dissolve)) {
941 $key = substr(random_string(),0,16);
942 $data = bin2hex(aes_encrypt($postvars['data'],$key));
943 $postvars['data'] = $data;
944 logger('rino: sent key = ' . $key);
947 if($dfrn_version >= 2.1) {
948 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
949 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
952 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
956 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
957 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
960 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
964 logger('md5 rawkey ' . md5($postvars['key']));
966 $postvars['key'] = bin2hex($postvars['key']);
969 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
971 $xml = post_url($contact['notify'],$postvars);
973 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
975 $curl_stat = $a->get_curl_code();
976 if((! $curl_stat) || (! strlen($xml)))
977 return(-1); // timed out
979 if(strpos($xml,'<?xml') === false) {
980 logger('dfrn_deliver: phase 2: no valid XML returned');
981 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
985 $res = parse_xml_string($xml);
993 * consume_feed - process atom feed and update anything/everything we might need to update
995 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
997 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
998 * It is this person's stuff that is going to be updated.
999 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1000 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1001 * have a contact record.
1002 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1003 * might not) try and subscribe to it.
1007 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
1009 require_once('library/simplepie/simplepie.inc');
1011 if(! strlen($xml)) {
1012 logger('consume_feed: empty input');
1016 $feed = new SimplePie();
1017 $feed->set_raw_data($xml);
1019 $feed->enable_order_by_date(true);
1021 $feed->enable_order_by_date(false);
1025 logger('consume_feed: Error parsing XML: ' . $feed->error());
1027 $permalink = $feed->get_permalink();
1029 // Check at the feed level for updated contact name and/or photo
1033 $photo_timestamp = '';
1037 $hubs = $feed->get_links('hub');
1040 $hub = implode(',', $hubs);
1042 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1044 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1046 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1047 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1048 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1049 $new_name = $elems['name'][0]['data'];
1051 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1052 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1053 $photo_url = $elems['link'][0]['attribs']['']['href'];
1056 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1057 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1061 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1062 logger('consume_feed: Updating photo for ' . $contact['name']);
1063 require_once("Photo.php");
1064 $photo_failure = false;
1065 $have_photo = false;
1067 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1068 intval($contact['id']),
1069 intval($contact['uid'])
1072 $resource_id = $r[0]['resource-id'];
1076 $resource_id = photo_new_resource();
1079 $img_str = fetch_url($photo_url,true);
1080 $img = new Photo($img_str);
1081 if($img->is_valid()) {
1083 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1084 dbesc($resource_id),
1085 intval($contact['id']),
1086 intval($contact['uid'])
1090 $img->scaleImageSquare(175);
1092 $hash = $resource_id;
1093 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1095 $img->scaleImage(80);
1096 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1098 $img->scaleImage(48);
1099 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1103 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1104 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1105 dbesc(datetime_convert()),
1106 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1107 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1108 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1109 intval($contact['uid']),
1110 intval($contact['id'])
1115 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1116 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1117 dbesc(notags(trim($new_name))),
1118 dbesc(datetime_convert()),
1119 intval($contact['uid']),
1120 intval($contact['id'])
1124 if(strlen($birthday)) {
1125 if(substr($birthday,0,4) != $contact['bdyear']) {
1126 logger('consume_feed: updating birthday: ' . $birthday);
1130 * Add new birthday event for this person
1132 * $bdtext is just a readable placeholder in case the event is shared
1133 * with others. We will replace it during presentation to our $importer
1134 * to contain a sparkle link and perhaps a photo.
1138 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1141 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1142 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1143 intval($contact['uid']),
1144 intval($contact['id']),
1145 dbesc(datetime_convert()),
1146 dbesc(datetime_convert()),
1147 dbesc(datetime_convert('UTC','UTC', $birthday)),
1148 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1156 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1157 dbesc(substr($birthday,0,4)),
1158 intval($contact['uid']),
1159 intval($contact['id'])
1162 // This function is called twice without reloading the contact
1163 // Make sure we only create one event. This is why &$contact
1164 // is a reference var in this function
1166 $contact['bdyear'] = substr($birthday,0,4);
1172 // process any deleted entries
1174 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1175 if(is_array($del_entries) && count($del_entries)) {
1176 foreach($del_entries as $dentry) {
1178 if(isset($dentry['attribs']['']['ref'])) {
1179 $uri = $dentry['attribs']['']['ref'];
1181 if(isset($dentry['attribs']['']['when'])) {
1182 $when = $dentry['attribs']['']['when'];
1183 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1186 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1188 if($deleted && is_array($contact)) {
1189 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1191 intval($importer['uid']),
1192 intval($contact['id'])
1197 if(! $item['deleted'])
1198 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1200 if($item['uri'] == $item['parent-uri']) {
1201 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1202 `body` = '', `title` = ''
1203 WHERE `parent-uri` = '%s' AND `uid` = %d",
1205 dbesc(datetime_convert()),
1206 dbesc($item['uri']),
1207 intval($importer['uid'])
1211 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1212 `body` = '', `title` = ''
1213 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1215 dbesc(datetime_convert()),
1217 intval($importer['uid'])
1219 if($item['last-child']) {
1220 // ensure that last-child is set in case the comment that had it just got wiped.
1221 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1222 dbesc(datetime_convert()),
1223 dbesc($item['parent-uri']),
1224 intval($item['uid'])
1226 // who is the last child now?
1227 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1228 ORDER BY `created` DESC LIMIT 1",
1229 dbesc($item['parent-uri']),
1230 intval($importer['uid'])
1233 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1244 // Now process the feed
1246 if($feed->get_item_quantity()) {
1248 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1250 // in inverse date order
1252 $items = array_reverse($feed->get_items());
1254 $items = $feed->get_items();
1257 foreach($items as $item) {
1260 $item_id = $item->get_id();
1261 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1262 if(isset($rawthread[0]['attribs']['']['ref'])) {
1264 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1267 if(($is_reply) && is_array($contact)) {
1269 // Have we seen it? If not, import it.
1271 $item_id = $item->get_id();
1272 $datarray = get_atom_elements($feed,$item);
1274 if(! x($datarray,'author-name'))
1275 $datarray['author-name'] = $contact['name'];
1276 if(! x($datarray,'author-link'))
1277 $datarray['author-link'] = $contact['url'];
1278 if(! x($datarray,'author-avatar'))
1279 $datarray['author-avatar'] = $contact['thumb'];
1282 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1284 intval($importer['uid'])
1287 // Update content if 'updated' changes
1290 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1291 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1292 dbesc($datarray['body']),
1293 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1295 intval($importer['uid'])
1299 // update last-child if it changes
1301 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1302 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
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 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1309 intval($allow[0]['data']),
1310 dbesc(datetime_convert()),
1312 intval($importer['uid'])
1318 $force_parent = false;
1319 if($contact['network'] === 'stat') {
1320 $force_parent = true;
1321 if(strlen($datarray['title']))
1322 unset($datarray['title']);
1323 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1324 dbesc(datetime_convert()),
1326 intval($importer['uid'])
1328 $datarray['last-child'] = 1;
1331 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1332 // one way feed - no remote comment ability
1333 $datarray['last-child'] = 0;
1335 $datarray['parent-uri'] = $parent_uri;
1336 $datarray['uid'] = $importer['uid'];
1337 $datarray['contact-id'] = $contact['id'];
1338 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1339 $datarray['type'] = 'activity';
1340 $datarray['gravity'] = GRAVITY_LIKE;
1343 $r = item_store($datarray,$force_parent);
1349 // Head post of a conversation. Have we seen it? If not, import it.
1351 $item_id = $item->get_id();
1353 $datarray = get_atom_elements($feed,$item);
1355 if(is_array($contact)) {
1356 if(! x($datarray,'author-name'))
1357 $datarray['author-name'] = $contact['name'];
1358 if(! x($datarray,'author-link'))
1359 $datarray['author-link'] = $contact['url'];
1360 if(! x($datarray,'author-avatar'))
1361 $datarray['author-avatar'] = $contact['thumb'];
1364 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1365 $ev = bbtoevent($datarray['body']);
1366 if(x($ev,'desc') && x($ev,'start')) {
1367 $ev['uid'] = $importer['uid'];
1368 $ev['uri'] = $item_id;
1369 $ev['edited'] = $datarray['edited'];
1370 $ev['private'] = $datarray['private'];
1372 if(is_array($contact))
1373 $ev['cid'] = $contact['id'];
1374 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1376 intval($importer['uid'])
1379 $ev['id'] = $r[0]['id'];
1380 $xyz = event_store($ev);
1385 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1387 intval($importer['uid'])
1390 // Update content if 'updated' changes
1393 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1394 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1395 dbesc($datarray['body']),
1396 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1398 intval($importer['uid'])
1402 // update last-child if it changes
1404 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1405 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1406 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1407 intval($allow[0]['data']),
1408 dbesc(datetime_convert()),
1410 intval($importer['uid'])
1416 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1417 logger('consume-feed: New follower');
1418 new_follower($importer,$contact,$datarray,$item);
1421 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1422 lose_follower($importer,$contact,$datarray,$item);
1425 if(! is_array($contact))
1428 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1429 if(strlen($datarray['title']))
1430 unset($datarray['title']);
1431 $datarray['last-child'] = 1;
1434 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1435 // one way feed - no remote comment ability
1436 $datarray['last-child'] = 0;
1439 // This is my contact on another system, but it's really me.
1440 // Turn this into a wall post.
1442 if($contact['remote_self'])
1443 $datarray['wall'] = 1;
1445 $datarray['parent-uri'] = $item_id;
1446 $datarray['uid'] = $importer['uid'];
1447 $datarray['contact-id'] = $contact['id'];
1448 $r = item_store($datarray);
1456 function new_follower($importer,$contact,$datarray,$item) {
1457 $url = notags(trim($datarray['author-link']));
1458 $name = notags(trim($datarray['author-name']));
1459 $photo = notags(trim($datarray['author-avatar']));
1461 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1462 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1463 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1465 if(is_array($contact)) {
1466 if($contact['network'] == 'stat' && $contact['rel'] == CONTACT_IS_SHARING) {
1467 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1468 intval(CONTACT_IS_FRIEND),
1469 intval($contact['id']),
1470 intval($importer['uid'])
1474 // send email notification to owner?
1478 // create contact record
1480 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`,
1481 `blocked`, `readonly`, `pending`, `writable` )
1482 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
1483 intval($importer['uid']),
1484 dbesc(datetime_convert()),
1490 intval(CONTACT_IS_FOLLOWER)
1492 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1493 intval($importer['uid']),
1495 intval(CONTACT_IS_FOLLOWER)
1498 $contact_record = $r[0];
1500 // create notification
1501 $hash = random_string();
1503 if(is_array($contact_record)) {
1504 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1505 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1506 intval($importer['uid']),
1507 intval($contact_record['id']),
1509 dbesc(datetime_convert())
1512 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1513 intval($importer['uid'])
1517 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1518 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1519 $email = replace_macros($email_tpl, array(
1520 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1522 '$myname' => $r[0]['username'],
1523 '$siteurl' => $a->get_baseurl(),
1524 '$sitename' => $a->config['sitename']
1526 $res = mail($r[0]['email'],
1527 t("You have a new follower at ") . $a->config['sitename'],
1529 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1530 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1531 . 'Content-transfer-encoding: 8bit' );
1538 function lose_follower($importer,$contact,$datarray,$item) {
1540 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1541 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1542 intval(CONTACT_IS_SHARING),
1543 intval($contact['id'])
1547 contact_remove($contact['id']);
1552 function subscribe_to_hub($url,$importer,$contact) {
1554 if(is_array($importer)) {
1555 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1556 intval($importer['uid'])
1562 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1564 // Use a single verify token, even if multiple hubs
1566 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1568 $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1570 logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1572 if(! strlen($contact['hub-verify'])) {
1573 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1574 dbesc($verify_token),
1575 intval($contact['id'])
1579 post_url($url,$params);
1585 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1589 $name = xmlify($name);
1590 $uri = xmlify($uri);
1593 $photo = xmlify($photo);
1597 $o .= "<name>$name</name>\r\n";
1598 $o .= "<uri>$uri</uri>\r\n";
1599 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1600 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1602 call_hooks('atom_author', $o);
1604 $o .= "</$tag>\r\n";
1608 function atom_entry($item,$type,$author,$owner,$comment = false) {
1612 if($item['deleted'])
1613 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1616 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1617 $body = fix_private_photos($item['body'],$owner['uid']);
1619 $body = $item['body'];
1622 $o = "\r\n\r\n<entry>\r\n";
1624 if(is_array($author))
1625 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1627 $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']));
1628 if(strlen($item['owner-name']))
1629 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1631 if($item['parent'] != $item['id'])
1632 $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";
1634 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1635 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1636 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1637 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1638 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1639 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
1640 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1642 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1644 if($item['location']) {
1645 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1646 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1650 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1652 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1653 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1656 $o .= '<dfrn:extid>' . $item['extid'] . '</dfrn:extid>' . "\r\n";
1659 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . $item['app'] . '" ></statusnet:notice_info>';
1660 $verb = construct_verb($item);
1661 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1662 $actobj = construct_activity_object($item);
1665 $actarg = construct_activity_target($item);
1669 $tags = item_getfeedtags($item);
1671 foreach($tags as $t) {
1672 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1676 $o .= item_getfeedattach($item);
1678 $mentioned = get_mentions($item);
1682 call_hooks('atom_entry', $o);
1684 $o .= '</entry>' . "\r\n";
1689 function fix_private_photos($s,$uid) {
1691 logger('fix_private_photos');
1693 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
1694 $image = $matches[1];
1695 logger('fix_private_photos: found photo ' . $image);
1696 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1697 $i = basename($image);
1698 $i = str_replace('.jpg','',$i);
1699 $x = strpos($i,'-');
1701 $res = substr($i,$x+1);
1702 $i = substr($i,0,$x);
1703 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1709 logger('replacing photo');
1710 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1713 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1721 function item_getfeedtags($item) {
1724 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1726 for($x = 0; $x < count($matches); $x ++) {
1728 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1732 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1734 for($x = 0; $x < count($matches); $x ++) {
1736 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1742 function item_getfeedattach($item) {
1744 $arr = explode(',',$item['attach']);
1746 foreach($arr as $r) {
1748 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
1750 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1751 if(intval($matches[2]))
1752 $ret .= 'length="' . intval($matches[2]) . '" ';
1753 if($matches[4] !== ' ')
1754 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1755 $ret .= ' />' . "\r\n";
1764 function item_expire($uid,$days) {
1766 if((! $uid) || (! $days))
1769 $r = q("SELECT * FROM `item`
1771 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
1781 logger('expire: # items=' . count($r) );
1783 foreach($r as $item) {
1785 // Only expire posts, not photos and photo comments
1787 if(strlen($item['resource-id']))
1790 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1791 dbesc(datetime_convert()),
1792 dbesc(datetime_convert()),
1798 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1799 dbesc(datetime_convert()),
1800 dbesc(datetime_convert()),
1801 dbesc($item['parent-uri']),
1802 intval($item['uid'])
1807 proc_run('php',"include/notifier.php","expire","$uid");
1812 function drop_items($items) {
1816 foreach($items as $item) {
1817 $owner = drop_item($item,false);
1818 if($owner && ! $uid)
1823 // multiple threads may have been deleted, send an expire notification
1826 proc_run('php',"include/notifier.php","expire","$uid");
1830 function drop_item($id,$interactive = true) {
1834 // locate item to be deleted
1836 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1843 notice( t('Item not found.') . EOL);
1844 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1849 $owner = $item['uid'];
1851 // check if logged in user is either the author or owner of this item
1853 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
1857 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1858 dbesc(datetime_convert()),
1859 dbesc(datetime_convert()),
1863 // If item is a link to a photo resource, nuke all the associated photos
1864 // (visitors will not have photo resources)
1865 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1866 // generate a resource-id and therefore aren't intimately linked to the item.
1868 if(strlen($item['resource-id'])) {
1869 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
1870 dbesc($item['resource-id']),
1871 intval($item['uid'])
1873 // ignore the result
1876 // If item is a link to an event, nuke the event record.
1878 if(intval($item['event-id'])) {
1879 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1880 intval($item['event-id']),
1881 intval($item['uid'])
1883 // ignore the result
1887 // If it's the parent of a comment thread, kill all the kids
1889 if($item['uri'] == $item['parent-uri']) {
1890 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = ''
1891 WHERE `parent-uri` = '%s' AND `uid` = %d ",
1892 dbesc(datetime_convert()),
1893 dbesc(datetime_convert()),
1894 dbesc($item['parent-uri']),
1895 intval($item['uid'])
1897 // ignore the result
1900 // ensure that last-child is set in case the comment that had it just got wiped.
1901 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1902 dbesc(datetime_convert()),
1903 dbesc($item['parent-uri']),
1904 intval($item['uid'])
1906 // who is the last child now?
1907 $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",
1908 dbesc($item['parent-uri']),
1909 intval($item['uid'])
1912 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1917 $drop_id = intval($item['id']);
1919 // send the notification upstream/downstream as the case may be
1924 proc_run('php',"include/notifier.php","drop","$drop_id");
1925 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1931 notice( t('Permission denied.') . EOL);
1932 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);