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', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1586 dbesc($datarray['title']),
1587 dbesc($datarray['body']),
1588 dbesc($datarray['tag']),
1589 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1591 intval($importer['uid'])
1595 // update last-child if it changes
1597 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1598 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1599 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1600 dbesc(datetime_convert()),
1602 intval($importer['uid'])
1604 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1605 intval($allow[0]['data']),
1606 dbesc(datetime_convert()),
1608 intval($importer['uid'])
1614 $force_parent = false;
1615 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1616 if($contact['network'] === NETWORK_OSTATUS)
1617 $force_parent = true;
1618 if(strlen($datarray['title']))
1619 unset($datarray['title']);
1620 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1621 dbesc(datetime_convert()),
1623 intval($importer['uid'])
1625 $datarray['last-child'] = 1;
1628 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1629 // one way feed - no remote comment ability
1630 $datarray['last-child'] = 0;
1632 $datarray['parent-uri'] = $parent_uri;
1633 $datarray['uid'] = $importer['uid'];
1634 $datarray['contact-id'] = $contact['id'];
1635 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1636 $datarray['type'] = 'activity';
1637 $datarray['gravity'] = GRAVITY_LIKE;
1638 // only one like or dislike per person
1639 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1640 intval($datarray['uid']),
1641 intval($datarray['contact-id']),
1642 dbesc($datarray['verb'])
1648 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1649 $xo = parse_xml_string($datarray['object'],false);
1650 $xt = parse_xml_string($datarray['target'],false);
1652 if($xt->type == ACTIVITY_OBJ_NOTE) {
1653 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1655 intval($importer['importer_uid'])
1660 // extract tag, if not duplicate, add to parent item
1661 if($xo->id && $xo->content) {
1662 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1663 if(! (stristr($r[0]['tag'],$newtag))) {
1664 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1665 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1673 $r = item_store($datarray,$force_parent);
1679 // Head post of a conversation. Have we seen it? If not, import it.
1681 $item_id = $item->get_id();
1683 $datarray = get_atom_elements($feed,$item);
1685 if(is_array($contact)) {
1686 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1687 $datarray['author-name'] = $contact['name'];
1688 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1689 $datarray['author-link'] = $contact['url'];
1690 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1691 $datarray['author-avatar'] = $contact['thumb'];
1694 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1695 logger('consume_feed: no author information! ' . print_r($datarray,true));
1699 // special handling for events
1701 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1702 $ev = bbtoevent($datarray['body']);
1703 if(x($ev,'desc') && x($ev,'start')) {
1704 $ev['uid'] = $importer['uid'];
1705 $ev['uri'] = $item_id;
1706 $ev['edited'] = $datarray['edited'];
1707 $ev['private'] = $datarray['private'];
1709 if(is_array($contact))
1710 $ev['cid'] = $contact['id'];
1711 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1713 intval($importer['uid'])
1716 $ev['id'] = $r[0]['id'];
1717 $xyz = event_store($ev);
1722 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1724 intval($importer['uid'])
1727 // Update content if 'updated' changes
1730 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1731 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1732 dbesc($datarray['title']),
1733 dbesc($datarray['body']),
1734 dbesc($datarray['tag']),
1735 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1737 intval($importer['uid'])
1741 // update last-child if it changes
1743 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1744 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1745 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1746 intval($allow[0]['data']),
1747 dbesc(datetime_convert()),
1749 intval($importer['uid'])
1755 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1756 logger('consume-feed: New follower');
1757 new_follower($importer,$contact,$datarray,$item);
1760 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1761 lose_follower($importer,$contact,$datarray,$item);
1765 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1766 logger('consume-feed: New friend request');
1767 new_follower($importer,$contact,$datarray,$item,true);
1770 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1771 lose_sharer($importer,$contact,$datarray,$item);
1776 if(! is_array($contact))
1779 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1780 if(strlen($datarray['title']))
1781 unset($datarray['title']);
1782 $datarray['last-child'] = 1;
1785 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1786 // one way feed - no remote comment ability
1787 $datarray['last-child'] = 0;
1790 // This is my contact on another system, but it's really me.
1791 // Turn this into a wall post.
1793 if($contact['remote_self'])
1794 $datarray['wall'] = 1;
1796 $datarray['parent-uri'] = $item_id;
1797 $datarray['uid'] = $importer['uid'];
1798 $datarray['contact-id'] = $contact['id'];
1800 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1801 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1802 // but otherwise there's a possible data mixup on the sender's system.
1803 // the tgroup delivery code called from item_store will correct it if it's a forum,
1804 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1805 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1806 $datarray['owner-name'] = $contact['name'];
1807 $datarray['owner-link'] = $contact['url'];
1808 $datarray['owner-avatar'] = $contact['thumb'];
1811 $r = item_store($datarray);
1819 function local_delivery($importer,$data) {
1823 if($importer['readonly']) {
1824 // We aren't receiving stuff from this person. But we will quietly ignore them
1825 // rather than a blatant "go away" message.
1826 logger('local_delivery: ignoring');
1831 // Consume notification feed. This may differ from consuming a public feed in several ways
1832 // - might contain email or friend suggestions
1833 // - might contain remote followup to our message
1834 // - in which case we need to accept it and then notify other conversants
1835 // - we may need to send various email notifications
1837 $feed = new SimplePie();
1838 $feed->set_raw_data($data);
1839 $feed->enable_order_by_date(false);
1842 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1843 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1844 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1846 $newloc['uid'] = $importer['importer_uid'];
1847 $newloc['cid'] = $importer['id'];
1848 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1849 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1850 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1851 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1852 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1853 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1854 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1855 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1856 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1857 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1860 // merge with current record, current contents have priority
1861 // update record, set url-updated
1862 // update profile photos
1867 // handle friend suggestion notification
1869 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1870 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1871 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1873 $fsugg['uid'] = $importer['importer_uid'];
1874 $fsugg['cid'] = $importer['id'];
1875 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1876 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1877 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1878 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1879 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1881 // Does our member already have a friend matching this description?
1883 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1884 dbesc($fsugg['name']),
1885 dbesc(normalise_link($fsugg['url'])),
1886 intval($fsugg['uid'])
1891 // Do we already have an fcontact record for this person?
1894 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1895 dbesc($fsugg['url']),
1896 dbesc($fsugg['name']),
1897 dbesc($fsugg['request'])
1903 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1904 dbesc($fsugg['name']),
1905 dbesc($fsugg['url']),
1906 dbesc($fsugg['photo']),
1907 dbesc($fsugg['request'])
1909 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1910 dbesc($fsugg['url']),
1911 dbesc($fsugg['name']),
1912 dbesc($fsugg['request'])
1917 // database record did not get created. Quietly give up.
1921 $hash = random_string();
1923 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1924 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1925 intval($fsugg['uid']),
1927 intval($fsugg['cid']),
1928 dbesc($fsugg['body']),
1930 dbesc(datetime_convert()),
1935 'type' => NOTIFY_SUGGEST,
1936 'notify_flags' => $importer['notify-flags'],
1937 'language' => $importer['language'],
1938 'to_name' => $importer['username'],
1939 'to_email' => $importer['email'],
1940 'uid' => $importer['importer_uid'],
1942 'link' => $a->get_baseurl() . '/notifications/intros',
1943 'source_name' => $importer['name'],
1944 'source_link' => $importer['url'],
1945 'source_photo' => $importer['photo'],
1946 'verb' => ACTIVITY_REQ_FRIEND,
1955 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1956 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1958 logger('local_delivery: private message received');
1961 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1964 $msg['uid'] = $importer['importer_uid'];
1965 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1966 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1967 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1968 $msg['contact-id'] = $importer['id'];
1969 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1970 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1972 $msg['replied'] = 0;
1973 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1974 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1975 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1979 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
1980 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1982 // send notifications.
1984 require_once('include/enotify.php');
1986 $notif_params = array(
1987 'type' => NOTIFY_MAIL,
1988 'notify_flags' => $importer['notify-flags'],
1989 'language' => $importer['language'],
1990 'to_name' => $importer['username'],
1991 'to_email' => $importer['email'],
1992 'uid' => $importer['importer_uid'],
1994 'source_name' => $msg['from-name'],
1995 'source_link' => $importer['url'],
1996 'source_photo' => $importer['thumb'],
1997 'verb' => ACTIVITY_POST,
2001 notification($notif_params);
2007 $community_page = 0;
2008 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2010 $community_page = intval($rawtags[0]['data']);
2012 if(intval($importer['forum']) != $community_page) {
2013 q("update contact set forum = %d where id = %d limit 1",
2014 intval($community_page),
2015 intval($importer['id'])
2017 $importer['forum'] = (string) $community_page;
2020 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2022 // process any deleted entries
2024 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2025 if(is_array($del_entries) && count($del_entries)) {
2026 foreach($del_entries as $dentry) {
2028 if(isset($dentry['attribs']['']['ref'])) {
2029 $uri = $dentry['attribs']['']['ref'];
2031 if(isset($dentry['attribs']['']['when'])) {
2032 $when = $dentry['attribs']['']['when'];
2033 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2036 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2040 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2041 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
2043 intval($importer['importer_uid']),
2044 intval($importer['id'])
2050 if($item['deleted'])
2053 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2055 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
2056 $xo = parse_xml_string($item['object'],false);
2057 $xt = parse_xml_string($item['target'],false);
2059 if($xt->type === ACTIVITY_OBJ_NOTE) {
2060 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2062 intval($importer['importer_uid'])
2066 // For tags, the owner cannot remove the tag on the author's copy of the post.
2068 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2069 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2070 $author_copy = (($item['origin']) ? true : false);
2072 if($owner_remove && $author_copy)
2074 if($author_remove || $owner_remove) {
2075 $tags = explode(',',$i[0]['tag']);
2078 foreach($tags as $tag)
2079 if(trim($tag) !== trim($xo->body))
2080 $newtags[] = trim($tag);
2082 q("update item set tag = '%s' where id = %d limit 1",
2083 dbesc(implode(',',$newtags)),
2091 if($item['uri'] == $item['parent-uri']) {
2092 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2093 WHERE `parent-uri` = '%s' AND `uid` = %d",
2095 dbesc(datetime_convert()),
2096 dbesc($item['uri']),
2097 intval($importer['importer_uid'])
2101 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2102 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2104 dbesc(datetime_convert()),
2106 intval($importer['importer_uid'])
2108 if($item['last-child']) {
2109 // ensure that last-child is set in case the comment that had it just got wiped.
2110 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2111 dbesc(datetime_convert()),
2112 dbesc($item['parent-uri']),
2113 intval($item['uid'])
2115 // who is the last child now?
2116 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2117 ORDER BY `created` DESC LIMIT 1",
2118 dbesc($item['parent-uri']),
2119 intval($importer['importer_uid'])
2122 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2134 foreach($feed->get_items() as $item) {
2137 $item_id = $item->get_id();
2138 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2139 if(isset($rawthread[0]['attribs']['']['ref'])) {
2141 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2147 if($importer['page-flags'] == PAGE_COMMUNITY) {
2150 logger('local_delivery: possible community reply');
2153 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2155 // was the top-level post for this reply written by somebody on this site?
2156 // Specifically, the recipient?
2158 $is_a_remote_comment = false;
2160 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2161 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2162 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2163 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2164 AND `item`.`uid` = %d
2169 intval($importer['importer_uid'])
2172 $is_a_remote_comment = true;
2174 // Does this have the characteristics of a community comment?
2175 // If it's a reply to a wall post on a community page it's a
2176 // valid community comment. Also forum_mode makes it valid for sure.
2177 // If neither, it's not.
2179 if($is_a_remote_comment && $community) {
2180 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2181 $is_a_remote_comment = false;
2182 logger('local_delivery: not a community reply');
2186 if($is_a_remote_comment) {
2187 logger('local_delivery: received remote comment');
2189 // remote reply to our post. Import and then notify everybody else.
2190 $datarray = get_atom_elements($feed,$item);
2193 // TODO: make this next part work against both delivery threads of a community post
2195 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2196 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2197 // they won't know what to do so don't report an error. Just quietly die.
2201 $datarray['type'] = 'remote-comment';
2202 $datarray['wall'] = 1;
2203 $datarray['parent-uri'] = $parent_uri;
2204 $datarray['uid'] = $importer['importer_uid'];
2205 $datarray['owner-name'] = $r[0]['name'];
2206 $datarray['owner-link'] = $r[0]['url'];
2207 $datarray['owner-avatar'] = $r[0]['thumb'];
2208 $datarray['contact-id'] = $importer['id'];
2209 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2211 $datarray['type'] = 'activity';
2212 $datarray['gravity'] = GRAVITY_LIKE;
2213 $datarray['last-child'] = 0;
2214 // only one like or dislike per person
2215 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2216 intval($datarray['uid']),
2217 intval($datarray['contact-id']),
2218 dbesc($datarray['verb'])
2224 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2227 $xo = parse_xml_string($datarray['object'],false);
2228 $xt = parse_xml_string($datarray['target'],false);
2230 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2232 // extract tag, if not duplicate, and this user allows tags, add to parent item
2234 if($xo->id && $xo->content) {
2235 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2237 if(! (stristr($r[0]['tag'],$newtag))) {
2238 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2239 intval($importer['importer_uid'])
2241 if(count($i) && ! ($i[0]['blocktags'])) {
2242 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2243 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2253 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2254 // if(! stristr($datarray['tag'],$newtag)) {
2255 // if(strlen($datarray['tag']))
2256 // $datarray['tag'] .= ',';
2257 // $datarray['tag'] .= $newtag;
2262 $posted_id = item_store($datarray);
2266 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2268 intval($importer['importer_uid'])
2271 $parent = $r[0]['parent'];
2274 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2275 dbesc(datetime_convert()),
2276 intval($importer['importer_uid']),
2277 intval($r[0]['parent'])
2280 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2281 dbesc(datetime_convert()),
2282 intval($importer['importer_uid']),
2287 if($posted_id && $parent) {
2289 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2291 if((! $is_like) && (! $importer['self'])) {
2293 require_once('include/enotify.php');
2296 'type' => NOTIFY_COMMENT,
2297 'notify_flags' => $importer['notify-flags'],
2298 'language' => $importer['language'],
2299 'to_name' => $importer['username'],
2300 'to_email' => $importer['email'],
2301 'uid' => $importer['importer_uid'],
2302 'item' => $datarray,
2303 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2304 'source_name' => stripslashes($datarray['author-name']),
2305 'source_link' => $datarray['author-link'],
2306 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2307 ? $importer['thumb'] : $datarray['author-avatar']),
2308 'verb' => ACTIVITY_POST,
2310 'parent' => $parent,
2323 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2325 $item_id = $item->get_id();
2326 $datarray = get_atom_elements($feed,$item);
2328 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2330 intval($importer['importer_uid'])
2333 // Update content if 'updated' changes
2336 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2337 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2338 dbesc($datarray['title']),
2339 dbesc($datarray['body']),
2340 dbesc($datarray['tag']),
2341 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2343 intval($importer['importer_uid'])
2347 // update last-child if it changes
2349 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2350 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2351 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2352 dbesc(datetime_convert()),
2354 intval($importer['importer_uid'])
2356 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2357 intval($allow[0]['data']),
2358 dbesc(datetime_convert()),
2360 intval($importer['importer_uid'])
2366 $datarray['parent-uri'] = $parent_uri;
2367 $datarray['uid'] = $importer['importer_uid'];
2368 $datarray['contact-id'] = $importer['id'];
2369 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2370 $datarray['type'] = 'activity';
2371 $datarray['gravity'] = GRAVITY_LIKE;
2372 // only one like or dislike per person
2373 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2374 intval($datarray['uid']),
2375 intval($datarray['contact-id']),
2376 dbesc($datarray['verb'])
2383 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2385 $xo = parse_xml_string($datarray['object'],false);
2386 $xt = parse_xml_string($datarray['target'],false);
2388 if($xt->type == ACTIVITY_OBJ_NOTE) {
2389 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2391 intval($importer['importer_uid'])
2396 // extract tag, if not duplicate, add to parent item
2398 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2399 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2400 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2408 $posted_id = item_store($datarray);
2410 // find out if our user is involved in this conversation and wants to be notified.
2412 if($datarray['type'] != 'activity') {
2414 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2416 intval($importer['importer_uid'])
2419 if(count($myconv)) {
2420 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2422 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2423 if(! link_compare($datarray['author-link'],$importer_url)) {
2426 foreach($myconv as $conv) {
2428 // now if we find a match, it means we're in this conversation
2430 if(! link_compare($conv['author-link'],$importer_url))
2433 require_once('include/enotify.php');
2435 $conv_parent = $conv['parent'];
2438 'type' => NOTIFY_COMMENT,
2439 'notify_flags' => $importer['notify-flags'],
2440 'language' => $importer['language'],
2441 'to_name' => $importer['username'],
2442 'to_email' => $importer['email'],
2443 'uid' => $importer['importer_uid'],
2444 'item' => $datarray,
2445 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2446 'source_name' => stripslashes($datarray['author-name']),
2447 'source_link' => $datarray['author-link'],
2448 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2449 ? $importer['thumb'] : $datarray['author-avatar']),
2450 'verb' => ACTIVITY_POST,
2452 'parent' => $conv_parent,
2456 // only send one notification
2468 // Head post of a conversation. Have we seen it? If not, import it.
2471 $item_id = $item->get_id();
2472 $datarray = get_atom_elements($feed,$item);
2474 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2475 $ev = bbtoevent($datarray['body']);
2476 if(x($ev,'desc') && x($ev,'start')) {
2477 $ev['cid'] = $importer['id'];
2478 $ev['uid'] = $importer['uid'];
2479 $ev['uri'] = $item_id;
2480 $ev['edited'] = $datarray['edited'];
2481 $ev['private'] = $datarray['private'];
2483 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2485 intval($importer['uid'])
2488 $ev['id'] = $r[0]['id'];
2489 $xyz = event_store($ev);
2494 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2496 intval($importer['importer_uid'])
2499 // Update content if 'updated' changes
2502 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2503 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2504 dbesc($datarray['title']),
2505 dbesc($datarray['body']),
2506 dbesc($datarray['tag']),
2507 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2509 intval($importer['importer_uid'])
2513 // update last-child if it changes
2515 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2516 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2517 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2518 intval($allow[0]['data']),
2519 dbesc(datetime_convert()),
2521 intval($importer['importer_uid'])
2527 // This is my contact on another system, but it's really me.
2528 // Turn this into a wall post.
2530 if($importer['remote_self'])
2531 $datarray['wall'] = 1;
2533 $datarray['parent-uri'] = $item_id;
2534 $datarray['uid'] = $importer['importer_uid'];
2535 $datarray['contact-id'] = $importer['id'];
2537 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2538 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2539 // but otherwise there's a possible data mixup on the sender's system.
2540 // the tgroup delivery code called from item_store will correct it if it's a forum,
2541 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2542 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2543 $datarray['owner-name'] = $importer['senderName'];
2544 $datarray['owner-link'] = $importer['url'];
2545 $datarray['owner-avatar'] = $importer['thumb'];
2548 $r = item_store($datarray);
2559 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2560 $url = notags(trim($datarray['author-link']));
2561 $name = notags(trim($datarray['author-name']));
2562 $photo = notags(trim($datarray['author-avatar']));
2564 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2565 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2566 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2568 if(is_array($contact)) {
2569 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2570 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2571 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2572 intval(CONTACT_IS_FRIEND),
2573 intval($contact['id']),
2574 intval($importer['uid'])
2577 // send email notification to owner?
2581 // create contact record
2583 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2584 `blocked`, `readonly`, `pending`, `writable` )
2585 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2586 intval($importer['uid']),
2587 dbesc(datetime_convert()),
2589 dbesc(normalise_link($url)),
2593 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2594 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2596 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2597 intval($importer['uid']),
2601 $contact_record = $r[0];
2603 // create notification
2604 $hash = random_string();
2606 if(is_array($contact_record)) {
2607 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2608 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2609 intval($importer['uid']),
2610 intval($contact_record['id']),
2612 dbesc(datetime_convert())
2615 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2616 intval($importer['uid'])
2620 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2621 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2622 $email = replace_macros($email_tpl, array(
2623 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2625 '$myname' => $r[0]['username'],
2626 '$siteurl' => $a->get_baseurl(),
2627 '$sitename' => $a->config['sitename']
2629 $res = mail($r[0]['email'],
2630 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2632 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2633 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2634 . 'Content-transfer-encoding: 8bit' );
2641 function lose_follower($importer,$contact,$datarray,$item) {
2643 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2644 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2645 intval(CONTACT_IS_SHARING),
2646 intval($contact['id'])
2650 contact_remove($contact['id']);
2654 function lose_sharer($importer,$contact,$datarray,$item) {
2656 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2657 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2658 intval(CONTACT_IS_FOLLOWER),
2659 intval($contact['id'])
2663 contact_remove($contact['id']);
2668 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2670 if(is_array($importer)) {
2671 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2672 intval($importer['uid'])
2676 // Diaspora has different message-ids in feeds than they do
2677 // through the direct Diaspora protocol. If we try and use
2678 // the feed, we'll get duplicates. So don't.
2680 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2683 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2685 // Use a single verify token, even if multiple hubs
2687 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2689 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2691 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2693 if(! strlen($contact['hub-verify'])) {
2694 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2695 dbesc($verify_token),
2696 intval($contact['id'])
2700 post_url($url,$params);
2706 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2710 $name = xmlify($name);
2711 $uri = xmlify($uri);
2714 $photo = xmlify($photo);
2718 $o .= "<name>$name</name>\r\n";
2719 $o .= "<uri>$uri</uri>\r\n";
2720 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2721 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2723 call_hooks('atom_author', $o);
2725 $o .= "</$tag>\r\n";
2729 function atom_entry($item,$type,$author,$owner,$comment = false) {
2733 if(! $item['parent'])
2736 if($item['deleted'])
2737 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2740 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2741 $body = fix_private_photos($item['body'],$owner['uid']);
2743 $body = $item['body'];
2746 $o = "\r\n\r\n<entry>\r\n";
2748 if(is_array($author))
2749 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2751 $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']));
2752 if(strlen($item['owner-name']))
2753 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2755 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2756 $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";
2758 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2759 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2760 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2761 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2762 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2763 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2764 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2766 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2768 if($item['location']) {
2769 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2770 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2774 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2776 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2777 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2780 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2781 if($item['bookmark'])
2782 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2785 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2788 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2790 if($item['signed_text']) {
2791 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2792 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2795 $verb = construct_verb($item);
2796 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2797 $actobj = construct_activity_object($item);
2800 $actarg = construct_activity_target($item);
2804 $tags = item_getfeedtags($item);
2806 foreach($tags as $t) {
2807 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2811 $o .= item_getfeedattach($item);
2813 $mentioned = get_mentions($item);
2817 call_hooks('atom_entry', $o);
2819 $o .= '</entry>' . "\r\n";
2824 function fix_private_photos($s,$uid) {
2826 logger('fix_private_photos');
2828 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2829 $image = $matches[1];
2830 logger('fix_private_photos: found photo ' . $image);
2831 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2832 $i = basename($image);
2833 $i = str_replace('.jpg','',$i);
2834 $x = strpos($i,'-');
2836 $res = substr($i,$x+1);
2837 $i = substr($i,0,$x);
2838 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2844 logger('replacing photo');
2845 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2848 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2856 function item_getfeedtags($item) {
2859 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2861 for($x = 0; $x < $cnt; $x ++) {
2863 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2867 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2869 for($x = 0; $x < $cnt; $x ++) {
2871 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2877 function item_getfeedattach($item) {
2879 $arr = explode(',',$item['attach']);
2881 foreach($arr as $r) {
2883 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2885 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2886 if(intval($matches[2]))
2887 $ret .= 'length="' . intval($matches[2]) . '" ';
2888 if($matches[4] !== ' ')
2889 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2890 $ret .= ' />' . "\r\n";
2899 function item_expire($uid,$days) {
2901 if((! $uid) || (! $days))
2904 $r = q("SELECT * FROM `item`
2906 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
2916 $expire_items = get_pconfig($uid, 'expire','items');
2917 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2919 $expire_notes = get_pconfig($uid, 'expire','notes');
2920 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2922 $expire_starred = get_pconfig($uid, 'expire','starred');
2923 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2925 $expire_photos = get_pconfig($uid, 'expire','photos');
2926 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2928 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2930 foreach($r as $item) {
2932 // Only expire posts, not photos and photo comments
2934 if($expire_photos==0 && strlen($item['resource-id']))
2936 if($expire_starred==0 && intval($item['starred']))
2938 if($expire_notes==0 && $item['type']=='note')
2940 if($expire_items==0 && $item['type']!='note')
2943 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2944 dbesc(datetime_convert()),
2945 dbesc(datetime_convert()),
2951 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2952 dbesc(datetime_convert()),
2953 dbesc(datetime_convert()),
2954 dbesc($item['parent-uri']),
2955 intval($item['uid'])
2960 proc_run('php',"include/notifier.php","expire","$uid");
2965 function drop_items($items) {
2968 if((! local_user()) && (! $remote_user()))
2972 foreach($items as $item) {
2973 $owner = drop_item($item,false);
2974 if($owner && ! $uid)
2979 // multiple threads may have been deleted, send an expire notification
2982 proc_run('php',"include/notifier.php","expire","$uid");
2986 function drop_item($id,$interactive = true) {
2990 // locate item to be deleted
2992 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2999 notice( t('Item not found.') . EOL);
3000 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3005 $owner = $item['uid'];
3007 // check if logged in user is either the author or owner of this item
3009 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3013 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3014 dbesc(datetime_convert()),
3015 dbesc(datetime_convert()),
3019 // If item is a link to a photo resource, nuke all the associated photos
3020 // (visitors will not have photo resources)
3021 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3022 // generate a resource-id and therefore aren't intimately linked to the item.
3024 if(strlen($item['resource-id'])) {
3025 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3026 dbesc($item['resource-id']),
3027 intval($item['uid'])
3029 // ignore the result
3032 // If item is a link to an event, nuke the event record.
3034 if(intval($item['event-id'])) {
3035 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3036 intval($item['event-id']),
3037 intval($item['uid'])
3039 // ignore the result
3043 // If it's the parent of a comment thread, kill all the kids
3045 if($item['uri'] == $item['parent-uri']) {
3046 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3047 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3048 dbesc(datetime_convert()),
3049 dbesc(datetime_convert()),
3050 dbesc($item['parent-uri']),
3051 intval($item['uid'])
3053 // ignore the result
3056 // ensure that last-child is set in case the comment that had it just got wiped.
3057 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3058 dbesc(datetime_convert()),
3059 dbesc($item['parent-uri']),
3060 intval($item['uid'])
3062 // who is the last child now?
3063 $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",
3064 dbesc($item['parent-uri']),
3065 intval($item['uid'])
3068 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3073 $drop_id = intval($item['id']);
3075 // send the notification upstream/downstream as the case may be
3080 proc_run('php',"include/notifier.php","drop","$drop_id");
3081 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3087 notice( t('Permission denied.') . EOL);
3088 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);