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']);
438 elseif(! $have_real_body) {
440 // it's not one of our messages and it has no tags
441 // so it's probably just text. We'll escape it just to be safe.
443 $res['body'] = escape_tags($res['body']);
446 // this tag is obsolete but we keep it for really old sites
448 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
449 if($allow && $allow[0]['data'] == 1)
450 $res['last-child'] = 1;
452 $res['last-child'] = 0;
454 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
455 if($private && $private[0]['data'] == 1)
460 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
461 if($extid && $extid[0]['data'])
462 $res['extid'] = $extid[0]['data'];
464 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
466 $res['location'] = unxmlify($rawlocation[0]['data']);
469 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
471 $res['created'] = unxmlify($rawcreated[0]['data']);
474 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
476 $res['edited'] = unxmlify($rawedited[0]['data']);
478 if((x($res,'edited')) && (! (x($res,'created'))))
479 $res['created'] = $res['edited'];
481 if(! $res['created'])
482 $res['created'] = $item->get_date('c');
485 $res['edited'] = $item->get_date('c');
488 // Disallow time travelling posts
490 $d1 = strtotime($res['created']);
491 $d2 = strtotime($res['edited']);
492 $d3 = strtotime('now');
495 $res['created'] = datetime_convert();
497 $res['edited'] = datetime_convert();
499 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
500 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
501 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
502 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
503 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
504 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
505 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
506 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
507 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
509 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
510 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
512 foreach($base as $link) {
513 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
514 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
515 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
520 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
522 $res['coord'] = unxmlify($rawgeo[0]['data']);
525 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
527 // select between supported verbs
530 $res['verb'] = unxmlify($rawverb[0]['data']);
533 // translate OStatus unfollow to activity streams if it happened to get selected
535 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
536 $res['verb'] = ACTIVITY_UNFOLLOW;
538 $cats = $item->get_categories();
541 foreach($cats as $cat) {
542 $term = $cat->get_term();
544 $term = $cat->get_label();
545 $scheme = $cat->get_scheme();
546 if($scheme && $term && stristr($scheme,'X-DFRN:'))
547 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
549 $tag_arr[] = notags(trim($term));
551 $res['tag'] = implode(',', $tag_arr);
554 $attach = $item->get_enclosures();
557 foreach($attach as $att) {
558 $len = intval($att->get_length());
559 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
560 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
561 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
562 if(strpos($type,';'))
563 $type = substr($type,0,strpos($type,';'));
564 if((! $link) || (strpos($link,'http') !== 0))
570 $type = 'application/octet-stream';
572 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
574 $res['attach'] = implode(',', $att_arr);
577 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
580 $res['object'] = '<object>' . "\n";
581 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
582 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
583 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
585 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
586 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
587 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
588 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
589 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
590 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
591 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
592 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
594 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
595 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
596 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
597 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
599 $body = html2bb_video($body);
601 $config = HTMLPurifier_Config::createDefault();
602 $config->set('Cache.DefinitionImpl', null);
604 $purifier = new HTMLPurifier($config);
605 $body = $purifier->purify($body);
606 $body = html2bbcode($body);
609 $res['object'] .= '<content>' . $body . '</content>' . "\n";
612 $res['object'] .= '</object>' . "\n";
615 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
618 $res['target'] = '<target>' . "\n";
619 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
620 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
622 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
623 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
625 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
626 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
627 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
628 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
629 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
630 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
632 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
633 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
634 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
635 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
637 $body = html2bb_video($body);
639 $config = HTMLPurifier_Config::createDefault();
640 $config->set('Cache.DefinitionImpl', null);
642 $purifier = new HTMLPurifier($config);
643 $body = $purifier->purify($body);
644 $body = html2bbcode($body);
647 $res['target'] .= '<content>' . $body . '</content>' . "\n";
650 $res['target'] .= '</target>' . "\n";
653 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
655 call_hooks('parse_atom', $arr);
660 function encode_rel_links($links) {
662 if(! ((is_array($links)) && (count($links))))
664 foreach($links as $link) {
666 if($link['attribs']['']['rel'])
667 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
668 if($link['attribs']['']['type'])
669 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
670 if($link['attribs']['']['href'])
671 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
672 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
673 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
674 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
675 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
681 function item_store($arr,$force_parent = false) {
683 // If a Diaspora signature structure was passed in, pull it out of the
684 // item array and set it aside for later storage.
687 if(x($arr,'dsprsig')) {
688 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
689 unset($arr['dsprsig']);
692 if(x($arr, 'gravity'))
693 $arr['gravity'] = intval($arr['gravity']);
694 elseif($arr['parent-uri'] === $arr['uri'])
696 elseif(activity_match($arr['verb'],ACTIVITY_POST))
699 $arr['gravity'] = 6; // extensible catchall
702 $arr['type'] = 'remote';
704 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
706 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
707 $arr['body'] = strip_tags($arr['body']);
710 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
711 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
712 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
713 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
714 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
715 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
716 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
717 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
718 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
719 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
720 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
721 $arr['commented'] = datetime_convert();
722 $arr['received'] = datetime_convert();
723 $arr['changed'] = datetime_convert();
724 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
725 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
726 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
727 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
728 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
730 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
731 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
732 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
733 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
734 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
735 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
736 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
737 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
738 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
739 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
740 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
741 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
742 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
743 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
744 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
745 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
746 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
747 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
748 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
750 if($arr['parent-uri'] === $arr['uri']) {
753 $allow_cid = $arr['allow_cid'];
754 $allow_gid = $arr['allow_gid'];
755 $deny_cid = $arr['deny_cid'];
756 $deny_gid = $arr['deny_gid'];
760 // find the parent and snarf the item id and ACL's
761 // and anything else we need to inherit
763 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
764 dbesc($arr['parent-uri']),
770 // is the new message multi-level threaded?
771 // even though we don't support it now, preserve the info
772 // and re-attach to the conversation parent.
774 if($r[0]['uri'] != $r[0]['parent-uri']) {
775 $arr['thr-parent'] = $arr['parent-uri'];
776 $arr['parent-uri'] = $r[0]['parent-uri'];
777 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
778 ORDER BY `id` ASC LIMIT 1",
779 dbesc($r[0]['parent-uri']),
780 dbesc($r[0]['parent-uri']),
787 $parent_id = $r[0]['id'];
788 $parent_deleted = $r[0]['deleted'];
789 $allow_cid = $r[0]['allow_cid'];
790 $allow_gid = $r[0]['allow_gid'];
791 $deny_cid = $r[0]['deny_cid'];
792 $deny_gid = $r[0]['deny_gid'];
793 $arr['wall'] = $r[0]['wall'];
797 // Allow one to see reply tweets from status.net even when
798 // we don't have or can't see the original post.
801 logger('item_store: $force_parent=true, reply converted to top-level post.');
803 $arr['thr-parent'] = $arr['parent-uri'];
804 $arr['parent-uri'] = $arr['uri'];
808 logger('item_store: item parent was not found - ignoring item');
816 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
820 if($r && count($r)) {
821 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
825 call_hooks('post_remote',$arr);
827 if(x($arr,'cancel')) {
828 logger('item_store: post cancelled by plugin.');
834 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
836 $r = dbq("INSERT INTO `item` (`"
837 . implode("`, `", array_keys($arr))
839 . implode("', '", array_values($arr))
842 // find the item we just created
844 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
845 $arr['uri'], // already dbesc'd
850 $current_post = $r[0]['id'];
851 logger('item_store: created item ' . $current_post);
854 logger('item_store: could not locate created item');
858 logger('item_store: duplicated post occurred. Removing duplicates.');
859 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
862 intval($current_post)
866 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
867 $parent_id = $current_post;
869 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
872 $private = $arr['private'];
874 // Set parent id - and also make sure to inherit the parent's ACL's.
876 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
877 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
884 intval($parent_deleted),
885 intval($current_post)
888 // update the commented timestamp on the parent
890 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
891 dbesc(datetime_convert()),
892 dbesc(datetime_convert()),
897 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
898 intval($current_post),
899 dbesc($dsprsig->signed_text),
900 dbesc($dsprsig->signature),
901 dbesc($dsprsig->signer)
907 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
910 if($arr['last-child']) {
911 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
914 intval($current_post)
918 tag_deliver($arr['uid'],$current_post);
920 return $current_post;
923 function get_item_contact($item,$contacts) {
924 if(! count($contacts) || (! is_array($item)))
926 foreach($contacts as $contact) {
927 if($contact['id'] == $item['contact-id']) {
936 function tag_deliver($uid,$item_id) {
938 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
944 $u = q("select uid, nickname, language, username, email, `page-flags`, `notify-flags` from user where uid = %d limit 1",
950 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
952 $i = q("select * from item where id = %d and uid = %d limit 1",
961 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
963 // Diaspora uses their own hardwired link URL in @-tags
964 // instead of the one we supply with webfinger
966 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
968 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
970 foreach($matches as $mtch) {
971 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
973 logger('tag_deliver: mention found: ' . $mtch[2]);
981 // send a notification
983 require_once('include/enotify.php');
985 'type' => NOTIFY_TAGSELF,
986 'notify_flags' => $u[0]['notify-flags'],
987 'language' => $u[0]['language'],
988 'to_name' => $u[0]['username'],
989 'to_email' => $u[0]['email'],
990 'uid' => $u[0]['uid'],
992 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
993 'source_name' => $item['author-name'],
994 'source_link' => $item['author-link'],
995 'source_photo' => $item['author-avatar'],
996 'verb' => ACTIVITY_TAG,
1000 if(! $community_page)
1003 // tgroup delivery - setup a second delivery chain
1004 // prevent delivery looping - only proceed
1005 // if the message originated elsewhere and is a top-level post
1007 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1010 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1013 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1014 intval($u[0]['uid'])
1019 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",
1020 dbesc($c[0]['name']),
1021 dbesc($c[0]['url']),
1022 dbesc($c[0]['thumb']),
1026 proc_run('php','include/notifier.php','tgroup',$item_id);
1035 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1039 // if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
1042 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1044 if($contact['duplex'] && $contact['dfrn-id'])
1045 $idtosend = '0:' . $orig_id;
1046 if($contact['duplex'] && $contact['issued-id'])
1047 $idtosend = '1:' . $orig_id;
1049 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1051 $rino_enable = get_config('system','rino_encrypt');
1056 $ssl_val = intval(get_config('system','ssl_policy'));
1060 case SSL_POLICY_FULL:
1061 $ssl_policy = 'full';
1063 case SSL_POLICY_SELFSIGN:
1064 $ssl_policy = 'self';
1066 case SSL_POLICY_NONE:
1068 $ssl_policy = 'none';
1072 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1074 logger('dfrn_deliver: ' . $url);
1076 $xml = fetch_url($url);
1078 $curl_stat = $a->get_curl_code();
1080 return(-1); // timed out
1082 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1087 if(strpos($xml,'<?xml') === false) {
1088 logger('dfrn_deliver: no valid XML returned');
1089 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1093 $res = parse_xml_string($xml);
1095 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1096 return (($res->status) ? $res->status : 3);
1098 $postvars = array();
1099 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1100 $challenge = hex2bin((string) $res->challenge);
1101 $perm = (($res->perm) ? $res->perm : null);
1102 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1103 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1104 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1106 $final_dfrn_id = '';
1109 if((($perm == 'rw') && (! intval($contact['writable'])))
1110 || (($perm == 'r') && (intval($contact['writable'])))) {
1111 q("update contact set writable = %d where id = %d limit 1",
1112 intval(($perm == 'rw') ? 1 : 0),
1113 intval($contact['id'])
1115 $contact['writable'] = (string) 1 - intval($contact['writable']);
1119 if(($contact['duplex'] && strlen($contact['pubkey']))
1120 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1121 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1122 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1123 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1126 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1127 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1130 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1132 if(strpos($final_dfrn_id,':') == 1)
1133 $final_dfrn_id = substr($final_dfrn_id,2);
1135 if($final_dfrn_id != $orig_id) {
1136 logger('dfrn_deliver: wrong dfrn_id.');
1137 // did not decode properly - cannot trust this site
1141 $postvars['dfrn_id'] = $idtosend;
1142 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1144 $postvars['dissolve'] = '1';
1147 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1148 $postvars['data'] = $atom;
1149 $postvars['perm'] = 'rw';
1152 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1153 $postvars['perm'] = 'r';
1156 $postvars['ssl_policy'] = $ssl_policy;
1159 $postvars['page'] = '1';
1161 if($rino && $rino_allowed && (! $dissolve)) {
1162 $key = substr(random_string(),0,16);
1163 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1164 $postvars['data'] = $data;
1165 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1168 if($dfrn_version >= 2.1) {
1169 if(($contact['duplex'] && strlen($contact['pubkey']))
1170 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1171 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1173 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1176 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1180 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1181 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1184 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1188 logger('md5 rawkey ' . md5($postvars['key']));
1190 $postvars['key'] = bin2hex($postvars['key']);
1193 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1195 $xml = post_url($contact['notify'],$postvars);
1197 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1199 $curl_stat = $a->get_curl_code();
1200 if((! $curl_stat) || (! strlen($xml)))
1201 return(-1); // timed out
1203 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1206 if(strpos($xml,'<?xml') === false) {
1207 logger('dfrn_deliver: phase 2: no valid XML returned');
1208 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1212 $res = parse_xml_string($xml);
1214 return $res->status;
1220 * consume_feed - process atom feed and update anything/everything we might need to update
1222 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1224 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1225 * It is this person's stuff that is going to be updated.
1226 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1227 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1228 * have a contact record.
1229 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1230 * might not) try and subscribe to it.
1231 * $datedir sorts in reverse order
1232 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1233 * imported prior to its children being seen in the stream unless we are certain
1234 * of how the feed is arranged/ordered.
1235 * With $pass = 1, we only pull parent items out of the stream.
1236 * With $pass = 2, we only pull children (comments/likes).
1238 * So running this twice, first with pass 1 and then with pass 2 will do the right
1239 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1240 * model where comments can have sub-threads. That would require some massive sorting
1241 * to get all the feed items into a mostly linear ordering, and might still require
1245 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1247 require_once('library/simplepie/simplepie.inc');
1249 if(! strlen($xml)) {
1250 logger('consume_feed: empty input');
1254 $feed = new SimplePie();
1255 $feed->set_raw_data($xml);
1257 $feed->enable_order_by_date(true);
1259 $feed->enable_order_by_date(false);
1263 logger('consume_feed: Error parsing XML: ' . $feed->error());
1265 $permalink = $feed->get_permalink();
1267 // Check at the feed level for updated contact name and/or photo
1271 $photo_timestamp = '';
1275 $hubs = $feed->get_links('hub');
1278 $hub = implode(',', $hubs);
1280 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1282 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1284 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1285 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1286 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1287 $new_name = $elems['name'][0]['data'];
1289 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1290 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1291 $photo_url = $elems['link'][0]['attribs']['']['href'];
1294 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1295 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1299 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1300 logger('consume_feed: Updating photo for ' . $contact['name']);
1301 require_once("Photo.php");
1302 $photo_failure = false;
1303 $have_photo = false;
1305 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1306 intval($contact['id']),
1307 intval($contact['uid'])
1310 $resource_id = $r[0]['resource-id'];
1314 $resource_id = photo_new_resource();
1317 $img_str = fetch_url($photo_url,true);
1318 $img = new Photo($img_str);
1319 if($img->is_valid()) {
1321 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1322 dbesc($resource_id),
1323 intval($contact['id']),
1324 intval($contact['uid'])
1328 $img->scaleImageSquare(175);
1330 $hash = $resource_id;
1331 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1333 $img->scaleImage(80);
1334 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1336 $img->scaleImage(48);
1337 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1341 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1342 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1343 dbesc(datetime_convert()),
1344 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1345 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1346 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1347 intval($contact['uid']),
1348 intval($contact['id'])
1353 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1354 $r = q("select * from contact where uid = %d and id = %d limit 1",
1355 intval($contact['uid']),
1356 intval($contact['id'])
1359 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1360 dbesc(notags(trim($new_name))),
1361 dbesc(datetime_convert()),
1362 intval($contact['uid']),
1363 intval($contact['id'])
1366 // do our best to update the name on content items
1369 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1370 dbesc(notags(trim($new_name))),
1371 dbesc($r[0]['name']),
1372 dbesc($r[0]['url']),
1373 intval($contact['uid'])
1378 if(strlen($birthday)) {
1379 if(substr($birthday,0,4) != $contact['bdyear']) {
1380 logger('consume_feed: updating birthday: ' . $birthday);
1384 * Add new birthday event for this person
1386 * $bdtext is just a readable placeholder in case the event is shared
1387 * with others. We will replace it during presentation to our $importer
1388 * to contain a sparkle link and perhaps a photo.
1392 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1395 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1396 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1397 intval($contact['uid']),
1398 intval($contact['id']),
1399 dbesc(datetime_convert()),
1400 dbesc(datetime_convert()),
1401 dbesc(datetime_convert('UTC','UTC', $birthday)),
1402 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1410 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1411 dbesc(substr($birthday,0,4)),
1412 intval($contact['uid']),
1413 intval($contact['id'])
1416 // This function is called twice without reloading the contact
1417 // Make sure we only create one event. This is why &$contact
1418 // is a reference var in this function
1420 $contact['bdyear'] = substr($birthday,0,4);
1425 $community_page = 0;
1426 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1428 $community_page = intval($rawtags[0]['data']);
1430 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1431 q("update contact set forum = %d where id = %d limit 1",
1432 intval($community_page),
1433 intval($contact['id'])
1435 $contact['forum'] = (string) $community_page;
1439 // process any deleted entries
1441 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1442 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1443 foreach($del_entries as $dentry) {
1445 if(isset($dentry['attribs']['']['ref'])) {
1446 $uri = $dentry['attribs']['']['ref'];
1448 if(isset($dentry['attribs']['']['when'])) {
1449 $when = $dentry['attribs']['']['when'];
1450 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1453 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1455 if($deleted && is_array($contact)) {
1456 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1457 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1459 intval($importer['uid']),
1460 intval($contact['id'])
1465 if(! $item['deleted'])
1466 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1468 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1469 $xo = parse_xml_string($item['object'],false);
1470 $xt = parse_xml_string($item['target'],false);
1471 if($xt->type === ACTIVITY_OBJ_NOTE) {
1472 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1474 intval($importer['importer_uid'])
1478 // For tags, the owner cannot remove the tag on the author's copy of the post.
1480 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1481 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1482 $author_copy = (($item['origin']) ? true : false);
1484 if($owner_remove && $author_copy)
1486 if($author_remove || $owner_remove) {
1487 $tags = explode(',',$i[0]['tag']);
1490 foreach($tags as $tag)
1491 if(trim($tag) !== trim($xo->body))
1492 $newtags[] = trim($tag);
1494 q("update item set tag = '%s' where id = %d limit 1",
1495 dbesc(implode(',',$newtags)),
1503 if($item['uri'] == $item['parent-uri']) {
1504 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1505 `body` = '', `title` = ''
1506 WHERE `parent-uri` = '%s' AND `uid` = %d",
1508 dbesc(datetime_convert()),
1509 dbesc($item['uri']),
1510 intval($importer['uid'])
1514 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1515 `body` = '', `title` = ''
1516 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1518 dbesc(datetime_convert()),
1520 intval($importer['uid'])
1522 if($item['last-child']) {
1523 // ensure that last-child is set in case the comment that had it just got wiped.
1524 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1525 dbesc(datetime_convert()),
1526 dbesc($item['parent-uri']),
1527 intval($item['uid'])
1529 // who is the last child now?
1530 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1531 ORDER BY `created` DESC LIMIT 1",
1532 dbesc($item['parent-uri']),
1533 intval($importer['uid'])
1536 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1547 // Now process the feed
1549 if($feed->get_item_quantity()) {
1551 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1553 // in inverse date order
1555 $items = array_reverse($feed->get_items());
1557 $items = $feed->get_items();
1560 foreach($items as $item) {
1563 $item_id = $item->get_id();
1564 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1565 if(isset($rawthread[0]['attribs']['']['ref'])) {
1567 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1570 if(($is_reply) && is_array($contact)) {
1575 // Have we seen it? If not, import it.
1577 $item_id = $item->get_id();
1578 $datarray = get_atom_elements($feed,$item);
1581 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1582 $datarray['author-name'] = $contact['name'];
1583 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1584 $datarray['author-link'] = $contact['url'];
1585 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1586 $datarray['author-avatar'] = $contact['thumb'];
1588 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1589 logger('consume_feed: no author information! ' . print_r($datarray,true));
1593 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1595 intval($importer['uid'])
1598 // Update content if 'updated' changes
1601 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1602 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1603 dbesc($datarray['title']),
1604 dbesc($datarray['body']),
1605 dbesc($datarray['tag']),
1606 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1608 intval($importer['uid'])
1612 // update last-child if it changes
1614 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1615 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1616 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1617 dbesc(datetime_convert()),
1619 intval($importer['uid'])
1621 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1622 intval($allow[0]['data']),
1623 dbesc(datetime_convert()),
1625 intval($importer['uid'])
1631 $force_parent = false;
1632 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1633 if($contact['network'] === NETWORK_OSTATUS)
1634 $force_parent = true;
1635 if(strlen($datarray['title']))
1636 unset($datarray['title']);
1637 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1638 dbesc(datetime_convert()),
1640 intval($importer['uid'])
1642 $datarray['last-child'] = 1;
1645 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1646 // one way feed - no remote comment ability
1647 $datarray['last-child'] = 0;
1649 $datarray['parent-uri'] = $parent_uri;
1650 $datarray['uid'] = $importer['uid'];
1651 $datarray['contact-id'] = $contact['id'];
1652 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1653 $datarray['type'] = 'activity';
1654 $datarray['gravity'] = GRAVITY_LIKE;
1655 // only one like or dislike per person
1656 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1657 intval($datarray['uid']),
1658 intval($datarray['contact-id']),
1659 dbesc($datarray['verb'])
1665 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1666 $xo = parse_xml_string($datarray['object'],false);
1667 $xt = parse_xml_string($datarray['target'],false);
1669 if($xt->type == ACTIVITY_OBJ_NOTE) {
1670 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1672 intval($importer['importer_uid'])
1677 // extract tag, if not duplicate, add to parent item
1678 if($xo->id && $xo->content) {
1679 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1680 if(! (stristr($r[0]['tag'],$newtag))) {
1681 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1682 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1690 $r = item_store($datarray,$force_parent);
1696 // Head post of a conversation. Have we seen it? If not, import it.
1698 $item_id = $item->get_id();
1700 $datarray = get_atom_elements($feed,$item);
1702 if(is_array($contact)) {
1703 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1704 $datarray['author-name'] = $contact['name'];
1705 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1706 $datarray['author-link'] = $contact['url'];
1707 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1708 $datarray['author-avatar'] = $contact['thumb'];
1711 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1712 logger('consume_feed: no author information! ' . print_r($datarray,true));
1716 // special handling for events
1718 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1719 $ev = bbtoevent($datarray['body']);
1720 if(x($ev,'desc') && x($ev,'start')) {
1721 $ev['uid'] = $importer['uid'];
1722 $ev['uri'] = $item_id;
1723 $ev['edited'] = $datarray['edited'];
1724 $ev['private'] = $datarray['private'];
1726 if(is_array($contact))
1727 $ev['cid'] = $contact['id'];
1728 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1730 intval($importer['uid'])
1733 $ev['id'] = $r[0]['id'];
1734 $xyz = event_store($ev);
1739 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1741 intval($importer['uid'])
1744 // Update content if 'updated' changes
1747 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1748 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1749 dbesc($datarray['title']),
1750 dbesc($datarray['body']),
1751 dbesc($datarray['tag']),
1752 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1754 intval($importer['uid'])
1758 // update last-child if it changes
1760 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1761 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1762 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1763 intval($allow[0]['data']),
1764 dbesc(datetime_convert()),
1766 intval($importer['uid'])
1772 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1773 logger('consume-feed: New follower');
1774 new_follower($importer,$contact,$datarray,$item);
1777 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1778 lose_follower($importer,$contact,$datarray,$item);
1782 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1783 logger('consume-feed: New friend request');
1784 new_follower($importer,$contact,$datarray,$item,true);
1787 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1788 lose_sharer($importer,$contact,$datarray,$item);
1793 if(! is_array($contact))
1796 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1797 if(strlen($datarray['title']))
1798 unset($datarray['title']);
1799 $datarray['last-child'] = 1;
1802 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1803 // one way feed - no remote comment ability
1804 $datarray['last-child'] = 0;
1807 // This is my contact on another system, but it's really me.
1808 // Turn this into a wall post.
1810 if($contact['remote_self'])
1811 $datarray['wall'] = 1;
1813 $datarray['parent-uri'] = $item_id;
1814 $datarray['uid'] = $importer['uid'];
1815 $datarray['contact-id'] = $contact['id'];
1817 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1818 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1819 // but otherwise there's a possible data mixup on the sender's system.
1820 // the tgroup delivery code called from item_store will correct it if it's a forum,
1821 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1822 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1823 $datarray['owner-name'] = $contact['name'];
1824 $datarray['owner-link'] = $contact['url'];
1825 $datarray['owner-avatar'] = $contact['thumb'];
1828 $r = item_store($datarray);
1836 function local_delivery($importer,$data) {
1840 if($importer['readonly']) {
1841 // We aren't receiving stuff from this person. But we will quietly ignore them
1842 // rather than a blatant "go away" message.
1843 logger('local_delivery: ignoring');
1848 // Consume notification feed. This may differ from consuming a public feed in several ways
1849 // - might contain email or friend suggestions
1850 // - might contain remote followup to our message
1851 // - in which case we need to accept it and then notify other conversants
1852 // - we may need to send various email notifications
1854 $feed = new SimplePie();
1855 $feed->set_raw_data($data);
1856 $feed->enable_order_by_date(false);
1859 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1860 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1861 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1863 $newloc['uid'] = $importer['importer_uid'];
1864 $newloc['cid'] = $importer['id'];
1865 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1866 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1867 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1868 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1869 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1870 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1871 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1872 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1873 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1874 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1877 // merge with current record, current contents have priority
1878 // update record, set url-updated
1879 // update profile photos
1884 // handle friend suggestion notification
1886 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1887 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1888 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1890 $fsugg['uid'] = $importer['importer_uid'];
1891 $fsugg['cid'] = $importer['id'];
1892 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1893 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1894 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1895 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1896 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1898 // Does our member already have a friend matching this description?
1900 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1901 dbesc($fsugg['name']),
1902 dbesc(normalise_link($fsugg['url'])),
1903 intval($fsugg['uid'])
1908 // Do we already have an fcontact record for this person?
1911 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1912 dbesc($fsugg['url']),
1913 dbesc($fsugg['name']),
1914 dbesc($fsugg['request'])
1919 // OK, we do. Do we already have an introduction for this person ?
1920 $r = q("select id from intro where uid = %d and fid = %d limit 1",
1921 intval($fsugg['uid']),
1928 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1929 dbesc($fsugg['name']),
1930 dbesc($fsugg['url']),
1931 dbesc($fsugg['photo']),
1932 dbesc($fsugg['request'])
1934 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1935 dbesc($fsugg['url']),
1936 dbesc($fsugg['name']),
1937 dbesc($fsugg['request'])
1942 // database record did not get created. Quietly give up.
1947 $hash = random_string();
1949 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1950 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1951 intval($fsugg['uid']),
1953 intval($fsugg['cid']),
1954 dbesc($fsugg['body']),
1956 dbesc(datetime_convert()),
1961 'type' => NOTIFY_SUGGEST,
1962 'notify_flags' => $importer['notify-flags'],
1963 'language' => $importer['language'],
1964 'to_name' => $importer['username'],
1965 'to_email' => $importer['email'],
1966 'uid' => $importer['importer_uid'],
1968 'link' => $a->get_baseurl() . '/notifications/intros',
1969 'source_name' => $importer['name'],
1970 'source_link' => $importer['url'],
1971 'source_photo' => $importer['photo'],
1972 'verb' => ACTIVITY_REQ_FRIEND,
1981 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1982 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1984 logger('local_delivery: private message received');
1987 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1990 $msg['uid'] = $importer['importer_uid'];
1991 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1992 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1993 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1994 $msg['contact-id'] = $importer['id'];
1995 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1996 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1998 $msg['replied'] = 0;
1999 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2000 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2001 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2005 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2006 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2008 // send notifications.
2010 require_once('include/enotify.php');
2012 $notif_params = array(
2013 'type' => NOTIFY_MAIL,
2014 'notify_flags' => $importer['notify-flags'],
2015 'language' => $importer['language'],
2016 'to_name' => $importer['username'],
2017 'to_email' => $importer['email'],
2018 'uid' => $importer['importer_uid'],
2020 'source_name' => $msg['from-name'],
2021 'source_link' => $importer['url'],
2022 'source_photo' => $importer['thumb'],
2023 'verb' => ACTIVITY_POST,
2027 notification($notif_params);
2033 $community_page = 0;
2034 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2036 $community_page = intval($rawtags[0]['data']);
2038 if(intval($importer['forum']) != $community_page) {
2039 q("update contact set forum = %d where id = %d limit 1",
2040 intval($community_page),
2041 intval($importer['id'])
2043 $importer['forum'] = (string) $community_page;
2046 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2048 // process any deleted entries
2050 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2051 if(is_array($del_entries) && count($del_entries)) {
2052 foreach($del_entries as $dentry) {
2054 if(isset($dentry['attribs']['']['ref'])) {
2055 $uri = $dentry['attribs']['']['ref'];
2057 if(isset($dentry['attribs']['']['when'])) {
2058 $when = $dentry['attribs']['']['when'];
2059 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2062 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2066 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2067 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2069 intval($importer['importer_uid']),
2070 intval($importer['id'])
2076 if($item['deleted'])
2079 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2081 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
2082 $xo = parse_xml_string($item['object'],false);
2083 $xt = parse_xml_string($item['target'],false);
2085 if($xt->type === ACTIVITY_OBJ_NOTE) {
2086 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2088 intval($importer['importer_uid'])
2092 // For tags, the owner cannot remove the tag on the author's copy of the post.
2094 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2095 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2096 $author_copy = (($item['origin']) ? true : false);
2098 if($owner_remove && $author_copy)
2100 if($author_remove || $owner_remove) {
2101 $tags = explode(',',$i[0]['tag']);
2104 foreach($tags as $tag)
2105 if(trim($tag) !== trim($xo->body))
2106 $newtags[] = trim($tag);
2108 q("update item set tag = '%s' where id = %d limit 1",
2109 dbesc(implode(',',$newtags)),
2117 if($item['uri'] == $item['parent-uri']) {
2118 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2119 WHERE `parent-uri` = '%s' AND `uid` = %d",
2121 dbesc(datetime_convert()),
2122 dbesc($item['uri']),
2123 intval($importer['importer_uid'])
2127 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2128 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2130 dbesc(datetime_convert()),
2132 intval($importer['importer_uid'])
2134 if($item['last-child']) {
2135 // ensure that last-child is set in case the comment that had it just got wiped.
2136 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2137 dbesc(datetime_convert()),
2138 dbesc($item['parent-uri']),
2139 intval($item['uid'])
2141 // who is the last child now?
2142 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2143 ORDER BY `created` DESC LIMIT 1",
2144 dbesc($item['parent-uri']),
2145 intval($importer['importer_uid'])
2148 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2160 foreach($feed->get_items() as $item) {
2163 $item_id = $item->get_id();
2164 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2165 if(isset($rawthread[0]['attribs']['']['ref'])) {
2167 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2173 if($importer['page-flags'] == PAGE_COMMUNITY) {
2176 logger('local_delivery: possible community reply');
2179 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2181 // was the top-level post for this reply written by somebody on this site?
2182 // Specifically, the recipient?
2184 $is_a_remote_comment = false;
2186 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2187 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2188 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2189 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2190 AND `item`.`uid` = %d
2195 intval($importer['importer_uid'])
2198 $is_a_remote_comment = true;
2200 // Does this have the characteristics of a community comment?
2201 // If it's a reply to a wall post on a community page it's a
2202 // valid community comment. Also forum_mode makes it valid for sure.
2203 // If neither, it's not.
2205 if($is_a_remote_comment && $community) {
2206 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2207 $is_a_remote_comment = false;
2208 logger('local_delivery: not a community reply');
2212 if($is_a_remote_comment) {
2213 logger('local_delivery: received remote comment');
2215 // remote reply to our post. Import and then notify everybody else.
2216 $datarray = get_atom_elements($feed,$item);
2219 // TODO: make this next part work against both delivery threads of a community post
2221 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2222 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2223 // they won't know what to do so don't report an error. Just quietly die.
2227 $datarray['type'] = 'remote-comment';
2228 $datarray['wall'] = 1;
2229 $datarray['parent-uri'] = $parent_uri;
2230 $datarray['uid'] = $importer['importer_uid'];
2231 $datarray['owner-name'] = $r[0]['name'];
2232 $datarray['owner-link'] = $r[0]['url'];
2233 $datarray['owner-avatar'] = $r[0]['thumb'];
2234 $datarray['contact-id'] = $importer['id'];
2235 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2237 $datarray['type'] = 'activity';
2238 $datarray['gravity'] = GRAVITY_LIKE;
2239 $datarray['last-child'] = 0;
2240 // only one like or dislike per person
2241 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2242 intval($datarray['uid']),
2243 intval($datarray['contact-id']),
2244 dbesc($datarray['verb'])
2250 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2253 $xo = parse_xml_string($datarray['object'],false);
2254 $xt = parse_xml_string($datarray['target'],false);
2256 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2258 // extract tag, if not duplicate, and this user allows tags, add to parent item
2260 if($xo->id && $xo->content) {
2261 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2263 if(! (stristr($r[0]['tag'],$newtag))) {
2264 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2265 intval($importer['importer_uid'])
2267 if(count($i) && ! ($i[0]['blocktags'])) {
2268 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2269 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2279 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2280 // if(! stristr($datarray['tag'],$newtag)) {
2281 // if(strlen($datarray['tag']))
2282 // $datarray['tag'] .= ',';
2283 // $datarray['tag'] .= $newtag;
2288 $posted_id = item_store($datarray);
2292 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2294 intval($importer['importer_uid'])
2297 $parent = $r[0]['parent'];
2300 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2301 dbesc(datetime_convert()),
2302 intval($importer['importer_uid']),
2303 intval($r[0]['parent'])
2306 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2307 dbesc(datetime_convert()),
2308 intval($importer['importer_uid']),
2313 if($posted_id && $parent) {
2315 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2317 if((! $is_like) && (! $importer['self'])) {
2319 require_once('include/enotify.php');
2322 'type' => NOTIFY_COMMENT,
2323 'notify_flags' => $importer['notify-flags'],
2324 'language' => $importer['language'],
2325 'to_name' => $importer['username'],
2326 'to_email' => $importer['email'],
2327 'uid' => $importer['importer_uid'],
2328 'item' => $datarray,
2329 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2330 'source_name' => stripslashes($datarray['author-name']),
2331 'source_link' => $datarray['author-link'],
2332 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2333 ? $importer['thumb'] : $datarray['author-avatar']),
2334 'verb' => ACTIVITY_POST,
2336 'parent' => $parent,
2349 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2351 $item_id = $item->get_id();
2352 $datarray = get_atom_elements($feed,$item);
2354 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2356 intval($importer['importer_uid'])
2359 // Update content if 'updated' changes
2362 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2363 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2364 dbesc($datarray['title']),
2365 dbesc($datarray['body']),
2366 dbesc($datarray['tag']),
2367 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2369 intval($importer['importer_uid'])
2373 // update last-child if it changes
2375 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2376 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2377 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2378 dbesc(datetime_convert()),
2380 intval($importer['importer_uid'])
2382 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2383 intval($allow[0]['data']),
2384 dbesc(datetime_convert()),
2386 intval($importer['importer_uid'])
2392 $datarray['parent-uri'] = $parent_uri;
2393 $datarray['uid'] = $importer['importer_uid'];
2394 $datarray['contact-id'] = $importer['id'];
2395 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2396 $datarray['type'] = 'activity';
2397 $datarray['gravity'] = GRAVITY_LIKE;
2398 // only one like or dislike per person
2399 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2400 intval($datarray['uid']),
2401 intval($datarray['contact-id']),
2402 dbesc($datarray['verb'])
2409 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2411 $xo = parse_xml_string($datarray['object'],false);
2412 $xt = parse_xml_string($datarray['target'],false);
2414 if($xt->type == ACTIVITY_OBJ_NOTE) {
2415 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2417 intval($importer['importer_uid'])
2422 // extract tag, if not duplicate, add to parent item
2424 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2425 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2426 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2434 $posted_id = item_store($datarray);
2436 // find out if our user is involved in this conversation and wants to be notified.
2438 if($datarray['type'] != 'activity') {
2440 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2442 intval($importer['importer_uid'])
2445 if(count($myconv)) {
2446 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2448 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2449 if(! link_compare($datarray['author-link'],$importer_url)) {
2452 foreach($myconv as $conv) {
2454 // now if we find a match, it means we're in this conversation
2456 if(! link_compare($conv['author-link'],$importer_url))
2459 require_once('include/enotify.php');
2461 $conv_parent = $conv['parent'];
2464 'type' => NOTIFY_COMMENT,
2465 'notify_flags' => $importer['notify-flags'],
2466 'language' => $importer['language'],
2467 'to_name' => $importer['username'],
2468 'to_email' => $importer['email'],
2469 'uid' => $importer['importer_uid'],
2470 'item' => $datarray,
2471 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2472 'source_name' => stripslashes($datarray['author-name']),
2473 'source_link' => $datarray['author-link'],
2474 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2475 ? $importer['thumb'] : $datarray['author-avatar']),
2476 'verb' => ACTIVITY_POST,
2478 'parent' => $conv_parent,
2482 // only send one notification
2494 // Head post of a conversation. Have we seen it? If not, import it.
2497 $item_id = $item->get_id();
2498 $datarray = get_atom_elements($feed,$item);
2500 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2501 $ev = bbtoevent($datarray['body']);
2502 if(x($ev,'desc') && x($ev,'start')) {
2503 $ev['cid'] = $importer['id'];
2504 $ev['uid'] = $importer['uid'];
2505 $ev['uri'] = $item_id;
2506 $ev['edited'] = $datarray['edited'];
2507 $ev['private'] = $datarray['private'];
2509 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2511 intval($importer['uid'])
2514 $ev['id'] = $r[0]['id'];
2515 $xyz = event_store($ev);
2520 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2522 intval($importer['importer_uid'])
2525 // Update content if 'updated' changes
2528 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2529 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2530 dbesc($datarray['title']),
2531 dbesc($datarray['body']),
2532 dbesc($datarray['tag']),
2533 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2535 intval($importer['importer_uid'])
2539 // update last-child if it changes
2541 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2542 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2543 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2544 intval($allow[0]['data']),
2545 dbesc(datetime_convert()),
2547 intval($importer['importer_uid'])
2553 // This is my contact on another system, but it's really me.
2554 // Turn this into a wall post.
2556 if($importer['remote_self'])
2557 $datarray['wall'] = 1;
2559 $datarray['parent-uri'] = $item_id;
2560 $datarray['uid'] = $importer['importer_uid'];
2561 $datarray['contact-id'] = $importer['id'];
2563 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2564 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2565 // but otherwise there's a possible data mixup on the sender's system.
2566 // the tgroup delivery code called from item_store will correct it if it's a forum,
2567 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2568 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2569 $datarray['owner-name'] = $importer['senderName'];
2570 $datarray['owner-link'] = $importer['url'];
2571 $datarray['owner-avatar'] = $importer['thumb'];
2574 $r = item_store($datarray);
2585 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2586 $url = notags(trim($datarray['author-link']));
2587 $name = notags(trim($datarray['author-name']));
2588 $photo = notags(trim($datarray['author-avatar']));
2590 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2591 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2592 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2594 if(is_array($contact)) {
2595 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2596 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2597 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2598 intval(CONTACT_IS_FRIEND),
2599 intval($contact['id']),
2600 intval($importer['uid'])
2603 // send email notification to owner?
2607 // create contact record
2609 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2610 `blocked`, `readonly`, `pending`, `writable` )
2611 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2612 intval($importer['uid']),
2613 dbesc(datetime_convert()),
2615 dbesc(normalise_link($url)),
2619 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2620 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2622 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2623 intval($importer['uid']),
2627 $contact_record = $r[0];
2629 // create notification
2630 $hash = random_string();
2632 if(is_array($contact_record)) {
2633 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2634 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2635 intval($importer['uid']),
2636 intval($contact_record['id']),
2638 dbesc(datetime_convert())
2641 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2642 intval($importer['uid'])
2646 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2647 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2648 $email = replace_macros($email_tpl, array(
2649 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2651 '$myname' => $r[0]['username'],
2652 '$siteurl' => $a->get_baseurl(),
2653 '$sitename' => $a->config['sitename']
2655 $res = mail($r[0]['email'],
2656 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2658 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2659 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2660 . 'Content-transfer-encoding: 8bit' );
2667 function lose_follower($importer,$contact,$datarray,$item) {
2669 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2670 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2671 intval(CONTACT_IS_SHARING),
2672 intval($contact['id'])
2676 contact_remove($contact['id']);
2680 function lose_sharer($importer,$contact,$datarray,$item) {
2682 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2683 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2684 intval(CONTACT_IS_FOLLOWER),
2685 intval($contact['id'])
2689 contact_remove($contact['id']);
2694 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2696 if(is_array($importer)) {
2697 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2698 intval($importer['uid'])
2702 // Diaspora has different message-ids in feeds than they do
2703 // through the direct Diaspora protocol. If we try and use
2704 // the feed, we'll get duplicates. So don't.
2706 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2709 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2711 // Use a single verify token, even if multiple hubs
2713 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2715 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2717 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2719 if(! strlen($contact['hub-verify'])) {
2720 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2721 dbesc($verify_token),
2722 intval($contact['id'])
2726 post_url($url,$params);
2732 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2736 $name = xmlify($name);
2737 $uri = xmlify($uri);
2740 $photo = xmlify($photo);
2744 $o .= "<name>$name</name>\r\n";
2745 $o .= "<uri>$uri</uri>\r\n";
2746 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2747 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2749 call_hooks('atom_author', $o);
2751 $o .= "</$tag>\r\n";
2755 function atom_entry($item,$type,$author,$owner,$comment = false) {
2759 if(! $item['parent'])
2762 if($item['deleted'])
2763 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2766 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2767 $body = fix_private_photos($item['body'],$owner['uid']);
2769 $body = $item['body'];
2772 $o = "\r\n\r\n<entry>\r\n";
2774 if(is_array($author))
2775 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2777 $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']));
2778 if(strlen($item['owner-name']))
2779 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2781 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2782 $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";
2784 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2785 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2786 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2787 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2788 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2789 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2790 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2792 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2794 if($item['location']) {
2795 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2796 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2800 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2802 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2803 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2806 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2807 if($item['bookmark'])
2808 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2811 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2814 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2816 if($item['signed_text']) {
2817 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2818 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2821 $verb = construct_verb($item);
2822 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2823 $actobj = construct_activity_object($item);
2826 $actarg = construct_activity_target($item);
2830 $tags = item_getfeedtags($item);
2832 foreach($tags as $t) {
2833 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2837 $o .= item_getfeedattach($item);
2839 $mentioned = get_mentions($item);
2843 call_hooks('atom_entry', $o);
2845 $o .= '</entry>' . "\r\n";
2850 function fix_private_photos($s,$uid) {
2852 logger('fix_private_photos');
2854 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2855 $image = $matches[1];
2856 logger('fix_private_photos: found photo ' . $image);
2857 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2858 $i = basename($image);
2859 $i = str_replace('.jpg','',$i);
2860 $x = strpos($i,'-');
2862 $res = substr($i,$x+1);
2863 $i = substr($i,0,$x);
2864 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2870 logger('replacing photo');
2871 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2874 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2882 function item_getfeedtags($item) {
2885 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2887 for($x = 0; $x < $cnt; $x ++) {
2889 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2893 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2895 for($x = 0; $x < $cnt; $x ++) {
2897 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2903 function item_getfeedattach($item) {
2905 $arr = explode(',',$item['attach']);
2907 foreach($arr as $r) {
2909 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2911 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2912 if(intval($matches[2]))
2913 $ret .= 'length="' . intval($matches[2]) . '" ';
2914 if($matches[4] !== ' ')
2915 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2916 $ret .= ' />' . "\r\n";
2925 function item_expire($uid,$days) {
2927 if((! $uid) || (! $days))
2930 $r = q("SELECT * FROM `item`
2932 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
2942 $expire_items = get_pconfig($uid, 'expire','items');
2943 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2945 $expire_notes = get_pconfig($uid, 'expire','notes');
2946 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2948 $expire_starred = get_pconfig($uid, 'expire','starred');
2949 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2951 $expire_photos = get_pconfig($uid, 'expire','photos');
2952 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2954 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2956 foreach($r as $item) {
2958 // don't expire filed items
2960 if(strpos($item['file'],'[') !== false)
2963 // Only expire posts, not photos and photo comments
2965 if($expire_photos==0 && strlen($item['resource-id']))
2967 if($expire_starred==0 && intval($item['starred']))
2969 if($expire_notes==0 && $item['type']=='note')
2971 if($expire_items==0 && $item['type']!='note')
2974 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2975 dbesc(datetime_convert()),
2976 dbesc(datetime_convert()),
2982 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2983 dbesc(datetime_convert()),
2984 dbesc(datetime_convert()),
2985 dbesc($item['parent-uri']),
2986 intval($item['uid'])
2991 proc_run('php',"include/notifier.php","expire","$uid");
2996 function drop_items($items) {
2999 if((! local_user()) && (! $remote_user()))
3003 foreach($items as $item) {
3004 $owner = drop_item($item,false);
3005 if($owner && ! $uid)
3010 // multiple threads may have been deleted, send an expire notification
3013 proc_run('php',"include/notifier.php","expire","$uid");
3017 function drop_item($id,$interactive = true) {
3021 // locate item to be deleted
3023 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3030 notice( t('Item not found.') . EOL);
3031 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3036 $owner = $item['uid'];
3038 // check if logged in user is either the author or owner of this item
3040 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3044 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3045 dbesc(datetime_convert()),
3046 dbesc(datetime_convert()),
3050 // If item is a link to a photo resource, nuke all the associated photos
3051 // (visitors will not have photo resources)
3052 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3053 // generate a resource-id and therefore aren't intimately linked to the item.
3055 if(strlen($item['resource-id'])) {
3056 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3057 dbesc($item['resource-id']),
3058 intval($item['uid'])
3060 // ignore the result
3063 // If item is a link to an event, nuke the event record.
3065 if(intval($item['event-id'])) {
3066 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3067 intval($item['event-id']),
3068 intval($item['uid'])
3070 // ignore the result
3074 // If it's the parent of a comment thread, kill all the kids
3076 if($item['uri'] == $item['parent-uri']) {
3077 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3078 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3079 dbesc(datetime_convert()),
3080 dbesc(datetime_convert()),
3081 dbesc($item['parent-uri']),
3082 intval($item['uid'])
3084 // ignore the result
3087 // ensure that last-child is set in case the comment that had it just got wiped.
3088 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3089 dbesc(datetime_convert()),
3090 dbesc($item['parent-uri']),
3091 intval($item['uid'])
3093 // who is the last child now?
3094 $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",
3095 dbesc($item['parent-uri']),
3096 intval($item['uid'])
3099 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3104 $drop_id = intval($item['id']);
3106 // send the notification upstream/downstream as the case may be
3111 proc_run('php',"include/notifier.php","drop","$drop_id");
3112 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3118 notice( t('Permission denied.') . EOL);
3119 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);