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) {
10 // default permissions - anonymous user
12 if(! strlen($owner_nick))
15 $public_feed = (($dfrn_id) ? false : true);
19 if($public_feed && $a->argc > 2) {
20 for($x = 2; $x < $a->argc; $x++) {
21 if($a->argv[$x] == 'converse')
23 if($a->argv[$x] == 'starred')
29 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
31 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
32 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
33 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
41 $owner_id = $owner['user_uid'];
42 $owner_nick = $owner['nickname'];
44 $birthday = feed_birthday($owner_id,$owner['timezone']);
51 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
55 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
56 $my_id = '1:' . $dfrn_id;
59 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60 $my_id = '0:' . $dfrn_id;
67 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
75 $groups = init_groups_visitor($contact['id']);
78 for($x = 0; $x < count($groups); $x ++)
79 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
80 $gs = implode('|', $groups);
83 $gs = '<<>>' ; // Impossible to match
85 $sql_extra = sprintf("
86 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
87 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
88 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
89 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
91 intval($contact['id']),
92 intval($contact['id']),
103 if(! strlen($last_update))
104 $last_update = 'now -30 days';
108 $sql_extra .= " AND `contact`.`self` = 1 ";
111 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
113 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
114 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
115 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
116 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
117 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
118 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
119 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
120 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
121 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 AND `item`.`parent` != 0
122 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
123 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
125 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
132 // Will check further below if this actually returned results.
133 // We will provide an empty feed if that is the case.
137 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
141 $hubxml = feed_hublinks();
143 $salmon = feed_salmonlinks($owner_nick);
145 $atom .= replace_macros($feed_template, array(
146 '$version' => xmlify(FRIENDIKA_VERSION),
147 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
148 '$feed_title' => xmlify($owner['name']),
149 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
151 '$salmon' => $salmon,
152 '$name' => xmlify($owner['name']),
153 '$profile_page' => xmlify($owner['url']),
154 '$photo' => xmlify($owner['photo']),
155 '$thumb' => xmlify($owner['thumb']),
156 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
157 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
158 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
159 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
162 call_hooks('atom_feed', $atom);
164 if(! count($items)) {
166 call_hooks('atom_feed_end', $atom);
168 $atom .= '</feed>' . "\r\n";
172 foreach($items as $item) {
174 // public feeds get html, our own nodes use bbcode
178 // catch any email that's in a public conversation and make sure it doesn't leak
186 $atom .= atom_entry($item,$type,null,$owner,true);
189 call_hooks('atom_feed_end', $atom);
191 $atom .= '</feed>' . "\r\n";
197 function construct_verb($item) {
199 return $item['verb'];
200 return ACTIVITY_POST;
203 function construct_activity_object($item) {
205 if($item['object']) {
206 $o = '<as:object>' . "\r\n";
207 $r = parse_xml_string($item['object'],false);
213 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
215 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
217 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
219 if(substr($r->link,0,1) === '<') {
220 // patch up some facebook "like" activity objects that got stored incorrectly
221 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
222 // we can probably remove this hack here and in the following function in a few months time.
223 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
224 $r->link = str_replace('&','&', $r->link);
225 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
229 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
232 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
233 $o .= '</as:object>' . "\r\n";
240 function construct_activity_target($item) {
242 if($item['target']) {
243 $o = '<as:target>' . "\r\n";
244 $r = parse_xml_string($item['target'],false);
248 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
250 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
252 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
254 if(substr($r->link,0,1) === '<') {
255 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
256 $r->link = str_replace('&','&', $r->link);
257 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
261 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
264 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
265 $o .= '</as:target>' . "\r\n";
275 function get_atom_elements($feed,$item) {
277 require_once('library/HTMLPurifier.auto.php');
278 require_once('include/html2bbcode.php');
280 $best_photo = array();
284 $author = $item->get_author();
286 $res['author-name'] = unxmlify($author->get_name());
287 $res['author-link'] = unxmlify($author->get_link());
290 $res['author-name'] = unxmlify($feed->get_title());
291 $res['author-link'] = unxmlify($feed->get_permalink());
293 $res['uri'] = unxmlify($item->get_id());
294 $res['title'] = unxmlify($item->get_title());
295 $res['body'] = unxmlify($item->get_content());
296 $res['plink'] = unxmlify($item->get_link(0));
298 // look for a photo. We should check media size and find the best one,
299 // but for now let's just find any author photo
301 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
303 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
304 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
305 foreach($base as $link) {
306 if(! $res['author-avatar']) {
307 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
308 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
313 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
315 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
316 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
317 if($base && count($base)) {
318 foreach($base as $link) {
319 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
320 $res['author-link'] = unxmlify($link['attribs']['']['href']);
321 if(! $res['author-avatar']) {
322 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
323 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
329 // No photo/profile-link on the item - look at the feed level
331 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
332 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
333 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
334 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
335 foreach($base as $link) {
336 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
337 $res['author-link'] = unxmlify($link['attribs']['']['href']);
338 if(! $res['author-avatar']) {
339 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
340 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
345 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
347 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
348 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
350 if($base && count($base)) {
351 foreach($base as $link) {
352 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
353 $res['author-link'] = unxmlify($link['attribs']['']['href']);
354 if(! (x($res,'author-avatar'))) {
355 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
356 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
363 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
364 if($apps && $apps[0]['attribs']['']['source']) {
365 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
366 if($res['app'] === 'web')
367 $res['app'] = 'OStatus';
370 // base64 encoded json structure representing Diaspora signature
372 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
374 $res['dsprsig'] = unxmlify($dsig[0]['data']);
377 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
379 $res['guid'] = unxmlify($dguid[0]['data']);
381 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
383 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
387 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
390 $have_real_body = false;
392 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
394 $have_real_body = true;
395 $res['body'] = $rawenv[0]['data'];
396 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
397 // make sure nobody is trying to sneak some html tags by us
398 $res['body'] = notags(base64url_decode($res['body']));
401 $maxlen = get_max_import_size();
402 if($maxlen && (strlen($res['body']) > $maxlen))
403 $res['body'] = substr($res['body'],0, $maxlen);
405 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
406 // the content type. Our own network only emits text normally, though it might have been converted to
407 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
408 // have to assume it is all html and needs to be purified.
410 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
411 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
412 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
415 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
417 $res['body'] = html2bb_video($res['body']);
419 $res['body'] = oembed_html2bbcode($res['body']);
421 $config = HTMLPurifier_Config::createDefault();
422 $config->set('Cache.DefinitionImpl', null);
424 // we shouldn't need a whitelist, because the bbcode converter
425 // will strip out any unsupported tags.
426 // $config->set('HTML.Allowed', 'p,b,a[href],i');
428 $purifier = new HTMLPurifier($config);
429 $res['body'] = $purifier->purify($res['body']);
431 $res['body'] = html2bbcode($res['body']);
434 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
435 if($allow && $allow[0]['data'] == 1)
436 $res['last-child'] = 1;
438 $res['last-child'] = 0;
440 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
441 if($private && $private[0]['data'] == 1)
446 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
447 if($extid && $extid[0]['data'])
448 $res['extid'] = $extid[0]['data'];
450 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
452 $res['location'] = unxmlify($rawlocation[0]['data']);
455 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
457 $res['created'] = unxmlify($rawcreated[0]['data']);
460 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
462 $res['edited'] = unxmlify($rawedited[0]['data']);
464 if((x($res,'edited')) && (! (x($res,'created'))))
465 $res['created'] = $res['edited'];
467 if(! $res['created'])
468 $res['created'] = $item->get_date('c');
471 $res['edited'] = $item->get_date('c');
474 // Disallow time travelling posts
476 $d1 = strtotime($res['created']);
477 $d2 = strtotime($res['edited']);
478 $d3 = strtotime('now');
481 $res['created'] = datetime_convert();
483 $res['edited'] = datetime_convert();
485 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
486 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
487 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
488 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
489 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
490 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
491 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
492 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
493 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
495 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
496 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
498 foreach($base as $link) {
499 if(! $res['owner-avatar']) {
500 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
501 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
506 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
508 $res['coord'] = unxmlify($rawgeo[0]['data']);
511 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
513 // select between supported verbs
516 $res['verb'] = unxmlify($rawverb[0]['data']);
519 // translate OStatus unfollow to activity streams if it happened to get selected
521 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
522 $res['verb'] = ACTIVITY_UNFOLLOW;
524 $cats = $item->get_categories();
527 foreach($cats as $cat) {
528 $term = $cat->get_term();
530 $term = $cat->get_label();
531 $scheme = $cat->get_scheme();
532 if($scheme && $term && stristr($scheme,'X-DFRN:'))
533 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
535 $tag_arr[] = notags(trim($term));
537 $res['tag'] = implode(',', $tag_arr);
540 $attach = $item->get_enclosures();
543 foreach($attach as $att) {
544 $len = intval($att->get_length());
545 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
546 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
547 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
548 if(strpos($type,';'))
549 $type = substr($type,0,strpos($type,';'));
550 if((! $link) || (strpos($link,'http') !== 0))
556 $type = 'application/octet-stream';
558 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
560 $res['attach'] = implode(',', $att_arr);
563 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
566 $res['object'] = '<object>' . "\n";
567 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
568 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
569 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
571 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
572 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
573 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
574 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
575 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
576 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
577 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
578 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
580 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
581 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
582 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
583 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
585 $body = html2bb_video($body);
587 $config = HTMLPurifier_Config::createDefault();
588 $config->set('Cache.DefinitionImpl', null);
590 $purifier = new HTMLPurifier($config);
591 $body = $purifier->purify($body);
592 $body = html2bbcode($body);
595 $res['object'] .= '<content>' . $body . '</content>' . "\n";
598 $res['object'] .= '</object>' . "\n";
601 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
604 $res['target'] = '<target>' . "\n";
605 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
606 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
608 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
609 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
611 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
612 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
613 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
614 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
615 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
616 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
618 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
619 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
620 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
621 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
623 $body = html2bb_video($body);
625 $config = HTMLPurifier_Config::createDefault();
626 $config->set('Cache.DefinitionImpl', null);
628 $purifier = new HTMLPurifier($config);
629 $body = $purifier->purify($body);
630 $body = html2bbcode($body);
633 $res['target'] .= '<content>' . $body . '</content>' . "\n";
636 $res['target'] .= '</target>' . "\n";
639 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
641 call_hooks('parse_atom', $arr);
646 function encode_rel_links($links) {
648 if(! ((is_array($links)) && (count($links))))
650 foreach($links as $link) {
652 if($link['attribs']['']['rel'])
653 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
654 if($link['attribs']['']['type'])
655 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
656 if($link['attribs']['']['href'])
657 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
658 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
659 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
660 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
661 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
667 function item_store($arr,$force_parent = false) {
669 // If a Diaspora signature structure was passed in, pull it out of the
670 // item array and set it aside for later storage.
673 if(x($arr,'dsprsig')) {
674 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
675 unset($arr['dsprsig']);
679 $arr['gravity'] = intval($arr['gravity']);
680 elseif($arr['parent-uri'] === $arr['uri'])
682 elseif(activity_match($arr['verb'],ACTIVITY_POST))
685 $arr['gravity'] = 6; // extensible catchall
688 $arr['type'] = 'remote';
690 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
692 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
693 $arr['body'] = strip_tags($arr['body']);
696 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
697 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
698 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
699 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
700 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
701 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
702 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
703 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
704 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
705 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
706 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
707 $arr['commented'] = datetime_convert();
708 $arr['received'] = datetime_convert();
709 $arr['changed'] = datetime_convert();
710 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
711 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
712 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
713 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
714 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
716 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
717 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
718 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
719 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
720 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
721 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
722 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
723 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
724 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
725 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
726 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
727 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
728 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
729 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
730 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
731 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
732 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
733 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
734 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
736 if($arr['parent-uri'] === $arr['uri']) {
738 $allow_cid = $arr['allow_cid'];
739 $allow_gid = $arr['allow_gid'];
740 $deny_cid = $arr['deny_cid'];
741 $deny_gid = $arr['deny_gid'];
745 // find the parent and snarf the item id and ACL's
746 // and anything else we need to inherit
748 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
749 dbesc($arr['parent-uri']),
755 // is the new message multi-level threaded?
756 // even though we don't support it now, preserve the info
757 // and re-attach to the conversation parent.
759 if($r[0]['uri'] != $r[0]['parent-uri']) {
760 $arr['thr-parent'] = $arr['parent-uri'];
761 $arr['parent-uri'] = $r[0]['parent-uri'];
762 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
763 ORDER BY `id` ASC LIMIT 1",
764 dbesc($r[0]['parent-uri']),
765 dbesc($r[0]['parent-uri']),
772 $parent_id = $r[0]['id'];
773 $parent_deleted = $r[0]['deleted'];
774 $allow_cid = $r[0]['allow_cid'];
775 $allow_gid = $r[0]['allow_gid'];
776 $deny_cid = $r[0]['deny_cid'];
777 $deny_gid = $r[0]['deny_gid'];
778 $arr['wall'] = $r[0]['wall'];
782 // Allow one to see reply tweets from status.net even when
783 // we don't have or can't see the original post.
786 logger('item_store: $force_parent=true, reply converted to top-level post.');
788 $arr['thr-parent'] = $arr['parent-uri'];
789 $arr['parent-uri'] = $arr['uri'];
793 logger('item_store: item parent was not found - ignoring item');
799 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
803 if($r && count($r)) {
804 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
808 call_hooks('post_remote',$arr);
812 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
814 $r = dbq("INSERT INTO `item` (`"
815 . implode("`, `", array_keys($arr))
817 . implode("', '", array_values($arr))
820 // find the item we just created
822 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
823 $arr['uri'], // already dbesc'd
828 $current_post = $r[0]['id'];
829 logger('item_store: created item ' . $current_post);
832 logger('item_store: could not locate created item');
836 logger('item_store: duplicated post occurred. Removing duplicates.');
837 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
840 intval($current_post)
844 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
845 $parent_id = $current_post;
847 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
850 $private = $arr['private'];
852 // Set parent id - and also make sure to inherit the parent's ACL's.
854 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
855 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
862 intval($parent_deleted),
863 intval($current_post)
866 // update the commented timestamp on the parent
868 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
869 dbesc(datetime_convert()),
870 dbesc(datetime_convert()),
875 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
876 intval($current_post),
877 dbesc($dsprsig->signed_text),
878 dbesc($dsprsig->signature),
879 dbesc($dsprsig->signer)
885 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
888 if($arr['last-child']) {
889 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
892 intval($current_post)
896 return $current_post;
899 function get_item_contact($item,$contacts) {
900 if(! count($contacts) || (! is_array($item)))
902 foreach($contacts as $contact) {
903 if($contact['id'] == $item['contact-id']) {
912 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
916 if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
919 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
921 if($contact['duplex'] && $contact['dfrn-id'])
922 $idtosend = '0:' . $orig_id;
923 if($contact['duplex'] && $contact['issued-id'])
924 $idtosend = '1:' . $orig_id;
926 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
928 $rino_enable = get_config('system','rino_encrypt');
933 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
935 logger('dfrn_deliver: ' . $url);
937 $xml = fetch_url($url);
939 $curl_stat = $a->get_curl_code();
941 return(-1); // timed out
943 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
948 if(strpos($xml,'<?xml') === false) {
949 logger('dfrn_deliver: no valid XML returned');
950 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
954 $res = parse_xml_string($xml);
956 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
957 return (($res->status) ? $res->status : 3);
960 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
961 $challenge = hex2bin((string) $res->challenge);
962 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
963 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
968 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
969 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
970 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
973 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
974 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
977 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
979 if(strpos($final_dfrn_id,':') == 1)
980 $final_dfrn_id = substr($final_dfrn_id,2);
982 if($final_dfrn_id != $orig_id) {
983 logger('dfrn_deliver: wrong dfrn_id.');
984 // did not decode properly - cannot trust this site
988 $postvars['dfrn_id'] = $idtosend;
989 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
991 $postvars['dissolve'] = '1';
994 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
995 $postvars['data'] = $atom;
996 $postvars['perm'] = 'rw';
999 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1000 $postvars['perm'] = 'r';
1003 if($rino && $rino_allowed && (! $dissolve)) {
1004 $key = substr(random_string(),0,16);
1005 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1006 $postvars['data'] = $data;
1007 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1010 if($dfrn_version >= 2.1) {
1011 if(($contact['duplex'] && strlen($contact['pubkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1012 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1015 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1019 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1020 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1023 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1027 logger('md5 rawkey ' . md5($postvars['key']));
1029 $postvars['key'] = bin2hex($postvars['key']);
1032 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1034 $xml = post_url($contact['notify'],$postvars);
1036 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1038 $curl_stat = $a->get_curl_code();
1039 if((! $curl_stat) || (! strlen($xml)))
1040 return(-1); // timed out
1042 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1045 if(strpos($xml,'<?xml') === false) {
1046 logger('dfrn_deliver: phase 2: no valid XML returned');
1047 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1051 $res = parse_xml_string($xml);
1053 return $res->status;
1059 * consume_feed - process atom feed and update anything/everything we might need to update
1061 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1063 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1064 * It is this person's stuff that is going to be updated.
1065 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1066 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1067 * have a contact record.
1068 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1069 * might not) try and subscribe to it.
1070 * $datedir sorts in reverse order
1071 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1072 * imported prior to its children being seen in the stream unless we are certain
1073 * of how the feed is arranged/ordered.
1074 * With $pass = 1, we only pull parent items out of the stream.
1075 * With $pass = 2, we only pull children (comments/likes).
1077 * So running this twice, first with pass 1 and then with pass 2 will do the right
1078 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1079 * model where comments can have sub-threads. That would require some massive sorting
1080 * to get all the feed items into a mostly linear ordering, and might still require
1084 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1086 require_once('library/simplepie/simplepie.inc');
1088 if(! strlen($xml)) {
1089 logger('consume_feed: empty input');
1093 $feed = new SimplePie();
1094 $feed->set_raw_data($xml);
1096 $feed->enable_order_by_date(true);
1098 $feed->enable_order_by_date(false);
1102 logger('consume_feed: Error parsing XML: ' . $feed->error());
1104 $permalink = $feed->get_permalink();
1106 // Check at the feed level for updated contact name and/or photo
1110 $photo_timestamp = '';
1114 $hubs = $feed->get_links('hub');
1117 $hub = implode(',', $hubs);
1119 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1121 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1123 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1124 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1125 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1126 $new_name = $elems['name'][0]['data'];
1128 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1129 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1130 $photo_url = $elems['link'][0]['attribs']['']['href'];
1133 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1134 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1138 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1139 logger('consume_feed: Updating photo for ' . $contact['name']);
1140 require_once("Photo.php");
1141 $photo_failure = false;
1142 $have_photo = false;
1144 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1145 intval($contact['id']),
1146 intval($contact['uid'])
1149 $resource_id = $r[0]['resource-id'];
1153 $resource_id = photo_new_resource();
1156 $img_str = fetch_url($photo_url,true);
1157 $img = new Photo($img_str);
1158 if($img->is_valid()) {
1160 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1161 dbesc($resource_id),
1162 intval($contact['id']),
1163 intval($contact['uid'])
1167 $img->scaleImageSquare(175);
1169 $hash = $resource_id;
1170 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1172 $img->scaleImage(80);
1173 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1175 $img->scaleImage(48);
1176 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1180 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1181 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1182 dbesc(datetime_convert()),
1183 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1184 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1185 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1186 intval($contact['uid']),
1187 intval($contact['id'])
1192 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1193 q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1194 dbesc(notags(trim($new_name))),
1195 dbesc(datetime_convert()),
1196 intval($contact['uid']),
1197 intval($contact['id'])
1201 if(strlen($birthday)) {
1202 if(substr($birthday,0,4) != $contact['bdyear']) {
1203 logger('consume_feed: updating birthday: ' . $birthday);
1207 * Add new birthday event for this person
1209 * $bdtext is just a readable placeholder in case the event is shared
1210 * with others. We will replace it during presentation to our $importer
1211 * to contain a sparkle link and perhaps a photo.
1215 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1218 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1219 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1220 intval($contact['uid']),
1221 intval($contact['id']),
1222 dbesc(datetime_convert()),
1223 dbesc(datetime_convert()),
1224 dbesc(datetime_convert('UTC','UTC', $birthday)),
1225 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1233 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1234 dbesc(substr($birthday,0,4)),
1235 intval($contact['uid']),
1236 intval($contact['id'])
1239 // This function is called twice without reloading the contact
1240 // Make sure we only create one event. This is why &$contact
1241 // is a reference var in this function
1243 $contact['bdyear'] = substr($birthday,0,4);
1249 // process any deleted entries
1251 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1252 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1253 foreach($del_entries as $dentry) {
1255 if(isset($dentry['attribs']['']['ref'])) {
1256 $uri = $dentry['attribs']['']['ref'];
1258 if(isset($dentry['attribs']['']['when'])) {
1259 $when = $dentry['attribs']['']['when'];
1260 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1263 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1265 if($deleted && is_array($contact)) {
1266 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1267 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1269 intval($importer['uid']),
1270 intval($contact['id'])
1275 if(! $item['deleted'])
1276 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1278 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1279 $xo = parse_xml_string($item['object'],false);
1280 $xt = parse_xml_string($item['target'],false);
1281 if($xt->type === ACTIVITY_OBJ_NOTE) {
1282 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1284 intval($importer['importer_uid'])
1288 // For tags, the owner cannot remove the tag on the author's copy of the post.
1290 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1291 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1292 $author_copy = (($item['origin']) ? true : false);
1294 if($owner_remove && $author_copy)
1296 if($author_remove || $owner_remove) {
1297 $tags = explode(',',$i[0]['tag']);
1300 foreach($tags as $tag)
1301 if(trim($tag) !== trim($xo->body))
1302 $newtags[] = trim($tag);
1304 q("update item set tag = '%s' where id = %d limit 1",
1305 dbesc(implode(',',$newtags)),
1313 if($item['uri'] == $item['parent-uri']) {
1314 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1315 `body` = '', `title` = ''
1316 WHERE `parent-uri` = '%s' AND `uid` = %d",
1318 dbesc(datetime_convert()),
1319 dbesc($item['uri']),
1320 intval($importer['uid'])
1324 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1325 `body` = '', `title` = ''
1326 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1328 dbesc(datetime_convert()),
1330 intval($importer['uid'])
1332 if($item['last-child']) {
1333 // ensure that last-child is set in case the comment that had it just got wiped.
1334 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1335 dbesc(datetime_convert()),
1336 dbesc($item['parent-uri']),
1337 intval($item['uid'])
1339 // who is the last child now?
1340 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1341 ORDER BY `created` DESC LIMIT 1",
1342 dbesc($item['parent-uri']),
1343 intval($importer['uid'])
1346 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1357 // Now process the feed
1359 if($feed->get_item_quantity()) {
1361 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1363 // in inverse date order
1365 $items = array_reverse($feed->get_items());
1367 $items = $feed->get_items();
1370 foreach($items as $item) {
1373 $item_id = $item->get_id();
1374 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1375 if(isset($rawthread[0]['attribs']['']['ref'])) {
1377 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1380 if(($is_reply) && is_array($contact)) {
1385 // Have we seen it? If not, import it.
1387 $item_id = $item->get_id();
1388 $datarray = get_atom_elements($feed,$item);
1390 if(! x($datarray,'author-name'))
1391 $datarray['author-name'] = $contact['name'];
1392 if(! x($datarray,'author-link'))
1393 $datarray['author-link'] = $contact['url'];
1394 if(! x($datarray,'author-avatar'))
1395 $datarray['author-avatar'] = $contact['thumb'];
1398 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1400 intval($importer['uid'])
1403 // Update content if 'updated' changes
1406 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1407 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1408 dbesc($datarray['body']),
1409 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1411 intval($importer['uid'])
1415 // update last-child if it changes
1417 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1418 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1419 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1420 dbesc(datetime_convert()),
1422 intval($importer['uid'])
1424 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1425 intval($allow[0]['data']),
1426 dbesc(datetime_convert()),
1428 intval($importer['uid'])
1434 $force_parent = false;
1435 if($contact['network'] === NETWORK_OSTATUS) {
1436 $force_parent = true;
1437 if(strlen($datarray['title']))
1438 unset($datarray['title']);
1439 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1440 dbesc(datetime_convert()),
1442 intval($importer['uid'])
1444 $datarray['last-child'] = 1;
1447 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1448 // one way feed - no remote comment ability
1449 $datarray['last-child'] = 0;
1451 $datarray['parent-uri'] = $parent_uri;
1452 $datarray['uid'] = $importer['uid'];
1453 $datarray['contact-id'] = $contact['id'];
1454 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1455 $datarray['type'] = 'activity';
1456 $datarray['gravity'] = GRAVITY_LIKE;
1459 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1460 $xo = parse_xml_string($datarray['object'],false);
1461 $xt = parse_xml_string($datarray['target'],false);
1463 if($xt->type == ACTIVITY_OBJ_NOTE) {
1464 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1466 intval($importer['importer_uid'])
1471 // extract tag, if not duplicate, add to parent item
1472 if($xo->id && $xo->content) {
1473 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1474 if(! (stristr($r[0]['tag'],$newtag))) {
1475 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1476 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1484 $r = item_store($datarray,$force_parent);
1490 // Head post of a conversation. Have we seen it? If not, import it.
1492 $item_id = $item->get_id();
1494 $datarray = get_atom_elements($feed,$item);
1496 if(is_array($contact)) {
1497 if(! x($datarray,'author-name'))
1498 $datarray['author-name'] = $contact['name'];
1499 if(! x($datarray,'author-link'))
1500 $datarray['author-link'] = $contact['url'];
1501 if(! x($datarray,'author-avatar'))
1502 $datarray['author-avatar'] = $contact['thumb'];
1505 // special handling for events
1507 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1508 $ev = bbtoevent($datarray['body']);
1509 if(x($ev,'desc') && x($ev,'start')) {
1510 $ev['uid'] = $importer['uid'];
1511 $ev['uri'] = $item_id;
1512 $ev['edited'] = $datarray['edited'];
1513 $ev['private'] = $datarray['private'];
1515 if(is_array($contact))
1516 $ev['cid'] = $contact['id'];
1517 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1519 intval($importer['uid'])
1522 $ev['id'] = $r[0]['id'];
1523 $xyz = event_store($ev);
1528 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1530 intval($importer['uid'])
1533 // Update content if 'updated' changes
1536 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1537 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1538 dbesc($datarray['body']),
1539 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1541 intval($importer['uid'])
1545 // update last-child if it changes
1547 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1548 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1549 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1550 intval($allow[0]['data']),
1551 dbesc(datetime_convert()),
1553 intval($importer['uid'])
1559 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1560 logger('consume-feed: New follower');
1561 new_follower($importer,$contact,$datarray,$item);
1564 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1565 lose_follower($importer,$contact,$datarray,$item);
1569 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1570 logger('consume-feed: New friend request');
1571 new_follower($importer,$contact,$datarray,$item,true);
1574 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1575 lose_sharer($importer,$contact,$datarray,$item);
1580 if(! is_array($contact))
1583 if($contact['network'] === NETWORK_OSTATUS || stristr($permalink,'twitter.com')) {
1584 if(strlen($datarray['title']))
1585 unset($datarray['title']);
1586 $datarray['last-child'] = 1;
1589 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1590 // one way feed - no remote comment ability
1591 $datarray['last-child'] = 0;
1594 // This is my contact on another system, but it's really me.
1595 // Turn this into a wall post.
1597 if($contact['remote_self'])
1598 $datarray['wall'] = 1;
1600 $datarray['parent-uri'] = $item_id;
1601 $datarray['uid'] = $importer['uid'];
1602 $datarray['contact-id'] = $contact['id'];
1603 $r = item_store($datarray);
1611 function local_delivery($importer,$data) {
1615 if($importer['readonly']) {
1616 // We aren't receiving stuff from this person. But we will quietly ignore them
1617 // rather than a blatant "go away" message.
1618 logger('local_delivery: ignoring');
1623 // Consume notification feed. This may differ from consuming a public feed in several ways
1624 // - might contain email or friend suggestions
1625 // - might contain remote followup to our message
1626 // - in which case we need to accept it and then notify other conversants
1627 // - we may need to send various email notifications
1629 $feed = new SimplePie();
1630 $feed->set_raw_data($data);
1631 $feed->enable_order_by_date(false);
1634 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1635 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1636 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1638 $newloc['uid'] = $importer['importer_uid'];
1639 $newloc['cid'] = $importer['id'];
1640 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1641 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1642 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1643 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1644 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1645 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1646 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1647 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1648 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1649 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1652 // merge with current record, current contents have priority
1653 // update record, set url-updated
1654 // update profile photos
1659 // handle friend suggestion notification
1661 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1662 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1663 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1665 $fsugg['uid'] = $importer['importer_uid'];
1666 $fsugg['cid'] = $importer['id'];
1667 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1668 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1669 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1670 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1671 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1673 // Does our member already have a friend matching this description?
1675 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1676 dbesc($fsugg['name']),
1677 dbesc(normalise_link($fsugg['url'])),
1678 intval($fsugg['uid'])
1683 // Do we already have an fcontact record for this person?
1686 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1687 dbesc($fsugg['url']),
1688 dbesc($fsugg['name']),
1689 dbesc($fsugg['request'])
1695 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1696 dbesc($fsugg['name']),
1697 dbesc($fsugg['url']),
1698 dbesc($fsugg['photo']),
1699 dbesc($fsugg['request'])
1701 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1702 dbesc($fsugg['url']),
1703 dbesc($fsugg['name']),
1704 dbesc($fsugg['request'])
1709 // database record did not get created. Quietly give up.
1713 $hash = random_string();
1715 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1716 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1717 intval($fsugg['uid']),
1719 intval($fsugg['cid']),
1720 dbesc($fsugg['body']),
1722 dbesc(datetime_convert()),
1726 // TODO - send email notify (which may require a new notification preference)
1733 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1734 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1736 logger('local_delivery: private message received');
1739 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1742 $msg['uid'] = $importer['importer_uid'];
1743 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1744 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1745 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1746 $msg['contact-id'] = $importer['id'];
1747 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1748 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1750 $msg['replied'] = 0;
1751 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1752 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1753 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1757 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
1758 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1760 // send email notification if requested.
1762 require_once('bbcode.php');
1763 if($importer['notify-flags'] & NOTIFY_MAIL) {
1765 push_lang($importer['language']);
1767 // name of the automated email sender
1768 $msg['notificationfromname'] = t('Administrator');
1769 // noreply address to send from
1770 $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
1773 // process the message body to display properly in text mode
1774 // 1) substitute a \n character for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
1775 // 2) remove escape slashes
1776 // 3) decode any bbcode from the message editor
1777 // 4) decode any encoded html tags
1778 // 5) remove html tags
1780 = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",$msg['body']))),ENT_QUOTES,'UTF-8'));
1783 // process the message body to display properly in text mode
1784 // 1) substitute a <br /> tag for the "\" then "n", so it behaves properly (it doesn't come in as a \n character)
1785 // 2) remove escape slashes
1786 // 3) decode any bbcode from the message editor
1787 // 4) decode any encoded html tags
1789 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$msg['body']))));
1791 // load the template for private message notifications
1792 $tpl = get_intltext_template('mail_received_html_body_eml.tpl');
1793 $email_html_body_tpl = replace_macros($tpl,array(
1794 '$username' => $importer['username'],
1795 '$siteName' => $a->config['sitename'], // name of this site
1796 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
1797 '$thumb' => $importer['thumb'], // thumbnail url for sender icon
1798 '$email' => $importer['email'], // email address to send to
1799 '$url' => $importer['url'], // full url for the site
1800 '$from' => $msg['from-name'], // name of the person sending the message
1801 '$title' => stripslashes($msg['title']), // subject of the message
1802 '$htmlversion' => $msg['htmlversion'], // html version of the message
1803 '$mimeboundary' => $msg['mimeboundary'], // mime message divider
1804 '$hostname' => $a->get_hostname() // name of this host
1807 // load the template for private message notifications
1808 $tpl = get_intltext_template('mail_received_text_body_eml.tpl');
1809 $email_text_body_tpl = replace_macros($tpl,array(
1810 '$username' => $importer['username'],
1811 '$siteName' => $a->config['sitename'], // name of this site
1812 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
1813 '$thumb' => $importer['thumb'], // thumbnail url for sender icon
1814 '$email' => $importer['email'], // email address to send to
1815 '$url' => $importer['url'], // full url for the site
1816 '$from' => $msg['from-name'], // name of the person sending the message
1817 '$title' => stripslashes($msg['title']), // subject of the message
1818 '$textversion' => $msg['textversion'], // text version of the message
1819 '$mimeboundary' => $msg['mimeboundary'], // mime message divider
1820 '$hostname' => $a->get_hostname() // name of this host
1823 // use the EmailNotification library to send the message
1824 require_once("include/EmailNotification.php");
1825 EmailNotification::sendTextHtmlEmail(
1826 $msg['notificationfromname'],
1827 $msg['notificationfromemail'],
1828 $msg['notificationfromemail'],
1830 t('New mail received at ') . $a->config['sitename'],
1831 $email_html_body_tpl,
1832 $email_text_body_tpl
1841 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
1843 // process any deleted entries
1845 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1846 if(is_array($del_entries) && count($del_entries)) {
1847 foreach($del_entries as $dentry) {
1849 if(isset($dentry['attribs']['']['ref'])) {
1850 $uri = $dentry['attribs']['']['ref'];
1852 if(isset($dentry['attribs']['']['when'])) {
1853 $when = $dentry['attribs']['']['when'];
1854 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1857 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1861 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
1862 WHERE `uri` = '%s' AND `uid` = %d AND `contact-id` = %d LIMIT 1",
1864 intval($importer['importer_uid']),
1865 intval($importer['id'])
1871 if($item['deleted'])
1874 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1876 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1877 $xo = parse_xml_string($item['object'],false);
1878 $xt = parse_xml_string($item['target'],false);
1879 if($xt->type === ACTIVITY_OBJ_NOTE) {
1880 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1882 intval($importer['importer_uid'])
1886 // For tags, the owner cannot remove the tag on the author's copy of the post.
1888 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1889 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1890 $author_copy = (($item['origin']) ? true : false);
1892 if($owner_remove && $author_copy)
1894 if($author_remove || $owner_remove) {
1895 $tags = explode(',',$i[0]['tag']);
1898 foreach($tags as $tag)
1899 if(trim($tag) !== trim($xo->body))
1900 $newtags[] = trim($tag);
1902 q("update item set tag = '%s' where id = %d limit 1",
1903 dbesc(implode(',',$newtags)),
1911 if($item['uri'] == $item['parent-uri']) {
1912 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
1913 WHERE `parent-uri` = '%s' AND `uid` = %d",
1915 dbesc(datetime_convert()),
1916 dbesc($item['uri']),
1917 intval($importer['importer_uid'])
1921 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
1922 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1924 dbesc(datetime_convert()),
1926 intval($importer['importer_uid'])
1928 if($item['last-child']) {
1929 // ensure that last-child is set in case the comment that had it just got wiped.
1930 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1931 dbesc(datetime_convert()),
1932 dbesc($item['parent-uri']),
1933 intval($item['uid'])
1935 // who is the last child now?
1936 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
1937 ORDER BY `created` DESC LIMIT 1",
1938 dbesc($item['parent-uri']),
1939 intval($importer['importer_uid'])
1942 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1954 foreach($feed->get_items() as $item) {
1957 $item_id = $item->get_id();
1958 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
1959 if(isset($rawthread[0]['attribs']['']['ref'])) {
1961 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1966 // was the top-level post for this reply written by somebody on this site?
1967 // Specifically, the recipient?
1969 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`,
1970 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
1971 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1972 WHERE `contact`.`self` = 1 AND `item`.`wall` = 1 AND `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
1973 AND `item`.`uid` = %d LIMIT 1",
1976 intval($importer['importer_uid'])
1978 if($r && count($r)) {
1980 logger('local_delivery: received remote comment');
1982 // remote reply to our post. Import and then notify everybody else.
1983 $datarray = get_atom_elements($feed,$item);
1985 if(! link_compare($datarray['author-link'],$importer['url'])) {
1986 logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
1987 // they won't know what to do so don't report an error. Just quietly die.
1991 $datarray['type'] = 'remote-comment';
1992 $datarray['wall'] = 1;
1993 $datarray['parent-uri'] = $parent_uri;
1994 $datarray['uid'] = $importer['importer_uid'];
1995 $datarray['owner-name'] = $r[0]['name'];
1996 $datarray['owner-link'] = $r[0]['url'];
1997 $datarray['owner-avatar'] = $r[0]['thumb'];
1998 $datarray['contact-id'] = $importer['id'];
1999 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2001 $datarray['type'] = 'activity';
2002 $datarray['gravity'] = GRAVITY_LIKE;
2003 $datarray['last-child'] = 0;
2006 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2009 $xo = parse_xml_string($datarray['object'],false);
2010 $xt = parse_xml_string($datarray['target'],false);
2012 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2014 // extract tag, if not duplicate, and this user allows tags, add to parent item
2016 if($xo->id && $xo->content) {
2017 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2019 if(! (stristr($r[0]['tag'],$newtag))) {
2020 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2021 intval($importer['importer_uid'])
2023 if(count($i) && ! ($i[0]['blocktags'])) {
2024 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2025 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2034 $posted_id = item_store($datarray);
2038 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2040 intval($importer['importer_uid'])
2043 $parent = $r[0]['parent'];
2046 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2047 dbesc(datetime_convert()),
2048 intval($importer['importer_uid']),
2049 intval($r[0]['parent'])
2052 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2053 dbesc(datetime_convert()),
2054 intval($importer['importer_uid']),
2059 if($posted_id && $parent) {
2061 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2063 if((! $is_like) && ($importer['notify-flags'] & NOTIFY_COMMENT) && (! $importer['self'])) {
2064 push_lang($importer['language']);
2065 require_once('bbcode.php');
2066 $from = stripslashes($datarray['author-name']);
2068 // name of the automated email sender
2069 $msg['notificationfromname'] = stripslashes($datarray['author-name']);;
2070 // noreply address to send from
2071 $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
2074 // process the message body to display properly in text mode
2076 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
2079 // process the message body to display properly in text mode
2081 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
2083 $imgtouse = ((link_compare($datarray['author-link'],$importer['url'])) ? $importer['thumb'] : $datarray['author-avatar']);
2085 // load the template for private message notifications
2086 $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
2087 $email_html_body_tpl = replace_macros($tpl,array(
2088 '$username' => $importer['username'],
2089 '$sitename' => $a->config['sitename'], // name of this site
2090 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
2091 '$thumb' => $imgtouse, // thumbnail url for sender icon
2092 '$email' => $importer['email'], // email address to send to
2093 '$url' => $datarray['author-link'], // full url for the site
2094 '$from' => $from, // name of the person sending the message
2095 '$body' => $msg['htmlversion'], // html version of the message
2096 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2099 // load the template for private message notifications
2100 $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
2101 $email_text_body_tpl = replace_macros($tpl,array(
2102 '$username' => $importer['username'],
2103 '$sitename' => $a->config['sitename'], // name of this site
2104 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
2105 '$thumb' => $imgtouse, // thumbnail url for sender icon
2106 '$email' => $importer['email'], // email address to send to
2107 '$url' => $datarray['author-link'], // full url for the site
2108 '$from' => $from, // name of the person sending the message
2109 '$body' => $msg['textversion'], // text version of the message
2110 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2113 // use the EmailNotification library to send the message
2114 require_once("include/EmailNotification.php");
2115 EmailNotification::sendTextHtmlEmail(
2116 $msg['notificationfromname'],
2117 t("Administrator") . '@' . $a->get_hostname(),
2118 t("noreply") . '@' . $a->get_hostname(),
2120 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
2121 $email_html_body_tpl,
2122 $email_text_body_tpl
2133 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2135 $item_id = $item->get_id();
2136 $datarray = get_atom_elements($feed,$item);
2138 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2140 intval($importer['importer_uid'])
2143 // Update content if 'updated' changes
2146 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2147 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2148 dbesc($datarray['body']),
2149 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2151 intval($importer['importer_uid'])
2155 // update last-child if it changes
2157 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2158 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2159 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2160 dbesc(datetime_convert()),
2162 intval($importer['importer_uid'])
2164 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2165 intval($allow[0]['data']),
2166 dbesc(datetime_convert()),
2168 intval($importer['importer_uid'])
2174 $datarray['parent-uri'] = $parent_uri;
2175 $datarray['uid'] = $importer['importer_uid'];
2176 $datarray['contact-id'] = $importer['id'];
2177 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2178 $datarray['type'] = 'activity';
2179 $datarray['gravity'] = GRAVITY_LIKE;
2182 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2184 $xo = parse_xml_string($datarray['object'],false);
2185 $xt = parse_xml_string($datarray['target'],false);
2187 if($xt->type == ACTIVITY_OBJ_NOTE) {
2188 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2190 intval($importer['importer_uid'])
2195 // extract tag, if not duplicate, add to parent item
2197 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2198 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2199 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2207 $posted_id = item_store($datarray);
2209 // find out if our user is involved in this conversation and wants to be notified.
2211 if(($datarray['type'] != 'activity') && ($importer['notify-flags'] & NOTIFY_COMMENT)) {
2213 $myconv = q("SELECT `author-link`, `author-avatar` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2215 intval($importer['importer_uid'])
2217 if(count($myconv)) {
2218 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2219 foreach($myconv as $conv) {
2220 if(! link_compare($conv['author-link'],$importer_url))
2223 push_lang($importer['language']);
2224 require_once('bbcode.php');
2225 $from = stripslashes($datarray['author-name']);
2227 // name of the automated email sender
2228 $msg['notificationfromname'] = stripslashes($datarray['author-name']);;
2229 // noreply address to send from
2230 $msg['notificationfromemail'] = t('noreply') . '@' . $a->get_hostname();
2233 // process the message body to display properly in text mode
2235 = html_entity_decode(strip_tags(bbcode(stripslashes($datarray['body']))), ENT_QUOTES, 'UTF-8');
2238 // process the message body to display properly in text mode
2240 = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), "<br />\n",$datarray['body']))));
2242 $imgtouse = ((link_compare($datarray['author-link'],$importer['url'])) ? $importer['thumb'] : $datarray['author-avatar']);
2245 // load the template for private message notifications
2246 $tpl = get_intltext_template('cmnt_received_html_body_eml.tpl');
2247 $email_html_body_tpl = replace_macros($tpl,array(
2248 '$username' => $importer['username'],
2249 '$sitename' => $a->config['sitename'], // name of this site
2250 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
2251 '$thumb' => $imgtouse, // thumbnail url for sender icon
2252 '$url' => $datarray['author-link'], // full url for the site
2253 '$from' => $from, // name of the person sending the message
2254 '$body' => $msg['htmlversion'], // html version of the message
2255 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2258 // load the template for private message notifications
2259 $tpl = get_intltext_template('cmnt_received_text_body_eml.tpl');
2260 $email_text_body_tpl = replace_macros($tpl,array(
2261 '$username' => $importer['username'],
2262 '$sitename' => $a->config['sitename'], // name of this site
2263 '$siteurl' => $a->get_baseurl(), // descriptive url of this site
2264 '$thumb' => $imgtouse, // thumbnail url for sender icon
2265 '$url' => $datarray['author-link'], // full url for the site
2266 '$from' => $from, // name of the person sending the message
2267 '$body' => $msg['textversion'], // text version of the message
2268 '$display' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2271 // use the EmailNotification library to send the message
2272 require_once("include/EmailNotification.php");
2273 EmailNotification::sendTextHtmlEmail(
2274 $msg['notificationfromname'],
2275 t("Administrator@") . $a->get_hostname(),
2276 t("noreply") . '@' . $a->get_hostname(),
2278 sprintf( t('%s commented on an item at %s'), $from , $a->config['sitename']),
2279 $email_html_body_tpl,
2280 $email_text_body_tpl
2293 // Head post of a conversation. Have we seen it? If not, import it.
2296 $item_id = $item->get_id();
2297 $datarray = get_atom_elements($feed,$item);
2299 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2300 $ev = bbtoevent($datarray['body']);
2301 if(x($ev,'desc') && x($ev,'start')) {
2302 $ev['cid'] = $importer['id'];
2303 $ev['uid'] = $importer['uid'];
2304 $ev['uri'] = $item_id;
2305 $ev['edited'] = $datarray['edited'];
2306 $ev['private'] = $datarray['private'];
2308 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2310 intval($importer['uid'])
2313 $ev['id'] = $r[0]['id'];
2314 $xyz = event_store($ev);
2319 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2321 intval($importer['importer_uid'])
2324 // Update content if 'updated' changes
2327 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2328 $r = q("UPDATE `item` SET `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2329 dbesc($datarray['body']),
2330 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2332 intval($importer['importer_uid'])
2336 // update last-child if it changes
2338 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2339 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2340 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2341 intval($allow[0]['data']),
2342 dbesc(datetime_convert()),
2344 intval($importer['importer_uid'])
2350 // This is my contact on another system, but it's really me.
2351 // Turn this into a wall post.
2353 if($contact['remote_self'])
2354 $datarray['wall'] = 1;
2356 $datarray['parent-uri'] = $item_id;
2357 $datarray['uid'] = $importer['importer_uid'];
2358 $datarray['contact-id'] = $importer['id'];
2359 $r = item_store($datarray);
2370 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2371 $url = notags(trim($datarray['author-link']));
2372 $name = notags(trim($datarray['author-name']));
2373 $photo = notags(trim($datarray['author-avatar']));
2375 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2376 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2377 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2379 if(is_array($contact)) {
2380 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2381 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2382 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2383 intval(CONTACT_IS_FRIEND),
2384 intval($contact['id']),
2385 intval($importer['uid'])
2388 // send email notification to owner?
2392 // create contact record
2394 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2395 `blocked`, `readonly`, `pending`, `writable` )
2396 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2397 intval($importer['uid']),
2398 dbesc(datetime_convert()),
2400 dbesc(normalise_link($url)),
2404 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2405 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2407 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2408 intval($importer['uid']),
2412 $contact_record = $r[0];
2414 // create notification
2415 $hash = random_string();
2417 if(is_array($contact_record)) {
2418 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2419 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2420 intval($importer['uid']),
2421 intval($contact_record['id']),
2423 dbesc(datetime_convert())
2426 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2427 intval($importer['uid'])
2431 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2432 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2433 $email = replace_macros($email_tpl, array(
2434 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2436 '$myname' => $r[0]['username'],
2437 '$siteurl' => $a->get_baseurl(),
2438 '$sitename' => $a->config['sitename']
2440 $res = mail($r[0]['email'],
2441 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2443 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2444 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2445 . 'Content-transfer-encoding: 8bit' );
2452 function lose_follower($importer,$contact,$datarray,$item) {
2454 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2455 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2456 intval(CONTACT_IS_SHARING),
2457 intval($contact['id'])
2461 contact_remove($contact['id']);
2465 function lose_sharer($importer,$contact,$datarray,$item) {
2467 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2468 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2469 intval(CONTACT_IS_FOLLOWER),
2470 intval($contact['id'])
2474 contact_remove($contact['id']);
2479 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2481 if(is_array($importer)) {
2482 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2483 intval($importer['uid'])
2487 // Diaspora has different message-ids in feeds than they do
2488 // through the direct Diaspora protocol. If we try and use
2489 // the feed, we'll get duplicates. So don't.
2491 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2494 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2496 // Use a single verify token, even if multiple hubs
2498 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2500 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2502 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2504 if(! strlen($contact['hub-verify'])) {
2505 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2506 dbesc($verify_token),
2507 intval($contact['id'])
2511 post_url($url,$params);
2517 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2521 $name = xmlify($name);
2522 $uri = xmlify($uri);
2525 $photo = xmlify($photo);
2529 $o .= "<name>$name</name>\r\n";
2530 $o .= "<uri>$uri</uri>\r\n";
2531 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2532 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2534 call_hooks('atom_author', $o);
2536 $o .= "</$tag>\r\n";
2540 function atom_entry($item,$type,$author,$owner,$comment = false) {
2544 if(! $item['parent'])
2547 if($item['deleted'])
2548 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2551 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2552 $body = fix_private_photos($item['body'],$owner['uid']);
2554 $body = $item['body'];
2557 $o = "\r\n\r\n<entry>\r\n";
2559 if(is_array($author))
2560 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2562 $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']));
2563 if(strlen($item['owner-name']))
2564 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2566 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2567 $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";
2569 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2570 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2571 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2572 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2573 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2574 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2575 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2577 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2579 if($item['location']) {
2580 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2581 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2585 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2587 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2588 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2591 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2592 if($item['bookmark'])
2593 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2596 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2599 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2601 if($item['signed_text']) {
2602 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2603 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2606 $verb = construct_verb($item);
2607 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2608 $actobj = construct_activity_object($item);
2611 $actarg = construct_activity_target($item);
2615 $tags = item_getfeedtags($item);
2617 foreach($tags as $t) {
2618 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2622 $o .= item_getfeedattach($item);
2624 $mentioned = get_mentions($item);
2628 call_hooks('atom_entry', $o);
2630 $o .= '</entry>' . "\r\n";
2635 function fix_private_photos($s,$uid) {
2637 logger('fix_private_photos');
2639 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2640 $image = $matches[1];
2641 logger('fix_private_photos: found photo ' . $image);
2642 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2643 $i = basename($image);
2644 $i = str_replace('.jpg','',$i);
2645 $x = strpos($i,'-');
2647 $res = substr($i,$x+1);
2648 $i = substr($i,0,$x);
2649 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2655 logger('replacing photo');
2656 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2659 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2667 function item_getfeedtags($item) {
2670 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2672 for($x = 0; $x < $cnt; $x ++) {
2674 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2678 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2680 for($x = 0; $x < $cnt; $x ++) {
2682 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2688 function item_getfeedattach($item) {
2690 $arr = explode(',',$item['attach']);
2692 foreach($arr as $r) {
2694 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2696 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2697 if(intval($matches[2]))
2698 $ret .= 'length="' . intval($matches[2]) . '" ';
2699 if($matches[4] !== ' ')
2700 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2701 $ret .= ' />' . "\r\n";
2710 function item_expire($uid,$days) {
2712 if((! $uid) || (! $days))
2715 $r = q("SELECT * FROM `item`
2717 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
2727 logger('expire: # items=' . count($r) );
2729 foreach($r as $item) {
2731 // Only expire posts, not photos and photo comments
2733 if(strlen($item['resource-id']))
2736 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2737 dbesc(datetime_convert()),
2738 dbesc(datetime_convert()),
2744 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2745 dbesc(datetime_convert()),
2746 dbesc(datetime_convert()),
2747 dbesc($item['parent-uri']),
2748 intval($item['uid'])
2753 proc_run('php',"include/notifier.php","expire","$uid");
2758 function drop_items($items) {
2762 foreach($items as $item) {
2763 $owner = drop_item($item,false);
2764 if($owner && ! $uid)
2769 // multiple threads may have been deleted, send an expire notification
2772 proc_run('php',"include/notifier.php","expire","$uid");
2776 function drop_item($id,$interactive = true) {
2780 // locate item to be deleted
2782 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2789 notice( t('Item not found.') . EOL);
2790 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2795 $owner = $item['uid'];
2797 // check if logged in user is either the author or owner of this item
2799 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
2803 $r = q("UPDATE `item` SET `deleted` = 1, `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2804 dbesc(datetime_convert()),
2805 dbesc(datetime_convert()),
2809 // If item is a link to a photo resource, nuke all the associated photos
2810 // (visitors will not have photo resources)
2811 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
2812 // generate a resource-id and therefore aren't intimately linked to the item.
2814 if(strlen($item['resource-id'])) {
2815 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
2816 dbesc($item['resource-id']),
2817 intval($item['uid'])
2819 // ignore the result
2822 // If item is a link to an event, nuke the event record.
2824 if(intval($item['event-id'])) {
2825 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2826 intval($item['event-id']),
2827 intval($item['uid'])
2829 // ignore the result
2833 // If it's the parent of a comment thread, kill all the kids
2835 if($item['uri'] == $item['parent-uri']) {
2836 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = ''
2837 WHERE `parent-uri` = '%s' AND `uid` = %d ",
2838 dbesc(datetime_convert()),
2839 dbesc(datetime_convert()),
2840 dbesc($item['parent-uri']),
2841 intval($item['uid'])
2843 // ignore the result
2846 // ensure that last-child is set in case the comment that had it just got wiped.
2847 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2848 dbesc(datetime_convert()),
2849 dbesc($item['parent-uri']),
2850 intval($item['uid'])
2852 // who is the last child now?
2853 $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",
2854 dbesc($item['parent-uri']),
2855 intval($item['uid'])
2858 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2863 $drop_id = intval($item['id']);
2865 // send the notification upstream/downstream as the case may be
2870 proc_run('php',"include/notifier.php","drop","$drop_id");
2871 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2877 notice( t('Permission denied.') . EOL);
2878 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);