3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
8 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
11 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
12 $public_feed = (($dfrn_id) ? false : true);
13 $starred = false; // not yet implemented, possible security issues
16 if($public_feed && $a->argc > 2) {
17 for($x = 2; $x < $a->argc; $x++) {
18 if($a->argv[$x] == 'converse')
20 if($a->argv[$x] == 'starred')
25 // default permissions - anonymous user
27 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
29 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
30 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
31 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
39 $owner_id = $owner['user_uid'];
40 $owner_nick = $owner['nickname'];
42 $birthday = feed_birthday($owner_id,$owner['timezone']);
49 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
53 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
54 $my_id = '1:' . $dfrn_id;
57 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
58 $my_id = '0:' . $dfrn_id;
65 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
73 $groups = init_groups_visitor($contact['id']);
76 for($x = 0; $x < count($groups); $x ++)
77 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
78 $gs = implode('|', $groups);
81 $gs = '<<>>' ; // Impossible to match
83 $sql_extra = sprintf("
84 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
85 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
86 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
87 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
89 intval($contact['id']),
90 intval($contact['id']),
101 if(! strlen($last_update))
102 $last_update = 'now -30 days';
106 $sql_extra .= " AND `contact`.`self` = 1 ";
109 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
111 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
112 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
113 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
114 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
115 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
116 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
117 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
118 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
119 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
120 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
121 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
123 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
130 // Will check further below if this actually returned results.
131 // We will provide an empty feed if that is the case.
135 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
139 $hubxml = feed_hublinks();
141 $salmon = feed_salmonlinks($owner_nick);
143 $atom .= replace_macros($feed_template, array(
144 '$version' => xmlify(FRIENDICA_VERSION),
145 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
146 '$feed_title' => xmlify($owner['name']),
147 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
149 '$salmon' => $salmon,
150 '$name' => xmlify($owner['name']),
151 '$profile_page' => xmlify($owner['url']),
152 '$photo' => xmlify($owner['photo']),
153 '$thumb' => xmlify($owner['thumb']),
154 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
155 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
156 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
157 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
158 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
161 call_hooks('atom_feed', $atom);
163 if(! count($items)) {
165 call_hooks('atom_feed_end', $atom);
167 $atom .= '</feed>' . "\r\n";
171 foreach($items as $item) {
173 // public feeds get html, our own nodes use bbcode
177 // catch any email that's in a public conversation and make sure it doesn't leak
185 $atom .= atom_entry($item,$type,null,$owner,true);
188 call_hooks('atom_feed_end', $atom);
190 $atom .= '</feed>' . "\r\n";
196 function construct_verb($item) {
198 return $item['verb'];
199 return ACTIVITY_POST;
202 function construct_activity_object($item) {
204 if($item['object']) {
205 $o = '<as:object>' . "\r\n";
206 $r = parse_xml_string($item['object'],false);
212 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
214 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
216 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
218 if(substr($r->link,0,1) === '<') {
219 // patch up some facebook "like" activity objects that got stored incorrectly
220 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
221 // we can probably remove this hack here and in the following function in a few months time.
222 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
223 $r->link = str_replace('&','&', $r->link);
224 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
228 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
231 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
232 $o .= '</as:object>' . "\r\n";
239 function construct_activity_target($item) {
241 if($item['target']) {
242 $o = '<as:target>' . "\r\n";
243 $r = parse_xml_string($item['target'],false);
247 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
249 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
251 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
253 if(substr($r->link,0,1) === '<') {
254 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
255 $r->link = str_replace('&','&', $r->link);
256 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
260 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
263 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
264 $o .= '</as:target>' . "\r\n";
274 function get_atom_elements($feed,$item) {
276 require_once('library/HTMLPurifier.auto.php');
277 require_once('include/html2bbcode.php');
279 $best_photo = array();
283 $author = $item->get_author();
285 $res['author-name'] = unxmlify($author->get_name());
286 $res['author-link'] = unxmlify($author->get_link());
289 $res['author-name'] = unxmlify($feed->get_title());
290 $res['author-link'] = unxmlify($feed->get_permalink());
292 $res['uri'] = unxmlify($item->get_id());
293 $res['title'] = unxmlify($item->get_title());
294 $res['body'] = unxmlify($item->get_content());
295 $res['plink'] = unxmlify($item->get_link(0));
298 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
302 // look for a photo. We should check media size and find the best one,
303 // but for now let's just find any author photo
305 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
307 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
308 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
309 foreach($base as $link) {
310 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
311 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
312 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
317 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
319 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
320 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
321 if($base && count($base)) {
322 foreach($base as $link) {
323 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
324 $res['author-link'] = unxmlify($link['attribs']['']['href']);
325 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
326 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
327 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
333 // No photo/profile-link on the item - look at the feed level
335 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
336 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
337 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
338 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
339 foreach($base as $link) {
340 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
341 $res['author-link'] = unxmlify($link['attribs']['']['href']);
342 if(! $res['author-avatar']) {
343 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
344 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
349 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
351 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
352 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
354 if($base && count($base)) {
355 foreach($base as $link) {
356 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
357 $res['author-link'] = unxmlify($link['attribs']['']['href']);
358 if(! (x($res,'author-avatar'))) {
359 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
360 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
367 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
368 if($apps && $apps[0]['attribs']['']['source']) {
369 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
370 if($res['app'] === 'web')
371 $res['app'] = 'OStatus';
374 // base64 encoded json structure representing Diaspora signature
376 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
378 $res['dsprsig'] = unxmlify($dsig[0]['data']);
381 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
383 $res['guid'] = unxmlify($dguid[0]['data']);
385 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
387 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
391 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
394 $have_real_body = false;
396 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
398 $have_real_body = true;
399 $res['body'] = $rawenv[0]['data'];
400 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
401 // make sure nobody is trying to sneak some html tags by us
402 $res['body'] = notags(base64url_decode($res['body']));
405 $maxlen = get_max_import_size();
406 if($maxlen && (strlen($res['body']) > $maxlen))
407 $res['body'] = substr($res['body'],0, $maxlen);
409 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
410 // the content type. Our own network only emits text normally, though it might have been converted to
411 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
412 // have to assume it is all html and needs to be purified.
414 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
415 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
416 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
419 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
421 $res['body'] = reltoabs($res['body'],$base_url);
423 $res['body'] = html2bb_video($res['body']);
425 $res['body'] = oembed_html2bbcode($res['body']);
427 $config = HTMLPurifier_Config::createDefault();
428 $config->set('Cache.DefinitionImpl', null);
430 // we shouldn't need a whitelist, because the bbcode converter
431 // will strip out any unsupported tags.
433 $purifier = new HTMLPurifier($config);
434 $res['body'] = $purifier->purify($res['body']);
436 $res['body'] = @html2bbcode($res['body']);
439 $res['body'] = escape_tags($res['body']);
441 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
442 if($allow && $allow[0]['data'] == 1)
443 $res['last-child'] = 1;
445 $res['last-child'] = 0;
447 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
448 if($private && $private[0]['data'] == 1)
453 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
454 if($extid && $extid[0]['data'])
455 $res['extid'] = $extid[0]['data'];
457 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
459 $res['location'] = unxmlify($rawlocation[0]['data']);
462 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
464 $res['created'] = unxmlify($rawcreated[0]['data']);
467 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
469 $res['edited'] = unxmlify($rawedited[0]['data']);
471 if((x($res,'edited')) && (! (x($res,'created'))))
472 $res['created'] = $res['edited'];
474 if(! $res['created'])
475 $res['created'] = $item->get_date('c');
478 $res['edited'] = $item->get_date('c');
481 // Disallow time travelling posts
483 $d1 = strtotime($res['created']);
484 $d2 = strtotime($res['edited']);
485 $d3 = strtotime('now');
488 $res['created'] = datetime_convert();
490 $res['edited'] = datetime_convert();
492 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
493 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
494 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
495 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
496 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
497 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
498 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
499 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
500 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
502 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
503 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
505 foreach($base as $link) {
506 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
507 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
508 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
513 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
515 $res['coord'] = unxmlify($rawgeo[0]['data']);
518 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
520 // select between supported verbs
523 $res['verb'] = unxmlify($rawverb[0]['data']);
526 // translate OStatus unfollow to activity streams if it happened to get selected
528 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
529 $res['verb'] = ACTIVITY_UNFOLLOW;
531 $cats = $item->get_categories();
534 foreach($cats as $cat) {
535 $term = $cat->get_term();
537 $term = $cat->get_label();
538 $scheme = $cat->get_scheme();
539 if($scheme && $term && stristr($scheme,'X-DFRN:'))
540 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
542 $tag_arr[] = notags(trim($term));
544 $res['tag'] = implode(',', $tag_arr);
547 $attach = $item->get_enclosures();
550 foreach($attach as $att) {
551 $len = intval($att->get_length());
552 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
553 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
554 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
555 if(strpos($type,';'))
556 $type = substr($type,0,strpos($type,';'));
557 if((! $link) || (strpos($link,'http') !== 0))
563 $type = 'application/octet-stream';
565 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
567 $res['attach'] = implode(',', $att_arr);
570 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
573 $res['object'] = '<object>' . "\n";
574 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
575 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
576 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
578 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
579 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
580 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
581 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
582 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
583 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
584 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
585 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
587 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
588 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
589 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
590 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
592 $body = html2bb_video($body);
594 $config = HTMLPurifier_Config::createDefault();
595 $config->set('Cache.DefinitionImpl', null);
597 $purifier = new HTMLPurifier($config);
598 $body = $purifier->purify($body);
599 $body = html2bbcode($body);
602 $res['object'] .= '<content>' . $body . '</content>' . "\n";
605 $res['object'] .= '</object>' . "\n";
608 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
611 $res['target'] = '<target>' . "\n";
612 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
613 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
615 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
616 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
618 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
619 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
620 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
621 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
622 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
623 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
625 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
626 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
627 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
628 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
630 $body = html2bb_video($body);
632 $config = HTMLPurifier_Config::createDefault();
633 $config->set('Cache.DefinitionImpl', null);
635 $purifier = new HTMLPurifier($config);
636 $body = $purifier->purify($body);
637 $body = html2bbcode($body);
640 $res['target'] .= '<content>' . $body . '</content>' . "\n";
643 $res['target'] .= '</target>' . "\n";
646 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
648 call_hooks('parse_atom', $arr);
653 function encode_rel_links($links) {
655 if(! ((is_array($links)) && (count($links))))
657 foreach($links as $link) {
659 if($link['attribs']['']['rel'])
660 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
661 if($link['attribs']['']['type'])
662 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
663 if($link['attribs']['']['href'])
664 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
665 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
666 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
667 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
668 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
674 function item_store($arr,$force_parent = false) {
676 // If a Diaspora signature structure was passed in, pull it out of the
677 // item array and set it aside for later storage.
680 if(x($arr,'dsprsig')) {
681 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
682 unset($arr['dsprsig']);
685 if(x($arr, 'gravity'))
686 $arr['gravity'] = intval($arr['gravity']);
687 elseif($arr['parent-uri'] === $arr['uri'])
689 elseif(activity_match($arr['verb'],ACTIVITY_POST))
692 $arr['gravity'] = 6; // extensible catchall
695 $arr['type'] = 'remote';
697 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
699 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
700 $arr['body'] = strip_tags($arr['body']);
703 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
704 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
705 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
706 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
707 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
708 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
709 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
710 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
711 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
712 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
713 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
714 $arr['commented'] = datetime_convert();
715 $arr['received'] = datetime_convert();
716 $arr['changed'] = datetime_convert();
717 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
718 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
719 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
720 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
721 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
723 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
724 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
725 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
726 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
727 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
728 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
729 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
730 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
731 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
732 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
733 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
734 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
735 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
736 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
737 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
738 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
739 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
740 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
741 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
743 if($arr['parent-uri'] === $arr['uri']) {
746 $allow_cid = $arr['allow_cid'];
747 $allow_gid = $arr['allow_gid'];
748 $deny_cid = $arr['deny_cid'];
749 $deny_gid = $arr['deny_gid'];
753 // find the parent and snarf the item id and ACL's
754 // and anything else we need to inherit
756 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
757 dbesc($arr['parent-uri']),
763 // is the new message multi-level threaded?
764 // even though we don't support it now, preserve the info
765 // and re-attach to the conversation parent.
767 if($r[0]['uri'] != $r[0]['parent-uri']) {
768 $arr['thr-parent'] = $arr['parent-uri'];
769 $arr['parent-uri'] = $r[0]['parent-uri'];
770 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
771 ORDER BY `id` ASC LIMIT 1",
772 dbesc($r[0]['parent-uri']),
773 dbesc($r[0]['parent-uri']),
780 $parent_id = $r[0]['id'];
781 $parent_deleted = $r[0]['deleted'];
782 $allow_cid = $r[0]['allow_cid'];
783 $allow_gid = $r[0]['allow_gid'];
784 $deny_cid = $r[0]['deny_cid'];
785 $deny_gid = $r[0]['deny_gid'];
786 $arr['wall'] = $r[0]['wall'];
790 // Allow one to see reply tweets from status.net even when
791 // we don't have or can't see the original post.
794 logger('item_store: $force_parent=true, reply converted to top-level post.');
796 $arr['thr-parent'] = $arr['parent-uri'];
797 $arr['parent-uri'] = $arr['uri'];
801 logger('item_store: item parent was not found - ignoring item');
809 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
813 if($r && count($r)) {
814 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
818 call_hooks('post_remote',$arr);
820 if(x($arr,'cancel')) {
821 logger('item_store: post cancelled by plugin.');
827 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
829 $r = dbq("INSERT INTO `item` (`"
830 . implode("`, `", array_keys($arr))
832 . implode("', '", array_values($arr))
835 // find the item we just created
837 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
838 $arr['uri'], // already dbesc'd
843 $current_post = $r[0]['id'];
844 logger('item_store: created item ' . $current_post);
847 logger('item_store: could not locate created item');
851 logger('item_store: duplicated post occurred. Removing duplicates.');
852 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
855 intval($current_post)
859 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
860 $parent_id = $current_post;
862 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
865 $private = $arr['private'];
867 // Set parent id - and also make sure to inherit the parent's ACL's.
869 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
870 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
877 intval($parent_deleted),
878 intval($current_post)
881 // update the commented timestamp on the parent
883 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
884 dbesc(datetime_convert()),
885 dbesc(datetime_convert()),
890 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
891 intval($current_post),
892 dbesc($dsprsig->signed_text),
893 dbesc($dsprsig->signature),
894 dbesc($dsprsig->signer)
900 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
903 if($arr['last-child']) {
904 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
907 intval($current_post)
911 tag_deliver($arr['uid'],$current_post);
913 return $current_post;
916 function get_item_contact($item,$contacts) {
917 if(! count($contacts) || (! is_array($item)))
919 foreach($contacts as $contact) {
920 if($contact['id'] == $item['contact-id']) {
929 function tag_deliver($uid,$item_id) {
931 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
937 $u = q("select uid, nickname, language, username, email, `page-flags`, `notify-flags` from user where uid = %d limit 1",
943 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
945 $i = q("select * from item where id = %d and uid = %d limit 1",
954 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
956 // Diaspora uses their own hardwired link URL in @-tags
957 // instead of the one we supply with webfinger
959 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
961 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
963 foreach($matches as $mtch) {
964 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
966 logger('tag_deliver: mention found: ' . $mtch[2]);
974 // send a notification
976 require_once('include/enotify.php');
978 'type' => NOTIFY_TAGSELF,
979 'notify_flags' => $u[0]['notify-flags'],
980 'language' => $u[0]['language'],
981 'to_name' => $u[0]['username'],
982 'to_email' => $u[0]['email'],
983 'uid' => $u[0]['uid'],
985 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
986 'source_name' => $item['author-name'],
987 'source_link' => $item['author-link'],
988 'source_photo' => $item['author-avatar'],
989 'verb' => ACTIVITY_TAG,
993 if(! $community_page)
996 // tgroup delivery - setup a second delivery chain
997 // prevent delivery looping - only proceed
998 // if the message originated elsewhere and is a top-level post
1000 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1003 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1006 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1007 intval($u[0]['uid'])
1012 q("update item set wall = 1, origin = 1, forum_mode = 1, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s' where id = %d limit 1",
1013 dbesc($c[0]['name']),
1014 dbesc($c[0]['url']),
1015 dbesc($c[0]['thumb']),
1019 proc_run('php','include/notifier.php','tgroup',$item_id);
1028 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1032 // if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
1035 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1037 if($contact['duplex'] && $contact['dfrn-id'])
1038 $idtosend = '0:' . $orig_id;
1039 if($contact['duplex'] && $contact['issued-id'])
1040 $idtosend = '1:' . $orig_id;
1042 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1044 $rino_enable = get_config('system','rino_encrypt');
1049 $ssl_val = intval(get_config('system','ssl_policy'));
1053 case SSL_POLICY_FULL:
1054 $ssl_policy = 'full';
1056 case SSL_POLICY_SELFSIGN:
1057 $ssl_policy = 'self';
1059 case SSL_POLICY_NONE:
1061 $ssl_policy = 'none';
1065 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1067 logger('dfrn_deliver: ' . $url);
1069 $xml = fetch_url($url);
1071 $curl_stat = $a->get_curl_code();
1073 return(-1); // timed out
1075 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1080 if(strpos($xml,'<?xml') === false) {
1081 logger('dfrn_deliver: no valid XML returned');
1082 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1086 $res = parse_xml_string($xml);
1088 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1089 return (($res->status) ? $res->status : 3);
1091 $postvars = array();
1092 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1093 $challenge = hex2bin((string) $res->challenge);
1094 $perm = (($res->perm) ? $res->perm : null);
1095 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1096 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1097 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1099 $final_dfrn_id = '';
1102 if((($perm == 'rw') && (! intval($contact['writable'])))
1103 || (($perm == 'r') && (intval($contact['writable'])))) {
1104 q("update contact set writable = %d where id = %d limit 1",
1105 intval(($perm == 'rw') ? 1 : 0),
1106 intval($contact['id'])
1108 $contact['writable'] = (string) 1 - intval($contact['writable']);
1112 if(($contact['duplex'] && strlen($contact['pubkey']))
1113 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1114 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1115 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1116 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1119 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1120 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1123 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1125 if(strpos($final_dfrn_id,':') == 1)
1126 $final_dfrn_id = substr($final_dfrn_id,2);
1128 if($final_dfrn_id != $orig_id) {
1129 logger('dfrn_deliver: wrong dfrn_id.');
1130 // did not decode properly - cannot trust this site
1134 $postvars['dfrn_id'] = $idtosend;
1135 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1137 $postvars['dissolve'] = '1';
1140 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1141 $postvars['data'] = $atom;
1142 $postvars['perm'] = 'rw';
1145 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1146 $postvars['perm'] = 'r';
1149 $postvars['ssl_policy'] = $ssl_policy;
1152 $postvars['page'] = '1';
1154 if($rino && $rino_allowed && (! $dissolve)) {
1155 $key = substr(random_string(),0,16);
1156 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1157 $postvars['data'] = $data;
1158 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1161 if($dfrn_version >= 2.1) {
1162 if(($contact['duplex'] && strlen($contact['pubkey']))
1163 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1164 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1166 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1169 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1173 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1174 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1177 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1181 logger('md5 rawkey ' . md5($postvars['key']));
1183 $postvars['key'] = bin2hex($postvars['key']);
1186 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1188 $xml = post_url($contact['notify'],$postvars);
1190 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1192 $curl_stat = $a->get_curl_code();
1193 if((! $curl_stat) || (! strlen($xml)))
1194 return(-1); // timed out
1196 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1199 if(strpos($xml,'<?xml') === false) {
1200 logger('dfrn_deliver: phase 2: no valid XML returned');
1201 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1205 $res = parse_xml_string($xml);
1207 return $res->status;
1213 * consume_feed - process atom feed and update anything/everything we might need to update
1215 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1217 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1218 * It is this person's stuff that is going to be updated.
1219 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1220 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1221 * have a contact record.
1222 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1223 * might not) try and subscribe to it.
1224 * $datedir sorts in reverse order
1225 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1226 * imported prior to its children being seen in the stream unless we are certain
1227 * of how the feed is arranged/ordered.
1228 * With $pass = 1, we only pull parent items out of the stream.
1229 * With $pass = 2, we only pull children (comments/likes).
1231 * So running this twice, first with pass 1 and then with pass 2 will do the right
1232 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1233 * model where comments can have sub-threads. That would require some massive sorting
1234 * to get all the feed items into a mostly linear ordering, and might still require
1238 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1240 require_once('library/simplepie/simplepie.inc');
1242 if(! strlen($xml)) {
1243 logger('consume_feed: empty input');
1247 $feed = new SimplePie();
1248 $feed->set_raw_data($xml);
1250 $feed->enable_order_by_date(true);
1252 $feed->enable_order_by_date(false);
1256 logger('consume_feed: Error parsing XML: ' . $feed->error());
1258 $permalink = $feed->get_permalink();
1260 // Check at the feed level for updated contact name and/or photo
1264 $photo_timestamp = '';
1268 $hubs = $feed->get_links('hub');
1271 $hub = implode(',', $hubs);
1273 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1275 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1277 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1278 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1279 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1280 $new_name = $elems['name'][0]['data'];
1282 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1283 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1284 $photo_url = $elems['link'][0]['attribs']['']['href'];
1287 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1288 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1292 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1293 logger('consume_feed: Updating photo for ' . $contact['name']);
1294 require_once("Photo.php");
1295 $photo_failure = false;
1296 $have_photo = false;
1298 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1299 intval($contact['id']),
1300 intval($contact['uid'])
1303 $resource_id = $r[0]['resource-id'];
1307 $resource_id = photo_new_resource();
1310 $img_str = fetch_url($photo_url,true);
1311 $img = new Photo($img_str);
1312 if($img->is_valid()) {
1314 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1315 dbesc($resource_id),
1316 intval($contact['id']),
1317 intval($contact['uid'])
1321 $img->scaleImageSquare(175);
1323 $hash = $resource_id;
1324 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1326 $img->scaleImage(80);
1327 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1329 $img->scaleImage(48);
1330 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1334 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1335 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1336 dbesc(datetime_convert()),
1337 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1338 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1339 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1340 intval($contact['uid']),
1341 intval($contact['id'])
1346 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1347 $r = q("select * from contact where uid = %d and id = %d limit 1",
1348 intval($contact['uid']),
1349 intval($contact['id'])
1352 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1353 dbesc(notags(trim($new_name))),
1354 dbesc(datetime_convert()),
1355 intval($contact['uid']),
1356 intval($contact['id'])
1359 // do our best to update the name on content items
1362 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1363 dbesc(notags(trim($new_name))),
1364 dbesc($r[0]['name']),
1365 dbesc($r[0]['url']),
1366 intval($contact['uid'])
1371 if(strlen($birthday)) {
1372 if(substr($birthday,0,4) != $contact['bdyear']) {
1373 logger('consume_feed: updating birthday: ' . $birthday);
1377 * Add new birthday event for this person
1379 * $bdtext is just a readable placeholder in case the event is shared
1380 * with others. We will replace it during presentation to our $importer
1381 * to contain a sparkle link and perhaps a photo.
1385 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1388 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1389 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1390 intval($contact['uid']),
1391 intval($contact['id']),
1392 dbesc(datetime_convert()),
1393 dbesc(datetime_convert()),
1394 dbesc(datetime_convert('UTC','UTC', $birthday)),
1395 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1403 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1404 dbesc(substr($birthday,0,4)),
1405 intval($contact['uid']),
1406 intval($contact['id'])
1409 // This function is called twice without reloading the contact
1410 // Make sure we only create one event. This is why &$contact
1411 // is a reference var in this function
1413 $contact['bdyear'] = substr($birthday,0,4);
1418 $community_page = 0;
1419 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1421 $community_page = intval($rawtags[0]['data']);
1423 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1424 q("update contact set forum = %d where id = %d limit 1",
1425 intval($community_page),
1426 intval($contact['id'])
1428 $contact['forum'] = (string) $community_page;
1432 // process any deleted entries
1434 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1435 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1436 foreach($del_entries as $dentry) {
1438 if(isset($dentry['attribs']['']['ref'])) {
1439 $uri = $dentry['attribs']['']['ref'];
1441 if(isset($dentry['attribs']['']['when'])) {
1442 $when = $dentry['attribs']['']['when'];
1443 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1446 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1448 if($deleted && is_array($contact)) {
1449 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1450 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1452 intval($importer['uid']),
1453 intval($contact['id'])
1458 if(! $item['deleted'])
1459 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1461 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1462 $xo = parse_xml_string($item['object'],false);
1463 $xt = parse_xml_string($item['target'],false);
1464 if($xt->type === ACTIVITY_OBJ_NOTE) {
1465 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1467 intval($importer['importer_uid'])
1471 // For tags, the owner cannot remove the tag on the author's copy of the post.
1473 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1474 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1475 $author_copy = (($item['origin']) ? true : false);
1477 if($owner_remove && $author_copy)
1479 if($author_remove || $owner_remove) {
1480 $tags = explode(',',$i[0]['tag']);
1483 foreach($tags as $tag)
1484 if(trim($tag) !== trim($xo->body))
1485 $newtags[] = trim($tag);
1487 q("update item set tag = '%s' where id = %d limit 1",
1488 dbesc(implode(',',$newtags)),
1496 if($item['uri'] == $item['parent-uri']) {
1497 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1498 `body` = '', `title` = ''
1499 WHERE `parent-uri` = '%s' AND `uid` = %d",
1501 dbesc(datetime_convert()),
1502 dbesc($item['uri']),
1503 intval($importer['uid'])
1507 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1508 `body` = '', `title` = ''
1509 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1511 dbesc(datetime_convert()),
1513 intval($importer['uid'])
1515 if($item['last-child']) {
1516 // ensure that last-child is set in case the comment that had it just got wiped.
1517 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1518 dbesc(datetime_convert()),
1519 dbesc($item['parent-uri']),
1520 intval($item['uid'])
1522 // who is the last child now?
1523 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1524 ORDER BY `created` DESC LIMIT 1",
1525 dbesc($item['parent-uri']),
1526 intval($importer['uid'])
1529 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1540 // Now process the feed
1542 if($feed->get_item_quantity()) {
1544 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1546 // in inverse date order
1548 $items = array_reverse($feed->get_items());
1550 $items = $feed->get_items();
1553 foreach($items as $item) {
1556 $item_id = $item->get_id();
1557 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1558 if(isset($rawthread[0]['attribs']['']['ref'])) {
1560 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1563 if(($is_reply) && is_array($contact)) {
1568 // Have we seen it? If not, import it.
1570 $item_id = $item->get_id();
1571 $datarray = get_atom_elements($feed,$item);
1574 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1575 $datarray['author-name'] = $contact['name'];
1576 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1577 $datarray['author-link'] = $contact['url'];
1578 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1579 $datarray['author-avatar'] = $contact['thumb'];
1581 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1582 logger('consume_feed: no author information! ' . print_r($datarray,true));
1586 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1588 intval($importer['uid'])
1591 // Update content if 'updated' changes
1594 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1595 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1596 dbesc($datarray['title']),
1597 dbesc($datarray['body']),
1598 dbesc($datarray['tag']),
1599 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1601 intval($importer['uid'])
1605 // update last-child if it changes
1607 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1608 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1609 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1610 dbesc(datetime_convert()),
1612 intval($importer['uid'])
1614 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1615 intval($allow[0]['data']),
1616 dbesc(datetime_convert()),
1618 intval($importer['uid'])
1624 $force_parent = false;
1625 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1626 if($contact['network'] === NETWORK_OSTATUS)
1627 $force_parent = true;
1628 if(strlen($datarray['title']))
1629 unset($datarray['title']);
1630 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1631 dbesc(datetime_convert()),
1633 intval($importer['uid'])
1635 $datarray['last-child'] = 1;
1638 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1639 // one way feed - no remote comment ability
1640 $datarray['last-child'] = 0;
1642 $datarray['parent-uri'] = $parent_uri;
1643 $datarray['uid'] = $importer['uid'];
1644 $datarray['contact-id'] = $contact['id'];
1645 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1646 $datarray['type'] = 'activity';
1647 $datarray['gravity'] = GRAVITY_LIKE;
1648 // only one like or dislike per person
1649 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1650 intval($datarray['uid']),
1651 intval($datarray['contact-id']),
1652 dbesc($datarray['verb'])
1658 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1659 $xo = parse_xml_string($datarray['object'],false);
1660 $xt = parse_xml_string($datarray['target'],false);
1662 if($xt->type == ACTIVITY_OBJ_NOTE) {
1663 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1665 intval($importer['importer_uid'])
1670 // extract tag, if not duplicate, add to parent item
1671 if($xo->id && $xo->content) {
1672 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1673 if(! (stristr($r[0]['tag'],$newtag))) {
1674 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1675 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1683 $r = item_store($datarray,$force_parent);
1689 // Head post of a conversation. Have we seen it? If not, import it.
1691 $item_id = $item->get_id();
1693 $datarray = get_atom_elements($feed,$item);
1695 if(is_array($contact)) {
1696 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1697 $datarray['author-name'] = $contact['name'];
1698 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1699 $datarray['author-link'] = $contact['url'];
1700 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1701 $datarray['author-avatar'] = $contact['thumb'];
1704 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1705 logger('consume_feed: no author information! ' . print_r($datarray,true));
1709 // special handling for events
1711 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1712 $ev = bbtoevent($datarray['body']);
1713 if(x($ev,'desc') && x($ev,'start')) {
1714 $ev['uid'] = $importer['uid'];
1715 $ev['uri'] = $item_id;
1716 $ev['edited'] = $datarray['edited'];
1717 $ev['private'] = $datarray['private'];
1719 if(is_array($contact))
1720 $ev['cid'] = $contact['id'];
1721 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1723 intval($importer['uid'])
1726 $ev['id'] = $r[0]['id'];
1727 $xyz = event_store($ev);
1732 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1734 intval($importer['uid'])
1737 // Update content if 'updated' changes
1740 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1741 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1742 dbesc($datarray['title']),
1743 dbesc($datarray['body']),
1744 dbesc($datarray['tag']),
1745 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1747 intval($importer['uid'])
1751 // update last-child if it changes
1753 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1754 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1755 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1756 intval($allow[0]['data']),
1757 dbesc(datetime_convert()),
1759 intval($importer['uid'])
1765 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1766 logger('consume-feed: New follower');
1767 new_follower($importer,$contact,$datarray,$item);
1770 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1771 lose_follower($importer,$contact,$datarray,$item);
1775 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1776 logger('consume-feed: New friend request');
1777 new_follower($importer,$contact,$datarray,$item,true);
1780 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1781 lose_sharer($importer,$contact,$datarray,$item);
1786 if(! is_array($contact))
1789 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1790 if(strlen($datarray['title']))
1791 unset($datarray['title']);
1792 $datarray['last-child'] = 1;
1795 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1796 // one way feed - no remote comment ability
1797 $datarray['last-child'] = 0;
1800 // This is my contact on another system, but it's really me.
1801 // Turn this into a wall post.
1803 if($contact['remote_self'])
1804 $datarray['wall'] = 1;
1806 $datarray['parent-uri'] = $item_id;
1807 $datarray['uid'] = $importer['uid'];
1808 $datarray['contact-id'] = $contact['id'];
1810 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1811 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1812 // but otherwise there's a possible data mixup on the sender's system.
1813 // the tgroup delivery code called from item_store will correct it if it's a forum,
1814 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1815 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1816 $datarray['owner-name'] = $contact['name'];
1817 $datarray['owner-link'] = $contact['url'];
1818 $datarray['owner-avatar'] = $contact['thumb'];
1821 $r = item_store($datarray);
1829 function local_delivery($importer,$data) {
1833 if($importer['readonly']) {
1834 // We aren't receiving stuff from this person. But we will quietly ignore them
1835 // rather than a blatant "go away" message.
1836 logger('local_delivery: ignoring');
1841 // Consume notification feed. This may differ from consuming a public feed in several ways
1842 // - might contain email or friend suggestions
1843 // - might contain remote followup to our message
1844 // - in which case we need to accept it and then notify other conversants
1845 // - we may need to send various email notifications
1847 $feed = new SimplePie();
1848 $feed->set_raw_data($data);
1849 $feed->enable_order_by_date(false);
1852 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1853 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1854 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1856 $newloc['uid'] = $importer['importer_uid'];
1857 $newloc['cid'] = $importer['id'];
1858 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1859 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1860 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1861 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1862 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1863 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1864 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1865 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1866 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1867 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1870 // merge with current record, current contents have priority
1871 // update record, set url-updated
1872 // update profile photos
1877 // handle friend suggestion notification
1879 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1880 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1881 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1883 $fsugg['uid'] = $importer['importer_uid'];
1884 $fsugg['cid'] = $importer['id'];
1885 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1886 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1887 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1888 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1889 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1891 // Does our member already have a friend matching this description?
1893 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1894 dbesc($fsugg['name']),
1895 dbesc(normalise_link($fsugg['url'])),
1896 intval($fsugg['uid'])
1901 // Do we already have an fcontact record for this person?
1904 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1905 dbesc($fsugg['url']),
1906 dbesc($fsugg['name']),
1907 dbesc($fsugg['request'])
1912 // OK, we do. Do we already have an introduction for this person ?
1913 $r = q("select id from intro where uid = %d and fid = %d limit 1",
1914 intval($fsugg['uid']),
1921 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1922 dbesc($fsugg['name']),
1923 dbesc($fsugg['url']),
1924 dbesc($fsugg['photo']),
1925 dbesc($fsugg['request'])
1927 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1928 dbesc($fsugg['url']),
1929 dbesc($fsugg['name']),
1930 dbesc($fsugg['request'])
1935 // database record did not get created. Quietly give up.
1940 $hash = random_string();
1942 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1943 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1944 intval($fsugg['uid']),
1946 intval($fsugg['cid']),
1947 dbesc($fsugg['body']),
1949 dbesc(datetime_convert()),
1954 'type' => NOTIFY_SUGGEST,
1955 'notify_flags' => $importer['notify-flags'],
1956 'language' => $importer['language'],
1957 'to_name' => $importer['username'],
1958 'to_email' => $importer['email'],
1959 'uid' => $importer['importer_uid'],
1961 'link' => $a->get_baseurl() . '/notifications/intros',
1962 'source_name' => $importer['name'],
1963 'source_link' => $importer['url'],
1964 'source_photo' => $importer['photo'],
1965 'verb' => ACTIVITY_REQ_FRIEND,
1974 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1975 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1977 logger('local_delivery: private message received');
1980 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1983 $msg['uid'] = $importer['importer_uid'];
1984 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1985 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1986 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1987 $msg['contact-id'] = $importer['id'];
1988 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1989 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1991 $msg['replied'] = 0;
1992 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1993 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1994 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1998 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
1999 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2001 // send notifications.
2003 require_once('include/enotify.php');
2005 $notif_params = array(
2006 'type' => NOTIFY_MAIL,
2007 'notify_flags' => $importer['notify-flags'],
2008 'language' => $importer['language'],
2009 'to_name' => $importer['username'],
2010 'to_email' => $importer['email'],
2011 'uid' => $importer['importer_uid'],
2013 'source_name' => $msg['from-name'],
2014 'source_link' => $importer['url'],
2015 'source_photo' => $importer['thumb'],
2016 'verb' => ACTIVITY_POST,
2020 notification($notif_params);
2026 $community_page = 0;
2027 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2029 $community_page = intval($rawtags[0]['data']);
2031 if(intval($importer['forum']) != $community_page) {
2032 q("update contact set forum = %d where id = %d limit 1",
2033 intval($community_page),
2034 intval($importer['id'])
2036 $importer['forum'] = (string) $community_page;
2039 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2041 // process any deleted entries
2043 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2044 if(is_array($del_entries) && count($del_entries)) {
2045 foreach($del_entries as $dentry) {
2047 if(isset($dentry['attribs']['']['ref'])) {
2048 $uri = $dentry['attribs']['']['ref'];
2050 if(isset($dentry['attribs']['']['when'])) {
2051 $when = $dentry['attribs']['']['when'];
2052 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2055 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2059 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2060 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2062 intval($importer['importer_uid']),
2063 intval($importer['id'])
2069 if($item['deleted'])
2072 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2074 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
2075 $xo = parse_xml_string($item['object'],false);
2076 $xt = parse_xml_string($item['target'],false);
2078 if($xt->type === ACTIVITY_OBJ_NOTE) {
2079 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2081 intval($importer['importer_uid'])
2085 // For tags, the owner cannot remove the tag on the author's copy of the post.
2087 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2088 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2089 $author_copy = (($item['origin']) ? true : false);
2091 if($owner_remove && $author_copy)
2093 if($author_remove || $owner_remove) {
2094 $tags = explode(',',$i[0]['tag']);
2097 foreach($tags as $tag)
2098 if(trim($tag) !== trim($xo->body))
2099 $newtags[] = trim($tag);
2101 q("update item set tag = '%s' where id = %d limit 1",
2102 dbesc(implode(',',$newtags)),
2110 if($item['uri'] == $item['parent-uri']) {
2111 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2112 WHERE `parent-uri` = '%s' AND `uid` = %d",
2114 dbesc(datetime_convert()),
2115 dbesc($item['uri']),
2116 intval($importer['importer_uid'])
2120 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2121 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2123 dbesc(datetime_convert()),
2125 intval($importer['importer_uid'])
2127 if($item['last-child']) {
2128 // ensure that last-child is set in case the comment that had it just got wiped.
2129 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2130 dbesc(datetime_convert()),
2131 dbesc($item['parent-uri']),
2132 intval($item['uid'])
2134 // who is the last child now?
2135 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2136 ORDER BY `created` DESC LIMIT 1",
2137 dbesc($item['parent-uri']),
2138 intval($importer['importer_uid'])
2141 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2153 foreach($feed->get_items() as $item) {
2156 $item_id = $item->get_id();
2157 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2158 if(isset($rawthread[0]['attribs']['']['ref'])) {
2160 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2166 if($importer['page-flags'] == PAGE_COMMUNITY) {
2169 logger('local_delivery: possible community reply');
2172 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2174 // was the top-level post for this reply written by somebody on this site?
2175 // Specifically, the recipient?
2177 $is_a_remote_comment = false;
2179 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2180 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2181 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2182 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2183 AND `item`.`uid` = %d
2188 intval($importer['importer_uid'])
2191 $is_a_remote_comment = true;
2193 // Does this have the characteristics of a community comment?
2194 // If it's a reply to a wall post on a community page it's a
2195 // valid community comment. Also forum_mode makes it valid for sure.
2196 // If neither, it's not.
2198 if($is_a_remote_comment && $community) {
2199 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2200 $is_a_remote_comment = false;
2201 logger('local_delivery: not a community reply');
2205 if($is_a_remote_comment) {
2206 logger('local_delivery: received remote comment');
2208 // remote reply to our post. Import and then notify everybody else.
2209 $datarray = get_atom_elements($feed,$item);
2212 // TODO: make this next part work against both delivery threads of a community post
2214 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2215 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2216 // they won't know what to do so don't report an error. Just quietly die.
2220 $datarray['type'] = 'remote-comment';
2221 $datarray['wall'] = 1;
2222 $datarray['parent-uri'] = $parent_uri;
2223 $datarray['uid'] = $importer['importer_uid'];
2224 $datarray['owner-name'] = $r[0]['name'];
2225 $datarray['owner-link'] = $r[0]['url'];
2226 $datarray['owner-avatar'] = $r[0]['thumb'];
2227 $datarray['contact-id'] = $importer['id'];
2228 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2230 $datarray['type'] = 'activity';
2231 $datarray['gravity'] = GRAVITY_LIKE;
2232 $datarray['last-child'] = 0;
2233 // only one like or dislike per person
2234 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2235 intval($datarray['uid']),
2236 intval($datarray['contact-id']),
2237 dbesc($datarray['verb'])
2243 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2246 $xo = parse_xml_string($datarray['object'],false);
2247 $xt = parse_xml_string($datarray['target'],false);
2249 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2251 // extract tag, if not duplicate, and this user allows tags, add to parent item
2253 if($xo->id && $xo->content) {
2254 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2256 if(! (stristr($r[0]['tag'],$newtag))) {
2257 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2258 intval($importer['importer_uid'])
2260 if(count($i) && ! ($i[0]['blocktags'])) {
2261 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2262 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2272 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2273 // if(! stristr($datarray['tag'],$newtag)) {
2274 // if(strlen($datarray['tag']))
2275 // $datarray['tag'] .= ',';
2276 // $datarray['tag'] .= $newtag;
2281 $posted_id = item_store($datarray);
2285 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2287 intval($importer['importer_uid'])
2290 $parent = $r[0]['parent'];
2293 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2294 dbesc(datetime_convert()),
2295 intval($importer['importer_uid']),
2296 intval($r[0]['parent'])
2299 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2300 dbesc(datetime_convert()),
2301 intval($importer['importer_uid']),
2306 if($posted_id && $parent) {
2308 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2310 if((! $is_like) && (! $importer['self'])) {
2312 require_once('include/enotify.php');
2315 'type' => NOTIFY_COMMENT,
2316 'notify_flags' => $importer['notify-flags'],
2317 'language' => $importer['language'],
2318 'to_name' => $importer['username'],
2319 'to_email' => $importer['email'],
2320 'uid' => $importer['importer_uid'],
2321 'item' => $datarray,
2322 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2323 'source_name' => stripslashes($datarray['author-name']),
2324 'source_link' => $datarray['author-link'],
2325 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2326 ? $importer['thumb'] : $datarray['author-avatar']),
2327 'verb' => ACTIVITY_POST,
2329 'parent' => $parent,
2342 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2344 $item_id = $item->get_id();
2345 $datarray = get_atom_elements($feed,$item);
2347 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2349 intval($importer['importer_uid'])
2352 // Update content if 'updated' changes
2355 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2356 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2357 dbesc($datarray['title']),
2358 dbesc($datarray['body']),
2359 dbesc($datarray['tag']),
2360 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2362 intval($importer['importer_uid'])
2366 // update last-child if it changes
2368 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2369 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2370 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2371 dbesc(datetime_convert()),
2373 intval($importer['importer_uid'])
2375 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2376 intval($allow[0]['data']),
2377 dbesc(datetime_convert()),
2379 intval($importer['importer_uid'])
2385 $datarray['parent-uri'] = $parent_uri;
2386 $datarray['uid'] = $importer['importer_uid'];
2387 $datarray['contact-id'] = $importer['id'];
2388 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2389 $datarray['type'] = 'activity';
2390 $datarray['gravity'] = GRAVITY_LIKE;
2391 // only one like or dislike per person
2392 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2393 intval($datarray['uid']),
2394 intval($datarray['contact-id']),
2395 dbesc($datarray['verb'])
2402 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2404 $xo = parse_xml_string($datarray['object'],false);
2405 $xt = parse_xml_string($datarray['target'],false);
2407 if($xt->type == ACTIVITY_OBJ_NOTE) {
2408 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2410 intval($importer['importer_uid'])
2415 // extract tag, if not duplicate, add to parent item
2417 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2418 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2419 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2427 $posted_id = item_store($datarray);
2429 // find out if our user is involved in this conversation and wants to be notified.
2431 if($datarray['type'] != 'activity') {
2433 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2435 intval($importer['importer_uid'])
2438 if(count($myconv)) {
2439 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2441 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2442 if(! link_compare($datarray['author-link'],$importer_url)) {
2445 foreach($myconv as $conv) {
2447 // now if we find a match, it means we're in this conversation
2449 if(! link_compare($conv['author-link'],$importer_url))
2452 require_once('include/enotify.php');
2454 $conv_parent = $conv['parent'];
2457 'type' => NOTIFY_COMMENT,
2458 'notify_flags' => $importer['notify-flags'],
2459 'language' => $importer['language'],
2460 'to_name' => $importer['username'],
2461 'to_email' => $importer['email'],
2462 'uid' => $importer['importer_uid'],
2463 'item' => $datarray,
2464 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2465 'source_name' => stripslashes($datarray['author-name']),
2466 'source_link' => $datarray['author-link'],
2467 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2468 ? $importer['thumb'] : $datarray['author-avatar']),
2469 'verb' => ACTIVITY_POST,
2471 'parent' => $conv_parent,
2475 // only send one notification
2487 // Head post of a conversation. Have we seen it? If not, import it.
2490 $item_id = $item->get_id();
2491 $datarray = get_atom_elements($feed,$item);
2493 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2494 $ev = bbtoevent($datarray['body']);
2495 if(x($ev,'desc') && x($ev,'start')) {
2496 $ev['cid'] = $importer['id'];
2497 $ev['uid'] = $importer['uid'];
2498 $ev['uri'] = $item_id;
2499 $ev['edited'] = $datarray['edited'];
2500 $ev['private'] = $datarray['private'];
2502 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2504 intval($importer['uid'])
2507 $ev['id'] = $r[0]['id'];
2508 $xyz = event_store($ev);
2513 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2515 intval($importer['importer_uid'])
2518 // Update content if 'updated' changes
2521 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2522 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2523 dbesc($datarray['title']),
2524 dbesc($datarray['body']),
2525 dbesc($datarray['tag']),
2526 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2528 intval($importer['importer_uid'])
2532 // update last-child if it changes
2534 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2535 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2536 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2537 intval($allow[0]['data']),
2538 dbesc(datetime_convert()),
2540 intval($importer['importer_uid'])
2546 // This is my contact on another system, but it's really me.
2547 // Turn this into a wall post.
2549 if($importer['remote_self'])
2550 $datarray['wall'] = 1;
2552 $datarray['parent-uri'] = $item_id;
2553 $datarray['uid'] = $importer['importer_uid'];
2554 $datarray['contact-id'] = $importer['id'];
2556 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2557 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2558 // but otherwise there's a possible data mixup on the sender's system.
2559 // the tgroup delivery code called from item_store will correct it if it's a forum,
2560 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2561 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2562 $datarray['owner-name'] = $importer['senderName'];
2563 $datarray['owner-link'] = $importer['url'];
2564 $datarray['owner-avatar'] = $importer['thumb'];
2567 $r = item_store($datarray);
2578 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2579 $url = notags(trim($datarray['author-link']));
2580 $name = notags(trim($datarray['author-name']));
2581 $photo = notags(trim($datarray['author-avatar']));
2583 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2584 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2585 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2587 if(is_array($contact)) {
2588 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2589 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2590 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2591 intval(CONTACT_IS_FRIEND),
2592 intval($contact['id']),
2593 intval($importer['uid'])
2596 // send email notification to owner?
2600 // create contact record
2602 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2603 `blocked`, `readonly`, `pending`, `writable` )
2604 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2605 intval($importer['uid']),
2606 dbesc(datetime_convert()),
2608 dbesc(normalise_link($url)),
2612 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2613 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2615 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2616 intval($importer['uid']),
2620 $contact_record = $r[0];
2622 // create notification
2623 $hash = random_string();
2625 if(is_array($contact_record)) {
2626 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2627 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2628 intval($importer['uid']),
2629 intval($contact_record['id']),
2631 dbesc(datetime_convert())
2634 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2635 intval($importer['uid'])
2639 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2640 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2641 $email = replace_macros($email_tpl, array(
2642 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2644 '$myname' => $r[0]['username'],
2645 '$siteurl' => $a->get_baseurl(),
2646 '$sitename' => $a->config['sitename']
2648 $res = mail($r[0]['email'],
2649 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2651 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2652 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2653 . 'Content-transfer-encoding: 8bit' );
2660 function lose_follower($importer,$contact,$datarray,$item) {
2662 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2663 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2664 intval(CONTACT_IS_SHARING),
2665 intval($contact['id'])
2669 contact_remove($contact['id']);
2673 function lose_sharer($importer,$contact,$datarray,$item) {
2675 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2676 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2677 intval(CONTACT_IS_FOLLOWER),
2678 intval($contact['id'])
2682 contact_remove($contact['id']);
2687 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2689 if(is_array($importer)) {
2690 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2691 intval($importer['uid'])
2695 // Diaspora has different message-ids in feeds than they do
2696 // through the direct Diaspora protocol. If we try and use
2697 // the feed, we'll get duplicates. So don't.
2699 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2702 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2704 // Use a single verify token, even if multiple hubs
2706 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2708 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2710 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2712 if(! strlen($contact['hub-verify'])) {
2713 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2714 dbesc($verify_token),
2715 intval($contact['id'])
2719 post_url($url,$params);
2725 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2729 $name = xmlify($name);
2730 $uri = xmlify($uri);
2733 $photo = xmlify($photo);
2737 $o .= "<name>$name</name>\r\n";
2738 $o .= "<uri>$uri</uri>\r\n";
2739 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2740 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2742 call_hooks('atom_author', $o);
2744 $o .= "</$tag>\r\n";
2748 function atom_entry($item,$type,$author,$owner,$comment = false) {
2752 if(! $item['parent'])
2755 if($item['deleted'])
2756 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2759 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2760 $body = fix_private_photos($item['body'],$owner['uid']);
2762 $body = $item['body'];
2765 $o = "\r\n\r\n<entry>\r\n";
2767 if(is_array($author))
2768 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2770 $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']));
2771 if(strlen($item['owner-name']))
2772 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2774 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2775 $o .= '<thr:in-reply-to ref="' . xmlify($item['parent-uri']) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
2777 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2778 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2779 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2780 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2781 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2782 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2783 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2785 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2787 if($item['location']) {
2788 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2789 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2793 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2795 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2796 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2799 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2800 if($item['bookmark'])
2801 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2804 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2807 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2809 if($item['signed_text']) {
2810 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2811 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2814 $verb = construct_verb($item);
2815 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2816 $actobj = construct_activity_object($item);
2819 $actarg = construct_activity_target($item);
2823 $tags = item_getfeedtags($item);
2825 foreach($tags as $t) {
2826 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2830 $o .= item_getfeedattach($item);
2832 $mentioned = get_mentions($item);
2836 call_hooks('atom_entry', $o);
2838 $o .= '</entry>' . "\r\n";
2843 function fix_private_photos($s,$uid) {
2845 logger('fix_private_photos');
2847 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2848 $image = $matches[1];
2849 logger('fix_private_photos: found photo ' . $image);
2850 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2851 $i = basename($image);
2852 $i = str_replace('.jpg','',$i);
2853 $x = strpos($i,'-');
2855 $res = substr($i,$x+1);
2856 $i = substr($i,0,$x);
2857 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2863 logger('replacing photo');
2864 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2867 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2875 function item_getfeedtags($item) {
2878 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2880 for($x = 0; $x < $cnt; $x ++) {
2882 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2886 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2888 for($x = 0; $x < $cnt; $x ++) {
2890 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2896 function item_getfeedattach($item) {
2898 $arr = explode(',',$item['attach']);
2900 foreach($arr as $r) {
2902 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2904 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2905 if(intval($matches[2]))
2906 $ret .= 'length="' . intval($matches[2]) . '" ';
2907 if($matches[4] !== ' ')
2908 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2909 $ret .= ' />' . "\r\n";
2918 function item_expire($uid,$days) {
2920 if((! $uid) || (! $days))
2923 $r = q("SELECT * FROM `item`
2925 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
2935 $expire_items = get_pconfig($uid, 'expire','items');
2936 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2938 $expire_notes = get_pconfig($uid, 'expire','notes');
2939 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2941 $expire_starred = get_pconfig($uid, 'expire','starred');
2942 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2944 $expire_photos = get_pconfig($uid, 'expire','photos');
2945 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2947 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2949 foreach($r as $item) {
2951 // don't expire filed items
2953 if(strpos($item['file'],'[') !== false)
2956 // Only expire posts, not photos and photo comments
2958 if($expire_photos==0 && strlen($item['resource-id']))
2960 if($expire_starred==0 && intval($item['starred']))
2962 if($expire_notes==0 && $item['type']=='note')
2964 if($expire_items==0 && $item['type']!='note')
2967 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2968 dbesc(datetime_convert()),
2969 dbesc(datetime_convert()),
2975 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2976 dbesc(datetime_convert()),
2977 dbesc(datetime_convert()),
2978 dbesc($item['parent-uri']),
2979 intval($item['uid'])
2984 proc_run('php',"include/notifier.php","expire","$uid");
2989 function drop_items($items) {
2992 if((! local_user()) && (! $remote_user()))
2996 foreach($items as $item) {
2997 $owner = drop_item($item,false);
2998 if($owner && ! $uid)
3003 // multiple threads may have been deleted, send an expire notification
3006 proc_run('php',"include/notifier.php","expire","$uid");
3010 function drop_item($id,$interactive = true) {
3014 // locate item to be deleted
3016 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3023 notice( t('Item not found.') . EOL);
3024 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3029 $owner = $item['uid'];
3031 // check if logged in user is either the author or owner of this item
3033 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3037 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3038 dbesc(datetime_convert()),
3039 dbesc(datetime_convert()),
3043 // If item is a link to a photo resource, nuke all the associated photos
3044 // (visitors will not have photo resources)
3045 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3046 // generate a resource-id and therefore aren't intimately linked to the item.
3048 if(strlen($item['resource-id'])) {
3049 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3050 dbesc($item['resource-id']),
3051 intval($item['uid'])
3053 // ignore the result
3056 // If item is a link to an event, nuke the event record.
3058 if(intval($item['event-id'])) {
3059 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3060 intval($item['event-id']),
3061 intval($item['uid'])
3063 // ignore the result
3067 // If it's the parent of a comment thread, kill all the kids
3069 if($item['uri'] == $item['parent-uri']) {
3070 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3071 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3072 dbesc(datetime_convert()),
3073 dbesc(datetime_convert()),
3074 dbesc($item['parent-uri']),
3075 intval($item['uid'])
3077 // ignore the result
3080 // ensure that last-child is set in case the comment that had it just got wiped.
3081 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3082 dbesc(datetime_convert()),
3083 dbesc($item['parent-uri']),
3084 intval($item['uid'])
3086 // who is the last child now?
3087 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d ORDER BY `edited` DESC LIMIT 1",
3088 dbesc($item['parent-uri']),
3089 intval($item['uid'])
3092 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3097 $drop_id = intval($item['id']);
3099 // send the notification upstream/downstream as the case may be
3104 proc_run('php',"include/notifier.php","drop","$drop_id");
3105 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3111 notice( t('Permission denied.') . EOL);
3112 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);