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 $public_feed = (($dfrn_id) ? false : true);
19 if($public_feed && $a->argc > 2) {
20 for($x = 2; $x < $a->argc; $x++) {
21 if($a->argv[$x] == 'converse')
27 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
29 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
30 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
31 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
39 $owner_id = $owner['user_uid'];
40 $owner_nick = $owner['nickname'];
42 $birthday = feed_birthday($owner_id,$owner['timezone']);
49 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
53 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
54 $my_id = '1:' . $dfrn_id;
57 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
58 $my_id = '0:' . $dfrn_id;
65 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
73 $groups = init_groups_visitor($contact['id']);
76 for($x = 0; $x < count($groups); $x ++)
77 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
78 $gs = implode('|', $groups);
81 $gs = '<<>>' ; // Impossible to match
83 $sql_extra = sprintf("
84 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
85 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
86 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
87 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
89 intval($contact['id']),
90 intval($contact['id']),
101 if(! strlen($last_update))
102 $last_update = 'now -30 days';
106 $sql_extra .= " AND `contact`.`self` = 1 ";
109 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
111 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
112 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
113 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
114 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
115 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
116 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
117 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0
118 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
119 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
121 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
128 // Will check further below if this actually returned results.
129 // We will provide an empty feed if that is the case.
133 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
137 $hubxml = feed_hublinks();
139 $salmon = feed_salmonlinks($owner_nick);
141 $atom .= replace_macros($feed_template, array(
142 '$version' => xmlify(FRIENDIKA_VERSION),
143 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
144 '$feed_title' => xmlify($owner['name']),
145 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
147 '$salmon' => $salmon,
148 '$name' => xmlify($owner['name']),
149 '$profile_page' => xmlify($owner['url']),
150 '$photo' => xmlify($owner['photo']),
151 '$thumb' => xmlify($owner['thumb']),
152 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
153 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
154 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
155 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
158 call_hooks('atom_feed', $atom);
160 if(! count($items)) {
162 call_hooks('atom_feed_end', $atom);
164 $atom .= '</feed>' . "\r\n";
168 foreach($items as $item) {
170 // public feeds get html, our own nodes use bbcode
174 // catch any email that's in a public conversation and make sure it doesn't leak
182 $atom .= atom_entry($item,$type,null,$owner,true);
185 call_hooks('atom_feed_end', $atom);
187 $atom .= '</feed>' . "\r\n";
193 function construct_verb($item) {
195 return $item['verb'];
196 return ACTIVITY_POST;
199 function construct_activity_object($item) {
201 if($item['object']) {
202 $o = '<as:object>' . "\r\n";
203 $r = parse_xml_string($item['object'],false);
209 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
211 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
213 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
215 if(substr($r->link,0,1) === '<') {
216 // patch up some facebook "like" activity objects that got stored incorrectly
217 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
218 // we can probably remove this hack here and in the following function in a few months time.
219 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
220 $r->link = str_replace('&','&', $r->link);
221 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
225 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
228 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
229 $o .= '</as:object>' . "\r\n";
236 function construct_activity_target($item) {
238 if($item['target']) {
239 $o = '<as:target>' . "\r\n";
240 $r = parse_xml_string($item['target'],false);
244 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
246 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
248 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
250 if(substr($r->link,0,1) === '<') {
251 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
252 $r->link = str_replace('&','&', $r->link);
253 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
257 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
260 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
261 $o .= '</as:target>' . "\r\n";
271 function get_atom_elements($feed,$item) {
273 require_once('library/HTMLPurifier.auto.php');
274 require_once('include/html2bbcode.php');
276 $best_photo = array();
280 $author = $item->get_author();
282 $res['author-name'] = unxmlify($author->get_name());
283 $res['author-link'] = unxmlify($author->get_link());
286 $res['author-name'] = unxmlify($feed->get_title());
287 $res['author-link'] = unxmlify($feed->get_permalink());
289 $res['uri'] = unxmlify($item->get_id());
290 $res['title'] = unxmlify($item->get_title());
291 $res['body'] = unxmlify($item->get_content());
292 $res['plink'] = unxmlify($item->get_link(0));
294 // look for a photo. We should check media size and find the best one,
295 // but for now let's just find any author photo
297 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
299 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
300 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
301 foreach($base as $link) {
302 if(! $res['author-avatar']) {
303 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
304 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
309 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
311 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
312 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
313 if($base && count($base)) {
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'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
319 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
325 // No photo/profile-link on the item - look at the feed level
327 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
328 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
329 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
330 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
331 foreach($base as $link) {
332 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
333 $res['author-link'] = unxmlify($link['attribs']['']['href']);
334 if(! $res['author-avatar']) {
335 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
336 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
341 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
343 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
344 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
346 if($base && count($base)) {
347 foreach($base as $link) {
348 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
349 $res['author-link'] = unxmlify($link['attribs']['']['href']);
350 if(! (x($res,'author-avatar'))) {
351 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
352 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
359 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
360 if($apps && $apps[0]['attribs']['']['source']) {
361 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
362 if($res['app'] === 'web')
363 $res['app'] = 'OStatus';
367 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
370 $have_real_body = false;
372 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
374 $have_real_body = true;
375 $res['body'] = $rawenv[0]['data'];
376 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
377 // make sure nobody is trying to sneak some html tags by us
378 $res['body'] = notags(base64url_decode($res['body']));
381 $maxlen = get_max_import_size();
382 if($maxlen && (strlen($res['body']) > $maxlen))
383 $res['body'] = substr($res['body'],0, $maxlen);
385 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
386 // the content type. Our own network only emits text normally, though it might have been converted to
387 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
388 // have to assume it is all html and needs to be purified.
390 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
391 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
392 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
395 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
397 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
398 '[youtube]$1[/youtube]', $res['body']);
400 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
401 '[youtube]$1[/youtube]', $res['body']);
403 $res['body'] = oembed_html2bbcode($res['body']);
405 $config = HTMLPurifier_Config::createDefault();
406 $config->set('Cache.DefinitionImpl', null);
408 // we shouldn't need a whitelist, because the bbcode converter
409 // will strip out any unsupported tags.
410 // $config->set('HTML.Allowed', 'p,b,a[href],i');
412 $purifier = new HTMLPurifier($config);
413 $res['body'] = $purifier->purify($res['body']);
415 $res['body'] = html2bbcode($res['body']);
418 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
419 if($allow && $allow[0]['data'] == 1)
420 $res['last-child'] = 1;
422 $res['last-child'] = 0;
424 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
425 if($private && $private[0]['data'] == 1)
430 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
431 if($extid && $extid[0]['data'])
432 $res['extid'] = $extid[0]['data'];
434 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
436 $res['location'] = unxmlify($rawlocation[0]['data']);
439 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
441 $res['created'] = unxmlify($rawcreated[0]['data']);
444 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
446 $res['edited'] = unxmlify($rawedited[0]['data']);
448 if((x($res,'edited')) && (! (x($res,'created'))))
449 $res['created'] = $res['edited'];
451 if(! $res['created'])
452 $res['created'] = $item->get_date('c');
455 $res['edited'] = $item->get_date('c');
458 // Disallow time travelling posts
460 $d1 = strtotime($res['created']);
461 $d2 = strtotime($res['edited']);
462 $d3 = strtotime('now');
465 $res['created'] = datetime_convert();
467 $res['edited'] = datetime_convert();
469 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
470 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
471 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
472 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
473 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
474 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
475 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
476 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
477 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
479 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
480 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
482 foreach($base as $link) {
483 if(! $res['owner-avatar']) {
484 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
485 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
490 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
492 $res['coord'] = unxmlify($rawgeo[0]['data']);
495 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
497 // select between supported verbs
500 $res['verb'] = unxmlify($rawverb[0]['data']);
503 // translate OStatus unfollow to activity streams if it happened to get selected
505 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
506 $res['verb'] = ACTIVITY_UNFOLLOW;
508 $cats = $item->get_categories();
511 foreach($cats as $cat) {
512 $term = $cat->get_term();
514 $term = $cat->get_label();
515 $scheme = $cat->get_scheme();
516 if($scheme && $term && stristr($scheme,'X-DFRN:'))
517 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
519 $tag_arr[] = notags(trim($term));
521 $res['tag'] = implode(',', $tag_arr);
524 $attach = $item->get_enclosures();
527 foreach($attach as $att) {
528 $len = intval($att->get_length());
529 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
530 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
531 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
532 if(strpos($type,';'))
533 $type = substr($type,0,strpos($type,';'));
534 if((! $link) || (strpos($link,'http') !== 0))
540 $type = 'application/octet-stream';
542 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
544 $res['attach'] = implode(',', $att_arr);
547 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
550 $res['object'] = '<object>' . "\n";
551 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
552 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
553 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
555 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
556 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
557 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
558 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
559 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
560 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
561 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
562 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
564 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
565 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
566 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
567 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
569 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
570 '[youtube]$1[/youtube]', $body);
572 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
573 '[youtube]$1[/youtube]', $res['body']);
576 $config = HTMLPurifier_Config::createDefault();
577 $config->set('Cache.DefinitionImpl', null);
579 $purifier = new HTMLPurifier($config);
580 $body = $purifier->purify($body);
581 $body = html2bbcode($body);
584 $res['object'] .= '<content>' . $body . '</content>' . "\n";
587 $res['object'] .= '</object>' . "\n";
590 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
593 $res['target'] = '<target>' . "\n";
594 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
595 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
597 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
598 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
600 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
601 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
602 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
603 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
604 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
605 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
607 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
608 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
609 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
610 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
612 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
613 '[youtube]$1[/youtube]', $body);
615 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
616 '[youtube]$1[/youtube]', $res['body']);
618 $config = HTMLPurifier_Config::createDefault();
619 $config->set('Cache.DefinitionImpl', null);
621 $purifier = new HTMLPurifier($config);
622 $body = $purifier->purify($body);
623 $body = html2bbcode($body);
626 $res['target'] .= '<content>' . $body . '</content>' . "\n";
629 $res['target'] .= '</target>' . "\n";
632 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
634 call_hooks('parse_atom', $arr);
639 function encode_rel_links($links) {
641 if(! ((is_array($links)) && (count($links))))
643 foreach($links as $link) {
645 if($link['attribs']['']['rel'])
646 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
647 if($link['attribs']['']['type'])
648 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
649 if($link['attribs']['']['href'])
650 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
651 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
652 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
653 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
654 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
660 function item_store($arr,$force_parent = false) {
663 $arr['gravity'] = intval($arr['gravity']);
664 elseif($arr['parent-uri'] == $arr['uri'])
666 elseif(activity_match($arr['verb'],ACTIVITY_POST))
669 $arr['gravity'] = 6; // extensible catchall
672 $arr['type'] = 'remote';
674 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
676 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
677 $arr['body'] = strip_tags($arr['body']);
680 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
681 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
682 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
683 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
684 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
685 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
686 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
687 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
688 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
689 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
690 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
691 $arr['received'] = datetime_convert();
692 $arr['changed'] = datetime_convert();
693 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
694 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
695 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
696 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
697 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
699 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
700 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
701 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
702 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
703 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
704 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
705 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
706 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
707 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
708 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
709 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
710 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
711 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
712 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
713 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
714 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
715 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
717 if($arr['parent-uri'] === $arr['uri']) {
719 $allow_cid = $arr['allow_cid'];
720 $allow_gid = $arr['allow_gid'];
721 $deny_cid = $arr['deny_cid'];
722 $deny_gid = $arr['deny_gid'];
726 // find the parent and snarf the item id and ACL's
727 // and anything else we need to inherit
729 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
730 dbesc($arr['parent-uri']),
736 // is the new message multi-level threaded?
737 // even though we don't support it now, preserve the info
738 // and re-attach to the conversation parent.
740 if($r[0]['uri'] != $r[0]['parent-uri']) {
741 $arr['thr-parent'] = $arr['parent-uri'];
742 $arr['parent-uri'] = $r[0]['parent-uri'];
743 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d LIMIT 1",
744 dbesc($r[0]['parent-uri']),
745 dbesc($r[0]['parent-uri']),
752 $parent_id = $r[0]['id'];
753 $parent_deleted = $r[0]['deleted'];
754 $allow_cid = $r[0]['allow_cid'];
755 $allow_gid = $r[0]['allow_gid'];
756 $deny_cid = $r[0]['deny_cid'];
757 $deny_gid = $r[0]['deny_gid'];
758 $arr['wall'] = $r[0]['wall'];
762 // Allow one to see reply tweets from status.net even when
763 // we don't have or can't see the original post.
766 logger('item_store: $force_parent=true, reply converted to top-level post.');
768 $arr['thr-parent'] = $arr['parent-uri'];
769 $arr['parent-uri'] = $arr['uri'];
773 logger('item_store: item parent was not found - ignoring item');
780 call_hooks('post_remote',$arr);
784 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
786 $r = dbq("INSERT INTO `item` (`"
787 . implode("`, `", array_keys($arr))
789 . implode("', '", array_values($arr))
792 // find the item we just created
794 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
795 $arr['uri'], // already dbesc'd
799 // This is not good, but perhaps we encountered a rare race/cache condition, so back off and try again.
801 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
802 $arr['uri'], // already dbesc'd
808 $current_post = $r[0]['id'];
809 logger('item_store: created item ' . $current_post);
812 logger('item_store: could not locate created item');
816 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
817 $parent_id = $current_post;
819 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
822 $private = $arr['private'];
824 // Set parent id - and also make sure to inherit the parent's ACL's.
826 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
827 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
834 intval($parent_deleted),
835 intval($current_post)
839 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
842 if($arr['last-child']) {
843 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
846 intval($current_post)
850 return $current_post;
853 function get_item_contact($item,$contacts) {
854 if(! count($contacts) || (! is_array($item)))
856 foreach($contacts as $contact) {
857 if($contact['id'] == $item['contact-id']) {
866 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
870 if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
873 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
875 if($contact['duplex'] && $contact['dfrn-id'])
876 $idtosend = '0:' . $orig_id;
877 if($contact['duplex'] && $contact['issued-id'])
878 $idtosend = '1:' . $orig_id;
880 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
882 $rino_enable = get_config('system','rino_encrypt');
887 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
889 logger('dfrn_deliver: ' . $url);
891 $xml = fetch_url($url);
893 $curl_stat = $a->get_curl_code();
895 return(-1); // timed out
897 logger('dfrn_deliver: ' . $xml);
902 if(strpos($xml,'<?xml') === false) {
903 logger('dfrn_deliver: no valid XML returned');
904 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
908 $res = parse_xml_string($xml);
910 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
911 return (($res->status) ? $res->status : 3);
914 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
915 $challenge = hex2bin((string) $res->challenge);
916 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
917 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
922 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
923 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
924 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
927 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
928 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
931 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
933 if(strpos($final_dfrn_id,':') == 1)
934 $final_dfrn_id = substr($final_dfrn_id,2);
936 if($final_dfrn_id != $orig_id) {
937 logger('dfrn_deliver: wrong dfrn_id.');
938 // did not decode properly - cannot trust this site
942 $postvars['dfrn_id'] = $idtosend;
943 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
945 $postvars['dissolve'] = '1';
948 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
949 $postvars['data'] = $atom;
950 $postvars['perm'] = 'rw';
953 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
954 $postvars['perm'] = 'r';
957 if($rino && $rino_allowed && (! $dissolve)) {
958 $key = substr(random_string(),0,16);
959 $data = bin2hex(aes_encrypt($postvars['data'],$key));
960 $postvars['data'] = $data;
961 logger('rino: sent key = ' . $key);
964 if($dfrn_version >= 2.1) {
965 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
966 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
969 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
973 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
974 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
977 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
981 logger('md5 rawkey ' . md5($postvars['key']));
983 $postvars['key'] = bin2hex($postvars['key']);
986 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
988 $xml = post_url($contact['notify'],$postvars);
990 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
992 $curl_stat = $a->get_curl_code();
993 if((! $curl_stat) || (! strlen($xml)))
994 return(-1); // timed out
996 if(strpos($xml,'<?xml') === false) {
997 logger('dfrn_deliver: phase 2: no valid XML returned');
998 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1002 $res = parse_xml_string($xml);
1004 return $res->status;
1010 * consume_feed - process atom feed and update anything/everything we might need to update
1012 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1014 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1015 * It is this person's stuff that is going to be updated.
1016 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1017 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1018 * have a contact record.
1019 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1020 * might not) try and subscribe to it.
1024 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
1026 require_once('library/simplepie/simplepie.inc');
1028 if(! strlen($xml)) {
1029 logger('consume_feed: empty input');
1033 $feed = new SimplePie();
1034 $feed->set_raw_data($xml);
1036 $feed->enable_order_by_date(true);
1038 $feed->enable_order_by_date(false);
1042 logger('consume_feed: Error parsing XML: ' . $feed->error());
1044 $permalink = $feed->get_permalink();
1046 // Check at the feed level for updated contact name and/or photo
1050 $photo_timestamp = '';
1054 $hubs = $feed->get_links('hub');
1057 $hub = implode(',', $hubs);
1059 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1061 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1063 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1064 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1065 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1066 $new_name = $elems['name'][0]['data'];
1068 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1069 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1070 $photo_url = $elems['link'][0]['attribs']['']['href'];
1073 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1074 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1078 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1079 logger('consume_feed: Updating photo for ' . $contact['name']);
1080 require_once("Photo.php");
1081 $photo_failure = false;
1082 $have_photo = false;
1084 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1085 intval($contact['id']),
1086 intval($contact['uid'])
1089 $resource_id = $r[0]['resource-id'];
1093 $resource_id = photo_new_resource();
1096 $img_str = fetch_url($photo_url,true);
1097 $img = new Photo($img_str);
1098 if($img->is_valid()) {
1100 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1101 dbesc($resource_id),
1102 intval($contact['id']),
1103 intval($contact['uid'])
1107 $img->scaleImageSquare(175);
1109 $hash = $resource_id;
1110 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1112 $img->scaleImage(80);
1113 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1115 $img->scaleImage(48);
1116 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1120 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1121 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1122 dbesc(datetime_convert()),
1123 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1124 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1125 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1126 intval($contact['uid']),
1127 intval($contact['id'])
1132 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1133 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1134 dbesc(notags(trim($new_name))),
1135 dbesc(datetime_convert()),
1136 intval($contact['uid']),
1137 intval($contact['id'])
1141 if(strlen($birthday)) {
1142 if(substr($birthday,0,4) != $contact['bdyear']) {
1143 logger('consume_feed: updating birthday: ' . $birthday);
1147 * Add new birthday event for this person
1149 * $bdtext is just a readable placeholder in case the event is shared
1150 * with others. We will replace it during presentation to our $importer
1151 * to contain a sparkle link and perhaps a photo.
1155 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1158 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1159 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1160 intval($contact['uid']),
1161 intval($contact['id']),
1162 dbesc(datetime_convert()),
1163 dbesc(datetime_convert()),
1164 dbesc(datetime_convert('UTC','UTC', $birthday)),
1165 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1173 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1174 dbesc(substr($birthday,0,4)),
1175 intval($contact['uid']),
1176 intval($contact['id'])
1179 // This function is called twice without reloading the contact
1180 // Make sure we only create one event. This is why &$contact
1181 // is a reference var in this function
1183 $contact['bdyear'] = substr($birthday,0,4);
1189 // process any deleted entries
1191 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1192 if(is_array($del_entries) && count($del_entries)) {
1193 foreach($del_entries as $dentry) {
1195 if(isset($dentry['attribs']['']['ref'])) {
1196 $uri = $dentry['attribs']['']['ref'];
1198 if(isset($dentry['attribs']['']['when'])) {
1199 $when = $dentry['attribs']['']['when'];
1200 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1203 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1205 if($deleted && is_array($contact)) {
1206 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1208 intval($importer['uid']),
1209 intval($contact['id'])
1214 if(! $item['deleted'])
1215 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1217 if($item['uri'] == $item['parent-uri']) {
1218 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1219 `body` = '', `title` = ''
1220 WHERE `parent-uri` = '%s' AND `uid` = %d",
1222 dbesc(datetime_convert()),
1223 dbesc($item['uri']),
1224 intval($importer['uid'])
1228 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1229 `body` = '', `title` = ''
1230 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1232 dbesc(datetime_convert()),
1234 intval($importer['uid'])
1236 if($item['last-child']) {
1237 // ensure that last-child is set in case the comment that had it just got wiped.
1238 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1239 dbesc(datetime_convert()),
1240 dbesc($item['parent-uri']),
1241 intval($item['uid'])
1243 // who is the last child now?
1244 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1245 ORDER BY `created` DESC LIMIT 1",
1246 dbesc($item['parent-uri']),
1247 intval($importer['uid'])
1250 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1261 // Now process the feed
1263 if($feed->get_item_quantity()) {
1265 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1267 // in inverse date order
1269 $items = array_reverse($feed->get_items());
1271 $items = $feed->get_items();
1274 foreach($items as $item) {
1277 $item_id = $item->get_id();
1278 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1279 if(isset($rawthread[0]['attribs']['']['ref'])) {
1281 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1284 if(($is_reply) && is_array($contact)) {
1286 // Have we seen it? If not, import it.
1288 $item_id = $item->get_id();
1289 $datarray = get_atom_elements($feed,$item);
1291 if(! x($datarray,'author-name'))
1292 $datarray['author-name'] = $contact['name'];
1293 if(! x($datarray,'author-link'))
1294 $datarray['author-link'] = $contact['url'];
1295 if(! x($datarray,'author-avatar'))
1296 $datarray['author-avatar'] = $contact['thumb'];
1299 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1301 intval($importer['uid'])
1304 // Update content if 'updated' changes
1307 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1308 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1309 dbesc($datarray['body']),
1310 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1312 intval($importer['uid'])
1316 // update last-child if it changes
1318 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1319 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1320 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1321 dbesc(datetime_convert()),
1323 intval($importer['uid'])
1325 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1326 intval($allow[0]['data']),
1327 dbesc(datetime_convert()),
1329 intval($importer['uid'])
1335 $force_parent = false;
1336 if($contact['network'] === 'stat') {
1337 $force_parent = true;
1338 if(strlen($datarray['title']))
1339 unset($datarray['title']);
1340 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1341 dbesc(datetime_convert()),
1343 intval($importer['uid'])
1345 $datarray['last-child'] = 1;
1348 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1349 // one way feed - no remote comment ability
1350 $datarray['last-child'] = 0;
1352 $datarray['parent-uri'] = $parent_uri;
1353 $datarray['uid'] = $importer['uid'];
1354 $datarray['contact-id'] = $contact['id'];
1355 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1356 $datarray['type'] = 'activity';
1357 $datarray['gravity'] = GRAVITY_LIKE;
1360 $r = item_store($datarray,$force_parent);
1366 // Head post of a conversation. Have we seen it? If not, import it.
1368 $item_id = $item->get_id();
1370 $datarray = get_atom_elements($feed,$item);
1372 if(is_array($contact)) {
1373 if(! x($datarray,'author-name'))
1374 $datarray['author-name'] = $contact['name'];
1375 if(! x($datarray,'author-link'))
1376 $datarray['author-link'] = $contact['url'];
1377 if(! x($datarray,'author-avatar'))
1378 $datarray['author-avatar'] = $contact['thumb'];
1381 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1382 $ev = bbtoevent($datarray['body']);
1383 if(x($ev,'desc') && x($ev,'start')) {
1384 $ev['uid'] = $importer['uid'];
1385 $ev['uri'] = $item_id;
1386 $ev['edited'] = $datarray['edited'];
1387 $ev['private'] = $datarray['private'];
1389 if(is_array($contact))
1390 $ev['cid'] = $contact['id'];
1391 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1393 intval($importer['uid'])
1396 $ev['id'] = $r[0]['id'];
1397 $xyz = event_store($ev);
1402 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1404 intval($importer['uid'])
1407 // Update content if 'updated' changes
1410 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1411 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1412 dbesc($datarray['body']),
1413 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1415 intval($importer['uid'])
1419 // update last-child if it changes
1421 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1422 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1423 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1424 intval($allow[0]['data']),
1425 dbesc(datetime_convert()),
1427 intval($importer['uid'])
1433 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1434 logger('consume-feed: New follower');
1435 new_follower($importer,$contact,$datarray,$item);
1438 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1439 lose_follower($importer,$contact,$datarray,$item);
1442 if(! is_array($contact))
1445 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1446 if(strlen($datarray['title']))
1447 unset($datarray['title']);
1448 $datarray['last-child'] = 1;
1451 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1452 // one way feed - no remote comment ability
1453 $datarray['last-child'] = 0;
1456 // This is my contact on another system, but it's really me.
1457 // Turn this into a wall post.
1459 if($contact['remote_self'])
1460 $datarray['wall'] = 1;
1462 $datarray['parent-uri'] = $item_id;
1463 $datarray['uid'] = $importer['uid'];
1464 $datarray['contact-id'] = $contact['id'];
1465 $r = item_store($datarray);
1473 function new_follower($importer,$contact,$datarray,$item) {
1474 $url = notags(trim($datarray['author-link']));
1475 $name = notags(trim($datarray['author-name']));
1476 $photo = notags(trim($datarray['author-avatar']));
1478 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1479 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1480 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1482 if(is_array($contact)) {
1483 if($contact['network'] == 'stat' && $contact['rel'] == CONTACT_IS_SHARING) {
1484 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1485 intval(CONTACT_IS_FRIEND),
1486 intval($contact['id']),
1487 intval($importer['uid'])
1491 // send email notification to owner?
1495 // create contact record
1497 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`,
1498 `blocked`, `readonly`, `pending`, `writable` )
1499 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
1500 intval($importer['uid']),
1501 dbesc(datetime_convert()),
1507 intval(CONTACT_IS_FOLLOWER)
1509 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1510 intval($importer['uid']),
1512 intval(CONTACT_IS_FOLLOWER)
1515 $contact_record = $r[0];
1517 // create notification
1518 $hash = random_string();
1520 if(is_array($contact_record)) {
1521 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1522 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1523 intval($importer['uid']),
1524 intval($contact_record['id']),
1526 dbesc(datetime_convert())
1529 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1530 intval($importer['uid'])
1534 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1535 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1536 $email = replace_macros($email_tpl, array(
1537 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1539 '$myname' => $r[0]['username'],
1540 '$siteurl' => $a->get_baseurl(),
1541 '$sitename' => $a->config['sitename']
1543 $res = mail($r[0]['email'],
1544 t("You have a new follower at ") . $a->config['sitename'],
1546 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1547 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1548 . 'Content-transfer-encoding: 8bit' );
1555 function lose_follower($importer,$contact,$datarray,$item) {
1557 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1558 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1559 intval(CONTACT_IS_SHARING),
1560 intval($contact['id'])
1564 contact_remove($contact['id']);
1569 function subscribe_to_hub($url,$importer,$contact) {
1571 if(is_array($importer)) {
1572 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1573 intval($importer['uid'])
1576 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
1579 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1581 // Use a single verify token, even if multiple hubs
1583 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1585 $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1587 logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1589 if(! strlen($contact['hub-verify'])) {
1590 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1591 dbesc($verify_token),
1592 intval($contact['id'])
1596 post_url($url,$params);
1602 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1606 $name = xmlify($name);
1607 $uri = xmlify($uri);
1610 $photo = xmlify($photo);
1614 $o .= "<name>$name</name>\r\n";
1615 $o .= "<uri>$uri</uri>\r\n";
1616 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1617 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1619 call_hooks('atom_author', $o);
1621 $o .= "</$tag>\r\n";
1625 function atom_entry($item,$type,$author,$owner,$comment = false) {
1629 if($item['deleted'])
1630 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1633 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1634 $body = fix_private_photos($item['body'],$owner['uid']);
1636 $body = $item['body'];
1639 $o = "\r\n\r\n<entry>\r\n";
1641 if(is_array($author))
1642 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1644 $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']));
1645 if(strlen($item['owner-name']))
1646 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1648 if($item['parent'] != $item['id'])
1649 $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";
1651 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1652 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1653 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1654 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1655 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1656 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
1657 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1659 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1661 if($item['location']) {
1662 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1663 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1667 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1669 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1670 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1673 $o .= '<dfrn:extid>' . $item['extid'] . '</dfrn:extid>' . "\r\n";
1676 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . $item['app'] . '" ></statusnet:notice_info>';
1677 $verb = construct_verb($item);
1678 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1679 $actobj = construct_activity_object($item);
1682 $actarg = construct_activity_target($item);
1686 $tags = item_getfeedtags($item);
1688 foreach($tags as $t) {
1689 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1693 $o .= item_getfeedattach($item);
1695 $mentioned = get_mentions($item);
1699 call_hooks('atom_entry', $o);
1701 $o .= '</entry>' . "\r\n";
1706 function fix_private_photos($s,$uid) {
1708 logger('fix_private_photos');
1710 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
1711 $image = $matches[1];
1712 logger('fix_private_photos: found photo ' . $image);
1713 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1714 $i = basename($image);
1715 $i = str_replace('.jpg','',$i);
1716 $x = strpos($i,'-');
1718 $res = substr($i,$x+1);
1719 $i = substr($i,0,$x);
1720 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1726 logger('replacing photo');
1727 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1730 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1738 function item_getfeedtags($item) {
1741 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1743 for($x = 0; $x < count($matches); $x ++) {
1745 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1749 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1751 for($x = 0; $x < count($matches); $x ++) {
1753 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1759 function item_getfeedattach($item) {
1761 $arr = explode(',',$item['attach']);
1763 foreach($arr as $r) {
1765 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
1767 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1768 if(intval($matches[2]))
1769 $ret .= 'length="' . intval($matches[2]) . '" ';
1770 if($matches[4] !== ' ')
1771 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1772 $ret .= ' />' . "\r\n";
1781 function item_expire($uid,$days) {
1783 if((! $uid) || (! $days))
1786 $r = q("SELECT * FROM `item`
1788 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
1798 logger('expire: # items=' . count($r) );
1800 foreach($r as $item) {
1802 // Only expire posts, not photos and photo comments
1804 if(strlen($item['resource-id']))
1807 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1808 dbesc(datetime_convert()),
1809 dbesc(datetime_convert()),
1815 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1816 dbesc(datetime_convert()),
1817 dbesc(datetime_convert()),
1818 dbesc($item['parent-uri']),
1819 intval($item['uid'])
1824 proc_run('php',"include/notifier.php","expire","$uid");
1829 function drop_items($items) {
1833 foreach($items as $item) {
1834 $owner = drop_item($item,false);
1835 if($owner && ! $uid)
1840 // multiple threads may have been deleted, send an expire notification
1843 proc_run('php',"include/notifier.php","expire","$uid");
1847 function drop_item($id,$interactive = true) {
1851 // locate item to be deleted
1853 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1860 notice( t('Item not found.') . EOL);
1861 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1866 $owner = $item['uid'];
1868 // check if logged in user is either the author or owner of this item
1870 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
1874 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1875 dbesc(datetime_convert()),
1876 dbesc(datetime_convert()),
1880 // If item is a link to a photo resource, nuke all the associated photos
1881 // (visitors will not have photo resources)
1882 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1883 // generate a resource-id and therefore aren't intimately linked to the item.
1885 if(strlen($item['resource-id'])) {
1886 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
1887 dbesc($item['resource-id']),
1888 intval($item['uid'])
1890 // ignore the result
1893 // If item is a link to an event, nuke the event record.
1895 if(intval($item['event-id'])) {
1896 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1897 intval($item['event-id']),
1898 intval($item['uid'])
1900 // ignore the result
1904 // If it's the parent of a comment thread, kill all the kids
1906 if($item['uri'] == $item['parent-uri']) {
1907 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = ''
1908 WHERE `parent-uri` = '%s' AND `uid` = %d ",
1909 dbesc(datetime_convert()),
1910 dbesc(datetime_convert()),
1911 dbesc($item['parent-uri']),
1912 intval($item['uid'])
1914 // ignore the result
1917 // ensure that last-child is set in case the comment that had it just got wiped.
1918 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1919 dbesc(datetime_convert()),
1920 dbesc($item['parent-uri']),
1921 intval($item['uid'])
1923 // who is the last child now?
1924 $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",
1925 dbesc($item['parent-uri']),
1926 intval($item['uid'])
1929 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1934 $drop_id = intval($item['id']);
1936 // send the notification upstream/downstream as the case may be
1941 proc_run('php',"include/notifier.php","drop","$drop_id");
1942 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1948 notice( t('Permission denied.') . EOL);
1949 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);