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`, `user`.`page-flags`
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`.`moderated` = 0 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(FRIENDICA_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>' : ''),
160 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
163 call_hooks('atom_feed', $atom);
165 if(! count($items)) {
167 call_hooks('atom_feed_end', $atom);
169 $atom .= '</feed>' . "\r\n";
173 foreach($items as $item) {
175 // public feeds get html, our own nodes use bbcode
179 // catch any email that's in a public conversation and make sure it doesn't leak
187 $atom .= atom_entry($item,$type,null,$owner,true);
190 call_hooks('atom_feed_end', $atom);
192 $atom .= '</feed>' . "\r\n";
198 function construct_verb($item) {
200 return $item['verb'];
201 return ACTIVITY_POST;
204 function construct_activity_object($item) {
206 if($item['object']) {
207 $o = '<as:object>' . "\r\n";
208 $r = parse_xml_string($item['object'],false);
214 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
216 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
218 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
220 if(substr($r->link,0,1) === '<') {
221 // patch up some facebook "like" activity objects that got stored incorrectly
222 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
223 // we can probably remove this hack here and in the following function in a few months time.
224 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
225 $r->link = str_replace('&','&', $r->link);
226 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
230 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
233 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
234 $o .= '</as:object>' . "\r\n";
241 function construct_activity_target($item) {
243 if($item['target']) {
244 $o = '<as:target>' . "\r\n";
245 $r = parse_xml_string($item['target'],false);
249 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
251 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
253 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
255 if(substr($r->link,0,1) === '<') {
256 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
257 $r->link = str_replace('&','&', $r->link);
258 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
262 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
265 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
266 $o .= '</as:target>' . "\r\n";
276 function get_atom_elements($feed,$item) {
278 require_once('library/HTMLPurifier.auto.php');
279 require_once('include/html2bbcode.php');
281 $best_photo = array();
285 $author = $item->get_author();
287 $res['author-name'] = unxmlify($author->get_name());
288 $res['author-link'] = unxmlify($author->get_link());
291 $res['author-name'] = unxmlify($feed->get_title());
292 $res['author-link'] = unxmlify($feed->get_permalink());
294 $res['uri'] = unxmlify($item->get_id());
295 $res['title'] = unxmlify($item->get_title());
296 $res['body'] = unxmlify($item->get_content());
297 $res['plink'] = unxmlify($item->get_link(0));
300 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
304 // look for a photo. We should check media size and find the best one,
305 // but for now let's just find any author photo
307 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
309 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
310 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
311 foreach($base as $link) {
312 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
313 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
314 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
319 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
321 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
322 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
323 if($base && count($base)) {
324 foreach($base as $link) {
325 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
326 $res['author-link'] = unxmlify($link['attribs']['']['href']);
327 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
328 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
329 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
335 // No photo/profile-link on the item - look at the feed level
337 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
338 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
339 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
340 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
341 foreach($base as $link) {
342 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
343 $res['author-link'] = unxmlify($link['attribs']['']['href']);
344 if(! $res['author-avatar']) {
345 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
346 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
351 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
353 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
354 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
356 if($base && count($base)) {
357 foreach($base as $link) {
358 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
359 $res['author-link'] = unxmlify($link['attribs']['']['href']);
360 if(! (x($res,'author-avatar'))) {
361 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
362 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
369 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
370 if($apps && $apps[0]['attribs']['']['source']) {
371 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
372 if($res['app'] === 'web')
373 $res['app'] = 'OStatus';
376 // base64 encoded json structure representing Diaspora signature
378 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
380 $res['dsprsig'] = unxmlify($dsig[0]['data']);
383 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
385 $res['guid'] = unxmlify($dguid[0]['data']);
387 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
389 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
393 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
396 $have_real_body = false;
398 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
400 $have_real_body = true;
401 $res['body'] = $rawenv[0]['data'];
402 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
403 // make sure nobody is trying to sneak some html tags by us
404 $res['body'] = notags(base64url_decode($res['body']));
407 $maxlen = get_max_import_size();
408 if($maxlen && (strlen($res['body']) > $maxlen))
409 $res['body'] = substr($res['body'],0, $maxlen);
411 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
412 // the content type. Our own network only emits text normally, though it might have been converted to
413 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
414 // have to assume it is all html and needs to be purified.
416 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
417 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
418 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
421 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
423 $res['body'] = reltoabs($res['body'],$base_url);
425 $res['body'] = html2bb_video($res['body']);
427 $res['body'] = oembed_html2bbcode($res['body']);
429 $config = HTMLPurifier_Config::createDefault();
430 $config->set('Cache.DefinitionImpl', null);
432 // we shouldn't need a whitelist, because the bbcode converter
433 // will strip out any unsupported tags.
434 // $config->set('HTML.Allowed', 'p,b,a[href],i');
436 $purifier = new HTMLPurifier($config);
437 $res['body'] = $purifier->purify($res['body']);
439 $res['body'] = html2bbcode($res['body']);
442 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
443 if($allow && $allow[0]['data'] == 1)
444 $res['last-child'] = 1;
446 $res['last-child'] = 0;
448 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
449 if($private && $private[0]['data'] == 1)
454 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
455 if($extid && $extid[0]['data'])
456 $res['extid'] = $extid[0]['data'];
458 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
460 $res['location'] = unxmlify($rawlocation[0]['data']);
463 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
465 $res['created'] = unxmlify($rawcreated[0]['data']);
468 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
470 $res['edited'] = unxmlify($rawedited[0]['data']);
472 if((x($res,'edited')) && (! (x($res,'created'))))
473 $res['created'] = $res['edited'];
475 if(! $res['created'])
476 $res['created'] = $item->get_date('c');
479 $res['edited'] = $item->get_date('c');
482 // Disallow time travelling posts
484 $d1 = strtotime($res['created']);
485 $d2 = strtotime($res['edited']);
486 $d3 = strtotime('now');
489 $res['created'] = datetime_convert();
491 $res['edited'] = datetime_convert();
493 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
494 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
495 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
496 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
497 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
498 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
499 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
500 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
501 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
503 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
504 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
506 foreach($base as $link) {
507 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
508 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
509 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
514 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
516 $res['coord'] = unxmlify($rawgeo[0]['data']);
519 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
521 // select between supported verbs
524 $res['verb'] = unxmlify($rawverb[0]['data']);
527 // translate OStatus unfollow to activity streams if it happened to get selected
529 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
530 $res['verb'] = ACTIVITY_UNFOLLOW;
532 $cats = $item->get_categories();
535 foreach($cats as $cat) {
536 $term = $cat->get_term();
538 $term = $cat->get_label();
539 $scheme = $cat->get_scheme();
540 if($scheme && $term && stristr($scheme,'X-DFRN:'))
541 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
543 $tag_arr[] = notags(trim($term));
545 $res['tag'] = implode(',', $tag_arr);
548 $attach = $item->get_enclosures();
551 foreach($attach as $att) {
552 $len = intval($att->get_length());
553 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
554 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
555 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
556 if(strpos($type,';'))
557 $type = substr($type,0,strpos($type,';'));
558 if((! $link) || (strpos($link,'http') !== 0))
564 $type = 'application/octet-stream';
566 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
568 $res['attach'] = implode(',', $att_arr);
571 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
574 $res['object'] = '<object>' . "\n";
575 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
576 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
577 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
579 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
580 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
581 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
582 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
583 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
584 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
585 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
586 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
588 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
589 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
590 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
591 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
593 $body = html2bb_video($body);
595 $config = HTMLPurifier_Config::createDefault();
596 $config->set('Cache.DefinitionImpl', null);
598 $purifier = new HTMLPurifier($config);
599 $body = $purifier->purify($body);
600 $body = html2bbcode($body);
603 $res['object'] .= '<content>' . $body . '</content>' . "\n";
606 $res['object'] .= '</object>' . "\n";
609 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
612 $res['target'] = '<target>' . "\n";
613 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
614 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
616 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
617 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
619 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
620 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
621 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
622 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
623 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
624 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
626 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
627 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
628 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
629 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
631 $body = html2bb_video($body);
633 $config = HTMLPurifier_Config::createDefault();
634 $config->set('Cache.DefinitionImpl', null);
636 $purifier = new HTMLPurifier($config);
637 $body = $purifier->purify($body);
638 $body = html2bbcode($body);
641 $res['target'] .= '<content>' . $body . '</content>' . "\n";
644 $res['target'] .= '</target>' . "\n";
647 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
649 call_hooks('parse_atom', $arr);
654 function encode_rel_links($links) {
656 if(! ((is_array($links)) && (count($links))))
658 foreach($links as $link) {
660 if($link['attribs']['']['rel'])
661 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
662 if($link['attribs']['']['type'])
663 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
664 if($link['attribs']['']['href'])
665 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
666 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
667 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
668 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
669 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
675 function item_store($arr,$force_parent = false) {
677 // If a Diaspora signature structure was passed in, pull it out of the
678 // item array and set it aside for later storage.
681 if(x($arr,'dsprsig')) {
682 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
683 unset($arr['dsprsig']);
686 if(x($arr, 'gravity'))
687 $arr['gravity'] = intval($arr['gravity']);
688 elseif($arr['parent-uri'] === $arr['uri'])
690 elseif(activity_match($arr['verb'],ACTIVITY_POST))
693 $arr['gravity'] = 6; // extensible catchall
696 $arr['type'] = 'remote';
698 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
700 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
701 $arr['body'] = strip_tags($arr['body']);
704 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
705 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
706 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
707 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
708 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
709 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
710 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
711 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
712 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
713 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
714 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
715 $arr['commented'] = datetime_convert();
716 $arr['received'] = datetime_convert();
717 $arr['changed'] = datetime_convert();
718 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
719 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
720 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
721 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
722 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
724 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
725 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
726 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
727 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
728 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
729 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
730 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
731 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
732 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
733 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
734 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
735 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
736 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
737 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
738 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
739 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
740 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
741 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
742 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
744 if($arr['parent-uri'] === $arr['uri']) {
747 $allow_cid = $arr['allow_cid'];
748 $allow_gid = $arr['allow_gid'];
749 $deny_cid = $arr['deny_cid'];
750 $deny_gid = $arr['deny_gid'];
754 // find the parent and snarf the item id and ACL's
755 // and anything else we need to inherit
757 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
758 dbesc($arr['parent-uri']),
764 // is the new message multi-level threaded?
765 // even though we don't support it now, preserve the info
766 // and re-attach to the conversation parent.
768 if($r[0]['uri'] != $r[0]['parent-uri']) {
769 $arr['thr-parent'] = $arr['parent-uri'];
770 $arr['parent-uri'] = $r[0]['parent-uri'];
771 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
772 ORDER BY `id` ASC LIMIT 1",
773 dbesc($r[0]['parent-uri']),
774 dbesc($r[0]['parent-uri']),
781 $parent_id = $r[0]['id'];
782 $parent_deleted = $r[0]['deleted'];
783 $allow_cid = $r[0]['allow_cid'];
784 $allow_gid = $r[0]['allow_gid'];
785 $deny_cid = $r[0]['deny_cid'];
786 $deny_gid = $r[0]['deny_gid'];
787 $arr['wall'] = $r[0]['wall'];
791 // Allow one to see reply tweets from status.net even when
792 // we don't have or can't see the original post.
795 logger('item_store: $force_parent=true, reply converted to top-level post.');
797 $arr['thr-parent'] = $arr['parent-uri'];
798 $arr['parent-uri'] = $arr['uri'];
802 logger('item_store: item parent was not found - ignoring item');
810 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
814 if($r && count($r)) {
815 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
819 call_hooks('post_remote',$arr);
821 if(x($arr,'cancel')) {
822 logger('item_store: post cancelled by plugin.');
828 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
830 $r = dbq("INSERT INTO `item` (`"
831 . implode("`, `", array_keys($arr))
833 . implode("', '", array_values($arr))
836 // find the item we just created
838 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
839 $arr['uri'], // already dbesc'd
844 $current_post = $r[0]['id'];
845 logger('item_store: created item ' . $current_post);
848 logger('item_store: could not locate created item');
852 logger('item_store: duplicated post occurred. Removing duplicates.');
853 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
856 intval($current_post)
860 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
861 $parent_id = $current_post;
863 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
866 $private = $arr['private'];
868 // Set parent id - and also make sure to inherit the parent's ACL's.
870 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
871 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
878 intval($parent_deleted),
879 intval($current_post)
882 // update the commented timestamp on the parent
884 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
885 dbesc(datetime_convert()),
886 dbesc(datetime_convert()),
891 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
892 intval($current_post),
893 dbesc($dsprsig->signed_text),
894 dbesc($dsprsig->signature),
895 dbesc($dsprsig->signer)
901 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
904 if($arr['last-child']) {
905 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
908 intval($current_post)
912 tag_deliver($arr['uid'],$current_post);
914 return $current_post;
917 function get_item_contact($item,$contacts) {
918 if(! count($contacts) || (! is_array($item)))
920 foreach($contacts as $contact) {
921 if($contact['id'] == $item['contact-id']) {
930 function tag_deliver($uid,$item_id) {
932 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
938 $u = q("select uid, nickname, language, username, email, `page-flags`, `notify-flags` from user where uid = %d limit 1",
944 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
946 $i = q("select * from item where id = %d and uid = %d limit 1",
955 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
957 // Diaspora uses their own hardwired link URL in @-tags
958 // instead of the one we supply with webfinger
960 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
962 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
964 foreach($matches as $mtch) {
965 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
967 logger('tag_deliver: mention found: ' . $mtch[2]);
975 // send a notification
977 require_once('include/enotify.php');
979 'type' => NOTIFY_TAGSELF,
980 'notify_flags' => $u[0]['notify-flags'],
981 'language' => $u[0]['language'],
982 'to_name' => $u[0]['username'],
983 'to_email' => $u[0]['email'],
984 'uid' => $u[0]['uid'],
986 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
987 'source_name' => $item['author-name'],
988 'source_link' => $item['author-link'],
989 'source_photo' => $item['author-avatar'],
990 'verb' => ACTIVITY_TAG,
994 if(! $community_page)
997 // tgroup delivery - setup a second delivery chain
998 // prevent delivery looping - only proceed
999 // if the message originated elsewhere and is a top-level post
1001 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1004 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1007 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1008 intval($u[0]['uid'])
1013 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",
1014 dbesc($c[0]['name']),
1015 dbesc($c[0]['url']),
1016 dbesc($c[0]['thumb']),
1020 proc_run('php','include/notifier.php','tgroup',$item_id);
1029 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1033 // if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
1036 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1038 if($contact['duplex'] && $contact['dfrn-id'])
1039 $idtosend = '0:' . $orig_id;
1040 if($contact['duplex'] && $contact['issued-id'])
1041 $idtosend = '1:' . $orig_id;
1043 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1045 $rino_enable = get_config('system','rino_encrypt');
1050 $ssl_val = intval(get_config('system','ssl_policy'));
1054 case SSL_POLICY_FULL:
1055 $ssl_policy = 'full';
1057 case SSL_POLICY_SELFSIGN:
1058 $ssl_policy = 'self';
1060 case SSL_POLICY_NONE:
1062 $ssl_policy = 'none';
1066 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1068 logger('dfrn_deliver: ' . $url);
1070 $xml = fetch_url($url);
1072 $curl_stat = $a->get_curl_code();
1074 return(-1); // timed out
1076 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1081 if(strpos($xml,'<?xml') === false) {
1082 logger('dfrn_deliver: no valid XML returned');
1083 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1087 $res = parse_xml_string($xml);
1089 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1090 return (($res->status) ? $res->status : 3);
1092 $postvars = array();
1093 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1094 $challenge = hex2bin((string) $res->challenge);
1095 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1096 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1097 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1099 $final_dfrn_id = '';
1102 if(($contact['duplex'] && strlen($contact['pubkey']))
1103 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1104 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1105 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1106 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1109 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1110 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1113 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1115 if(strpos($final_dfrn_id,':') == 1)
1116 $final_dfrn_id = substr($final_dfrn_id,2);
1118 if($final_dfrn_id != $orig_id) {
1119 logger('dfrn_deliver: wrong dfrn_id.');
1120 // did not decode properly - cannot trust this site
1124 $postvars['dfrn_id'] = $idtosend;
1125 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1127 $postvars['dissolve'] = '1';
1130 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1131 $postvars['data'] = $atom;
1132 $postvars['perm'] = 'rw';
1135 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1136 $postvars['perm'] = 'r';
1139 $postvars['ssl_policy'] = $ssl_policy;
1142 $postvars['page'] = '1';
1144 if($rino && $rino_allowed && (! $dissolve)) {
1145 $key = substr(random_string(),0,16);
1146 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1147 $postvars['data'] = $data;
1148 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1151 if($dfrn_version >= 2.1) {
1152 if(($contact['duplex'] && strlen($contact['pubkey']))
1153 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1154 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1156 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1159 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1163 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1164 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1167 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1171 logger('md5 rawkey ' . md5($postvars['key']));
1173 $postvars['key'] = bin2hex($postvars['key']);
1176 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1178 $xml = post_url($contact['notify'],$postvars);
1180 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1182 $curl_stat = $a->get_curl_code();
1183 if((! $curl_stat) || (! strlen($xml)))
1184 return(-1); // timed out
1186 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1189 if(strpos($xml,'<?xml') === false) {
1190 logger('dfrn_deliver: phase 2: no valid XML returned');
1191 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1195 $res = parse_xml_string($xml);
1197 return $res->status;
1203 * consume_feed - process atom feed and update anything/everything we might need to update
1205 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1207 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1208 * It is this person's stuff that is going to be updated.
1209 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1210 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1211 * have a contact record.
1212 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1213 * might not) try and subscribe to it.
1214 * $datedir sorts in reverse order
1215 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1216 * imported prior to its children being seen in the stream unless we are certain
1217 * of how the feed is arranged/ordered.
1218 * With $pass = 1, we only pull parent items out of the stream.
1219 * With $pass = 2, we only pull children (comments/likes).
1221 * So running this twice, first with pass 1 and then with pass 2 will do the right
1222 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1223 * model where comments can have sub-threads. That would require some massive sorting
1224 * to get all the feed items into a mostly linear ordering, and might still require
1228 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1230 require_once('library/simplepie/simplepie.inc');
1232 if(! strlen($xml)) {
1233 logger('consume_feed: empty input');
1237 $feed = new SimplePie();
1238 $feed->set_raw_data($xml);
1240 $feed->enable_order_by_date(true);
1242 $feed->enable_order_by_date(false);
1246 logger('consume_feed: Error parsing XML: ' . $feed->error());
1248 $permalink = $feed->get_permalink();
1250 // Check at the feed level for updated contact name and/or photo
1254 $photo_timestamp = '';
1258 $hubs = $feed->get_links('hub');
1261 $hub = implode(',', $hubs);
1263 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1265 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1267 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1268 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1269 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1270 $new_name = $elems['name'][0]['data'];
1272 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1273 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1274 $photo_url = $elems['link'][0]['attribs']['']['href'];
1277 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1278 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1282 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1283 logger('consume_feed: Updating photo for ' . $contact['name']);
1284 require_once("Photo.php");
1285 $photo_failure = false;
1286 $have_photo = false;
1288 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1289 intval($contact['id']),
1290 intval($contact['uid'])
1293 $resource_id = $r[0]['resource-id'];
1297 $resource_id = photo_new_resource();
1300 $img_str = fetch_url($photo_url,true);
1301 $img = new Photo($img_str);
1302 if($img->is_valid()) {
1304 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1305 dbesc($resource_id),
1306 intval($contact['id']),
1307 intval($contact['uid'])
1311 $img->scaleImageSquare(175);
1313 $hash = $resource_id;
1314 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1316 $img->scaleImage(80);
1317 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1319 $img->scaleImage(48);
1320 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1324 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1325 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1326 dbesc(datetime_convert()),
1327 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1328 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1329 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1330 intval($contact['uid']),
1331 intval($contact['id'])
1336 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1337 $r = q("select * from contact where uid = %d and id = %d limit 1",
1338 intval($contact['uid']),
1339 intval($contact['id'])
1342 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1343 dbesc(notags(trim($new_name))),
1344 dbesc(datetime_convert()),
1345 intval($contact['uid']),
1346 intval($contact['id'])
1349 // do our best to update the name on content items
1352 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1353 dbesc(notags(trim($new_name))),
1354 dbesc($r[0]['name']),
1355 dbesc($r[0]['url']),
1356 intval($contact['uid'])
1361 if(strlen($birthday)) {
1362 if(substr($birthday,0,4) != $contact['bdyear']) {
1363 logger('consume_feed: updating birthday: ' . $birthday);
1367 * Add new birthday event for this person
1369 * $bdtext is just a readable placeholder in case the event is shared
1370 * with others. We will replace it during presentation to our $importer
1371 * to contain a sparkle link and perhaps a photo.
1375 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1378 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1379 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1380 intval($contact['uid']),
1381 intval($contact['id']),
1382 dbesc(datetime_convert()),
1383 dbesc(datetime_convert()),
1384 dbesc(datetime_convert('UTC','UTC', $birthday)),
1385 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1393 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1394 dbesc(substr($birthday,0,4)),
1395 intval($contact['uid']),
1396 intval($contact['id'])
1399 // This function is called twice without reloading the contact
1400 // Make sure we only create one event. This is why &$contact
1401 // is a reference var in this function
1403 $contact['bdyear'] = substr($birthday,0,4);
1408 $community_page = 0;
1409 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1411 $community_page = intval($rawtags[0]['data']);
1413 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1414 q("update contact set forum = %d where id = %d limit 1",
1415 intval($community_page),
1416 intval($contact['id'])
1418 $contact['forum'] = (string) $community_page;
1422 // process any deleted entries
1424 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1425 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1426 foreach($del_entries as $dentry) {
1428 if(isset($dentry['attribs']['']['ref'])) {
1429 $uri = $dentry['attribs']['']['ref'];
1431 if(isset($dentry['attribs']['']['when'])) {
1432 $when = $dentry['attribs']['']['when'];
1433 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1436 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1438 if($deleted && is_array($contact)) {
1439 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1440 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1442 intval($importer['uid']),
1443 intval($contact['id'])
1448 if(! $item['deleted'])
1449 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1451 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1452 $xo = parse_xml_string($item['object'],false);
1453 $xt = parse_xml_string($item['target'],false);
1454 if($xt->type === ACTIVITY_OBJ_NOTE) {
1455 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1457 intval($importer['importer_uid'])
1461 // For tags, the owner cannot remove the tag on the author's copy of the post.
1463 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1464 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1465 $author_copy = (($item['origin']) ? true : false);
1467 if($owner_remove && $author_copy)
1469 if($author_remove || $owner_remove) {
1470 $tags = explode(',',$i[0]['tag']);
1473 foreach($tags as $tag)
1474 if(trim($tag) !== trim($xo->body))
1475 $newtags[] = trim($tag);
1477 q("update item set tag = '%s' where id = %d limit 1",
1478 dbesc(implode(',',$newtags)),
1486 if($item['uri'] == $item['parent-uri']) {
1487 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1488 `body` = '', `title` = ''
1489 WHERE `parent-uri` = '%s' AND `uid` = %d",
1491 dbesc(datetime_convert()),
1492 dbesc($item['uri']),
1493 intval($importer['uid'])
1497 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1498 `body` = '', `title` = ''
1499 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1501 dbesc(datetime_convert()),
1503 intval($importer['uid'])
1505 if($item['last-child']) {
1506 // ensure that last-child is set in case the comment that had it just got wiped.
1507 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1508 dbesc(datetime_convert()),
1509 dbesc($item['parent-uri']),
1510 intval($item['uid'])
1512 // who is the last child now?
1513 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1514 ORDER BY `created` DESC LIMIT 1",
1515 dbesc($item['parent-uri']),
1516 intval($importer['uid'])
1519 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1530 // Now process the feed
1532 if($feed->get_item_quantity()) {
1534 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1536 // in inverse date order
1538 $items = array_reverse($feed->get_items());
1540 $items = $feed->get_items();
1543 foreach($items as $item) {
1546 $item_id = $item->get_id();
1547 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1548 if(isset($rawthread[0]['attribs']['']['ref'])) {
1550 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1553 if(($is_reply) && is_array($contact)) {
1558 // Have we seen it? If not, import it.
1560 $item_id = $item->get_id();
1561 $datarray = get_atom_elements($feed,$item);
1564 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1565 $datarray['author-name'] = $contact['name'];
1566 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1567 $datarray['author-link'] = $contact['url'];
1568 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1569 $datarray['author-avatar'] = $contact['thumb'];
1571 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1572 logger('consume_feed: no author information! ' . print_r($datarray,true));
1576 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1578 intval($importer['uid'])
1581 // Update content if 'updated' changes
1584 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1585 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1586 dbesc($datarray['title']),
1587 dbesc($datarray['body']),
1588 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1590 intval($importer['uid'])
1594 // update last-child if it changes
1596 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1597 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1598 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1599 dbesc(datetime_convert()),
1601 intval($importer['uid'])
1603 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1604 intval($allow[0]['data']),
1605 dbesc(datetime_convert()),
1607 intval($importer['uid'])
1613 $force_parent = false;
1614 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1615 if($contact['network'] === NETWORK_OSTATUS)
1616 $force_parent = true;
1617 if(strlen($datarray['title']))
1618 unset($datarray['title']);
1619 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1620 dbesc(datetime_convert()),
1622 intval($importer['uid'])
1624 $datarray['last-child'] = 1;
1627 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1628 // one way feed - no remote comment ability
1629 $datarray['last-child'] = 0;
1631 $datarray['parent-uri'] = $parent_uri;
1632 $datarray['uid'] = $importer['uid'];
1633 $datarray['contact-id'] = $contact['id'];
1634 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1635 $datarray['type'] = 'activity';
1636 $datarray['gravity'] = GRAVITY_LIKE;
1637 // only one like or dislike per person
1638 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1639 intval($datarray['uid']),
1640 intval($datarray['contact-id']),
1641 dbesc($datarray['verb'])
1647 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1648 $xo = parse_xml_string($datarray['object'],false);
1649 $xt = parse_xml_string($datarray['target'],false);
1651 if($xt->type == ACTIVITY_OBJ_NOTE) {
1652 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1654 intval($importer['importer_uid'])
1659 // extract tag, if not duplicate, add to parent item
1660 if($xo->id && $xo->content) {
1661 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1662 if(! (stristr($r[0]['tag'],$newtag))) {
1663 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1664 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1672 $r = item_store($datarray,$force_parent);
1678 // Head post of a conversation. Have we seen it? If not, import it.
1680 $item_id = $item->get_id();
1682 $datarray = get_atom_elements($feed,$item);
1684 if(is_array($contact)) {
1685 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1686 $datarray['author-name'] = $contact['name'];
1687 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1688 $datarray['author-link'] = $contact['url'];
1689 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1690 $datarray['author-avatar'] = $contact['thumb'];
1693 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1694 logger('consume_feed: no author information! ' . print_r($datarray,true));
1698 // special handling for events
1700 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1701 $ev = bbtoevent($datarray['body']);
1702 if(x($ev,'desc') && x($ev,'start')) {
1703 $ev['uid'] = $importer['uid'];
1704 $ev['uri'] = $item_id;
1705 $ev['edited'] = $datarray['edited'];
1706 $ev['private'] = $datarray['private'];
1708 if(is_array($contact))
1709 $ev['cid'] = $contact['id'];
1710 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1712 intval($importer['uid'])
1715 $ev['id'] = $r[0]['id'];
1716 $xyz = event_store($ev);
1721 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1723 intval($importer['uid'])
1726 // Update content if 'updated' changes
1729 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1730 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1731 dbesc($datarray['title']),
1732 dbesc($datarray['body']),
1733 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1735 intval($importer['uid'])
1739 // update last-child if it changes
1741 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1742 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1743 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1744 intval($allow[0]['data']),
1745 dbesc(datetime_convert()),
1747 intval($importer['uid'])
1753 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1754 logger('consume-feed: New follower');
1755 new_follower($importer,$contact,$datarray,$item);
1758 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1759 lose_follower($importer,$contact,$datarray,$item);
1763 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1764 logger('consume-feed: New friend request');
1765 new_follower($importer,$contact,$datarray,$item,true);
1768 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1769 lose_sharer($importer,$contact,$datarray,$item);
1774 if(! is_array($contact))
1777 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1778 if(strlen($datarray['title']))
1779 unset($datarray['title']);
1780 $datarray['last-child'] = 1;
1783 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1784 // one way feed - no remote comment ability
1785 $datarray['last-child'] = 0;
1788 // This is my contact on another system, but it's really me.
1789 // Turn this into a wall post.
1791 if($contact['remote_self'])
1792 $datarray['wall'] = 1;
1794 $datarray['parent-uri'] = $item_id;
1795 $datarray['uid'] = $importer['uid'];
1796 $datarray['contact-id'] = $contact['id'];
1798 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1799 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1800 // but otherwise there's a possible data mixup on the sender's system.
1801 // the tgroup delivery code called from item_store will correct it if it's a forum,
1802 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1803 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
1804 $datarray['owner-name'] = $contact['name'];
1805 $datarray['owner-link'] = $contact['url'];
1806 $datarray['owner-avatar'] = $contact['thumb'];
1809 $r = item_store($datarray);
1817 function local_delivery($importer,$data) {
1821 if($importer['readonly']) {
1822 // We aren't receiving stuff from this person. But we will quietly ignore them
1823 // rather than a blatant "go away" message.
1824 logger('local_delivery: ignoring');
1829 // Consume notification feed. This may differ from consuming a public feed in several ways
1830 // - might contain email or friend suggestions
1831 // - might contain remote followup to our message
1832 // - in which case we need to accept it and then notify other conversants
1833 // - we may need to send various email notifications
1835 $feed = new SimplePie();
1836 $feed->set_raw_data($data);
1837 $feed->enable_order_by_date(false);
1840 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1841 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1842 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1844 $newloc['uid'] = $importer['importer_uid'];
1845 $newloc['cid'] = $importer['id'];
1846 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1847 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1848 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1849 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1850 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1851 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1852 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1853 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1854 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1855 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1858 // merge with current record, current contents have priority
1859 // update record, set url-updated
1860 // update profile photos
1865 // handle friend suggestion notification
1867 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1868 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1869 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1871 $fsugg['uid'] = $importer['importer_uid'];
1872 $fsugg['cid'] = $importer['id'];
1873 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1874 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1875 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1876 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1877 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1879 // Does our member already have a friend matching this description?
1881 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1882 dbesc($fsugg['name']),
1883 dbesc(normalise_link($fsugg['url'])),
1884 intval($fsugg['uid'])
1889 // Do we already have an fcontact record for this person?
1892 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1893 dbesc($fsugg['url']),
1894 dbesc($fsugg['name']),
1895 dbesc($fsugg['request'])
1901 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1902 dbesc($fsugg['name']),
1903 dbesc($fsugg['url']),
1904 dbesc($fsugg['photo']),
1905 dbesc($fsugg['request'])
1907 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1908 dbesc($fsugg['url']),
1909 dbesc($fsugg['name']),
1910 dbesc($fsugg['request'])
1915 // database record did not get created. Quietly give up.
1919 $hash = random_string();
1921 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1922 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1923 intval($fsugg['uid']),
1925 intval($fsugg['cid']),
1926 dbesc($fsugg['body']),
1928 dbesc(datetime_convert()),
1933 'type' => NOTIFY_SUGGEST,
1934 'notify_flags' => $importer['notify-flags'],
1935 'language' => $importer['language'],
1936 'to_name' => $importer['username'],
1937 'to_email' => $importer['email'],
1938 'uid' => $importer['importer_uid'],
1940 'link' => $a->get_baseurl() . '/notifications/intros',
1941 'source_name' => $importer['name'],
1942 'source_link' => $importer['url'],
1943 'source_photo' => $importer['photo'],
1944 'verb' => ACTIVITY_REQ_FRIEND,
1953 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1954 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1956 logger('local_delivery: private message received');
1959 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1962 $msg['uid'] = $importer['importer_uid'];
1963 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1964 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1965 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1966 $msg['contact-id'] = $importer['id'];
1967 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1968 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1970 $msg['replied'] = 0;
1971 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1972 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1973 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1977 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
1978 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1980 // send notifications.
1982 require_once('include/enotify.php');
1984 $notif_params = array(
1985 'type' => NOTIFY_MAIL,
1986 'notify_flags' => $importer['notify-flags'],
1987 'language' => $importer['language'],
1988 'to_name' => $importer['username'],
1989 'to_email' => $importer['email'],
1990 'uid' => $importer['importer_uid'],
1992 'source_name' => $msg['from-name'],
1993 'source_link' => $importer['url'],
1994 'source_photo' => $importer['thumb'],
1995 'verb' => ACTIVITY_POST,
1999 notification($notif_params);
2005 $community_page = 0;
2006 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2008 $community_page = intval($rawtags[0]['data']);
2010 if(intval($importer['forum']) != $community_page) {
2011 q("update contact set forum = %d where id = %d limit 1",
2012 intval($community_page),
2013 intval($importer['id'])
2015 $importer['forum'] = (string) $community_page;
2018 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2020 // process any deleted entries
2022 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2023 if(is_array($del_entries) && count($del_entries)) {
2024 foreach($del_entries as $dentry) {
2026 if(isset($dentry['attribs']['']['ref'])) {
2027 $uri = $dentry['attribs']['']['ref'];
2029 if(isset($dentry['attribs']['']['when'])) {
2030 $when = $dentry['attribs']['']['when'];
2031 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2034 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2038 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2039 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
2041 intval($importer['importer_uid']),
2042 intval($importer['id'])
2048 if($item['deleted'])
2051 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2053 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
2054 $xo = parse_xml_string($item['object'],false);
2055 $xt = parse_xml_string($item['target'],false);
2057 if($xt->type === ACTIVITY_OBJ_NOTE) {
2058 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2060 intval($importer['importer_uid'])
2064 // For tags, the owner cannot remove the tag on the author's copy of the post.
2066 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2067 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2068 $author_copy = (($item['origin']) ? true : false);
2070 if($owner_remove && $author_copy)
2072 if($author_remove || $owner_remove) {
2073 $tags = explode(',',$i[0]['tag']);
2076 foreach($tags as $tag)
2077 if(trim($tag) !== trim($xo->body))
2078 $newtags[] = trim($tag);
2080 q("update item set tag = '%s' where id = %d limit 1",
2081 dbesc(implode(',',$newtags)),
2089 if($item['uri'] == $item['parent-uri']) {
2090 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2091 WHERE `parent-uri` = '%s' AND `uid` = %d",
2093 dbesc(datetime_convert()),
2094 dbesc($item['uri']),
2095 intval($importer['importer_uid'])
2099 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2100 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2102 dbesc(datetime_convert()),
2104 intval($importer['importer_uid'])
2106 if($item['last-child']) {
2107 // ensure that last-child is set in case the comment that had it just got wiped.
2108 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2109 dbesc(datetime_convert()),
2110 dbesc($item['parent-uri']),
2111 intval($item['uid'])
2113 // who is the last child now?
2114 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2115 ORDER BY `created` DESC LIMIT 1",
2116 dbesc($item['parent-uri']),
2117 intval($importer['importer_uid'])
2120 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2132 foreach($feed->get_items() as $item) {
2135 $item_id = $item->get_id();
2136 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2137 if(isset($rawthread[0]['attribs']['']['ref'])) {
2139 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2145 if($importer['page-flags'] == PAGE_COMMUNITY) {
2148 logger('local_delivery: possible community reply');
2151 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2153 // was the top-level post for this reply written by somebody on this site?
2154 // Specifically, the recipient?
2156 $is_a_remote_comment = false;
2158 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2159 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2160 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2161 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2162 AND `item`.`uid` = %d
2167 intval($importer['importer_uid'])
2170 $is_a_remote_comment = true;
2172 // Does this have the characteristics of a community comment?
2173 // If it's a reply to a wall post on a community page it's a
2174 // valid community comment. Also forum_mode makes it valid for sure.
2175 // If neither, it's not.
2177 if($is_a_remote_comment && $community) {
2178 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2179 $is_a_remote_comment = false;
2180 logger('local_delivery: not a community reply');
2184 if($is_a_remote_comment) {
2185 logger('local_delivery: received remote comment');
2187 // remote reply to our post. Import and then notify everybody else.
2188 $datarray = get_atom_elements($feed,$item);
2191 // TODO: make this next part work against both delivery threads of a community post
2193 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2194 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2195 // they won't know what to do so don't report an error. Just quietly die.
2199 $datarray['type'] = 'remote-comment';
2200 $datarray['wall'] = 1;
2201 $datarray['parent-uri'] = $parent_uri;
2202 $datarray['uid'] = $importer['importer_uid'];
2203 $datarray['owner-name'] = $r[0]['name'];
2204 $datarray['owner-link'] = $r[0]['url'];
2205 $datarray['owner-avatar'] = $r[0]['thumb'];
2206 $datarray['contact-id'] = $importer['id'];
2207 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2209 $datarray['type'] = 'activity';
2210 $datarray['gravity'] = GRAVITY_LIKE;
2211 $datarray['last-child'] = 0;
2212 // only one like or dislike per person
2213 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2214 intval($datarray['uid']),
2215 intval($datarray['contact-id']),
2216 dbesc($datarray['verb'])
2222 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2225 $xo = parse_xml_string($datarray['object'],false);
2226 $xt = parse_xml_string($datarray['target'],false);
2228 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2230 // extract tag, if not duplicate, and this user allows tags, add to parent item
2232 if($xo->id && $xo->content) {
2233 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2235 if(! (stristr($r[0]['tag'],$newtag))) {
2236 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2237 intval($importer['importer_uid'])
2239 if(count($i) && ! ($i[0]['blocktags'])) {
2240 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2241 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2251 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2252 // if(! stristr($datarray['tag'],$newtag)) {
2253 // if(strlen($datarray['tag']))
2254 // $datarray['tag'] .= ',';
2255 // $datarray['tag'] .= $newtag;
2260 $posted_id = item_store($datarray);
2264 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2266 intval($importer['importer_uid'])
2269 $parent = $r[0]['parent'];
2272 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2273 dbesc(datetime_convert()),
2274 intval($importer['importer_uid']),
2275 intval($r[0]['parent'])
2278 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2279 dbesc(datetime_convert()),
2280 intval($importer['importer_uid']),
2285 if($posted_id && $parent) {
2287 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2289 if((! $is_like) && (! $importer['self'])) {
2291 require_once('include/enotify.php');
2294 'type' => NOTIFY_COMMENT,
2295 'notify_flags' => $importer['notify-flags'],
2296 'language' => $importer['language'],
2297 'to_name' => $importer['username'],
2298 'to_email' => $importer['email'],
2299 'uid' => $importer['importer_uid'],
2300 'item' => $datarray,
2301 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2302 'source_name' => stripslashes($datarray['author-name']),
2303 'source_link' => $datarray['author-link'],
2304 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2305 ? $importer['thumb'] : $datarray['author-avatar']),
2306 'verb' => ACTIVITY_POST,
2308 'parent' => $parent,
2321 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2323 $item_id = $item->get_id();
2324 $datarray = get_atom_elements($feed,$item);
2326 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2328 intval($importer['importer_uid'])
2331 // Update content if 'updated' changes
2334 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2335 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2336 dbesc($datarray['title']),
2337 dbesc($datarray['body']),
2338 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2340 intval($importer['importer_uid'])
2344 // update last-child if it changes
2346 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2347 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2348 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2349 dbesc(datetime_convert()),
2351 intval($importer['importer_uid'])
2353 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2354 intval($allow[0]['data']),
2355 dbesc(datetime_convert()),
2357 intval($importer['importer_uid'])
2363 $datarray['parent-uri'] = $parent_uri;
2364 $datarray['uid'] = $importer['importer_uid'];
2365 $datarray['contact-id'] = $importer['id'];
2366 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2367 $datarray['type'] = 'activity';
2368 $datarray['gravity'] = GRAVITY_LIKE;
2369 // only one like or dislike per person
2370 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2371 intval($datarray['uid']),
2372 intval($datarray['contact-id']),
2373 dbesc($datarray['verb'])
2380 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2382 $xo = parse_xml_string($datarray['object'],false);
2383 $xt = parse_xml_string($datarray['target'],false);
2385 if($xt->type == ACTIVITY_OBJ_NOTE) {
2386 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2388 intval($importer['importer_uid'])
2393 // extract tag, if not duplicate, add to parent item
2395 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2396 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2397 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2405 $posted_id = item_store($datarray);
2407 // find out if our user is involved in this conversation and wants to be notified.
2409 if($datarray['type'] != 'activity') {
2411 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2413 intval($importer['importer_uid'])
2416 if(count($myconv)) {
2417 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2419 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2420 if(! link_compare($datarray['author-link'],$importer_url)) {
2423 foreach($myconv as $conv) {
2425 // now if we find a match, it means we're in this conversation
2427 if(! link_compare($conv['author-link'],$importer_url))
2430 require_once('include/enotify.php');
2432 $conv_parent = $conv['parent'];
2435 'type' => NOTIFY_COMMENT,
2436 'notify_flags' => $importer['notify-flags'],
2437 'language' => $importer['language'],
2438 'to_name' => $importer['username'],
2439 'to_email' => $importer['email'],
2440 'uid' => $importer['importer_uid'],
2441 'item' => $datarray,
2442 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2443 'source_name' => stripslashes($datarray['author-name']),
2444 'source_link' => $datarray['author-link'],
2445 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2446 ? $importer['thumb'] : $datarray['author-avatar']),
2447 'verb' => ACTIVITY_POST,
2449 'parent' => $conv_parent,
2453 // only send one notification
2465 // Head post of a conversation. Have we seen it? If not, import it.
2468 $item_id = $item->get_id();
2469 $datarray = get_atom_elements($feed,$item);
2471 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2472 $ev = bbtoevent($datarray['body']);
2473 if(x($ev,'desc') && x($ev,'start')) {
2474 $ev['cid'] = $importer['id'];
2475 $ev['uid'] = $importer['uid'];
2476 $ev['uri'] = $item_id;
2477 $ev['edited'] = $datarray['edited'];
2478 $ev['private'] = $datarray['private'];
2480 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2482 intval($importer['uid'])
2485 $ev['id'] = $r[0]['id'];
2486 $xyz = event_store($ev);
2491 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2493 intval($importer['importer_uid'])
2496 // Update content if 'updated' changes
2499 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2500 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2501 dbesc($datarray['title']),
2502 dbesc($datarray['body']),
2503 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2505 intval($importer['importer_uid'])
2509 // update last-child if it changes
2511 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2512 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2513 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2514 intval($allow[0]['data']),
2515 dbesc(datetime_convert()),
2517 intval($importer['importer_uid'])
2523 // This is my contact on another system, but it's really me.
2524 // Turn this into a wall post.
2526 if($importer['remote_self'])
2527 $datarray['wall'] = 1;
2529 $datarray['parent-uri'] = $item_id;
2530 $datarray['uid'] = $importer['importer_uid'];
2531 $datarray['contact-id'] = $importer['id'];
2533 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2534 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2535 // but otherwise there's a possible data mixup on the sender's system.
2536 // the tgroup delivery code called from item_store will correct it if it's a forum,
2537 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2538 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2539 $datarray['owner-name'] = $importer['senderName'];
2540 $datarray['owner-link'] = $importer['url'];
2541 $datarray['owner-avatar'] = $importer['thumb'];
2544 $r = item_store($datarray);
2555 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2556 $url = notags(trim($datarray['author-link']));
2557 $name = notags(trim($datarray['author-name']));
2558 $photo = notags(trim($datarray['author-avatar']));
2560 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2561 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2562 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2564 if(is_array($contact)) {
2565 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2566 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2567 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2568 intval(CONTACT_IS_FRIEND),
2569 intval($contact['id']),
2570 intval($importer['uid'])
2573 // send email notification to owner?
2577 // create contact record
2579 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2580 `blocked`, `readonly`, `pending`, `writable` )
2581 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2582 intval($importer['uid']),
2583 dbesc(datetime_convert()),
2585 dbesc(normalise_link($url)),
2589 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2590 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2592 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2593 intval($importer['uid']),
2597 $contact_record = $r[0];
2599 // create notification
2600 $hash = random_string();
2602 if(is_array($contact_record)) {
2603 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2604 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2605 intval($importer['uid']),
2606 intval($contact_record['id']),
2608 dbesc(datetime_convert())
2611 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2612 intval($importer['uid'])
2616 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2617 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2618 $email = replace_macros($email_tpl, array(
2619 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2621 '$myname' => $r[0]['username'],
2622 '$siteurl' => $a->get_baseurl(),
2623 '$sitename' => $a->config['sitename']
2625 $res = mail($r[0]['email'],
2626 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2628 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2629 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2630 . 'Content-transfer-encoding: 8bit' );
2637 function lose_follower($importer,$contact,$datarray,$item) {
2639 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2640 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2641 intval(CONTACT_IS_SHARING),
2642 intval($contact['id'])
2646 contact_remove($contact['id']);
2650 function lose_sharer($importer,$contact,$datarray,$item) {
2652 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2653 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2654 intval(CONTACT_IS_FOLLOWER),
2655 intval($contact['id'])
2659 contact_remove($contact['id']);
2664 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2666 if(is_array($importer)) {
2667 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2668 intval($importer['uid'])
2672 // Diaspora has different message-ids in feeds than they do
2673 // through the direct Diaspora protocol. If we try and use
2674 // the feed, we'll get duplicates. So don't.
2676 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2679 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2681 // Use a single verify token, even if multiple hubs
2683 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2685 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2687 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2689 if(! strlen($contact['hub-verify'])) {
2690 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2691 dbesc($verify_token),
2692 intval($contact['id'])
2696 post_url($url,$params);
2702 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2706 $name = xmlify($name);
2707 $uri = xmlify($uri);
2710 $photo = xmlify($photo);
2714 $o .= "<name>$name</name>\r\n";
2715 $o .= "<uri>$uri</uri>\r\n";
2716 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2717 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2719 call_hooks('atom_author', $o);
2721 $o .= "</$tag>\r\n";
2725 function atom_entry($item,$type,$author,$owner,$comment = false) {
2729 if(! $item['parent'])
2732 if($item['deleted'])
2733 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2736 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2737 $body = fix_private_photos($item['body'],$owner['uid']);
2739 $body = $item['body'];
2742 $o = "\r\n\r\n<entry>\r\n";
2744 if(is_array($author))
2745 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2747 $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']));
2748 if(strlen($item['owner-name']))
2749 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2751 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2752 $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";
2754 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2755 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2756 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2757 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2758 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2759 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2760 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2762 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2764 if($item['location']) {
2765 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2766 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2770 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2772 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2773 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2776 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2777 if($item['bookmark'])
2778 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2781 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2784 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2786 if($item['signed_text']) {
2787 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2788 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2791 $verb = construct_verb($item);
2792 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2793 $actobj = construct_activity_object($item);
2796 $actarg = construct_activity_target($item);
2800 $tags = item_getfeedtags($item);
2802 foreach($tags as $t) {
2803 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2807 $o .= item_getfeedattach($item);
2809 $mentioned = get_mentions($item);
2813 call_hooks('atom_entry', $o);
2815 $o .= '</entry>' . "\r\n";
2820 function fix_private_photos($s,$uid) {
2822 logger('fix_private_photos');
2824 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2825 $image = $matches[1];
2826 logger('fix_private_photos: found photo ' . $image);
2827 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2828 $i = basename($image);
2829 $i = str_replace('.jpg','',$i);
2830 $x = strpos($i,'-');
2832 $res = substr($i,$x+1);
2833 $i = substr($i,0,$x);
2834 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2840 logger('replacing photo');
2841 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2844 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2852 function item_getfeedtags($item) {
2855 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2857 for($x = 0; $x < $cnt; $x ++) {
2859 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2863 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2865 for($x = 0; $x < $cnt; $x ++) {
2867 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2873 function item_getfeedattach($item) {
2875 $arr = explode(',',$item['attach']);
2877 foreach($arr as $r) {
2879 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2881 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2882 if(intval($matches[2]))
2883 $ret .= 'length="' . intval($matches[2]) . '" ';
2884 if($matches[4] !== ' ')
2885 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2886 $ret .= ' />' . "\r\n";
2895 function item_expire($uid,$days) {
2897 if((! $uid) || (! $days))
2900 $r = q("SELECT * FROM `item`
2902 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
2912 $expire_items = get_pconfig($uid, 'expire','items');
2913 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2915 $expire_notes = get_pconfig($uid, 'expire','notes');
2916 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2918 $expire_starred = get_pconfig($uid, 'expire','starred');
2919 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2921 $expire_photos = get_pconfig($uid, 'expire','photos');
2922 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2924 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2926 foreach($r as $item) {
2928 // Only expire posts, not photos and photo comments
2930 if($expire_photos==0 && strlen($item['resource-id']))
2932 if($expire_starred==0 && intval($item['starred']))
2934 if($expire_notes==0 && $item['type']=='note')
2936 if($expire_items==0 && $item['type']!='note')
2939 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2940 dbesc(datetime_convert()),
2941 dbesc(datetime_convert()),
2947 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2948 dbesc(datetime_convert()),
2949 dbesc(datetime_convert()),
2950 dbesc($item['parent-uri']),
2951 intval($item['uid'])
2956 proc_run('php',"include/notifier.php","expire","$uid");
2961 function drop_items($items) {
2964 if((! local_user()) && (! $remote_user()))
2968 foreach($items as $item) {
2969 $owner = drop_item($item,false);
2970 if($owner && ! $uid)
2975 // multiple threads may have been deleted, send an expire notification
2978 proc_run('php',"include/notifier.php","expire","$uid");
2982 function drop_item($id,$interactive = true) {
2986 // locate item to be deleted
2988 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2995 notice( t('Item not found.') . EOL);
2996 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3001 $owner = $item['uid'];
3003 // check if logged in user is either the author or owner of this item
3005 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3009 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3010 dbesc(datetime_convert()),
3011 dbesc(datetime_convert()),
3015 // If item is a link to a photo resource, nuke all the associated photos
3016 // (visitors will not have photo resources)
3017 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3018 // generate a resource-id and therefore aren't intimately linked to the item.
3020 if(strlen($item['resource-id'])) {
3021 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3022 dbesc($item['resource-id']),
3023 intval($item['uid'])
3025 // ignore the result
3028 // If item is a link to an event, nuke the event record.
3030 if(intval($item['event-id'])) {
3031 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3032 intval($item['event-id']),
3033 intval($item['uid'])
3035 // ignore the result
3039 // If it's the parent of a comment thread, kill all the kids
3041 if($item['uri'] == $item['parent-uri']) {
3042 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3043 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3044 dbesc(datetime_convert()),
3045 dbesc(datetime_convert()),
3046 dbesc($item['parent-uri']),
3047 intval($item['uid'])
3049 // ignore the result
3052 // ensure that last-child is set in case the comment that had it just got wiped.
3053 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3054 dbesc(datetime_convert()),
3055 dbesc($item['parent-uri']),
3056 intval($item['uid'])
3058 // who is the last child now?
3059 $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",
3060 dbesc($item['parent-uri']),
3061 intval($item['uid'])
3064 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3069 $drop_id = intval($item['id']);
3071 // send the notification upstream/downstream as the case may be
3076 proc_run('php',"include/notifier.php","drop","$drop_id");
3077 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3083 notice( t('Permission denied.') . EOL);
3084 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);