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) {
10 // default permissions - anonymous user
12 if(! strlen($owner_nick))
15 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
17 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
18 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
19 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
27 $owner_id = $owner['user_uid'];
28 $owner_nick = $owner['nickname'];
30 $birthday = feed_birthday($owner_id,$owner['timezone']);
32 if(strlen($dfrn_id)) {
37 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
41 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
42 $my_id = '1:' . $dfrn_id;
45 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
46 $my_id = '0:' . $dfrn_id;
53 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
61 $groups = init_groups_visitor($contact['id']);
64 for($x = 0; $x < count($groups); $x ++)
65 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
66 $gs = implode('|', $groups);
69 $gs = '<<>>' ; // Impossible to match
71 $sql_extra = sprintf("
72 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
73 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
74 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
75 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
77 intval($contact['id']),
78 intval($contact['id']),
84 if($dfrn_id === '' || $dfrn_id === '*')
89 if(! strlen($last_update))
90 $last_update = 'now -30 days';
92 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
94 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
95 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
96 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
97 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
98 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
99 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
100 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0
101 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
102 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
104 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
111 // Will check further below if this actually returned results.
112 // We will provide an empty feed if that is the case.
116 $feed_template = get_markup_template('atom_feed.tpl');
120 $hubxml = feed_hublinks();
122 $salmon = feed_salmonlinks($owner_nick);
124 $atom .= replace_macros($feed_template, array(
125 '$version' => xmlify(FRIENDIKA_VERSION),
126 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
127 '$feed_title' => xmlify($owner['name']),
128 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
130 '$salmon' => $salmon,
131 '$name' => xmlify($owner['name']),
132 '$profile_page' => xmlify($owner['url']),
133 '$photo' => xmlify($owner['photo']),
134 '$thumb' => xmlify($owner['thumb']),
135 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
136 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
137 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
138 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
141 call_hooks('atom_feed', $atom);
143 if(! count($items)) {
145 call_hooks('atom_feed_end', $atom);
147 $atom .= '</feed>' . "\r\n";
151 foreach($items as $item) {
153 // public feeds get html, our own nodes use bbcode
155 if($dfrn_id === '') {
162 $atom .= atom_entry($item,$type,null,$owner,true);
165 call_hooks('atom_feed_end', $atom);
167 $atom .= '</feed>' . "\r\n";
173 function construct_verb($item) {
175 return $item['verb'];
176 return ACTIVITY_POST;
179 function construct_activity_object($item) {
181 if($item['object']) {
182 $o = '<as:object>' . "\r\n";
183 $r = parse_xml_string($item['object']);
185 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
187 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
189 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
191 if(substr($r->link,0,1) === '<')
194 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
197 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
198 $o .= '</as:object>' . "\r\n";
205 function construct_activity_target($item) {
207 if($item['target']) {
208 $o = '<as:target>' . "\r\n";
209 $r = parse_xml_string($item['target']);
211 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
213 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
215 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
217 if(substr($r->link,0,1) === '<')
220 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
223 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
224 $o .= '</as:target>' . "\r\n";
234 function get_atom_elements($feed,$item) {
236 require_once('library/HTMLPurifier.auto.php');
237 require_once('include/html2bbcode.php');
239 $best_photo = array();
243 $author = $item->get_author();
245 $res['author-name'] = unxmlify($author->get_name());
246 $res['author-link'] = unxmlify($author->get_link());
249 $res['author-name'] = unxmlify($feed->get_title());
250 $res['author-link'] = unxmlify($feed->get_permalink());
252 $res['uri'] = unxmlify($item->get_id());
253 $res['title'] = unxmlify($item->get_title());
254 $res['body'] = unxmlify($item->get_content());
255 $res['plink'] = unxmlify($item->get_link(0));
257 // look for a photo. We should check media size and find the best one,
258 // but for now let's just find any author photo
260 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
262 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
263 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
264 foreach($base as $link) {
265 if(! $res['author-avatar']) {
266 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
267 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
272 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
274 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
275 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
276 if($base && count($base)) {
277 foreach($base as $link) {
278 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
279 $res['author-link'] = unxmlify($link['attribs']['']['href']);
280 if(! $res['author-avatar']) {
281 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
282 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
288 // No photo/profile-link on the item - look at the feed level
290 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
291 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
292 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
293 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
294 foreach($base as $link) {
295 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
296 $res['author-link'] = unxmlify($link['attribs']['']['href']);
297 if(! $res['author-avatar']) {
298 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
299 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
304 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
306 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
307 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
309 if($base && count($base)) {
310 foreach($base as $link) {
311 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
312 $res['author-link'] = unxmlify($link['attribs']['']['href']);
313 if(! (x($res,'author-avatar'))) {
314 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
315 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
324 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
327 $have_real_body = false;
329 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
331 $have_real_body = true;
332 $res['body'] = $rawenv[0]['data'];
333 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
334 // make sure nobody is trying to sneak some html tags by us
335 $res['body'] = notags(base64url_decode($res['body']));
338 $maxlen = get_max_import_size();
339 if($maxlen && (strlen($res['body']) > $maxlen))
340 $res['body'] = substr($res['body'],0, $maxlen);
342 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
343 // the content type. Our own network only emits text normally, though it might have been converted to
344 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
345 // have to assume it is all html and needs to be purified.
347 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
348 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
349 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
352 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
354 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
355 '[youtube]$1[/youtube]', $res['body']);
357 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
358 '[youtube]$1[/youtube]', $res['body']);
360 $res['body'] = oembed_html2bbcode($res['body']);
362 $config = HTMLPurifier_Config::createDefault();
363 $config->set('Cache.DefinitionImpl', null);
365 // we shouldn't need a whitelist, because the bbcode converter
366 // will strip out any unsupported tags.
367 // $config->set('HTML.Allowed', 'p,b,a[href],i');
369 $purifier = new HTMLPurifier($config);
370 $res['body'] = $purifier->purify($res['body']);
372 $res['body'] = html2bbcode($res['body']);
375 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
376 if($allow && $allow[0]['data'] == 1)
377 $res['last-child'] = 1;
379 $res['last-child'] = 0;
381 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
382 if($private && $private[0]['data'] == 1)
387 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
388 if($extid && $extid[0]['data'])
389 $res['extid'] = $extid[0]['data'];
391 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
393 $res['location'] = unxmlify($rawlocation[0]['data']);
396 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
398 $res['created'] = unxmlify($rawcreated[0]['data']);
401 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
403 $res['edited'] = unxmlify($rawedited[0]['data']);
405 if((x($res,'edited')) && (! (x($res,'created'))))
406 $res['created'] = $res['edited'];
408 if(! $res['created'])
409 $res['created'] = $item->get_date('c');
412 $res['edited'] = $item->get_date('c');
415 // Disallow time travelling posts
417 $d1 = strtotime($res['created']);
418 $d2 = strtotime($res['edited']);
419 $d3 = strtotime('now');
422 $res['created'] = datetime_convert();
424 $res['edited'] = datetime_convert();
426 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
427 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
428 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
429 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
430 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
431 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
432 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
433 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
434 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
436 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
437 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
439 foreach($base as $link) {
440 if(! $res['owner-avatar']) {
441 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
442 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
447 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
449 $res['coord'] = unxmlify($rawgeo[0]['data']);
452 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
454 // select between supported verbs
457 $res['verb'] = unxmlify($rawverb[0]['data']);
460 // translate OStatus unfollow to activity streams if it happened to get selected
462 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
463 $res['verb'] = ACTIVITY_UNFOLLOW;
466 $cats = $item->get_categories();
469 foreach($cats as $cat) {
470 $term = $cat->get_term();
472 $term = $cat->get_label();
473 $scheme = $cat->get_scheme();
474 if($scheme && $term && stristr($scheme,'X-DFRN:'))
475 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
477 $tag_arr[] = notags(trim($term));
479 $res['tag'] = implode(',', $tag_arr);
482 $attach = $item->get_enclosures();
485 foreach($attach as $att) {
486 $len = intval($att->get_length());
487 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
488 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
489 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
490 if(strpos($type,';'))
491 $type = substr($type,0,strpos($type,';'));
492 if((! $link) || (strpos($link,'http') !== 0))
498 $type = 'application/octet-stream';
500 $att_arr[] = '[attach]href="' . $link . '" size="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
502 $res['attach'] = implode(',', $att_arr);
505 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
508 $res['object'] = '<object>' . "\n";
509 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
510 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
511 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
513 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
514 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
515 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
516 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
517 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
518 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
519 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
520 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
522 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
523 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
524 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
525 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
527 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
528 '[youtube]$1[/youtube]', $body);
530 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
531 '[youtube]$1[/youtube]', $res['body']);
534 $config = HTMLPurifier_Config::createDefault();
535 $config->set('Cache.DefinitionImpl', null);
537 $purifier = new HTMLPurifier($config);
538 $body = $purifier->purify($body);
539 $body = html2bbcode($body);
542 $res['object'] .= '<content>' . $body . '</content>' . "\n";
545 $res['object'] .= '</object>' . "\n";
548 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
551 $res['target'] = '<target>' . "\n";
552 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
553 $res['target'] .= '<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['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
558 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
559 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
560 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
561 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
562 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
563 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
565 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
566 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
567 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
568 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
570 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
571 '[youtube]$1[/youtube]', $body);
573 $res['body'] = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
574 '[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['target'] .= '<content>' . $body . '</content>' . "\n";
587 $res['target'] .= '</target>' . "\n";
590 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
592 call_hooks('parse_atom', $arr);
597 function encode_rel_links($links) {
599 if(! ((is_array($links)) && (count($links))))
601 foreach($links as $link) {
603 if($link['attribs']['']['rel'])
604 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
605 if($link['attribs']['']['type'])
606 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
607 if($link['attribs']['']['href'])
608 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
609 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
610 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
611 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
612 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
618 function item_store($arr,$force_parent = false) {
621 $arr['gravity'] = intval($arr['gravity']);
622 elseif($arr['parent-uri'] == $arr['uri'])
624 elseif(activity_match($arr['verb'],ACTIVITY_POST))
627 $arr['gravity'] = 6; // extensible catchall
630 $arr['type'] = 'remote';
632 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
634 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
635 $arr['body'] = strip_tags($arr['body']);
638 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
639 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
640 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
641 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
642 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
643 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
644 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
645 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
646 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
647 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
648 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
649 $arr['changed'] = datetime_convert();
650 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
651 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
652 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
653 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
654 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
656 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
657 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
658 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
659 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
660 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
661 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
662 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
663 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
664 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
665 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
666 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
667 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
668 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
669 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
670 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
672 if($arr['parent-uri'] === $arr['uri']) {
674 $allow_cid = $arr['allow_cid'];
675 $allow_gid = $arr['allow_gid'];
676 $deny_cid = $arr['deny_cid'];
677 $deny_gid = $arr['deny_gid'];
681 // find the parent and snarf the item id and ACL's
682 // and anything else we need to inherit
684 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
685 dbesc($arr['parent-uri']),
691 // is the new message multi-level threaded?
692 // even though we don't support it now, preserve the info
693 // and re-attach to the conversation parent.
695 if($r[0]['uri'] != $r[0]['parent-uri']) {
696 $arr['thr-parent'] = $arr['parent-uri'];
697 $arr['parent-uri'] = $r[0]['parent-uri'];
700 $parent_id = $r[0]['id'];
701 $parent_deleted = $r[0]['deleted'];
702 $allow_cid = $r[0]['allow_cid'];
703 $allow_gid = $r[0]['allow_gid'];
704 $deny_cid = $r[0]['deny_cid'];
705 $deny_gid = $r[0]['deny_gid'];
706 $arr['wall'] = $r[0]['wall'];
710 // Allow one to see reply tweets from status.net even when
711 // we don't have or can't see the original post.
714 logger('item_store: $force_parent=true, reply converted to top-level post.');
716 $arr['thr-parent'] = $arr['parent-uri'];
717 $arr['parent-uri'] = $arr['uri'];
721 logger('item_store: item parent was not found - ignoring item');
727 call_hooks('post_remote',$arr);
731 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
733 $r = dbq("INSERT INTO `item` (`"
734 . implode("`, `", array_keys($arr))
736 . implode("', '", array_values($arr))
739 // find the item we just created
741 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
742 $arr['uri'], // already dbesc'd
746 // This is not good, but perhaps we encountered a rare race/cache condition, so back off and try again.
748 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
749 $arr['uri'], // already dbesc'd
755 $current_post = $r[0]['id'];
756 logger('item_store: created item ' . $current_post);
759 logger('item_store: could not locate created item');
763 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
764 $parent_id = $current_post;
766 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
769 $private = $arr['private'];
771 // Set parent id - and also make sure to inherit the parent's ACL's.
773 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
774 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
781 intval($parent_deleted),
782 intval($current_post)
786 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
789 if($arr['last-child']) {
790 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
793 intval($current_post)
797 return $current_post;
800 function get_item_contact($item,$contacts) {
801 if(! count($contacts) || (! is_array($item)))
803 foreach($contacts as $contact) {
804 if($contact['id'] == $item['contact-id']) {
813 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
817 if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
820 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
822 if($contact['duplex'] && $contact['dfrn-id'])
823 $idtosend = '0:' . $orig_id;
824 if($contact['duplex'] && $contact['issued-id'])
825 $idtosend = '1:' . $orig_id;
827 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
829 $rino_enable = get_config('system','rino_encrypt');
834 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
836 logger('dfrn_deliver: ' . $url);
838 $xml = fetch_url($url);
840 $curl_stat = $a->get_curl_code();
842 return(-1); // timed out
844 logger('dfrn_deliver: ' . $xml);
849 if(strpos($xml,'<?xml') === false) {
850 logger('dfrn_deliver: no valid XML returned');
851 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
855 $res = parse_xml_string($xml);
857 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
858 return (($res->status) ? $res->status : 3);
861 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
862 $challenge = hex2bin((string) $res->challenge);
863 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
864 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
869 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
870 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
871 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
874 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
875 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
878 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
880 if(strpos($final_dfrn_id,':') == 1)
881 $final_dfrn_id = substr($final_dfrn_id,2);
883 if($final_dfrn_id != $orig_id) {
884 logger('dfrn_deliver: wrong dfrn_id.');
885 // did not decode properly - cannot trust this site
889 $postvars['dfrn_id'] = $idtosend;
890 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
892 $postvars['dissolve'] = '1';
895 if((($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
896 $postvars['data'] = $atom;
897 $postvars['perm'] = 'rw';
900 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
901 $postvars['perm'] = 'r';
904 if($rino && $rino_allowed && (! $dissolve)) {
905 $key = substr(random_string(),0,16);
906 $data = bin2hex(aes_encrypt($postvars['data'],$key));
907 $postvars['data'] = $data;
908 logger('rino: sent key = ' . $key);
911 if($dfrn_version >= 2.1) {
912 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
913 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
916 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
920 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
921 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
924 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
928 logger('md5 rawkey ' . md5($postvars['key']));
930 $postvars['key'] = bin2hex($postvars['key']);
933 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
935 $xml = post_url($contact['notify'],$postvars);
937 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
939 $curl_stat = $a->get_curl_code();
940 if((! $curl_stat) || (! strlen($xml)))
941 return(-1); // timed out
943 if(strpos($xml,'<?xml') === false) {
944 logger('dfrn_deliver: phase 2: no valid XML returned');
945 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
949 $res = parse_xml_string($xml);
957 * consume_feed - process atom feed and update anything/everything we might need to update
959 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
961 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
962 * It is this person's stuff that is going to be updated.
963 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
964 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
965 * have a contact record.
966 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
967 * might not) try and subscribe to it.
971 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $secure_feed = false) {
973 require_once('simplepie/simplepie.inc');
975 $feed = new SimplePie();
976 $feed->set_raw_data($xml);
978 $feed->enable_order_by_date(true);
980 $feed->enable_order_by_date(false);
984 logger('consume_feed: Error parsing XML: ' . $feed->error());
986 $permalink = $feed->get_permalink();
988 // Check at the feed level for updated contact name and/or photo
992 $photo_timestamp = '';
996 $hubs = $feed->get_links('hub');
999 $hub = implode(',', $hubs);
1001 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1003 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1004 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1005 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1006 $new_name = $elems['name'][0]['data'];
1008 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1009 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1010 $photo_url = $elems['link'][0]['attribs']['']['href'];
1013 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1014 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1018 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1019 logger('consume_feed: Updating photo for ' . $contact['name']);
1020 require_once("Photo.php");
1021 $photo_failure = false;
1022 $have_photo = false;
1024 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1025 intval($contact['id']),
1026 intval($contact['uid'])
1029 $resource_id = $r[0]['resource-id'];
1033 $resource_id = photo_new_resource();
1036 $img_str = fetch_url($photo_url,true);
1037 $img = new Photo($img_str);
1038 if($img->is_valid()) {
1040 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1041 dbesc($resource_id),
1042 intval($contact['id']),
1043 intval($contact['uid'])
1047 $img->scaleImageSquare(175);
1049 $hash = $resource_id;
1050 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
1052 $img->scaleImage(80);
1053 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
1055 $img->scaleImage(48);
1056 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
1060 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1061 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1062 dbesc(datetime_convert()),
1063 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1064 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1065 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1066 intval($contact['uid']),
1067 intval($contact['id'])
1072 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1073 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1074 dbesc(notags(trim($new_name))),
1075 dbesc(datetime_convert()),
1076 intval($contact['uid']),
1077 intval($contact['id'])
1081 if(strlen($birthday)) {
1082 if(substr($birthday,0,4) != $contact['bdyear']) {
1083 logger('consume_feed: updating birthday: ' . $birthday);
1087 * Add new birthday event for this person
1089 * $bdtext is just a readable placeholder in case the event is shared
1090 * with others. We will replace it during presentation to our $importer
1091 * to contain a sparkle link and perhaps a photo.
1095 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1098 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1099 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1100 intval($contact['uid']),
1101 intval($contact['id']),
1102 dbesc(datetime_convert()),
1103 dbesc(datetime_convert()),
1104 dbesc(datetime_convert('UTC','UTC', $birthday)),
1105 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1113 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1114 dbesc(substr($birthday,0,4)),
1115 intval($contact['uid']),
1116 intval($contact['id'])
1119 // This function is called twice without reloading the contact
1120 // Make sure we only create one event. This is why &$contact
1121 // is a reference var in this function
1123 $contact['bdyear'] = substr($birthday,0,4);
1129 // process any deleted entries
1131 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1132 if(is_array($del_entries) && count($del_entries)) {
1133 foreach($del_entries as $dentry) {
1135 if(isset($dentry['attribs']['']['ref'])) {
1136 $uri = $dentry['attribs']['']['ref'];
1138 if(isset($dentry['attribs']['']['when'])) {
1139 $when = $dentry['attribs']['']['when'];
1140 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1143 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1145 if($deleted && is_array($contact)) {
1146 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1148 intval($importer['uid']),
1149 intval($contact['id'])
1154 if(! $item['deleted'])
1155 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1157 if($item['uri'] == $item['parent-uri']) {
1158 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1159 `body` = '', `title` = ''
1160 WHERE `parent-uri` = '%s' AND `uid` = %d",
1162 dbesc(datetime_convert()),
1163 dbesc($item['uri']),
1164 intval($importer['uid'])
1168 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1169 `body` = '', `title` = ''
1170 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1172 dbesc(datetime_convert()),
1174 intval($importer['uid'])
1176 if($item['last-child']) {
1177 // ensure that last-child is set in case the comment that had it just got wiped.
1178 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1179 dbesc(datetime_convert()),
1180 dbesc($item['parent-uri']),
1181 intval($item['uid'])
1183 // who is the last child now?
1184 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1185 ORDER BY `created` DESC LIMIT 1",
1186 dbesc($item['parent-uri']),
1187 intval($importer['uid'])
1190 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1201 // Now process the feed
1203 if($feed->get_item_quantity()) {
1205 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1207 // in inverse date order
1209 $items = array_reverse($feed->get_items());
1211 $items = $feed->get_items();
1214 foreach($items as $item) {
1217 $item_id = $item->get_id();
1218 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1219 if(isset($rawthread[0]['attribs']['']['ref'])) {
1221 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1224 if(($is_reply) && is_array($contact)) {
1226 // Have we seen it? If not, import it.
1228 $item_id = $item->get_id();
1229 $datarray = get_atom_elements($feed,$item);
1231 if(! x($datarray,'author-name'))
1232 $datarray['author-name'] = $contact['name'];
1233 if(! x($datarray,'author-link'))
1234 $datarray['author-link'] = $contact['url'];
1235 if(! x($datarray,'author-avatar'))
1236 $datarray['author-avatar'] = $contact['thumb'];
1238 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1240 intval($importer['uid'])
1243 // Update content if 'updated' changes
1246 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1247 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1248 dbesc($datarray['body']),
1249 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1251 intval($importer['uid'])
1255 // update last-child if it changes
1257 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1258 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1259 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1260 dbesc(datetime_convert()),
1262 intval($importer['uid'])
1264 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1265 intval($allow[0]['data']),
1266 dbesc(datetime_convert()),
1268 intval($importer['uid'])
1274 $force_parent = false;
1275 if($contact['network'] === 'stat') {
1276 $force_parent = true;
1277 if(strlen($datarray['title']))
1278 unset($datarray['title']);
1279 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1280 dbesc(datetime_convert()),
1282 intval($importer['uid'])
1284 $datarray['last-child'] = 1;
1287 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1288 // one way feed - no remote comment ability
1289 $datarray['last-child'] = 0;
1291 $datarray['parent-uri'] = $parent_uri;
1292 $datarray['uid'] = $importer['uid'];
1293 $datarray['contact-id'] = $contact['id'];
1294 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1295 $datarray['type'] = 'activity';
1296 $datarray['gravity'] = GRAVITY_LIKE;
1299 $r = item_store($datarray,$force_parent);
1305 // Head post of a conversation. Have we seen it? If not, import it.
1307 $item_id = $item->get_id();
1309 $datarray = get_atom_elements($feed,$item);
1311 if(is_array($contact)) {
1312 if(! x($datarray,'author-name'))
1313 $datarray['author-name'] = $contact['name'];
1314 if(! x($datarray,'author-link'))
1315 $datarray['author-link'] = $contact['url'];
1316 if(! x($datarray,'author-avatar'))
1317 $datarray['author-avatar'] = $contact['thumb'];
1320 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1322 intval($importer['uid'])
1325 // Update content if 'updated' changes
1328 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1329 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1330 dbesc($datarray['body']),
1331 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1333 intval($importer['uid'])
1337 // update last-child if it changes
1339 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1340 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1341 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1342 intval($allow[0]['data']),
1343 dbesc(datetime_convert()),
1345 intval($importer['uid'])
1351 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1352 logger('consume-feed: New follower');
1353 new_follower($importer,$contact,$datarray,$item);
1356 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1357 lose_follower($importer,$contact,$datarray,$item);
1360 if(! is_array($contact))
1363 if($contact['network'] === 'stat' || stristr($permalink,'twitter.com')) {
1364 if(strlen($datarray['title']))
1365 unset($datarray['title']);
1366 $datarray['last-child'] = 1;
1369 if(($contact['network'] === 'feed') || (! strlen($contact['notify']))) {
1370 // one way feed - no remote comment ability
1371 $datarray['last-child'] = 0;
1374 $datarray['parent-uri'] = $item_id;
1375 $datarray['uid'] = $importer['uid'];
1376 $datarray['contact-id'] = $contact['id'];
1377 $r = item_store($datarray);
1385 function new_follower($importer,$contact,$datarray,$item) {
1386 $url = notags(trim($datarray['author-link']));
1387 $name = notags(trim($datarray['author-name']));
1388 $photo = notags(trim($datarray['author-avatar']));
1390 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1391 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1392 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1394 if(is_array($contact)) {
1395 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1396 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1398 intval($contact['id']),
1399 intval($importer['uid'])
1403 // send email notification to owner?
1407 // create contact record - set to readonly
1409 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`,
1410 `blocked`, `readonly`, `pending`, `writable` )
1411 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1, 1 ) ",
1412 intval($importer['uid']),
1413 dbesc(datetime_convert()),
1421 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1422 intval($importer['uid']),
1427 $contact_record = $r[0];
1429 // create notification
1430 $hash = random_string();
1432 if(is_array($contact_record)) {
1433 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1434 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1435 intval($importer['uid']),
1436 intval($contact_record['id']),
1438 dbesc(datetime_convert())
1441 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1442 intval($importer['uid'])
1446 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1447 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
1448 $email = replace_macros($email_tpl, array(
1449 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1451 '$myname' => $r[0]['username'],
1452 '$siteurl' => $a->get_baseurl(),
1453 '$sitename' => $a->config['sitename']
1455 $res = mail($r[0]['email'],
1456 t("You have a new follower at ") . $a->config['sitename'],
1458 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
1459 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1460 . 'Content-transfer-encoding: 8bit' );
1467 function lose_follower($importer,$contact,$datarray,$item) {
1469 if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1470 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1472 intval($contact['id'])
1476 contact_remove($contact['id']);
1481 function subscribe_to_hub($url,$importer,$contact) {
1483 if(is_array($importer)) {
1484 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1485 intval($importer['uid'])
1491 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1493 // Use a single verify token, even if multiple hubs
1495 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1497 $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1499 logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1501 if(! strlen($contact['hub-verify'])) {
1502 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1503 dbesc($verify_token),
1504 intval($contact['id'])
1508 post_url($url,$params);
1514 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1518 $name = xmlify($name);
1519 $uri = xmlify($uri);
1522 $photo = xmlify($photo);
1526 $o .= "<name>$name</name>\r\n";
1527 $o .= "<uri>$uri</uri>\r\n";
1528 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1529 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1531 call_hooks('atom_author', $o);
1533 $o .= "</$tag>\r\n";
1537 function atom_entry($item,$type,$author,$owner,$comment = false) {
1541 if($item['deleted'])
1542 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1545 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
1546 $body = fix_private_photos($item['body'],$owner['uid']);
1548 $body = $item['body'];
1551 $o = "\r\n\r\n<entry>\r\n";
1553 if(is_array($author))
1554 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1556 $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']));
1557 if(strlen($item['owner-name']))
1558 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1560 if($item['parent'] != $item['id'])
1561 $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";
1563 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1564 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1565 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1566 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1567 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
1568 $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($body) : $body) . '</content>' . "\r\n";
1569 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1571 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1573 if($item['location']) {
1574 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1575 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1579 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1581 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
1582 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
1585 $o .= '<dfrn:extid>' . $item['extid'] . '</dfrn:extid>' . "\r\n";
1588 $verb = construct_verb($item);
1589 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1590 $actobj = construct_activity_object($item);
1593 $actarg = construct_activity_target($item);
1597 $tags = item_getfeedtags($item);
1599 foreach($tags as $t) {
1600 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
1604 $o .= item_getfeedattach($item);
1606 $mentioned = get_mentions($item);
1610 call_hooks('atom_entry', $o);
1612 $o .= '</entry>' . "\r\n";
1617 function fix_private_photos($s,$uid) {
1619 logger('fix_private_photos');
1621 if(preg_match("/\[img\](.+?)\[\/img\]/is",$s,$matches)) {
1622 $image = $matches[1];
1623 logger('fix_private_photos: found photo ' . $image);
1624 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
1625 $i = basename($image);
1626 $i = str_replace('.jpg','',$i);
1627 $x = strpos($i,'-');
1629 $res = substr($i,$x+1);
1630 $i = substr($i,0,$x);
1631 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
1637 logger('replacing photo');
1638 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
1641 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
1649 function item_getfeedtags($item) {
1652 $cnt = preg_match_all('|\#\[url\=(.+?)\](.+?)\[\/url\]|',$item['tag'],$matches);
1654 for($x = 0; $x < count($matches); $x ++) {
1656 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1660 $cnt = preg_match_all('|\@\[url\=(.+?)\](.+?)\[\/url\]|',$item['tag'],$matches);
1662 for($x = 0; $x < count($matches); $x ++) {
1664 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
1670 function item_getfeedattach($item) {
1672 $arr = explode(',',$item['attach']);
1674 foreach($arr as $r) {
1676 $cnt = preg_match('|\[attach\]href=\"(.+?)\" size=\"(.+?)\" type=\"(.+?)\" title=\"(.+?)\"\[\/attach\]|',$r,$matches);
1678 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
1679 if(intval($matches[2]))
1680 $ret .= 'size="' . intval($matches[2]) . '" ';
1681 if($matches[4] !== ' ')
1682 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
1683 $ret .= ' />' . "\r\n";
1692 function item_expire($uid,$days) {
1694 if((! $uid) || (! $days))
1697 $r = q("SELECT * FROM `item`
1699 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
1709 logger('expire: # items=' . count($r) );
1711 foreach($r as $item) {
1713 // Only expire posts, not photos and photo comments
1715 if(strlen($item['resource-id']))
1718 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1719 dbesc(datetime_convert()),
1720 dbesc(datetime_convert()),
1726 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1727 dbesc(datetime_convert()),
1728 dbesc(datetime_convert()),
1729 dbesc($item['parent-uri']),
1730 intval($item['uid'])
1735 proc_run('php',"include/notifier.php","expire","$uid");