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",
35 if($dfrn_id && $dfrn_id != '*') {
40 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
44 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
45 $my_id = '1:' . $dfrn_id;
48 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
49 $my_id = '0:' . $dfrn_id;
56 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
64 $groups = init_groups_visitor($contact['id']);
67 for($x = 0; $x < count($groups); $x ++)
68 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
69 $gs = implode('|', $groups);
72 $gs = '<<>>' ; // Impossible to match
74 $sql_extra = sprintf("
75 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
76 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
77 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
78 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
80 intval($contact['id']),
81 intval($contact['id']),
87 if($dfrn_id === '' || $dfrn_id === '*')
92 if(! strlen($last_update))
93 $last_update = 'now - 30 days';
95 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
97 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
98 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
99 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
100 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
101 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`
102 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
103 WHERE `item`.`uid` = %d AND `item`.`visible` = 1
104 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
105 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
107 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
114 // Will check further below if this actually returned results.
115 // We will provide an empty feed in any case.
119 $feed_template = load_view_file('view/atom_feed.tpl');
120 $tomb_template = load_view_file('view/atom_tomb.tpl');
121 $item_template = load_view_file('view/atom_item.tpl');
122 $cmnt_template = load_view_file('view/atom_cmnt.tpl');
126 $hub = get_config('system','huburl');
130 $hubs = explode(',', $hub);
132 foreach($hubs as $h) {
136 $hubxml .= '<link rel="hub" href="' . xmlify($h) . '" />' . "\n" ;
141 $salmon = '<link rel="salmon" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ;
142 $salmon .= '<link rel="http://salmon-protocol.org/ns/salmon-replies" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ;
143 $salmon .= '<link rel="http://salmon-protocol.org/ns/salmon-mention" href="' . xmlify($a->get_baseurl() . '/salmon/' . $owner_nick) . '" />' . "\n" ;
146 $atom .= replace_macros($feed_template, array(
147 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
148 '$feed_title' => xmlify($owner['name']),
149 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
151 '$salmon' => $salmon,
152 '$name' => xmlify($owner['name']),
153 '$profile_page' => xmlify($owner['url']),
154 '$photo' => xmlify($owner['photo']),
155 '$thumb' => xmlify($owner['thumb']),
156 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
157 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
158 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME))
162 if(! count($items)) {
163 $atom .= '</feed>' . "\r\n";
167 foreach($items as $item) {
169 // public feeds get html, our own nodes use bbcode
171 if($dfrn_id === '*') {
172 $allow = (($item['last-child']) ? 1 : 0);
173 $item['body'] = bbcode($item['body']);
177 $allow = ((($item['last-child']) && ($contact['rel']) && ($contact['rel'] != REL_FAN)) ? 1 : 0);
181 if($item['deleted']) {
182 $atom .= replace_macros($tomb_template, array(
183 '$id' => xmlify($item['uri']),
184 '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00' , ATOM_TIME))
188 $verb = construct_verb($item);
189 $actobj = construct_activity($item);
190 $mentioned = get_mentions($item);
192 if($item['parent'] == $item['id']) {
193 $atom .= replace_macros($item_template, array(
194 '$name' => xmlify($item['name']),
195 '$profile_page' => xmlify($item['url']),
196 '$thumb' => xmlify($item['thumb']),
197 '$owner_name' => xmlify($item['owner-name']),
198 '$owner_profile_page' => xmlify($item['owner-link']),
199 '$owner_thumb' => xmlify($item['owner-avatar']),
200 '$item_id' => xmlify($item['uri']),
201 '$title' => xmlify($item['title']),
202 '$published' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
203 '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00' , ATOM_TIME)),
204 '$location' => xmlify($item['location']),
205 '$coord' => xmlify($item['coord']),
207 '$alt' => xmlify($a->get_baseurl() . '/display/' . $owner_nick . '/' . $item['id']),
208 '$content' => xmlify($item['body']),
209 '$verb' => xmlify($verb),
210 '$actobj' => $actobj, // do not xmlify
211 '$mentioned' => $mentioned,
212 '$comment_allow' => $allow
216 $atom .= replace_macros($cmnt_template, array(
217 '$name' => xmlify($item['name']),
218 '$profile_page' => xmlify($item['url']),
219 '$thumb' => xmlify($item['thumb']),
220 '$item_id' => xmlify($item['uri']),
221 '$title' => xmlify($item['title']),
222 '$published' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
223 '$updated' => xmlify(datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00' , ATOM_TIME)),
225 '$content' => xmlify($item['body']),
226 '$alt' => xmlify($a->get_baseurl() . '/display/' . $owner_nick . '/' . $item['id']),
227 '$verb' => xmlify($verb),
228 '$actobj' => $actobj, // do not xmlify
229 '$mentioned' => $mentioned,
230 '$parent_id' => xmlify($item['parent-uri']),
231 '$comment_allow' => $allow
237 $atom .= '</feed>' . "\r\n";
242 function construct_verb($item) {
244 return $item['verb'];
245 return ACTIVITY_POST;
248 function construct_activity($item) {
250 if($item['object']) {
251 $o = '<as:object>' . "\r\n";
252 $r = @simplexml_load_string($item['object']);
254 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
256 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
258 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
260 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
262 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
263 $o .= '</as:object>' . "\r\n";
273 function get_atom_elements($feed,$item) {
275 require_once('library/HTMLPurifier.auto.php');
276 require_once('include/html2bbcode.php');
278 $best_photo = array();
282 $author = $item->get_author();
283 $res['author-name'] = unxmlify($author->get_name());
284 $res['author-link'] = unxmlify($author->get_link());
285 $res['uri'] = unxmlify($item->get_id());
286 $res['title'] = unxmlify($item->get_title());
287 $res['body'] = unxmlify($item->get_content());
290 // look for a photo. We should check media size and find the best one,
291 // but for now let's just find any author photo
293 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
295 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
296 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
297 foreach($base as $link) {
298 if(! $res['author-avatar']) {
299 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
300 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
305 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
307 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
308 $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(! $res['author-avatar']) {
314 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
315 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
321 // No photo/profile-link on the item - look at the feed level
323 if((! $res['author-link']) || (! $res['author-avatar'])) {
324 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
325 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
326 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
327 foreach($base as $link) {
328 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
329 $res['author-link'] = unxmlify($link['attribs']['']['href']);
330 if(! $res['author-avatar']) {
331 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
332 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
337 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
339 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
340 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
342 if($base && count($base)) {
343 foreach($base as $link) {
344 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
345 $res['author-link'] = unxmlify($link['attribs']['']['href']);
346 if(! $res['author-avatar']) {
347 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
348 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
356 $maxlen = get_max_import_size();
357 if($maxlen && (strlen($res['body']) > $maxlen))
358 $res['body'] = substr($res['body'],0, $maxlen);
360 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
361 // the content type. Our own network only emits text normally, though it might have been converted to
362 // html if we used a pubsubhubbub transport. But if we see even one html open tag in our text, we will
363 // have to assume it is all html and needs to be purified.
365 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
366 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
367 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
371 if(strpos($res['body'],'<')) {
373 $res['body'] = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
374 '[youtube]$1[/youtube]', $res['body']);
376 $config = HTMLPurifier_Config::createDefault();
377 $config->set('Cache.DefinitionImpl', null);
379 // we shouldn't need a whitelist, because the bbcode converter
380 // will strip out any unsupported tags.
381 // $config->set('HTML.Allowed', 'p,b,a[href],i');
383 $purifier = new HTMLPurifier($config);
384 $res['body'] = $purifier->purify($res['body']);
388 $res['body'] = html2bbcode($res['body']);
391 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
392 if($allow && $allow[0]['data'] == 1)
393 $res['last-child'] = 1;
395 $res['last-child'] = 0;
397 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
399 $res['created'] = unxmlify($rawcreated[0]['data']);
401 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
403 $res['location'] = unxmlify($rawlocation[0]['data']);
406 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
408 $res['edited'] = unxmlify($rawcreated[0]['data']);
410 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
411 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
412 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
413 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
414 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
415 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
416 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
417 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
418 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
420 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
421 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
423 foreach($base as $link) {
424 if(! $res['owner-avatar']) {
425 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
426 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
431 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
433 $res['coord'] = unxmlify($rawgeo[0]['data']);
436 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
437 // select between supported verbs
439 $res['verb'] = unxmlify($rawverb[0]['data']);
441 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
444 $res['object'] = '<object>' . "\n";
445 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
446 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
447 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
449 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
450 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
452 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['rel'] === 'alternate')
453 $res['object'] .= '<link>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'][0]['attribs']['']['href'] . '</link>' . "\n";
454 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
455 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
456 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
457 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
459 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
460 if(strpos($body,'<')) {
462 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
463 '[youtube]$1[/youtube]', $body);
465 $config = HTMLPurifier_Config::createDefault();
466 $config->set('Cache.DefinitionImpl', null);
468 $purifier = new HTMLPurifier($config);
469 $body = $purifier->purify($body);
472 $body = html2bbcode($body);
473 $res['object'] .= '<content>' . $body . '</content>' . "\n";
476 $res['object'] .= '</object>' . "\n";
482 function item_store($arr) {
485 $arr['gravity'] = intval($arr['gravity']);
486 elseif($arr['parent-uri'] == $arr['uri'])
488 elseif(activity_match($arr['verb'],ACTIVITY_POST))
492 $arr['type'] = 'remote';
493 $arr['wall'] = ((intval($arr['wall'])) ? 1 : 0);
494 $arr['uri'] = notags(trim($arr['uri']));
495 $arr['author-name'] = notags(trim($arr['author-name']));
496 $arr['author-link'] = notags(trim($arr['author-link']));
497 $arr['author-avatar'] = notags(trim($arr['author-avatar']));
498 $arr['owner-name'] = notags(trim($arr['owner-name']));
499 $arr['owner-link'] = notags(trim($arr['owner-link']));
500 $arr['owner-avatar'] = notags(trim($arr['owner-avatar']));
501 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
502 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
503 $arr['changed'] = datetime_convert();
504 $arr['title'] = notags(trim($arr['title']));
505 $arr['location'] = notags(trim($arr['location']));
506 $arr['coord'] = notags(trim($arr['coord']));
507 $arr['body'] = escape_tags(trim($arr['body']));
508 $arr['last-child'] = intval($arr['last-child']);
509 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1);
511 $arr['parent-uri'] = notags(trim($arr['parent-uri']));
512 $arr['verb'] = notags(trim($arr['verb']));
513 $arr['object-type'] = notags(trim($arr['object-type']));
514 $arr['object'] = trim($arr['object']);
517 $parent_missing = false;
521 $r = q("INSERT INTO `item` (`"
522 . implode("`, `", array_keys($arr))
524 . implode("', '", array_values($arr))
527 // find the parent and snarf the item id and ACL's
529 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
530 dbesc($arr['parent-uri']),
535 $parent_id = $r[0]['id'];
536 $allow_cid = $r[0]['allow_cid'];
537 $allow_gid = $r[0]['allow_gid'];
538 $deny_cid = $r[0]['deny_cid'];
539 $deny_gid = $r[0]['deny_gid'];
542 $parent_missing = true;
545 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
546 $arr['uri'], // already dbesc'd
550 $current_post = $r[0]['id'];
554 if($parent_missing) {
556 // perhaps the parent was deleted, but in any case, this thread is dead
557 // and unfortunately our brand new item now has to be destroyed
559 q("DELETE FROM `item` WHERE `id` = %d LIMIT 1",
560 intval($current_post)
565 // Set parent id - all of the parent's ACL's are also inherited by this post
567 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
568 `deny_cid` = '%s', `deny_gid` = '%s' WHERE `id` = %d LIMIT 1",
574 intval($current_post)
577 return $current_post;
580 function get_item_contact($item,$contacts) {
581 if(! count($contacts) || (! is_array($item)))
583 foreach($contacts as $contact) {
584 if($contact['id'] == $item['contact-id']) {
593 function dfrn_deliver($owner,$contact,$atom) {
596 if((! strlen($contact['dfrn-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
599 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
601 if($contact['duplex'] && $contact['dfrn-id'])
602 $idtosend = '0:' . $orig_id;
603 if($contact['duplex'] && $contact['issued-id'])
604 $idtosend = '1:' . $orig_id;
606 $url = $contact['notify'] . '?dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION ;
608 logger('dfrn_deliver: ' . $url);
610 $xml = fetch_url($url);
612 logger('dfrn_deliver: ' . $xml);
617 $res = simplexml_load_string($xml);
619 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
620 return (($res->status) ? $res->status : 3);
623 $sent_dfrn_id = hex2bin($res->dfrn_id);
624 $challenge = hex2bin($res->challenge);
630 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
631 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
632 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
635 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
636 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
639 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
641 if(strpos($final_dfrn_id,':') == 1)
642 $final_dfrn_id = substr($final_dfrn_id,2);
644 if($final_dfrn_id != $orig_id) {
645 logger('dfrn_deliver: wrong dfrn_id.');
646 // did not decode properly - cannot trust this site
650 $postvars['dfrn_id'] = $idtosend;
651 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
653 if(($contact['rel']) && ($contact['rel'] != REL_FAN) && (! $contact['blocked']) && (! $contact['readonly'])) {
654 $postvars['data'] = $atom;
656 elseif($owner['page-flags'] == PAGE_COMMUNITY) {
657 $postvars['data'] = $atom;
660 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
663 $xml = post_url($contact['notify'],$postvars);
665 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true) . "\n" . "RECEIVING: " . $xml);
667 $res = simplexml_load_string($xml);
676 * consume_feed - process atom feed and update anything/everything we might need to update
678 * $xml = the (atom) feed to consume - no RSS spoken here, it might partially work since simplepie
679 * handles both, but we don't claim it will work well, and are reasonably certain it won't.
680 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
681 * It is this person's stuff that is going to be updated.
682 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
683 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
684 * have a contact record.
685 * $hub = should wefind ahub declation in the feed, pass it back to our calling process, who might (or
686 * might not) try and subscribe to it.
690 function consume_feed($xml,$importer,$contact, &$hub) {
692 require_once('simplepie/simplepie.inc');
694 $feed = new SimplePie();
695 $feed->set_raw_data($xml);
696 $feed->enable_order_by_date(false);
699 // Check at the feed level for updated contact name and/or photo
700 $debugging = get_config('system','debugging');
704 $photo_timestamp = '';
708 $hubs = $feed->get_links('hub');
711 $hub = implode(',', $hubs);
713 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
715 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
716 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
717 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
718 $new_name = $elems['name'][0]['data'];
720 if(($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
721 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
722 $photo_url = $elems['link'][0]['attribs']['']['href'];
725 if(! $photo_timestamp) {
726 $photo_rawupdate = $feed->get_feed_tags(NAMESPACE_DFRN,'icon-updated');
727 if($photo_rawupdate) {
728 $photo_timestamp = datetime_convert('UTC','UTC',$photo_rawupdate[0]['data']);
729 $photo_url = $feed->get_image_url();
732 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
734 require_once("Photo.php");
735 $photo_failure = false;
737 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
738 intval($contact['id']),
739 intval($contact['uid'])
742 $resource_id = $r[0]['resource-id'];
743 $img_str = fetch_url($photo_url,true);
744 $img = new Photo($img_str);
745 if($img->is_valid()) {
746 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND contact-id` = %d AND `uid` = %d",
748 intval($contact['id']),
749 intval($contact['uid'])
752 $img->scaleImageSquare(175);
754 $hash = $resource_id;
755 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 4);
757 $img->scaleImage(80);
758 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), t('Contact Photos') , 5);
760 q("UPDATE `contact` SET `avatar-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
761 dbesc(datetime_convert()),
762 intval($contact['uid']),
763 intval($contact['id'])
769 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
770 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
771 dbesc(notags(trim($new_name))),
772 dbesc(datetime_convert()),
773 intval($contact['uid']),
774 intval($contact['id'])
778 // Now process the feed
779 if($feed->get_item_quantity()) {
780 foreach($feed->get_items() as $item) {
784 $rawdelete = $item->get_item_tags( NAMESPACE_TOMB, 'deleted-entry');
785 if(isset($rawdelete[0]['attribs']['']['ref'])) {
786 $uri = $rawthread[0]['attribs']['']['ref'];
788 if(isset($rawdelete[0]['attribs']['']['when'])) {
789 $when = $rawthread[0]['attribs']['']['when'];
790 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
793 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
795 if($deleted && is_array($contact)) {
796 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
798 intval($importer['uid']),
799 intval($contact['id'])
803 if($item['uri'] == $item['parent-uri']) {
804 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
805 `body` = '', `title` = ''
806 WHERE `parent-uri` = '%s' AND `uid` = %d",
808 dbesc(datetime_convert()),
810 intval($importer['uid'])
814 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
815 `body` = '', `title` = ''
816 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
818 dbesc(datetime_convert()),
820 intval($importer['uid'])
822 if($item['last-child']) {
823 // ensure that last-child is set in case the comment that had it just got wiped.
824 $q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
825 dbesc(datetime_convert()),
826 dbesc($item['parent-uri']),
829 // who is the last child now?
830 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
831 ORDER BY `created` DESC LIMIT 1",
832 dbesc($item['parent-uri']),
833 intval($importer['uid'])
836 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
848 $item_id = $item->get_id();
849 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
850 if(isset($rawthread[0]['attribs']['']['ref'])) {
852 $parent_uri = $rawthread[0]['attribs']['']['ref'];
856 if(($is_reply) && is_array($contact)) {
858 // Have we seen it? If not, import it.
860 $item_id = $item->get_id();
862 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
864 intval($importer['uid'])
866 // FIXME update content if 'updated' changes
868 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
869 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
870 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
871 dbesc(datetime_convert()),
873 intval($importer['uid'])
875 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
876 intval($allow[0]['data']),
877 dbesc(datetime_convert()),
879 intval($importer['uid'])
885 $datarray = get_atom_elements($feed,$item);
886 if($contact['network'] === 'stat' && strlen($datarray['title']))
887 unset($datarray['title']);
888 $datarray['parent-uri'] = $parent_uri;
889 $datarray['uid'] = $importer['uid'];
890 $datarray['contact-id'] = $contact['id'];
891 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
892 $datarray['type'] = 'activity';
893 $datarray['gravity'] = GRAVITY_LIKE;
896 $r = item_store($datarray);
901 // Head post of a conversation. Have we seen it? If not, import it.
903 $item_id = $item->get_id();
904 $r = q("SELECT `uid`, `last-child`, `edited` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
906 intval($importer['uid'])
909 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
910 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
911 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
912 intval($allow[0]['data']),
913 dbesc(datetime_convert()),
915 intval($importer['uid'])
920 $datarray = get_atom_elements($feed,$item);
922 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
923 logger('consume-feed: New follower');
924 new_follower($importer,$contact,$datarray,$item);
927 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
928 lose_follower($importer,$contact,$datarray,$item);
931 if(! is_array($contact))
934 if($contact['network'] === 'stat') {
935 if(strlen($datarray['title']))
936 unset($datarray['title']);
937 if(($contact['rel'] == REL_VIP) || ($contact['rel'] == REL_BUD))
938 $datarray['last-child'] = 1;
940 $datarray['parent-uri'] = $item_id;
941 $datarray['uid'] = $importer['uid'];
942 $datarray['contact-id'] = $contact['id'];
943 $r = item_store($datarray);
952 function new_follower($importer,$contact,$datarray,$item) {
953 $url = notags(trim($datarray['author-link']));
954 $name = notags(trim($datarray['author-name']));
955 $photo = notags(trim($datarray['author-avatar']));
957 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
958 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
959 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
961 if(is_array($contact)) {
962 if($contact['network'] == 'stat' && $contact['rel'] == REL_FAN) {
963 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
965 intval($contact['id']),
966 intval($importer['uid'])
970 // send email notification to owner?
974 // create contact record - set to readonly
976 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `name`, `nick`, `photo`, `network`, `rel`,
977 `blocked`, `readonly`, `pending` )
978 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 1, 1 ) ",
979 intval($importer['uid']),
980 dbesc(datetime_convert()),
988 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 AND `rel` = %d LIMIT 1",
989 intval($importer['uid']),
994 $contact_record = $r[0];
996 // create notification
997 $hash = random_string();
999 if(is_array($contact_record)) {
1000 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
1001 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
1002 intval($importer['uid']),
1003 intval($contact_record['id']),
1005 dbesc(datetime_convert())
1011 function lose_follower($importer,$contact,$datarray,$item) {
1013 if(($contact['rel'] == REL_BUD) || ($contact['rel'] == REL_FAN)) {
1014 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
1016 intval($contact['id'])
1020 contact_remove($contact['id']);
1025 function subscribe_to_hub($url,$importer,$contact) {
1027 if(is_array($importer)) {
1028 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
1029 intval($importer['uid'])
1035 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
1037 // Use a single verify token, even if multiple hubs
1039 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
1041 $params= 'hub.mode=subscribe&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
1043 if(! strlen($contact['hub-verify'])) {
1044 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
1045 dbesc($verify_token),
1046 intval($contact['id'])
1050 post_url($url,$params);