3 require_once('bbcode.php');
4 require_once('oembed.php');
5 require_once('include/salmon.php');
7 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
9 // default permissions - anonymous user
11 if(! strlen($owner_nick))
14 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
16 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
17 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
18 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
26 $owner_id = $owner['user_uid'];
27 $owner_nick = $owner['nickname'];
29 $birthday = feed_birthday($owner_id,$owner['timezone']);
31 if(strlen($dfrn_id)) {
36 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
40 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
41 $my_id = '1:' . $dfrn_id;
44 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
45 $my_id = '0:' . $dfrn_id;
52 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
60 $groups = init_groups_visitor($contact['id']);
63 for($x = 0; $x < count($groups); $x ++)
64 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
65 $gs = implode('|', $groups);
68 $gs = '<<>>' ; // Impossible to match
70 $sql_extra = sprintf("
71 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
72 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
73 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
74 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
76 intval($contact['id']),
77 intval($contact['id']),
83 if($dfrn_id === '' || $dfrn_id === '*')
88 if(! strlen($last_update))
89 $last_update = 'now -30 days';
91 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
93 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
94 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
95 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
96 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
97 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
98 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
99 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0
100 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
101 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
103 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
110 // Will check further below if this actually returned results.
111 // We will provide an empty feed if that is the case.
115 $feed_template = get_markup_template('atom_feed.tpl');
119 $hubxml = feed_hublinks();
121 $salmon = feed_salmonlinks($owner_nick);
123 $atom .= replace_macros($feed_template, array(
124 '$version' => xmlify(FRIENDIKA_VERSION),
125 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
126 '$feed_title' => xmlify($owner['name']),
127 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
129 '$salmon' => $salmon,
130 '$name' => xmlify($owner['name']),
131 '$profile_page' => xmlify($owner['url']),
132 '$photo' => xmlify($owner['photo']),
133 '$thumb' => xmlify($owner['thumb']),
134 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
135 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
136 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
137 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
140 call_hooks('atom_feed', $atom);
142 if(! count($items)) {
144 call_hooks('atom_feed_end', $atom);
146 $atom .= '</feed>' . "\r\n";
150 foreach($items as $item) {
152 // public feeds get html, our own nodes use bbcode
154 if($dfrn_id === '') {
161 $atom .= atom_entry($item,$type,null,$owner,true);
164 call_hooks('atom_feed_end', $atom);
166 $atom .= '</feed>' . "\r\n";
172 function construct_verb($item) {
174 return $item['verb'];
175 return ACTIVITY_POST;
178 function construct_activity_object($item) {
180 if($item['object']) {
181 $o = '<as:object>' . "\r\n";
182 $r = parse_xml_string($item['object'],false);
188 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
190 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
192 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
194 if(substr($r->link,0,1) === '<') {
195 // patch up some facebook "like" activity objects that got stored incorrectly
196 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
197 // we can probably remove this hack here and in the following function in a few months time.
198 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
199 $r->link = str_replace('&','&', $r->link);
200 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
204 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
207 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
208 $o .= '</as:object>' . "\r\n";
215 function construct_activity_target($item) {
217 if($item['target']) {
218 $o = '<as:target>' . "\r\n";
219 $r = parse_xml_string($item['target'],false);
223 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
225 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
227 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
229 if(substr($r->link,0,1) === '<') {
230 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
231 $r->link = str_replace('&','&', $r->link);
232 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
236 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
239 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
240 $o .= '</as:target>' . "\r\n";
250 function get_atom_elements($feed,$item) {
252 require_once('library/HTMLPurifier.auto.php');
253 require_once('include/html2bbcode.php');
255 $best_photo = array();
259 $author = $item->get_author();
261 $res['author-name'] = unxmlify($author->get_name());
262 $res['author-link'] = unxmlify($author->get_link());
265 $res['author-name'] = unxmlify($feed->get_title());
266 $res['author-link'] = unxmlify($feed->get_permalink());
268 $res['uri'] = unxmlify($item->get_id());
269 $res['title'] = unxmlify($item->get_title());
270 $res['body'] = unxmlify($item->get_content());
271 $res['plink'] = unxmlify($item->get_link(0));
273 // look for a photo. We should check media size and find the best one,
274 // but for now let's just find any author photo
276 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
278 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
279 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
280 foreach($base as $link) {
281 if(! $res['author-avatar']) {
282 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
283 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
288 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
290 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
291 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
292 if($base && count($base)) {
293 foreach($base as $link) {
294 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
295 $res['author-link'] = unxmlify($link['attribs']['']['href']);
296 if(! $res['author-avatar']) {
297 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
298 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
304 // No photo/profile-link on the item - look at the feed level
306 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
307 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
308 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
309 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
310 foreach($base as $link) {
311 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
312 $res['author-link'] = unxmlify($link['attribs']['']['href']);
313 if(! $res['author-avatar']) {
314 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
315 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
320 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
322 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
323 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
325 if($base && count($base)) {
326 foreach($base as $link) {
327 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
328 $res['author-link'] = unxmlify($link['attribs']['']['href']);
329 if(! (x($res,'author-avatar'))) {
330 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
331 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
338 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
339 if($apps && $apps[0]['attribs']['']['source']) {
340 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
341 if($res['app'] === 'web')
342 $res['app'] = 'OStatus';
346 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
349 $have_real_body = false;
351 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
353 $have_real_body = true;
354 $res['body'] = $rawenv[0]['data'];
355 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
356 // make sure nobody is trying to sneak some html tags by us
357 $res['body'] = notags(base64url_decode($res['body']));
360 $maxlen = get_max_import_size();
361 if($maxlen && (strlen($res['body']) > $maxlen))
362 $res['body'] = substr($res['body'],0, $maxlen);
364 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
365 // the content type. Our own network only emits text normally, though it might have been converted to
366 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
367 // have to assume it is all html and needs to be purified.
369 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
370 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
371 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
374 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
376 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
377 '[youtube]$1[/youtube]', $res['body']);
379 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
380 '[youtube]$1[/youtube]', $res['body']);
382 $res['body'] = oembed_html2bbcode($res['body']);
384 $config = HTMLPurifier_Config::createDefault();
385 $config->set('Cache.DefinitionImpl', null);
387 // we shouldn't need a whitelist, because the bbcode converter
388 // will strip out any unsupported tags.
389 // $config->set('HTML.Allowed', 'p,b,a[href],i');
391 $purifier = new HTMLPurifier($config);
392 $res['body'] = $purifier->purify($res['body']);
394 $res['body'] = html2bbcode($res['body']);
397 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
398 if($allow && $allow[0]['data'] == 1)
399 $res['last-child'] = 1;
401 $res['last-child'] = 0;
403 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
404 if($private && $private[0]['data'] == 1)
409 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
410 if($extid && $extid[0]['data'])
411 $res['extid'] = $extid[0]['data'];
413 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
415 $res['location'] = unxmlify($rawlocation[0]['data']);
418 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
420 $res['created'] = unxmlify($rawcreated[0]['data']);
423 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
425 $res['edited'] = unxmlify($rawedited[0]['data']);
427 if((x($res,'edited')) && (! (x($res,'created'))))
428 $res['created'] = $res['edited'];
430 if(! $res['created'])
431 $res['created'] = $item->get_date('c');
434 $res['edited'] = $item->get_date('c');
437 // Disallow time travelling posts
439 $d1 = strtotime($res['created']);
440 $d2 = strtotime($res['edited']);
441 $d3 = strtotime('now');
444 $res['created'] = datetime_convert();
446 $res['edited'] = datetime_convert();
448 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
449 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
450 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
451 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
452 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
453 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
454 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
455 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
456 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
458 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
459 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
461 foreach($base as $link) {
462 if(! $res['owner-avatar']) {
463 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
464 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
469 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
471 $res['coord'] = unxmlify($rawgeo[0]['data']);
474 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
476 // select between supported verbs
479 $res['verb'] = unxmlify($rawverb[0]['data']);
482 // translate OStatus unfollow to activity streams if it happened to get selected
484 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
485 $res['verb'] = ACTIVITY_UNFOLLOW;
487 $cats = $item->get_categories();
490 foreach($cats as $cat) {
491 $term = $cat->get_term();
493 $term = $cat->get_label();
494 $scheme = $cat->get_scheme();
495 if($scheme && $term && stristr($scheme,'X-DFRN:'))
496 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
498 $tag_arr[] = notags(trim($term));
500 $res['tag'] = implode(',', $tag_arr);
503 $attach = $item->get_enclosures();
506 foreach($attach as $att) {
507 $len = intval($att->get_length());
508 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
509 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
510 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
511 if(strpos($type,';'))
512 $type = substr($type,0,strpos($type,';'));
513 if((! $link) || (strpos($link,'http') !== 0))
519 $type = 'application/octet-stream';
521 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
523 $res['attach'] = implode(',', $att_arr);
526 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
529 $res['object'] = '<object>' . "\n";
530 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
531 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
532 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
534 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
535 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
536 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
537 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
538 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
539 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
540 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
541 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
543 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
544 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
545 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
546 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
548 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
549 '[youtube]$1[/youtube]', $body);
551 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
552 '[youtube]$1[/youtube]', $res['body']);
555 $config = HTMLPurifier_Config::createDefault();
556 $config->set('Cache.DefinitionImpl', null);
558 $purifier = new HTMLPurifier($config);
559 $body = $purifier->purify($body);
560 $body = html2bbcode($body);
563 $res['object'] .= '<content>' . $body . '</content>' . "\n";
566 $res['object'] .= '</object>' . "\n";
569 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
572 $res['target'] = '<target>' . "\n";
573 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
574 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
576 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
577 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
579 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
580 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
581 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
582 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
583 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
584 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
586 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
587 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
588 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
589 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
591 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
592 '[youtube]$1[/youtube]', $body);
594 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
595 '[youtube]$1[/youtube]', $res['body']);
597 $config = HTMLPurifier_Config::createDefault();
598 $config->set('Cache.DefinitionImpl', null);
600 $purifier = new HTMLPurifier($config);
601 $body = $purifier->purify($body);
602 $body = html2bbcode($body);
605 $res['target'] .= '<content>' . $body . '</content>' . "\n";
608 $res['target'] .= '</target>' . "\n";
611 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
613 call_hooks('parse_atom', $arr);
618 function encode_rel_links($links) {
620 if(! ((is_array($links)) && (count($links))))
622 foreach($links as $link) {
624 if($link['attribs']['']['rel'])
625 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
626 if($link['attribs']['']['type'])
627 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
628 if($link['attribs']['']['href'])
629 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
630 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
631 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
632 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
633 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
639 function item_store($arr,$force_parent = false) {
642 $arr['gravity'] = intval($arr['gravity']);
643 elseif($arr['parent-uri'] == $arr['uri'])
645 elseif(activity_match($arr['verb'],ACTIVITY_POST))
648 $arr['gravity'] = 6; // extensible catchall
651 $arr['type'] = 'remote';
653 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
655 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
656 $arr['body'] = strip_tags($arr['body']);
659 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
660 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
661 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
662 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
663 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
664 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
665 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
666 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
667 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
668 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
669 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
670 $arr['received'] = datetime_convert();
671 $arr['changed'] = datetime_convert();
672 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
673 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
674 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
675 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
676 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
678 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
679 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
680 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
681 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
682 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
683 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
684 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
685 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
686 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
687 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
688 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
689 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
690 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
691 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
692 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
693 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
695 if($arr['parent-uri'] === $arr['uri']) {
697 $allow_cid = $arr['allow_cid'];
698 $allow_gid = $arr['allow_gid'];
699 $deny_cid = $arr['deny_cid'];
700 $deny_gid = $arr['deny_gid'];
704 // find the parent and snarf the item id and ACL's
705 // and anything else we need to inherit
707 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
708 dbesc($arr['parent-uri']),
714 // is the new message multi-level threaded?
715 // even though we don't support it now, preserve the info
716 // and re-attach to the conversation parent.
718 if($r[0]['uri'] != $r[0]['parent-uri']) {
719 $arr['thr-parent'] = $arr['parent-uri'];
720 $arr['parent-uri'] = $r[0]['parent-uri'];
723 $parent_id = $r[0]['id'];
724 $parent_deleted = $r[0]['deleted'];
725 $allow_cid = $r[0]['allow_cid'];
726 $allow_gid = $r[0]['allow_gid'];
727 $deny_cid = $r[0]['deny_cid'];
728 $deny_gid = $r[0]['deny_gid'];
729 $arr['wall'] = $r[0]['wall'];
733 // Allow one to see reply tweets from status.net even when
734 // we don't have or can't see the original post.
737 logger('item_store: $force_parent=true, reply converted to top-level post.');
739 $arr['thr-parent'] = $arr['parent-uri'];
740 $arr['parent-uri'] = $arr['uri'];
744 logger('item_store: item parent was not found - ignoring item');
750 $arr['guid'] = get_guid();
752 call_hooks('post_remote',$arr);
756 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
758 $r = dbq("INSERT INTO `item` (`"
759 . implode("`, `", array_keys($arr))
761 . implode("', '", array_values($arr))
764 // find the item we just created
766 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
767 $arr['uri'], // already dbesc'd
771 // This is not good, but perhaps we encountered a rare race/cache condition, so back off and try again.
773 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
774 $arr['uri'], // already dbesc'd
780 $current_post = $r[0]['id'];
781 logger('item_store: created item ' . $current_post);
784 logger('item_store: could not locate created item');
788 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
789 $parent_id = $current_post;
791 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
794 $private = $arr['private'];
796 // Set parent id - and also make sure to inherit the parent's ACL's.
798 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
799 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
806 intval($parent_deleted),
807 intval($current_post)
811 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
814 if($arr['last-child']) {
815 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
818 intval($current_post)
822 return $current_post;
825 function get_item_contact($item,$contacts) {
826 if(! count($contacts) || (! is_array($item)))
828 foreach($contacts as $contact) {
829 if($contact['id'] == $item['contact-id']) {
838 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
842 if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
845 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
847 if($contact['duplex'] && $contact['dfrn-id'])
848 $idtosend = '0:' . $orig_id;
849 if($contact['duplex'] && $contact['issued-id'])
850 $idtosend = '1:' . $orig_id;
852 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
854 $rino_enable = get_config('system','rino_encrypt');
859 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
861 logger('dfrn_deliver: ' . $url);
863 $xml = fetch_url($url);
865 $curl_stat = $a->get_curl_code();
867 return(-1); // timed out
869 logger('dfrn_deliver: ' . $xml);
874 if(strpos($xml,'<?xml') === false) {
875 logger('dfrn_deliver: no valid XML returned');
876 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
880 $res = parse_xml_string($xml);
882 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
883 return (($res->status) ? $res->status : 3);
886 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
887 $challenge = hex2bin((string) $res->challenge);
888 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
889 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
894 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
895 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
896 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
899 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
900 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
903 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
905 if(strpos($final_dfrn_id,':') == 1)
906 $final_dfrn_id = substr($final_dfrn_id,2);
908 if($final_dfrn_id != $orig_id) {
909 logger('dfrn_deliver: wrong dfrn_id.');
910 // did not decode properly - cannot trust this site
914 $postvars['dfrn_id'] = $idtosend;
915 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
917 $postvars['dissolve'] = '1';
920 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
921 $postvars['data'] = $atom;
922 $postvars['perm'] = 'rw';
925 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
926 $postvars['perm'] = 'r';
929 if($rino && $rino_allowed && (! $dissolve)) {
930 $key = substr(random_string(),0,16);
931 $data = bin2hex(aes_encrypt($postvars['data'],$key));
932 $postvars['data'] = $data;
933 logger('rino: sent key = ' . $key);
936 if($dfrn_version >= 2.1) {
937 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
938 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
941 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
945 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
946 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
949 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
953 logger('md5 rawkey ' . md5($postvars['key']));
955 $postvars['key'] = bin2hex($postvars['key']);
958 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
960 $xml = post_url($contact['notify'],$postvars);
962 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
964 $curl_stat = $a->get_curl_code();
965 if((! $curl_stat) || (! strlen($xml)))
966 return(-1); // timed out
968 if(strpos($xml,'<?xml') === false) {
969 logger('dfrn_deliver: phase 2: no valid XML returned');
970 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
974 $res = parse_xml_string($xml);
982 * consume_feed - process atom feed and update anything/everything we might need to update
984 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
986 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
987 * It is this person's stuff that is going to be updated.
988 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
989 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
990 * have a contact record.
991 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
992 * might not) try and subscribe to it.
996 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
998 require_once('library/simplepie/simplepie.inc');
1000 if(! strlen($xml)) {
1001 logger('consume_feed: empty input');
1005 $feed = new SimplePie();
1006 $feed->set_raw_data($xml);
1008 $feed->enable_order_by_date(true);
1010 $feed->enable_order_by_date(false);
1014 logger('consume_feed: Error parsing XML: ' . $feed->error());
1016 $permalink = $feed->get_permalink();
1018 // Check at the feed level for updated contact name and/or photo
1022 $photo_timestamp = '';
1026 $hubs = $feed->get_links('hub');
1029 $hub = implode(',', $hubs);
1031 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1033 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1034 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1035 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1036 $new_name = $elems['name'][0]['data'];
1038 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1039 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1040 $photo_url = $elems['link'][0]['attribs']['']['href'];
1043 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1044 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1048 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1049 logger('consume_feed: Updating photo for ' . $contact['name']);
1050 require_once("Photo.php");
1051 $photo_failure = false;
1052 $have_photo = false;
1054 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1055 intval($contact['id']),
1056 intval($contact['uid'])
1059 $resource_id = $r[0]['resource-id'];
1063 $resource_id = photo_new_resource();
1066 $img_str = fetch_url($photo_url,true);
1067 $img = new Photo($img_str);
1068 if($img->is_valid()) {
1070 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1071 dbesc($resource_id),
1072 intval($contact['id']),
1073 intval($contact['uid'])
1077 $img->scaleImageSquare(175);
1079 $hash = $resource_id;
1080 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1082 $img->scaleImage(80);
1083 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1085 $img->scaleImage(48);
1086 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1090 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1091 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1092 dbesc(datetime_convert()),
1093 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1094 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1095 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1096 intval($contact['uid']),
1097 intval($contact['id'])
1102 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1103 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1104 dbesc(notags(trim($new_name))),
1105 dbesc(datetime_convert()),
1106 intval($contact['uid']),
1107 intval($contact['id'])
1111 if(strlen($birthday)) {
1112 if(substr($birthday,0,4) != $contact['bdyear']) {
1113 logger('consume_feed: updating birthday: ' . $birthday);
1117 * Add new birthday event for this person
1119 * $bdtext is just a readable placeholder in case the event is shared
1120 * with others. We will replace it during presentation to our $importer
1121 * to contain a sparkle link and perhaps a photo.
1125 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1128 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1129 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1130 intval($contact['uid']),
1131 intval($contact['id']),
1132 dbesc(datetime_convert()),
1133 dbesc(datetime_convert()),
1134 dbesc(datetime_convert('UTC','UTC', $birthday)),
1135 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1143 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1144 dbesc(substr($birthday,0,4)),
1145 intval($contact['uid']),
1146 intval($contact['id'])
1149 // This function is called twice without reloading the contact
1150 // Make sure we only create one event. This is why &$contact
1151 // is a reference var in this function
1153 $contact['bdyear'] = substr($birthday,0,4);
1159 // process any deleted entries
1161 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1162 if(is_array($del_entries) && count($del_entries)) {
1163 foreach($del_entries as $dentry) {
1165 if(isset($dentry['attribs']['']['ref'])) {
1166 $uri = $dentry['attribs']['']['ref'];
1168 if(isset($dentry['attribs']['']['when'])) {
1169 $when = $dentry['attribs']['']['when'];
1170 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1173 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1175 if($deleted && is_array($contact)) {
1176 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1178 intval($importer['uid']),
1179 intval($contact['id'])
1184 if(! $item['deleted'])
1185 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1187 if($item['uri'] == $item['parent-uri']) {
1188 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1189 `body` = '', `title` = ''
1190 WHERE `parent-uri` = '%s' AND `uid` = %d",
1192 dbesc(datetime_convert()),
1193 dbesc($item['uri']),
1194 intval($importer['uid'])
1198 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1199 `body` = '', `title` = ''
1200 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1202 dbesc(datetime_convert()),
1204 intval($importer['uid'])
1206 if($item['last-child']) {
1207 // ensure that last-child is set in case the comment that had it just got wiped.
1208 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1209 dbesc(datetime_convert()),
1210 dbesc($item['parent-uri']),
1211 intval($item['uid'])
1213 // who is the last child now?
1214 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1215 ORDER BY `created` DESC LIMIT 1",
1216 dbesc($item['parent-uri']),
1217 intval($importer['uid'])
1220 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1231 // Now process the feed
1233 if($feed->get_item_quantity()) {
1235 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1237 // in inverse date order
1239 $items = array_reverse($feed->get_items());
1241 $items = $feed->get_items();
1244 foreach($items as $item) {
1247 $item_id = $item->get_id();
1248 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1249 if(isset($rawthread[0]['attribs']['']['ref'])) {
1251 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1254 if(($is_reply) && is_array($contact)) {
1256 // Have we seen it? If not, import it.
1258 $item_id = $item->get_id();
1259 $datarray = get_atom_elements($feed,$item);
1261 if(! x($datarray,'author-name'))
1262 $datarray['author-name'] = $contact['name'];
1263 if(! x($datarray,'author-link'))
1264 $datarray['author-link'] = $contact['url'];
1265 if(! x($datarray,'author-avatar'))
1266 $datarray['author-avatar'] = $contact['thumb'];
1269 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1271 intval($importer['uid'])
1274 // Update content if 'updated' changes
1277 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1278 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1279 dbesc($datarray['body']),
1280 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1282 intval($importer['uid'])
1286 // update last-child if it changes
1288 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1289 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1290 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1291 dbesc(datetime_convert()),
1293 intval($importer['uid'])
1295 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1296 intval($allow[0]['data']),
1297 dbesc(datetime_convert()),
1299 intval($importer['uid'])
1305 $force_parent = false;
1306 if($contact['network'] === 'stat') {
1307 $force_parent = true;
1308 if(strlen($datarray['title']))
1309 unset($datarray['title']);
1310 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1311 dbesc(datetime_convert()),
1313 intval($importer['uid'])
1315 $datarray['last-child'] = 1;
1318 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1319 // one way feed - no remote comment ability
1320 $datarray['last-child'] = 0;
1322 $datarray['parent-uri'] = $parent_uri;
1323 $datarray['uid'] = $importer['uid'];
1324 $datarray['contact-id'] = $contact['id'];
1325 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1326 $datarray['type'] = 'activity';
1327 $datarray['gravity'] = GRAVITY_LIKE;
1330 $r = item_store($datarray,$force_parent);
1336 // Head post of a conversation. Have we seen it? If not, import it.
1338 $item_id = $item->get_id();
1340 $datarray = get_atom_elements($feed,$item);
1342 if(is_array($contact)) {
1343 if(! x($datarray,'author-name'))
1344 $datarray['author-name'] = $contact['name'];
1345 if(! x($datarray,'author-link'))
1346 $datarray['author-link'] = $contact['url'];
1347 if(! x($datarray,'author-avatar'))
1348 $datarray['author-avatar'] = $contact['thumb'];
1351 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1352 $ev = bbtoevent($datarray['body']);
1353 if(x($ev,'desc') && x($ev,'start')) {
1354 $ev['uid'] = $importer['uid'];
1355 $ev['uri'] = $item_id;
1356 $ev['edited'] = $datarray['edited'];
1357 $ev['private'] = $datarray['private'];
1359 if(is_array($contact))
1360 $ev['cid'] = $contact['id'];
1361 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1363 intval($importer['uid'])
1366 $ev['id'] = $r[0]['id'];
1367 $xyz = event_store($ev);
1372 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1374 intval($importer['uid'])
1377 // Update content if 'updated' changes
1380 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1381 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1382 dbesc($datarray['body']),
1383 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1385 intval($importer['uid'])
1389 // update last-child if it changes
1391 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1392 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1393 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1394 intval($allow[0]['data']),
1395 dbesc(datetime_convert()),
1397 intval($importer['uid'])
1403 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1404 logger('consume-feed: New follower');
1405 new_follower($importer,$contact,$datarray,$item);
1408 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1409 lose_follower($importer,$contact,$datarray,$item);
1412 if(! is_array($contact))
1415 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1416 if(strlen($datarray['title']))
1417 unset($datarray['title']);
1418 $datarray['last-child'] = 1;
1421 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1422 // one way feed - no remote comment ability
1423 $datarray['last-child'] = 0;
1426 // This is my contact on another system, but it's really me.
1427 // Turn this into a wall post.
1429 if($contact['remote_self'])
1430 $datarray['wall'] = 1;
1432 $datarray['parent-uri'] = $item_id;
1433 $datarray['uid'] = $importer['uid'];
1434 $datarray['contact-id'] = $contact['id'];
1435 $r = item_store($datarray);
1443 function new_follower($importer,$contact,$datarray,$item) {
1444 $url = notags(trim($datarray['author-link']));
1445 $name = notags(trim($datarray['author-name']));
1446 $photo = notags(trim($datarray['author-avatar']));
1448 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1449 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1450 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1452 if(is_array($contact)) {
1453 if($contact['network'] == 'stat' && $contact['rel'] == CONTACT_IS_SHARING) {
1454 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1455 intval(CONTACT_IS_FRIEND),
1456 intval($contact['id']),
1457 intval($importer['uid'])
1461 // send email notification to owner?
1465 // create contact record
1467 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`,
1468 `blocked`, `readonly`, `pending`, `writable` )
1469 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
1470 intval($importer['uid']),
1471 dbesc(datetime_convert()),
1477 intval(CONTACT_IS_FOLLOWER)
1479 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1480 intval($importer['uid']),
1482 intval(CONTACT_IS_FOLLOWER)
1485 $contact_record = $r[0];
1487 // create notification
1488 $hash = random_string();
1490 if(is_array($contact_record)) {
1491 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1492 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1493 intval($importer['uid']),
1494 intval($contact_record['id']),
1496 dbesc(datetime_convert())
1499 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1500 intval($importer['uid'])
1504 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1505 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1506 $email = replace_macros($email_tpl, array(
1507 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1509 '$myname' => $r[0]['username'],
1510 '$siteurl' => $a->get_baseurl(),
1511 '$sitename' => $a->config['sitename']
1513 $res = mail($r[0]['email'],
1514 t("You have a new follower at ") . $a->config['sitename'],
1516 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1517 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1518 . 'Content-transfer-encoding: 8bit' );
1525 function lose_follower($importer,$contact,$datarray,$item) {
1527 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
1528 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1529 intval(CONTACT_IS_SHARING),
1530 intval($contact['id'])
1534 contact_remove($contact['id']);
1539 function subscribe_to_hub($url,$importer,$contact) {
1541 if(is_array($importer)) {
1542 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1543 intval($importer['uid'])
1549 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1551 // Use a single verify token, even if multiple hubs
1553 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1555 $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1557 logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1559 if(! strlen($contact['hub-verify'])) {
1560 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1561 dbesc($verify_token),
1562 intval($contact['id'])
1566 post_url($url,$params);
1572 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1576 $name = xmlify($name);
1577 $uri = xmlify($uri);
1580 $photo = xmlify($photo);
1584 $o .= "<name>$name</name>\r\n";
1585 $o .= "<uri>$uri</uri>\r\n";
1586 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1587 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1589 call_hooks('atom_author', $o);
1591 $o .= "</$tag>\r\n";
1595 function atom_entry($item,$type,$author,$owner,$comment = false) {
1599 if($item['deleted'])
1600 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1603 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1604 $body = fix_private_photos($item['body'],$owner['uid']);
1606 $body = $item['body'];
1609 $o = "\r\n\r\n<entry>\r\n";
1611 if(is_array($author))
1612 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1614 $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']));
1615 if(strlen($item['owner-name']))
1616 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1618 if($item['parent'] != $item['id'])
1619 $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";
1621 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1622 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1623 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1624 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1625 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1626 $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($body) : $body) . '</content>' . "\r\n";
1627 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1629 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1631 if($item['location']) {
1632 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1633 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1637 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1639 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1640 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1643 $o .= '<dfrn:extid>' . $item['extid'] . '</dfrn:extid>' . "\r\n";
1646 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . $item['app'] . '" ></statusnet:notice_info>';
1647 $verb = construct_verb($item);
1648 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1649 $actobj = construct_activity_object($item);
1652 $actarg = construct_activity_target($item);
1656 $tags = item_getfeedtags($item);
1658 foreach($tags as $t) {
1659 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1663 $o .= item_getfeedattach($item);
1665 $mentioned = get_mentions($item);
1669 call_hooks('atom_entry', $o);
1671 $o .= '</entry>' . "\r\n";
1676 function fix_private_photos($s,$uid) {
1678 logger('fix_private_photos');
1680 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
1681 $image = $matches[1];
1682 logger('fix_private_photos: found photo ' . $image);
1683 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1684 $i = basename($image);
1685 $i = str_replace('.jpg','',$i);
1686 $x = strpos($i,'-');
1688 $res = substr($i,$x+1);
1689 $i = substr($i,0,$x);
1690 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1696 logger('replacing photo');
1697 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1700 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1708 function item_getfeedtags($item) {
1711 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1713 for($x = 0; $x < count($matches); $x ++) {
1715 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1719 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
1721 for($x = 0; $x < count($matches); $x ++) {
1723 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1729 function item_getfeedattach($item) {
1731 $arr = explode(',',$item['attach']);
1733 foreach($arr as $r) {
1735 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
1737 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1738 if(intval($matches[2]))
1739 $ret .= 'length="' . intval($matches[2]) . '" ';
1740 if($matches[4] !== ' ')
1741 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1742 $ret .= ' />' . "\r\n";
1751 function item_expire($uid,$days) {
1753 if((! $uid) || (! $days))
1756 $r = q("SELECT * FROM `item`
1758 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
1768 logger('expire: # items=' . count($r) );
1770 foreach($r as $item) {
1772 // Only expire posts, not photos and photo comments
1774 if(strlen($item['resource-id']))
1777 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1778 dbesc(datetime_convert()),
1779 dbesc(datetime_convert()),
1785 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1786 dbesc(datetime_convert()),
1787 dbesc(datetime_convert()),
1788 dbesc($item['parent-uri']),
1789 intval($item['uid'])
1794 proc_run('php',"include/notifier.php","expire","$uid");
1799 function drop_items($items) {
1803 foreach($items as $item) {
1804 $owner = drop_item($item,false);
1805 if($owner && ! $uid)
1810 // multiple threads may have been deleted, send an expire notification
1813 proc_run('php',"include/notifier.php","expire","$uid");
1817 function drop_item($id,$interactive = true) {
1821 // locate item to be deleted
1823 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
1830 notice( t('Item not found.') . EOL);
1831 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1836 $owner = $item['uid'];
1838 // check if logged in user is either the author or owner of this item
1840 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
1844 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1845 dbesc(datetime_convert()),
1846 dbesc(datetime_convert()),
1850 // If item is a link to a photo resource, nuke all the associated photos
1851 // (visitors will not have photo resources)
1852 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1853 // generate a resource-id and therefore aren't intimately linked to the item.
1855 if(strlen($item['resource-id'])) {
1856 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
1857 dbesc($item['resource-id']),
1858 intval($item['uid'])
1860 // ignore the result
1863 // If item is a link to an event, nuke the event record.
1865 if(intval($item['event-id'])) {
1866 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1867 intval($item['event-id']),
1868 intval($item['uid'])
1870 // ignore the result
1874 // If it's the parent of a comment thread, kill all the kids
1876 if($item['uri'] == $item['parent-uri']) {
1877 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = ''
1878 WHERE `parent-uri` = '%s' AND `uid` = %d ",
1879 dbesc(datetime_convert()),
1880 dbesc(datetime_convert()),
1881 dbesc($item['parent-uri']),
1882 intval($item['uid'])
1884 // ignore the result
1887 // ensure that last-child is set in case the comment that had it just got wiped.
1888 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1889 dbesc(datetime_convert()),
1890 dbesc($item['parent-uri']),
1891 intval($item['uid'])
1893 // who is the last child now?
1894 $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",
1895 dbesc($item['parent-uri']),
1896 intval($item['uid'])
1899 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1904 $drop_id = intval($item['id']);
1906 // send the notification upstream/downstream as the case may be
1911 proc_run('php',"include/notifier.php","drop","$drop_id");
1912 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
1918 notice( t('Permission denied.') . EOL);
1919 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);