3 require_once('bbcode.php');
5 function get_feed_for(&$a, $dfrn_id, $owner_id, $last_update, $direction = 0) {
8 // default permissions - anonymous user
17 if(strlen($owner_id) && ! intval($owner_id)) {
18 $r = q("SELECT `uid`, `nickname` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
22 $owner_id = $r[0]['uid'];
23 $owner_nick = $r[0]['nickname'];
27 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
32 $owner['nickname'] = $owner_nick;
37 if($dfrn_id && $dfrn_id != '*') {
42 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
46 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
47 $my_id = '1:' . $dfrn_id;
50 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
51 $my_id = '0:' . $dfrn_id;
58 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
66 $groups = init_groups_visitor($contact['id']);
69 for($x = 0; $x < count($groups); $x ++)
70 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
71 $gs = implode('|', $groups);
74 $gs = '<<>>' ; // Impossible to match
76 $sql_extra = sprintf("
77 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
78 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
79 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
80 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
82 intval($contact['id']),
83 intval($contact['id']),
89 if($dfrn_id === '' || $dfrn_id === '*')
94 if(! strlen($last_update))
95 $last_update = 'now -30 days';
97 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
99 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
100 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
101 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
102 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
103 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
104 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
105 WHERE `item`.`uid` = %d AND `item`.`visible` = 1
106 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
107 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
109 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
116 // Will check further below if this actually returned results.
117 // We will provide an empty feed in any case.
121 $feed_template = load_view_file('view/atom_feed.tpl');
125 $hub = get_config('system','huburl');
129 $hubs = explode(',', $hub);
131 foreach($hubs as $h) {
135 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
140 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ;
141 $salmon .= '<link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ;
142 $salmon .= '<link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ;
145 $atom .= replace_macros($feed_template, array(
146 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
147 '$feed_title' => xmlify($owner['name']),
148 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
150 '$salmon' => $salmon,
151 '$name' => xmlify($owner['name']),
152 '$profile_page' => xmlify($owner['url']),
153 '$photo' => xmlify($owner['photo']),
154 '$thumb' => xmlify($owner['thumb']),
155 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
156 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
157 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME))
161 if(! count($items)) {
162 $atom .= '</feed>' . "\r\n";
166 foreach($items as $item) {
168 // public feeds get html, our own nodes use bbcode
170 if($dfrn_id === '*') {
177 $atom .= atom_entry($item,$type,null,$owner,true);
180 $atom .= '</feed>' . "\r\n";
185 function construct_verb($item) {
187 return $item['verb'];
188 return ACTIVITY_POST;
191 function construct_activity_object($item) {
193 if($item['object']) {
194 $o = '<as:object>' . "\r\n";
195 $r = @simplexml_load_string($item['object']);
197 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
199 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
201 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
203 if(substr($r->link,0,1) === '<')
206 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
209 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
210 $o .= '</as:object>' . "\r\n";
217 function construct_activity_target($item) {
219 if($item['target']) {
220 $o = '<as:target>' . "\r\n";
221 $r = @simplexml_load_string($item['target']);
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) === '<')
232 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
235 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
236 $o .= '</as:target>' . "\r\n";
246 function get_atom_elements($feed,$item) {
248 require_once('library/HTMLPurifier.auto.php');
249 require_once('include/html2bbcode.php');
251 $best_photo = array();
255 $author = $item->get_author();
256 $res['author-name'] = unxmlify($author->get_name());
257 $res['author-link'] = unxmlify($author->get_link());
258 $res['uri'] = unxmlify($item->get_id());
259 $res['title'] = unxmlify($item->get_title());
260 $res['body'] = unxmlify($item->get_content());
263 // look for a photo. We should check media size and find the best one,
264 // but for now let's just find any author photo
266 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
268 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
269 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
270 foreach($base as $link) {
271 if(! $res['author-avatar']) {
272 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
273 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
278 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
280 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
281 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
282 if($base && count($base)) {
283 foreach($base as $link) {
284 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
285 $res['author-link'] = unxmlify($link['attribs']['']['href']);
286 if(! $res['author-avatar']) {
287 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
288 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
294 // No photo/profile-link on the item - look at the feed level
296 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
297 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
298 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
299 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
300 foreach($base as $link) {
301 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
302 $res['author-link'] = unxmlify($link['attribs']['']['href']);
303 if(! $res['author-avatar']) {
304 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
305 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
310 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
312 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
313 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
315 if($base && count($base)) {
316 foreach($base as $link) {
317 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
318 $res['author-link'] = unxmlify($link['attribs']['']['href']);
319 if(! (x($res,'author-avatar'))) {
320 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
321 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
329 $maxlen = get_max_import_size();
330 if($maxlen && (strlen($res['body']) > $maxlen))
331 $res['body'] = substr($res['body'],0, $maxlen);
333 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
334 // the content type. Our own network only emits text normally, though it might have been converted to
335 // html if we used a pubsubhubbub transport. But if we see even one html open tag in our text, we will
336 // have to assume it is all html and needs to be purified.
338 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
339 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
340 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
344 if(strpos($res['body'],'<')) {
346 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
347 '[youtube]$1[/youtube]', $res['body']);
349 $config = HTMLPurifier_Config::createDefault();
350 $config->set('Cache.DefinitionImpl', null);
352 // we shouldn't need a whitelist, because the bbcode converter
353 // will strip out any unsupported tags.
354 // $config->set('HTML.Allowed', 'p,b,a[href],i');
356 $purifier = new HTMLPurifier($config);
357 $res['body'] = $purifier->purify($res['body']);
361 $res['body'] = html2bbcode($res['body']);
364 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
365 if($allow && $allow[0]['data'] == 1)
366 $res['last-child'] = 1;
368 $res['last-child'] = 0;
370 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
372 $res['created'] = unxmlify($rawcreated[0]['data']);
374 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
376 $res['location'] = unxmlify($rawlocation[0]['data']);
379 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
381 $res['edited'] = unxmlify($rawcreated[0]['data']);
383 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
384 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
385 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
386 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
387 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
388 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
389 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
390 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
391 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
393 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
394 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
396 foreach($base as $link) {
397 if(! $res['owner-avatar']) {
398 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
399 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
404 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
406 $res['coord'] = unxmlify($rawgeo[0]['data']);
409 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
410 // select between supported verbs
412 $res['verb'] = unxmlify($rawverb[0]['data']);
414 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
417 $res['object'] = '<object>' . "\n";
418 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
419 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
420 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
422 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
423 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
424 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
425 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
426 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
427 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
428 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
429 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
431 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
432 if(strpos($body,'<')) {
434 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
435 '[youtube]$1[/youtube]', $body);
437 $config = HTMLPurifier_Config::createDefault();
438 $config->set('Cache.DefinitionImpl', null);
440 $purifier = new HTMLPurifier($config);
441 $body = $purifier->purify($body);
444 $body = html2bbcode($body);
445 $res['object'] .= '<content>' . $body . '</content>' . "\n";
448 $res['object'] .= '</object>' . "\n";
451 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
454 $res['target'] = '<target>' . "\n";
455 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
456 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
458 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
459 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
461 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
462 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
463 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
464 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
465 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
466 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
468 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
469 if(strpos($body,'<')) {
471 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
472 '[youtube]$1[/youtube]', $body);
474 $config = HTMLPurifier_Config::createDefault();
475 $config->set('Cache.DefinitionImpl', null);
477 $purifier = new HTMLPurifier($config);
478 $body = $purifier->purify($body);
481 $body = html2bbcode($body);
482 $res['target'] .= '<content>' . $body . '</content>' . "\n";
485 $res['target'] .= '</target>' . "\n";
491 function encode_rel_links($links) {
493 if(! ((is_array($links)) && (count($links))))
495 foreach($links as $link) {
497 if($link['attribs']['']['rel'])
498 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
499 if($link['attribs']['']['type'])
500 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
501 if($link['attribs']['']['href'])
502 $o .= 'type="' . $link['attribs']['']['href'] . '" ';
503 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
504 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
505 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
506 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
512 function item_store($arr) {
515 $arr['gravity'] = intval($arr['gravity']);
516 elseif($arr['parent-uri'] == $arr['uri'])
518 elseif(activity_match($arr['verb'],ACTIVITY_POST))
521 $arr['gravity'] = 6; // extensible catchall
524 $arr['type'] = 'remote';
525 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
526 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
527 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
528 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
529 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
530 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
531 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
532 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
533 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
534 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
535 $arr['changed'] = datetime_convert();
536 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
537 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
538 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
539 $arr['body'] = ((x($arr,'body')) ? escape_tags(trim($arr['body'])) : '');
540 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
541 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
543 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
544 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
545 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
546 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
547 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
548 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
551 $parent_missing = false;
555 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
557 $r = dbq("INSERT INTO `item` (`"
558 . implode("`, `", array_keys($arr))
560 . implode("', '", array_values($arr))
563 // find the parent and snarf the item id and ACL's
565 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
566 dbesc($arr['parent-uri']),
571 $parent_id = $r[0]['id'];
572 $allow_cid = $r[0]['allow_cid'];
573 $allow_gid = $r[0]['allow_gid'];
574 $deny_cid = $r[0]['deny_cid'];
575 $deny_gid = $r[0]['deny_gid'];
578 $parent_missing = true;
581 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
582 $arr['uri'], // already dbesc'd
586 $current_post = $r[0]['id'];
587 logger('item_store: created item ' . $current_post);
592 if($parent_missing) {
594 logger('item_store: item parent was not found - ignoring item');
596 // perhaps the parent was deleted, but in any case, this thread is dead
597 // and unfortunately our brand new item now has to be destroyed
599 q("DELETE FROM `item` WHERE `id` = %d LIMIT 1",
600 intval($current_post)
605 // Set parent id - all of the parent's ACL's are also inherited by this post
607 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
608 `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d LIMIT 1",
614 intval($current_post)
617 return $current_post;
620 function get_item_contact($item,$contacts) {
621 if(! count($contacts) || (! is_array($item)))
623 foreach($contacts as $contact) {
624 if($contact['id'] == $item['contact-id']) {
633 function dfrn_deliver($owner,$contact,$atom) {
636 if((! strlen($contact['dfrn-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
639 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
641 if($contact['duplex'] && $contact['dfrn-id'])
642 $idtosend = '0:' . $orig_id;
643 if($contact['duplex'] && $contact['issued-id'])
644 $idtosend = '1:' . $orig_id;
646 $url = $contact['notify'] . '?dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION ;
648 logger('dfrn_deliver: ' . $url);
650 $xml = fetch_url($url);
652 logger('dfrn_deliver: ' . $xml);
657 $res = simplexml_load_string($xml);
659 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
660 return (($res->status) ? $res->status : 3);
663 $sent_dfrn_id = hex2bin($res->dfrn_id);
664 $challenge = hex2bin($res->challenge);
670 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
671 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
672 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
675 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
676 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
679 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
681 if(strpos($final_dfrn_id,':') == 1)
682 $final_dfrn_id = substr($final_dfrn_id,2);
684 if($final_dfrn_id != $orig_id) {
685 logger('dfrn_deliver: wrong dfrn_id.');
686 // did not decode properly - cannot trust this site
690 $postvars['dfrn_id'] = $idtosend;
691 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
693 if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
694 $postvars['data'] = $atom;
696 elseif($owner['page-flags'] == PAGE_COMMUNITY) {
697 $postvars['data'] = $atom;
700 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
703 $xml = post_url($contact['notify'],$postvars);
705 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true) . "\n" . "RECEIVING: " . $xml);
707 $res = simplexml_load_string($xml);
716 * consume_feed - process atom feed and update anything/everything we might need to update
718 * $xml = the (atom) feed to consume - no RSS spoken here, it might partially work since simplepie
719 * handles both, but we don't claim it will work well, and are reasonably certain it won't.
720 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
721 * It is this person's stuff that is going to be updated.
722 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
723 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
724 * have a contact record.
725 * $hub = should wefind ahub declation in the feed, pass it back to our calling process, who might (or
726 * might not) try and subscribe to it.
730 function consume_feed($xml,$importer,$contact, &$hub, $datedir = 0) {
732 require_once('simplepie/simplepie.inc');
734 $feed = new SimplePie();
735 $feed->set_raw_data($xml);
737 $feed->enable_order_by_date(true);
739 $feed->enable_order_by_date(false);
742 // Check at the feed level for updated contact name and/or photo
743 $debugging = get_config('system','debugging');
747 $photo_timestamp = '';
751 $hubs = $feed->get_links('hub');
754 $hub = implode(',', $hubs);
756 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
758 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
759 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
760 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
761 $new_name = $elems['name'][0]['data'];
763 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
764 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
765 $photo_url = $elems['link'][0]['attribs']['']['href'];
769 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
770 logger('Consume feed: Updating photo for ' . $contact['name']);
771 require_once("Photo.php");
772 $photo_failure = false;
775 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
776 intval($contact['id']),
777 intval($contact['uid'])
780 $resource_id = $r[0]['resource-id'];
784 $resource_id = photo_new_resource();
787 $img_str = fetch_url($photo_url,true);
788 $img = new Photo($img_str);
789 if($img->is_valid()) {
791 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
793 intval($contact['id']),
794 intval($contact['uid'])
798 $img->scaleImageSquare(175);
800 $hash = $resource_id;
801 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
803 $img->scaleImage(80);
804 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
806 $img->scaleImage(48);
807 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 6);
811 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
812 WHERE `uid` = %d AND `id` = %d LIMIT 1",
813 dbesc(datetime_convert()),
814 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
815 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
816 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
817 intval($contact['uid']),
818 intval($contact['id'])
823 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
824 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
825 dbesc(notags(trim($new_name))),
826 dbesc(datetime_convert()),
827 intval($contact['uid']),
828 intval($contact['id'])
832 // Now process the feed
833 if($feed->get_item_quantity()) {
834 foreach($feed->get_items() as $item) {
838 $rawdelete = $item->get_item_tags( NAMESPACE_TOMB, 'deleted-entry');
839 if(isset($rawdelete[0]['attribs']['']['ref'])) {
840 $uri = $rawthread[0]['attribs']['']['ref'];
842 if(isset($rawdelete[0]['attribs']['']['when'])) {
843 $when = $rawthread[0]['attribs']['']['when'];
844 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
847 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
849 if($deleted && is_array($contact)) {
850 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
852 intval($importer['uid']),
853 intval($contact['id'])
857 if($item['uri'] == $item['parent-uri']) {
858 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
859 `body` = '', `title` = ''
860 WHERE `parent-uri` = '%s' AND `uid` = %d",
862 dbesc(datetime_convert()),
864 intval($importer['uid'])
868 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
869 `body` = '', `title` = ''
870 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
872 dbesc(datetime_convert()),
874 intval($importer['uid'])
876 if($item['last-child']) {
877 // ensure that last-child is set in case the comment that had it just got wiped.
878 $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
879 dbesc(datetime_convert()),
880 dbesc($item['parent-uri']),
883 // who is the last child now?
884 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
885 ORDER BY `created` DESC LIMIT 1",
886 dbesc($item['parent-uri']),
887 intval($importer['uid'])
890 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
902 $item_id = $item->get_id();
903 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
904 if(isset($rawthread[0]['attribs']['']['ref'])) {
906 $parent_uri = $rawthread[0]['attribs']['']['ref'];
910 if(($is_reply) && is_array($contact)) {
912 // Have we seen it? If not, import it.
914 $item_id = $item->get_id();
916 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
918 intval($importer['uid'])
920 // FIXME update content if 'updated' changes
922 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
923 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
924 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
925 dbesc(datetime_convert()),
927 intval($importer['uid'])
929 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
930 intval($allow[0]['data']),
931 dbesc(datetime_convert()),
933 intval($importer['uid'])
938 $datarray = get_atom_elements($feed,$item);
939 if($contact['network'] === 'stat') {
940 if(strlen($datarray['title']))
941 unset($datarray['title']);
942 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
943 dbesc(datetime_convert()),
945 intval($importer['uid'])
947 $datarray['last-child'] = 1;
949 $datarray['parent-uri'] = $parent_uri;
950 $datarray['uid'] = $importer['uid'];
951 $datarray['contact-id'] = $contact['id'];
952 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
953 $datarray['type'] = 'activity';
954 $datarray['gravity'] = GRAVITY_LIKE;
957 $r = item_store($datarray);
962 // Head post of a conversation. Have we seen it? If not, import it.
964 $item_id = $item->get_id();
965 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
967 intval($importer['uid'])
970 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
971 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
972 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
973 intval($allow[0]['data']),
974 dbesc(datetime_convert()),
976 intval($importer['uid'])
981 $datarray = get_atom_elements($feed,$item);
983 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
984 logger('consume-feed: New follower');
985 new_follower($importer,$contact,$datarray,$item);
988 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
989 lose_follower($importer,$contact,$datarray,$item);
992 if(! is_array($contact))
995 if($contact['network'] === 'stat') {
996 if(strlen($datarray['title']))
997 unset($datarray['title']);
998 $datarray['last-child'] = 1;
1001 $datarray['parent-uri'] = $item_id;
1002 $datarray['uid'] = $importer['uid'];
1003 $datarray['contact-id'] = $contact['id'];
1004 $r = item_store($datarray);
1013 function new_follower($importer,$contact,$datarray,$item) {
1014 $url = notags(trim($datarray['author-link']));
1015 $name = notags(trim($datarray['author-name']));
1016 $photo = notags(trim($datarray['author-avatar']));
1018 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
1019 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
1020 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
1022 if(is_array($contact)) {
1023 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
1024 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
1026 intval($contact['id']),
1027 intval($importer['uid'])
1031 // send email notification to owner?
1035 // create contact record - set to readonly
1037 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`,
1038 `blocked`, `readonly`, `pending` )
1039 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
1040 intval($importer['uid']),
1041 dbesc(datetime_convert()),
1049 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
1050 intval($importer['uid']),
1055 $contact_record = $r[0];
1057 // create notification
1058 $hash = random_string();
1060 if(is_array($contact_record)) {
1061 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1062 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1063 intval($importer['uid']),
1064 intval($contact_record['id']),
1066 dbesc(datetime_convert())
1069 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
1070 intval($importer['uid'])
1073 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
1074 $email_tpl = load_view_file('view/follow_notify_eml.tpl');
1075 $email = replace_macros($email_tpl, array(
1076 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
1078 '$myname' => $r[0]['username'],
1079 '$siteurl' => $a->get_baseurl(),
1080 '$sitename' => $a->config['sitename']
1082 $res = mail($r[0]['email'],
1083 t("You have a new follower at ") . $a->config['sitename'],
1085 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] );
1092 function lose_follower($importer,$contact,$datarray,$item) {
1094 if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1095 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1097 intval($contact['id'])
1101 contact_remove($contact['id']);
1106 function subscribe_to_hub($url,$importer,$contact) {
1108 if(is_array($importer)) {
1109 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1110 intval($importer['uid'])
1116 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1118 // Use a single verify token, even if multiple hubs
1120 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1122 $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1124 logger('subscribe_to_hub: subscribing ' . $contact['name'] . ' to hub ' . $url . ' with verifier ' . $verify_token);
1126 if(! strlen($contact['hub-verify'])) {
1127 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1128 dbesc($verify_token),
1129 intval($contact['id'])
1133 post_url($url,$params);
1139 function atom_author($tag,$name,$uri,$h,$w,$photo) {
1143 $name = xmlify($name);
1144 $uri = xmlify($uri);
1147 $photo = xmlify($photo);
1151 $o .= "<name>$name</name>\r\n";
1152 $o .= "<uri>$uri</uri>\r\n";
1153 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1154 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
1155 $o .= "</$tag>\r\n";
1159 function atom_entry($item,$type,$author,$owner,$comment = false) {
1161 if($item['deleted'])
1162 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
1166 $o = "\r\n\r\n<entry>\r\n";
1168 if(is_array($author))
1169 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
1171 $o .= atom_author('author',$item['name'],$item['url'],80,80,$item['thumb']);
1172 if(strlen($item['owner-name']))
1173 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
1175 if($item['parent'] != $item['id'])
1176 $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";
1178 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
1179 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
1180 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
1181 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
1182 $o .= '<content type="' . $type . '" >' . xmlify(($type === 'html') ? bbcode($item['body']) : $item['body']) . '</content>' . "\r\n";
1183 $o .= '<link rel="alternate" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
1185 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
1187 if($item['location']) {
1188 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
1189 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
1193 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
1195 $verb = construct_verb($item);
1196 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
1197 $actobj = construct_activity_object($item);
1200 $actarg = construct_activity_target($item);
1204 $mentioned = get_mentions($item);
1208 $o .= '</entry>' . "\r\n";