3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
8 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
11 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
12 $public_feed = (($dfrn_id) ? false : true);
13 $starred = false; // not yet implemented, possible security issues
16 if($public_feed && $a->argc > 2) {
17 for($x = 2; $x < $a->argc; $x++) {
18 if($a->argv[$x] == 'converse')
20 if($a->argv[$x] == 'starred')
22 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
23 $category = $a->argv[$x+1];
31 // default permissions - anonymous user
33 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
35 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
36 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
37 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
45 $owner_id = $owner['user_uid'];
46 $owner_nick = $owner['nickname'];
48 $birthday = feed_birthday($owner_id,$owner['timezone']);
55 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
59 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60 $my_id = '1:' . $dfrn_id;
63 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
64 $my_id = '0:' . $dfrn_id;
71 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
79 $groups = init_groups_visitor($contact['id']);
82 for($x = 0; $x < count($groups); $x ++)
83 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
84 $gs = implode('|', $groups);
87 $gs = '<<>>' ; // Impossible to match
89 $sql_extra = sprintf("
90 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
91 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
92 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
93 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
95 intval($contact['id']),
96 intval($contact['id']),
107 if(! strlen($last_update))
108 $last_update = 'now -30 days';
111 $sql_extra .= file_tag_file_query('item',$category,'category');
116 $sql_extra .= " AND `contact`.`self` = 1 ";
119 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
121 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
122 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
123 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
124 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
125 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
126 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
127 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
128 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
129 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
130 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
131 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
133 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
140 // Will check further below if this actually returned results.
141 // We will provide an empty feed if that is the case.
145 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
149 $hubxml = feed_hublinks();
151 $salmon = feed_salmonlinks($owner_nick);
153 $atom .= replace_macros($feed_template, array(
154 '$version' => xmlify(FRIENDICA_VERSION),
155 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
156 '$feed_title' => xmlify($owner['name']),
157 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
159 '$salmon' => $salmon,
160 '$name' => xmlify($owner['name']),
161 '$profile_page' => xmlify($owner['url']),
162 '$photo' => xmlify($owner['photo']),
163 '$thumb' => xmlify($owner['thumb']),
164 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
165 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
166 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
167 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
168 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
171 call_hooks('atom_feed', $atom);
173 if(! count($items)) {
175 call_hooks('atom_feed_end', $atom);
177 $atom .= '</feed>' . "\r\n";
181 foreach($items as $item) {
183 // public feeds get html, our own nodes use bbcode
187 // catch any email that's in a public conversation and make sure it doesn't leak
195 $atom .= atom_entry($item,$type,null,$owner,true);
198 call_hooks('atom_feed_end', $atom);
200 $atom .= '</feed>' . "\r\n";
206 function construct_verb($item) {
208 return $item['verb'];
209 return ACTIVITY_POST;
212 function construct_activity_object($item) {
214 if($item['object']) {
215 $o = '<as:object>' . "\r\n";
216 $r = parse_xml_string($item['object'],false);
222 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
224 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
226 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
228 if(substr($r->link,0,1) === '<') {
229 // patch up some facebook "like" activity objects that got stored incorrectly
230 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
231 // we can probably remove this hack here and in the following function in a few months time.
232 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
233 $r->link = str_replace('&','&', $r->link);
234 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
238 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
241 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
242 $o .= '</as:object>' . "\r\n";
249 function construct_activity_target($item) {
251 if($item['target']) {
252 $o = '<as:target>' . "\r\n";
253 $r = parse_xml_string($item['target'],false);
257 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
259 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
261 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
263 if(substr($r->link,0,1) === '<') {
264 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
265 $r->link = str_replace('&','&', $r->link);
266 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
270 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
273 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
274 $o .= '</as:target>' . "\r\n";
284 function get_atom_elements($feed,$item) {
286 require_once('library/HTMLPurifier.auto.php');
287 require_once('include/html2bbcode.php');
289 $best_photo = array();
293 $author = $item->get_author();
295 $res['author-name'] = unxmlify($author->get_name());
296 $res['author-link'] = unxmlify($author->get_link());
299 $res['author-name'] = unxmlify($feed->get_title());
300 $res['author-link'] = unxmlify($feed->get_permalink());
302 $res['uri'] = unxmlify($item->get_id());
303 $res['title'] = unxmlify($item->get_title());
304 $res['body'] = unxmlify($item->get_content());
305 $res['plink'] = unxmlify($item->get_link(0));
308 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
312 // look for a photo. We should check media size and find the best one,
313 // but for now let's just find any author photo
315 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
317 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
318 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
319 foreach($base as $link) {
320 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
321 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
322 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
327 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
329 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
330 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
331 if($base && count($base)) {
332 foreach($base as $link) {
333 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
334 $res['author-link'] = unxmlify($link['attribs']['']['href']);
335 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
336 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
337 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
343 // No photo/profile-link on the item - look at the feed level
345 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
346 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
347 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
348 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
349 foreach($base as $link) {
350 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
351 $res['author-link'] = unxmlify($link['attribs']['']['href']);
352 if(! $res['author-avatar']) {
353 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
354 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
359 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
361 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
362 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
364 if($base && count($base)) {
365 foreach($base as $link) {
366 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
367 $res['author-link'] = unxmlify($link['attribs']['']['href']);
368 if(! (x($res,'author-avatar'))) {
369 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
370 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
377 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
378 if($apps && $apps[0]['attribs']['']['source']) {
379 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
380 if($res['app'] === 'web')
381 $res['app'] = 'OStatus';
384 // base64 encoded json structure representing Diaspora signature
386 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
388 $res['dsprsig'] = unxmlify($dsig[0]['data']);
391 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
393 $res['guid'] = unxmlify($dguid[0]['data']);
395 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
397 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
401 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
404 $have_real_body = false;
406 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
408 $have_real_body = true;
409 $res['body'] = $rawenv[0]['data'];
410 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
411 // make sure nobody is trying to sneak some html tags by us
412 $res['body'] = notags(base64url_decode($res['body']));
415 $maxlen = get_max_import_size();
416 if($maxlen && (strlen($res['body']) > $maxlen))
417 $res['body'] = substr($res['body'],0, $maxlen);
419 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
420 // the content type. Our own network only emits text normally, though it might have been converted to
421 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
422 // have to assume it is all html and needs to be purified.
424 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
425 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
426 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
429 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
431 $res['body'] = reltoabs($res['body'],$base_url);
433 $res['body'] = html2bb_video($res['body']);
435 $res['body'] = oembed_html2bbcode($res['body']);
437 $config = HTMLPurifier_Config::createDefault();
438 $config->set('Cache.DefinitionImpl', null);
440 // we shouldn't need a whitelist, because the bbcode converter
441 // will strip out any unsupported tags.
443 $purifier = new HTMLPurifier($config);
444 $res['body'] = $purifier->purify($res['body']);
446 $res['body'] = @html2bbcode($res['body']);
448 elseif(! $have_real_body) {
450 // it's not one of our messages and it has no tags
451 // so it's probably just text. We'll escape it just to be safe.
453 $res['body'] = escape_tags($res['body']);
456 // this tag is obsolete but we keep it for really old sites
458 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
459 if($allow && $allow[0]['data'] == 1)
460 $res['last-child'] = 1;
462 $res['last-child'] = 0;
464 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
465 if($private && $private[0]['data'] == 1)
470 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
471 if($extid && $extid[0]['data'])
472 $res['extid'] = $extid[0]['data'];
474 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
476 $res['location'] = unxmlify($rawlocation[0]['data']);
479 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
481 $res['created'] = unxmlify($rawcreated[0]['data']);
484 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
486 $res['edited'] = unxmlify($rawedited[0]['data']);
488 if((x($res,'edited')) && (! (x($res,'created'))))
489 $res['created'] = $res['edited'];
491 if(! $res['created'])
492 $res['created'] = $item->get_date('c');
495 $res['edited'] = $item->get_date('c');
498 // Disallow time travelling posts
500 $d1 = strtotime($res['created']);
501 $d2 = strtotime($res['edited']);
502 $d3 = strtotime('now');
505 $res['created'] = datetime_convert();
507 $res['edited'] = datetime_convert();
509 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
510 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
511 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
512 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
513 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
514 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
515 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
516 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
517 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
519 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
520 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
522 foreach($base as $link) {
523 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
524 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
525 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
530 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
532 $res['coord'] = unxmlify($rawgeo[0]['data']);
535 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
537 // select between supported verbs
540 $res['verb'] = unxmlify($rawverb[0]['data']);
543 // translate OStatus unfollow to activity streams if it happened to get selected
545 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
546 $res['verb'] = ACTIVITY_UNFOLLOW;
548 $cats = $item->get_categories();
551 foreach($cats as $cat) {
552 $term = $cat->get_term();
554 $term = $cat->get_label();
555 $scheme = $cat->get_scheme();
556 if($scheme && $term && stristr($scheme,'X-DFRN:'))
557 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
559 $tag_arr[] = notags(trim($term));
561 $res['tag'] = implode(',', $tag_arr);
564 $attach = $item->get_enclosures();
567 foreach($attach as $att) {
568 $len = intval($att->get_length());
569 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
570 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
571 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
572 if(strpos($type,';'))
573 $type = substr($type,0,strpos($type,';'));
574 if((! $link) || (strpos($link,'http') !== 0))
580 $type = 'application/octet-stream';
582 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
584 $res['attach'] = implode(',', $att_arr);
587 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
590 $res['object'] = '<object>' . "\n";
591 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
592 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
593 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
595 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
596 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
597 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
598 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
599 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
600 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
601 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
602 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
604 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
605 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
606 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
607 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
609 $body = html2bb_video($body);
611 $config = HTMLPurifier_Config::createDefault();
612 $config->set('Cache.DefinitionImpl', null);
614 $purifier = new HTMLPurifier($config);
615 $body = $purifier->purify($body);
616 $body = html2bbcode($body);
619 $res['object'] .= '<content>' . $body . '</content>' . "\n";
622 $res['object'] .= '</object>' . "\n";
625 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
628 $res['target'] = '<target>' . "\n";
629 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
630 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
632 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
633 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
635 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
636 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
637 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
638 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
639 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
640 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
642 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
643 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
644 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
645 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
647 $body = html2bb_video($body);
649 $config = HTMLPurifier_Config::createDefault();
650 $config->set('Cache.DefinitionImpl', null);
652 $purifier = new HTMLPurifier($config);
653 $body = $purifier->purify($body);
654 $body = html2bbcode($body);
657 $res['target'] .= '<content>' . $body . '</content>' . "\n";
660 $res['target'] .= '</target>' . "\n";
663 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
665 call_hooks('parse_atom', $arr);
670 function encode_rel_links($links) {
672 if(! ((is_array($links)) && (count($links))))
674 foreach($links as $link) {
676 if($link['attribs']['']['rel'])
677 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
678 if($link['attribs']['']['type'])
679 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
680 if($link['attribs']['']['href'])
681 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
682 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
683 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
684 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
685 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
691 function item_store($arr,$force_parent = false) {
693 // If a Diaspora signature structure was passed in, pull it out of the
694 // item array and set it aside for later storage.
697 if(x($arr,'dsprsig')) {
698 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
699 unset($arr['dsprsig']);
702 if(x($arr, 'gravity'))
703 $arr['gravity'] = intval($arr['gravity']);
704 elseif($arr['parent-uri'] === $arr['uri'])
706 elseif(activity_match($arr['verb'],ACTIVITY_POST))
709 $arr['gravity'] = 6; // extensible catchall
712 $arr['type'] = 'remote';
714 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
716 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
717 $arr['body'] = strip_tags($arr['body']);
720 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
721 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
722 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
723 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
724 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
725 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
726 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
727 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
728 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
729 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
730 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
731 $arr['commented'] = datetime_convert();
732 $arr['received'] = datetime_convert();
733 $arr['changed'] = datetime_convert();
734 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
735 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
736 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
737 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
738 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
740 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
741 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
742 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
743 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
744 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
745 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
746 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
747 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
748 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
749 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
750 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
751 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
752 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
753 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
754 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
755 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
756 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
757 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
758 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
760 if($arr['parent-uri'] === $arr['uri']) {
763 $allow_cid = $arr['allow_cid'];
764 $allow_gid = $arr['allow_gid'];
765 $deny_cid = $arr['deny_cid'];
766 $deny_gid = $arr['deny_gid'];
770 // find the parent and snarf the item id and ACL's
771 // and anything else we need to inherit
773 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
774 dbesc($arr['parent-uri']),
780 // is the new message multi-level threaded?
781 // even though we don't support it now, preserve the info
782 // and re-attach to the conversation parent.
784 if($r[0]['uri'] != $r[0]['parent-uri']) {
785 $arr['thr-parent'] = $arr['parent-uri'];
786 $arr['parent-uri'] = $r[0]['parent-uri'];
787 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
788 ORDER BY `id` ASC LIMIT 1",
789 dbesc($r[0]['parent-uri']),
790 dbesc($r[0]['parent-uri']),
797 $parent_id = $r[0]['id'];
798 $parent_deleted = $r[0]['deleted'];
799 $allow_cid = $r[0]['allow_cid'];
800 $allow_gid = $r[0]['allow_gid'];
801 $deny_cid = $r[0]['deny_cid'];
802 $deny_gid = $r[0]['deny_gid'];
803 $arr['wall'] = $r[0]['wall'];
807 // Allow one to see reply tweets from status.net even when
808 // we don't have or can't see the original post.
811 logger('item_store: $force_parent=true, reply converted to top-level post.');
813 $arr['thr-parent'] = $arr['parent-uri'];
814 $arr['parent-uri'] = $arr['uri'];
818 logger('item_store: item parent was not found - ignoring item');
826 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
830 if($r && count($r)) {
831 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
835 call_hooks('post_remote',$arr);
837 if(x($arr,'cancel')) {
838 logger('item_store: post cancelled by plugin.');
844 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
846 $r = dbq("INSERT INTO `item` (`"
847 . implode("`, `", array_keys($arr))
849 . implode("', '", array_values($arr))
852 // find the item we just created
854 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
855 $arr['uri'], // already dbesc'd
860 $current_post = $r[0]['id'];
861 logger('item_store: created item ' . $current_post);
864 logger('item_store: could not locate created item');
868 logger('item_store: duplicated post occurred. Removing duplicates.');
869 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
872 intval($current_post)
876 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
877 $parent_id = $current_post;
879 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
882 $private = $arr['private'];
884 // Set parent id - and also make sure to inherit the parent's ACL's.
886 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
887 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
894 intval($parent_deleted),
895 intval($current_post)
898 // update the commented timestamp on the parent
900 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
901 dbesc(datetime_convert()),
902 dbesc(datetime_convert()),
907 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
908 intval($current_post),
909 dbesc($dsprsig->signed_text),
910 dbesc($dsprsig->signature),
911 dbesc($dsprsig->signer)
917 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
920 if($arr['last-child']) {
921 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
924 intval($current_post)
928 tag_deliver($arr['uid'],$current_post);
930 return $current_post;
933 function get_item_contact($item,$contacts) {
934 if(! count($contacts) || (! is_array($item)))
936 foreach($contacts as $contact) {
937 if($contact['id'] == $item['contact-id']) {
946 function tag_deliver($uid,$item_id) {
948 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
954 $u = q("select uid, nickname, language, username, email, `page-flags`, `notify-flags` from user where uid = %d limit 1",
960 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
962 $i = q("select * from item where id = %d and uid = %d limit 1",
971 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
973 // Diaspora uses their own hardwired link URL in @-tags
974 // instead of the one we supply with webfinger
976 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
978 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
980 foreach($matches as $mtch) {
981 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
983 logger('tag_deliver: mention found: ' . $mtch[2]);
991 // send a notification
993 require_once('include/enotify.php');
995 'type' => NOTIFY_TAGSELF,
996 'notify_flags' => $u[0]['notify-flags'],
997 'language' => $u[0]['language'],
998 'to_name' => $u[0]['username'],
999 'to_email' => $u[0]['email'],
1000 'uid' => $u[0]['uid'],
1002 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1003 'source_name' => $item['author-name'],
1004 'source_link' => $item['author-link'],
1005 'source_photo' => $item['author-avatar'],
1006 'verb' => ACTIVITY_TAG,
1010 if(! $community_page)
1013 // tgroup delivery - setup a second delivery chain
1014 // prevent delivery looping - only proceed
1015 // if the message originated elsewhere and is a top-level post
1017 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1020 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1023 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1024 intval($u[0]['uid'])
1029 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",
1030 dbesc($c[0]['name']),
1031 dbesc($c[0]['url']),
1032 dbesc($c[0]['thumb']),
1036 proc_run('php','include/notifier.php','tgroup',$item_id);
1045 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1049 // if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
1052 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1054 if($contact['duplex'] && $contact['dfrn-id'])
1055 $idtosend = '0:' . $orig_id;
1056 if($contact['duplex'] && $contact['issued-id'])
1057 $idtosend = '1:' . $orig_id;
1059 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1061 $rino_enable = get_config('system','rino_encrypt');
1066 $ssl_val = intval(get_config('system','ssl_policy'));
1070 case SSL_POLICY_FULL:
1071 $ssl_policy = 'full';
1073 case SSL_POLICY_SELFSIGN:
1074 $ssl_policy = 'self';
1076 case SSL_POLICY_NONE:
1078 $ssl_policy = 'none';
1082 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1084 logger('dfrn_deliver: ' . $url);
1086 $xml = fetch_url($url);
1088 $curl_stat = $a->get_curl_code();
1090 return(-1); // timed out
1092 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1097 if(strpos($xml,'<?xml') === false) {
1098 logger('dfrn_deliver: no valid XML returned');
1099 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1103 $res = parse_xml_string($xml);
1105 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1106 return (($res->status) ? $res->status : 3);
1108 $postvars = array();
1109 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1110 $challenge = hex2bin((string) $res->challenge);
1111 $perm = (($res->perm) ? $res->perm : null);
1112 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1113 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1114 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1116 $final_dfrn_id = '';
1119 if((($perm == 'rw') && (! intval($contact['writable'])))
1120 || (($perm == 'r') && (intval($contact['writable'])))) {
1121 q("update contact set writable = %d where id = %d limit 1",
1122 intval(($perm == 'rw') ? 1 : 0),
1123 intval($contact['id'])
1125 $contact['writable'] = (string) 1 - intval($contact['writable']);
1129 if(($contact['duplex'] && strlen($contact['pubkey']))
1130 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1131 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1132 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1133 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1136 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1137 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1140 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1142 if(strpos($final_dfrn_id,':') == 1)
1143 $final_dfrn_id = substr($final_dfrn_id,2);
1145 if($final_dfrn_id != $orig_id) {
1146 logger('dfrn_deliver: wrong dfrn_id.');
1147 // did not decode properly - cannot trust this site
1151 $postvars['dfrn_id'] = $idtosend;
1152 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1154 $postvars['dissolve'] = '1';
1157 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1158 $postvars['data'] = $atom;
1159 $postvars['perm'] = 'rw';
1162 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1163 $postvars['perm'] = 'r';
1166 $postvars['ssl_policy'] = $ssl_policy;
1169 $postvars['page'] = '1';
1171 if($rino && $rino_allowed && (! $dissolve)) {
1172 $key = substr(random_string(),0,16);
1173 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1174 $postvars['data'] = $data;
1175 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1178 if($dfrn_version >= 2.1) {
1179 if(($contact['duplex'] && strlen($contact['pubkey']))
1180 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1181 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1183 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1186 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1190 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1191 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1194 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1198 logger('md5 rawkey ' . md5($postvars['key']));
1200 $postvars['key'] = bin2hex($postvars['key']);
1203 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1205 $xml = post_url($contact['notify'],$postvars);
1207 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1209 $curl_stat = $a->get_curl_code();
1210 if((! $curl_stat) || (! strlen($xml)))
1211 return(-1); // timed out
1213 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1216 if(strpos($xml,'<?xml') === false) {
1217 logger('dfrn_deliver: phase 2: no valid XML returned');
1218 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1222 $res = parse_xml_string($xml);
1224 return $res->status;
1230 * consume_feed - process atom feed and update anything/everything we might need to update
1232 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1234 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1235 * It is this person's stuff that is going to be updated.
1236 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1237 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1238 * have a contact record.
1239 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1240 * might not) try and subscribe to it.
1241 * $datedir sorts in reverse order
1242 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1243 * imported prior to its children being seen in the stream unless we are certain
1244 * of how the feed is arranged/ordered.
1245 * With $pass = 1, we only pull parent items out of the stream.
1246 * With $pass = 2, we only pull children (comments/likes).
1248 * So running this twice, first with pass 1 and then with pass 2 will do the right
1249 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1250 * model where comments can have sub-threads. That would require some massive sorting
1251 * to get all the feed items into a mostly linear ordering, and might still require
1255 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1257 require_once('library/simplepie/simplepie.inc');
1259 if(! strlen($xml)) {
1260 logger('consume_feed: empty input');
1264 $feed = new SimplePie();
1265 $feed->set_raw_data($xml);
1267 $feed->enable_order_by_date(true);
1269 $feed->enable_order_by_date(false);
1273 logger('consume_feed: Error parsing XML: ' . $feed->error());
1275 $permalink = $feed->get_permalink();
1277 // Check at the feed level for updated contact name and/or photo
1281 $photo_timestamp = '';
1285 $hubs = $feed->get_links('hub');
1288 $hub = implode(',', $hubs);
1290 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1292 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1294 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1295 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1296 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1297 $new_name = $elems['name'][0]['data'];
1299 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1300 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1301 $photo_url = $elems['link'][0]['attribs']['']['href'];
1304 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1305 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1309 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1310 logger('consume_feed: Updating photo for ' . $contact['name']);
1311 require_once("Photo.php");
1312 $photo_failure = false;
1313 $have_photo = false;
1315 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1316 intval($contact['id']),
1317 intval($contact['uid'])
1320 $resource_id = $r[0]['resource-id'];
1324 $resource_id = photo_new_resource();
1327 $img_str = fetch_url($photo_url,true);
1328 $img = new Photo($img_str);
1329 if($img->is_valid()) {
1331 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1332 dbesc($resource_id),
1333 intval($contact['id']),
1334 intval($contact['uid'])
1338 $img->scaleImageSquare(175);
1340 $hash = $resource_id;
1341 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1343 $img->scaleImage(80);
1344 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1346 $img->scaleImage(48);
1347 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1351 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1352 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1353 dbesc(datetime_convert()),
1354 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1355 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1356 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1357 intval($contact['uid']),
1358 intval($contact['id'])
1363 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1364 $r = q("select * from contact where uid = %d and id = %d limit 1",
1365 intval($contact['uid']),
1366 intval($contact['id'])
1369 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1370 dbesc(notags(trim($new_name))),
1371 dbesc(datetime_convert()),
1372 intval($contact['uid']),
1373 intval($contact['id'])
1376 // do our best to update the name on content items
1379 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1380 dbesc(notags(trim($new_name))),
1381 dbesc($r[0]['name']),
1382 dbesc($r[0]['url']),
1383 intval($contact['uid'])
1388 if(strlen($birthday)) {
1389 if(substr($birthday,0,4) != $contact['bdyear']) {
1390 logger('consume_feed: updating birthday: ' . $birthday);
1394 * Add new birthday event for this person
1396 * $bdtext is just a readable placeholder in case the event is shared
1397 * with others. We will replace it during presentation to our $importer
1398 * to contain a sparkle link and perhaps a photo.
1402 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1405 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1406 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1407 intval($contact['uid']),
1408 intval($contact['id']),
1409 dbesc(datetime_convert()),
1410 dbesc(datetime_convert()),
1411 dbesc(datetime_convert('UTC','UTC', $birthday)),
1412 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1420 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1421 dbesc(substr($birthday,0,4)),
1422 intval($contact['uid']),
1423 intval($contact['id'])
1426 // This function is called twice without reloading the contact
1427 // Make sure we only create one event. This is why &$contact
1428 // is a reference var in this function
1430 $contact['bdyear'] = substr($birthday,0,4);
1435 $community_page = 0;
1436 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1438 $community_page = intval($rawtags[0]['data']);
1440 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1441 q("update contact set forum = %d where id = %d limit 1",
1442 intval($community_page),
1443 intval($contact['id'])
1445 $contact['forum'] = (string) $community_page;
1449 // process any deleted entries
1451 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1452 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1453 foreach($del_entries as $dentry) {
1455 if(isset($dentry['attribs']['']['ref'])) {
1456 $uri = $dentry['attribs']['']['ref'];
1458 if(isset($dentry['attribs']['']['when'])) {
1459 $when = $dentry['attribs']['']['when'];
1460 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1463 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1465 if($deleted && is_array($contact)) {
1466 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1467 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1469 intval($importer['uid']),
1470 intval($contact['id'])
1475 if(! $item['deleted'])
1476 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1478 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1479 $xo = parse_xml_string($item['object'],false);
1480 $xt = parse_xml_string($item['target'],false);
1481 if($xt->type === ACTIVITY_OBJ_NOTE) {
1482 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1484 intval($importer['importer_uid'])
1488 // For tags, the owner cannot remove the tag on the author's copy of the post.
1490 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1491 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1492 $author_copy = (($item['origin']) ? true : false);
1494 if($owner_remove && $author_copy)
1496 if($author_remove || $owner_remove) {
1497 $tags = explode(',',$i[0]['tag']);
1500 foreach($tags as $tag)
1501 if(trim($tag) !== trim($xo->body))
1502 $newtags[] = trim($tag);
1504 q("update item set tag = '%s' where id = %d limit 1",
1505 dbesc(implode(',',$newtags)),
1513 if($item['uri'] == $item['parent-uri']) {
1514 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1515 `body` = '', `title` = ''
1516 WHERE `parent-uri` = '%s' AND `uid` = %d",
1518 dbesc(datetime_convert()),
1519 dbesc($item['uri']),
1520 intval($importer['uid'])
1524 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1525 `body` = '', `title` = ''
1526 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1528 dbesc(datetime_convert()),
1530 intval($importer['uid'])
1532 if($item['last-child']) {
1533 // ensure that last-child is set in case the comment that had it just got wiped.
1534 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1535 dbesc(datetime_convert()),
1536 dbesc($item['parent-uri']),
1537 intval($item['uid'])
1539 // who is the last child now?
1540 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1541 ORDER BY `created` DESC LIMIT 1",
1542 dbesc($item['parent-uri']),
1543 intval($importer['uid'])
1546 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1557 // Now process the feed
1559 if($feed->get_item_quantity()) {
1561 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1563 // in inverse date order
1565 $items = array_reverse($feed->get_items());
1567 $items = $feed->get_items();
1570 foreach($items as $item) {
1573 $item_id = $item->get_id();
1574 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1575 if(isset($rawthread[0]['attribs']['']['ref'])) {
1577 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1580 if(($is_reply) && is_array($contact)) {
1585 // Have we seen it? If not, import it.
1587 $item_id = $item->get_id();
1588 $datarray = get_atom_elements($feed,$item);
1591 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1592 $datarray['author-name'] = $contact['name'];
1593 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1594 $datarray['author-link'] = $contact['url'];
1595 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1596 $datarray['author-avatar'] = $contact['thumb'];
1598 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1599 logger('consume_feed: no author information! ' . print_r($datarray,true));
1603 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1605 intval($importer['uid'])
1608 // Update content if 'updated' changes
1611 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1612 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1613 dbesc($datarray['title']),
1614 dbesc($datarray['body']),
1615 dbesc($datarray['tag']),
1616 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1618 intval($importer['uid'])
1622 // update last-child if it changes
1624 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1625 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1626 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1627 dbesc(datetime_convert()),
1629 intval($importer['uid'])
1631 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1632 intval($allow[0]['data']),
1633 dbesc(datetime_convert()),
1635 intval($importer['uid'])
1641 $force_parent = false;
1642 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1643 if($contact['network'] === NETWORK_OSTATUS)
1644 $force_parent = true;
1645 if(strlen($datarray['title']))
1646 unset($datarray['title']);
1647 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1648 dbesc(datetime_convert()),
1650 intval($importer['uid'])
1652 $datarray['last-child'] = 1;
1655 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1656 // one way feed - no remote comment ability
1657 $datarray['last-child'] = 0;
1659 $datarray['parent-uri'] = $parent_uri;
1660 $datarray['uid'] = $importer['uid'];
1661 $datarray['contact-id'] = $contact['id'];
1662 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1663 $datarray['type'] = 'activity';
1664 $datarray['gravity'] = GRAVITY_LIKE;
1665 // only one like or dislike per person
1666 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1667 intval($datarray['uid']),
1668 intval($datarray['contact-id']),
1669 dbesc($datarray['verb'])
1675 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1676 $xo = parse_xml_string($datarray['object'],false);
1677 $xt = parse_xml_string($datarray['target'],false);
1679 if($xt->type == ACTIVITY_OBJ_NOTE) {
1680 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1682 intval($importer['importer_uid'])
1687 // extract tag, if not duplicate, add to parent item
1688 if($xo->id && $xo->content) {
1689 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1690 if(! (stristr($r[0]['tag'],$newtag))) {
1691 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1692 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1700 $r = item_store($datarray,$force_parent);
1706 // Head post of a conversation. Have we seen it? If not, import it.
1708 $item_id = $item->get_id();
1710 $datarray = get_atom_elements($feed,$item);
1712 if(is_array($contact)) {
1713 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1714 $datarray['author-name'] = $contact['name'];
1715 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1716 $datarray['author-link'] = $contact['url'];
1717 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1718 $datarray['author-avatar'] = $contact['thumb'];
1721 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1722 logger('consume_feed: no author information! ' . print_r($datarray,true));
1726 // special handling for events
1728 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1729 $ev = bbtoevent($datarray['body']);
1730 if(x($ev,'desc') && x($ev,'start')) {
1731 $ev['uid'] = $importer['uid'];
1732 $ev['uri'] = $item_id;
1733 $ev['edited'] = $datarray['edited'];
1734 $ev['private'] = $datarray['private'];
1736 if(is_array($contact))
1737 $ev['cid'] = $contact['id'];
1738 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1740 intval($importer['uid'])
1743 $ev['id'] = $r[0]['id'];
1744 $xyz = event_store($ev);
1749 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1751 intval($importer['uid'])
1754 // Update content if 'updated' changes
1757 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1758 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1759 dbesc($datarray['title']),
1760 dbesc($datarray['body']),
1761 dbesc($datarray['tag']),
1762 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1764 intval($importer['uid'])
1768 // update last-child if it changes
1770 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1771 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1772 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1773 intval($allow[0]['data']),
1774 dbesc(datetime_convert()),
1776 intval($importer['uid'])
1782 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1783 logger('consume-feed: New follower');
1784 new_follower($importer,$contact,$datarray,$item);
1787 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1788 lose_follower($importer,$contact,$datarray,$item);
1792 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1793 logger('consume-feed: New friend request');
1794 new_follower($importer,$contact,$datarray,$item,true);
1797 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1798 lose_sharer($importer,$contact,$datarray,$item);
1803 if(! is_array($contact))
1806 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1807 if(strlen($datarray['title']))
1808 unset($datarray['title']);
1809 $datarray['last-child'] = 1;
1812 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1813 // one way feed - no remote comment ability
1814 $datarray['last-child'] = 0;
1817 // This is my contact on another system, but it's really me.
1818 // Turn this into a wall post.
1820 if($contact['remote_self'])
1821 $datarray['wall'] = 1;
1823 $datarray['parent-uri'] = $item_id;
1824 $datarray['uid'] = $importer['uid'];
1825 $datarray['contact-id'] = $contact['id'];
1827 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1828 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1829 // but otherwise there's a possible data mixup on the sender's system.
1830 // the tgroup delivery code called from item_store will correct it if it's a forum,
1831 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1832 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1833 $datarray['owner-name'] = $contact['name'];
1834 $datarray['owner-link'] = $contact['url'];
1835 $datarray['owner-avatar'] = $contact['thumb'];
1838 $r = item_store($datarray);
1846 function local_delivery($importer,$data) {
1850 if($importer['readonly']) {
1851 // We aren't receiving stuff from this person. But we will quietly ignore them
1852 // rather than a blatant "go away" message.
1853 logger('local_delivery: ignoring');
1858 // Consume notification feed. This may differ from consuming a public feed in several ways
1859 // - might contain email or friend suggestions
1860 // - might contain remote followup to our message
1861 // - in which case we need to accept it and then notify other conversants
1862 // - we may need to send various email notifications
1864 $feed = new SimplePie();
1865 $feed->set_raw_data($data);
1866 $feed->enable_order_by_date(false);
1870 // Currently unsupported - needs a lot of work
1871 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1872 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1873 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1875 $newloc['uid'] = $importer['importer_uid'];
1876 $newloc['cid'] = $importer['id'];
1877 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1878 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1879 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1880 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1881 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1882 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1883 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1884 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1885 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1886 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1889 // merge with current record, current contents have priority
1890 // update record, set url-updated
1891 // update profile photos
1897 // handle friend suggestion notification
1899 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1900 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1901 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1903 $fsugg['uid'] = $importer['importer_uid'];
1904 $fsugg['cid'] = $importer['id'];
1905 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1906 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1907 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1908 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1909 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1911 // Does our member already have a friend matching this description?
1913 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1914 dbesc($fsugg['name']),
1915 dbesc(normalise_link($fsugg['url'])),
1916 intval($fsugg['uid'])
1921 // Do we already have an fcontact record for this person?
1924 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1925 dbesc($fsugg['url']),
1926 dbesc($fsugg['name']),
1927 dbesc($fsugg['request'])
1932 // OK, we do. Do we already have an introduction for this person ?
1933 $r = q("select id from intro where uid = %d and fid = %d limit 1",
1934 intval($fsugg['uid']),
1941 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1942 dbesc($fsugg['name']),
1943 dbesc($fsugg['url']),
1944 dbesc($fsugg['photo']),
1945 dbesc($fsugg['request'])
1947 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1948 dbesc($fsugg['url']),
1949 dbesc($fsugg['name']),
1950 dbesc($fsugg['request'])
1955 // database record did not get created. Quietly give up.
1960 $hash = random_string();
1962 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1963 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1964 intval($fsugg['uid']),
1966 intval($fsugg['cid']),
1967 dbesc($fsugg['body']),
1969 dbesc(datetime_convert()),
1974 'type' => NOTIFY_SUGGEST,
1975 'notify_flags' => $importer['notify-flags'],
1976 'language' => $importer['language'],
1977 'to_name' => $importer['username'],
1978 'to_email' => $importer['email'],
1979 'uid' => $importer['importer_uid'],
1981 'link' => $a->get_baseurl() . '/notifications/intros',
1982 'source_name' => $importer['name'],
1983 'source_link' => $importer['url'],
1984 'source_photo' => $importer['photo'],
1985 'verb' => ACTIVITY_REQ_FRIEND,
1994 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1995 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1997 logger('local_delivery: private message received');
2000 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2003 $msg['uid'] = $importer['importer_uid'];
2004 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2005 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2006 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2007 $msg['contact-id'] = $importer['id'];
2008 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2009 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2011 $msg['replied'] = 0;
2012 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2013 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2014 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2018 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2019 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2021 // send notifications.
2023 require_once('include/enotify.php');
2025 $notif_params = array(
2026 'type' => NOTIFY_MAIL,
2027 'notify_flags' => $importer['notify-flags'],
2028 'language' => $importer['language'],
2029 'to_name' => $importer['username'],
2030 'to_email' => $importer['email'],
2031 'uid' => $importer['importer_uid'],
2033 'source_name' => $msg['from-name'],
2034 'source_link' => $importer['url'],
2035 'source_photo' => $importer['thumb'],
2036 'verb' => ACTIVITY_POST,
2040 notification($notif_params);
2046 $community_page = 0;
2047 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2049 $community_page = intval($rawtags[0]['data']);
2051 if(intval($importer['forum']) != $community_page) {
2052 q("update contact set forum = %d where id = %d limit 1",
2053 intval($community_page),
2054 intval($importer['id'])
2056 $importer['forum'] = (string) $community_page;
2059 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2061 // process any deleted entries
2063 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2064 if(is_array($del_entries) && count($del_entries)) {
2065 foreach($del_entries as $dentry) {
2067 if(isset($dentry['attribs']['']['ref'])) {
2068 $uri = $dentry['attribs']['']['ref'];
2070 if(isset($dentry['attribs']['']['when'])) {
2071 $when = $dentry['attribs']['']['when'];
2072 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2075 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2079 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2080 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2082 intval($importer['importer_uid']),
2083 intval($importer['id'])
2089 if($item['deleted'])
2092 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2094 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
2095 $xo = parse_xml_string($item['object'],false);
2096 $xt = parse_xml_string($item['target'],false);
2098 if($xt->type === ACTIVITY_OBJ_NOTE) {
2099 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2101 intval($importer['importer_uid'])
2105 // For tags, the owner cannot remove the tag on the author's copy of the post.
2107 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2108 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2109 $author_copy = (($item['origin']) ? true : false);
2111 if($owner_remove && $author_copy)
2113 if($author_remove || $owner_remove) {
2114 $tags = explode(',',$i[0]['tag']);
2117 foreach($tags as $tag)
2118 if(trim($tag) !== trim($xo->body))
2119 $newtags[] = trim($tag);
2121 q("update item set tag = '%s' where id = %d limit 1",
2122 dbesc(implode(',',$newtags)),
2130 if($item['uri'] == $item['parent-uri']) {
2131 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2132 WHERE `parent-uri` = '%s' AND `uid` = %d",
2134 dbesc(datetime_convert()),
2135 dbesc($item['uri']),
2136 intval($importer['importer_uid'])
2140 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2141 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2143 dbesc(datetime_convert()),
2145 intval($importer['importer_uid'])
2147 if($item['last-child']) {
2148 // ensure that last-child is set in case the comment that had it just got wiped.
2149 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2150 dbesc(datetime_convert()),
2151 dbesc($item['parent-uri']),
2152 intval($item['uid'])
2154 // who is the last child now?
2155 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2156 ORDER BY `created` DESC LIMIT 1",
2157 dbesc($item['parent-uri']),
2158 intval($importer['importer_uid'])
2161 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2173 foreach($feed->get_items() as $item) {
2176 $item_id = $item->get_id();
2177 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2178 if(isset($rawthread[0]['attribs']['']['ref'])) {
2180 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2186 if($importer['page-flags'] == PAGE_COMMUNITY) {
2189 logger('local_delivery: possible community reply');
2192 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2194 // was the top-level post for this reply written by somebody on this site?
2195 // Specifically, the recipient?
2197 $is_a_remote_comment = false;
2199 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2200 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2201 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2202 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2203 AND `item`.`uid` = %d
2208 intval($importer['importer_uid'])
2211 $is_a_remote_comment = true;
2213 // Does this have the characteristics of a community comment?
2214 // If it's a reply to a wall post on a community page it's a
2215 // valid community comment. Also forum_mode makes it valid for sure.
2216 // If neither, it's not.
2218 if($is_a_remote_comment && $community) {
2219 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2220 $is_a_remote_comment = false;
2221 logger('local_delivery: not a community reply');
2225 if($is_a_remote_comment) {
2226 logger('local_delivery: received remote comment');
2228 // remote reply to our post. Import and then notify everybody else.
2229 $datarray = get_atom_elements($feed,$item);
2232 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2234 intval($importer['importer_uid'])
2237 // Update content if 'updated' changes
2240 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2241 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2242 dbesc($datarray['title']),
2243 dbesc($datarray['body']),
2244 dbesc($datarray['tag']),
2245 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2247 intval($importer['importer_uid'])
2250 proc_run('php',"include/notifier.php","comment-import",$r[0]['id']);
2256 // TODO: make this next part work against both delivery threads of a community post
2258 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2259 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2260 // they won't know what to do so don't report an error. Just quietly die.
2264 $datarray['type'] = 'remote-comment';
2265 $datarray['wall'] = 1;
2266 $datarray['parent-uri'] = $parent_uri;
2267 $datarray['uid'] = $importer['importer_uid'];
2268 $datarray['owner-name'] = $r[0]['name'];
2269 $datarray['owner-link'] = $r[0]['url'];
2270 $datarray['owner-avatar'] = $r[0]['thumb'];
2271 $datarray['contact-id'] = $importer['id'];
2272 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2274 $datarray['type'] = 'activity';
2275 $datarray['gravity'] = GRAVITY_LIKE;
2276 $datarray['last-child'] = 0;
2277 // only one like or dislike per person
2278 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2279 intval($datarray['uid']),
2280 intval($datarray['contact-id']),
2281 dbesc($datarray['verb'])
2287 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2290 $xo = parse_xml_string($datarray['object'],false);
2291 $xt = parse_xml_string($datarray['target'],false);
2293 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2295 // extract tag, if not duplicate, and this user allows tags, add to parent item
2297 if($xo->id && $xo->content) {
2298 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2300 if(! (stristr($r[0]['tag'],$newtag))) {
2301 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2302 intval($importer['importer_uid'])
2304 if(count($i) && ! ($i[0]['blocktags'])) {
2305 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2306 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2316 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2317 // if(! stristr($datarray['tag'],$newtag)) {
2318 // if(strlen($datarray['tag']))
2319 // $datarray['tag'] .= ',';
2320 // $datarray['tag'] .= $newtag;
2325 $posted_id = item_store($datarray);
2329 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2331 intval($importer['importer_uid'])
2334 $parent = $r[0]['parent'];
2337 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2338 dbesc(datetime_convert()),
2339 intval($importer['importer_uid']),
2340 intval($r[0]['parent'])
2343 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2344 dbesc(datetime_convert()),
2345 intval($importer['importer_uid']),
2350 if($posted_id && $parent) {
2352 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2354 if((! $is_like) && (! $importer['self'])) {
2356 require_once('include/enotify.php');
2359 'type' => NOTIFY_COMMENT,
2360 'notify_flags' => $importer['notify-flags'],
2361 'language' => $importer['language'],
2362 'to_name' => $importer['username'],
2363 'to_email' => $importer['email'],
2364 'uid' => $importer['importer_uid'],
2365 'item' => $datarray,
2366 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2367 'source_name' => stripslashes($datarray['author-name']),
2368 'source_link' => $datarray['author-link'],
2369 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2370 ? $importer['thumb'] : $datarray['author-avatar']),
2371 'verb' => ACTIVITY_POST,
2373 'parent' => $parent,
2386 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2388 $item_id = $item->get_id();
2389 $datarray = get_atom_elements($feed,$item);
2391 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2393 intval($importer['importer_uid'])
2396 // Update content if 'updated' changes
2399 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2400 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2401 dbesc($datarray['title']),
2402 dbesc($datarray['body']),
2403 dbesc($datarray['tag']),
2404 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2406 intval($importer['importer_uid'])
2410 // update last-child if it changes
2412 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2413 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2414 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2415 dbesc(datetime_convert()),
2417 intval($importer['importer_uid'])
2419 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2420 intval($allow[0]['data']),
2421 dbesc(datetime_convert()),
2423 intval($importer['importer_uid'])
2429 $datarray['parent-uri'] = $parent_uri;
2430 $datarray['uid'] = $importer['importer_uid'];
2431 $datarray['contact-id'] = $importer['id'];
2432 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2433 $datarray['type'] = 'activity';
2434 $datarray['gravity'] = GRAVITY_LIKE;
2435 // only one like or dislike per person
2436 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2437 intval($datarray['uid']),
2438 intval($datarray['contact-id']),
2439 dbesc($datarray['verb'])
2446 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2448 $xo = parse_xml_string($datarray['object'],false);
2449 $xt = parse_xml_string($datarray['target'],false);
2451 if($xt->type == ACTIVITY_OBJ_NOTE) {
2452 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2454 intval($importer['importer_uid'])
2459 // extract tag, if not duplicate, add to parent item
2461 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2462 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2463 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2471 $posted_id = item_store($datarray);
2473 // find out if our user is involved in this conversation and wants to be notified.
2475 if($datarray['type'] != 'activity') {
2477 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2479 intval($importer['importer_uid'])
2482 if(count($myconv)) {
2483 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2485 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2486 if(! link_compare($datarray['author-link'],$importer_url)) {
2489 foreach($myconv as $conv) {
2491 // now if we find a match, it means we're in this conversation
2493 if(! link_compare($conv['author-link'],$importer_url))
2496 require_once('include/enotify.php');
2498 $conv_parent = $conv['parent'];
2501 'type' => NOTIFY_COMMENT,
2502 'notify_flags' => $importer['notify-flags'],
2503 'language' => $importer['language'],
2504 'to_name' => $importer['username'],
2505 'to_email' => $importer['email'],
2506 'uid' => $importer['importer_uid'],
2507 'item' => $datarray,
2508 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2509 'source_name' => stripslashes($datarray['author-name']),
2510 'source_link' => $datarray['author-link'],
2511 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2512 ? $importer['thumb'] : $datarray['author-avatar']),
2513 'verb' => ACTIVITY_POST,
2515 'parent' => $conv_parent,
2519 // only send one notification
2531 // Head post of a conversation. Have we seen it? If not, import it.
2534 $item_id = $item->get_id();
2535 $datarray = get_atom_elements($feed,$item);
2537 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2538 $ev = bbtoevent($datarray['body']);
2539 if(x($ev,'desc') && x($ev,'start')) {
2540 $ev['cid'] = $importer['id'];
2541 $ev['uid'] = $importer['uid'];
2542 $ev['uri'] = $item_id;
2543 $ev['edited'] = $datarray['edited'];
2544 $ev['private'] = $datarray['private'];
2546 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2548 intval($importer['uid'])
2551 $ev['id'] = $r[0]['id'];
2552 $xyz = event_store($ev);
2557 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2559 intval($importer['importer_uid'])
2562 // Update content if 'updated' changes
2565 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2566 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2567 dbesc($datarray['title']),
2568 dbesc($datarray['body']),
2569 dbesc($datarray['tag']),
2570 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2572 intval($importer['importer_uid'])
2576 // update last-child if it changes
2578 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2579 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2580 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2581 intval($allow[0]['data']),
2582 dbesc(datetime_convert()),
2584 intval($importer['importer_uid'])
2590 // This is my contact on another system, but it's really me.
2591 // Turn this into a wall post.
2593 if($importer['remote_self'])
2594 $datarray['wall'] = 1;
2596 $datarray['parent-uri'] = $item_id;
2597 $datarray['uid'] = $importer['importer_uid'];
2598 $datarray['contact-id'] = $importer['id'];
2600 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2601 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2602 // but otherwise there's a possible data mixup on the sender's system.
2603 // the tgroup delivery code called from item_store will correct it if it's a forum,
2604 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2605 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2606 $datarray['owner-name'] = $importer['senderName'];
2607 $datarray['owner-link'] = $importer['url'];
2608 $datarray['owner-avatar'] = $importer['thumb'];
2611 $r = item_store($datarray);
2622 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2623 $url = notags(trim($datarray['author-link']));
2624 $name = notags(trim($datarray['author-name']));
2625 $photo = notags(trim($datarray['author-avatar']));
2627 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2628 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2629 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2631 if(is_array($contact)) {
2632 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2633 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2634 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2635 intval(CONTACT_IS_FRIEND),
2636 intval($contact['id']),
2637 intval($importer['uid'])
2640 // send email notification to owner?
2644 // create contact record
2646 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2647 `blocked`, `readonly`, `pending`, `writable` )
2648 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2649 intval($importer['uid']),
2650 dbesc(datetime_convert()),
2652 dbesc(normalise_link($url)),
2656 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2657 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2659 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2660 intval($importer['uid']),
2664 $contact_record = $r[0];
2666 // create notification
2667 $hash = random_string();
2669 if(is_array($contact_record)) {
2670 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2671 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2672 intval($importer['uid']),
2673 intval($contact_record['id']),
2675 dbesc(datetime_convert())
2678 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2679 intval($importer['uid'])
2683 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2684 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2685 $email = replace_macros($email_tpl, array(
2686 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2688 '$myname' => $r[0]['username'],
2689 '$siteurl' => $a->get_baseurl(),
2690 '$sitename' => $a->config['sitename']
2692 $res = mail($r[0]['email'],
2693 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2695 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2696 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2697 . 'Content-transfer-encoding: 8bit' );
2704 function lose_follower($importer,$contact,$datarray,$item) {
2706 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2707 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2708 intval(CONTACT_IS_SHARING),
2709 intval($contact['id'])
2713 contact_remove($contact['id']);
2717 function lose_sharer($importer,$contact,$datarray,$item) {
2719 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2720 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2721 intval(CONTACT_IS_FOLLOWER),
2722 intval($contact['id'])
2726 contact_remove($contact['id']);
2731 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2733 if(is_array($importer)) {
2734 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2735 intval($importer['uid'])
2739 // Diaspora has different message-ids in feeds than they do
2740 // through the direct Diaspora protocol. If we try and use
2741 // the feed, we'll get duplicates. So don't.
2743 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2746 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2748 // Use a single verify token, even if multiple hubs
2750 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2752 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2754 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2756 if(! strlen($contact['hub-verify'])) {
2757 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2758 dbesc($verify_token),
2759 intval($contact['id'])
2763 post_url($url,$params);
2769 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2773 $name = xmlify($name);
2774 $uri = xmlify($uri);
2777 $photo = xmlify($photo);
2781 $o .= "<name>$name</name>\r\n";
2782 $o .= "<uri>$uri</uri>\r\n";
2783 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2784 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2786 call_hooks('atom_author', $o);
2788 $o .= "</$tag>\r\n";
2792 function atom_entry($item,$type,$author,$owner,$comment = false) {
2796 if(! $item['parent'])
2799 if($item['deleted'])
2800 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2803 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2804 $body = fix_private_photos($item['body'],$owner['uid']);
2806 $body = $item['body'];
2809 $o = "\r\n\r\n<entry>\r\n";
2811 if(is_array($author))
2812 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2814 $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']));
2815 if(strlen($item['owner-name']))
2816 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2818 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2819 $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";
2821 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2822 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2823 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2824 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2825 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2826 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2827 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2829 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2831 if($item['location']) {
2832 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2833 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2837 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2839 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2840 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2843 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2844 if($item['bookmark'])
2845 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2848 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2851 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2853 if($item['signed_text']) {
2854 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2855 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2858 $verb = construct_verb($item);
2859 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2860 $actobj = construct_activity_object($item);
2863 $actarg = construct_activity_target($item);
2867 $tags = item_getfeedtags($item);
2869 foreach($tags as $t) {
2870 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2874 $o .= item_getfeedattach($item);
2876 $mentioned = get_mentions($item);
2880 call_hooks('atom_entry', $o);
2882 $o .= '</entry>' . "\r\n";
2887 function fix_private_photos($s,$uid) {
2889 logger('fix_private_photos');
2891 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2892 $image = $matches[1];
2893 logger('fix_private_photos: found photo ' . $image);
2894 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2895 $i = basename($image);
2896 $i = str_replace('.jpg','',$i);
2897 $x = strpos($i,'-');
2899 $res = substr($i,$x+1);
2900 $i = substr($i,0,$x);
2901 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2907 logger('replacing photo');
2908 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2911 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2919 function item_getfeedtags($item) {
2922 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2924 for($x = 0; $x < $cnt; $x ++) {
2926 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2930 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2932 for($x = 0; $x < $cnt; $x ++) {
2934 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2940 function item_getfeedattach($item) {
2942 $arr = explode(',',$item['attach']);
2944 foreach($arr as $r) {
2946 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2948 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2949 if(intval($matches[2]))
2950 $ret .= 'length="' . intval($matches[2]) . '" ';
2951 if($matches[4] !== ' ')
2952 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2953 $ret .= ' />' . "\r\n";
2962 function item_expire($uid,$days) {
2964 if((! $uid) || (! $days))
2967 $r = q("SELECT * FROM `item`
2969 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
2979 $expire_items = get_pconfig($uid, 'expire','items');
2980 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2982 $expire_notes = get_pconfig($uid, 'expire','notes');
2983 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2985 $expire_starred = get_pconfig($uid, 'expire','starred');
2986 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2988 $expire_photos = get_pconfig($uid, 'expire','photos');
2989 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2991 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2993 foreach($r as $item) {
2995 // don't expire filed items
2997 if(strpos($item['file'],'[') !== false)
3000 // Only expire posts, not photos and photo comments
3002 if($expire_photos==0 && strlen($item['resource-id']))
3004 if($expire_starred==0 && intval($item['starred']))
3006 if($expire_notes==0 && $item['type']=='note')
3008 if($expire_items==0 && $item['type']!='note')
3012 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3013 dbesc(datetime_convert()),
3014 dbesc(datetime_convert()),
3018 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d) and uid = %d",
3019 intval($item['id']),
3023 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d) and uid = %d",
3024 intval($item['id']),
3030 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3031 dbesc(datetime_convert()),
3032 dbesc(datetime_convert()),
3033 dbesc($item['parent-uri']),
3034 intval($item['uid'])
3039 proc_run('php',"include/notifier.php","expire","$uid");
3044 function drop_items($items) {
3047 if((! local_user()) && (! $remote_user()))
3051 foreach($items as $item) {
3052 $owner = drop_item($item,false);
3053 if($owner && ! $uid)
3058 // multiple threads may have been deleted, send an expire notification
3061 proc_run('php',"include/notifier.php","expire","$uid");
3065 function drop_item($id,$interactive = true) {
3069 // locate item to be deleted
3071 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3078 notice( t('Item not found.') . EOL);
3079 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3084 $owner = $item['uid'];
3086 // check if logged in user is either the author or owner of this item
3088 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3092 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3093 dbesc(datetime_convert()),
3094 dbesc(datetime_convert()),
3098 // If item is a link to a photo resource, nuke all the associated photos
3099 // (visitors will not have photo resources)
3100 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3101 // generate a resource-id and therefore aren't intimately linked to the item.
3103 if(strlen($item['resource-id'])) {
3104 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3105 dbesc($item['resource-id']),
3106 intval($item['uid'])
3108 // ignore the result
3111 // If item is a link to an event, nuke the event record.
3113 if(intval($item['event-id'])) {
3114 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3115 intval($item['event-id']),
3116 intval($item['uid'])
3118 // ignore the result
3122 // If it's the parent of a comment thread, kill all the kids
3124 if($item['uri'] == $item['parent-uri']) {
3125 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3126 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3127 dbesc(datetime_convert()),
3128 dbesc(datetime_convert()),
3129 dbesc($item['parent-uri']),
3130 intval($item['uid'])
3132 // ignore the result
3135 // ensure that last-child is set in case the comment that had it just got wiped.
3136 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3137 dbesc(datetime_convert()),
3138 dbesc($item['parent-uri']),
3139 intval($item['uid'])
3141 // who is the last child now?
3142 $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",
3143 dbesc($item['parent-uri']),
3144 intval($item['uid'])
3147 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3152 $drop_id = intval($item['id']);
3154 // send the notification upstream/downstream as the case may be
3159 proc_run('php',"include/notifier.php","drop","$drop_id");
3160 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3166 notice( t('Permission denied.') . EOL);
3167 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);