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];
29 // default permissions - anonymous user
31 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
33 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
34 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
35 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
43 $owner_id = $owner['user_uid'];
44 $owner_nick = $owner['nickname'];
46 $birthday = feed_birthday($owner_id,$owner['timezone']);
53 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
57 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
58 $my_id = '1:' . $dfrn_id;
61 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
62 $my_id = '0:' . $dfrn_id;
69 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
77 $groups = init_groups_visitor($contact['id']);
80 for($x = 0; $x < count($groups); $x ++)
81 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
82 $gs = implode('|', $groups);
85 $gs = '<<>>' ; // Impossible to match
87 $sql_extra = sprintf("
88 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
89 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
90 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
91 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
93 intval($contact['id']),
94 intval($contact['id']),
105 if(! strlen($last_update))
106 $last_update = 'now -30 days';
108 if(isset($category)) {
109 $sql_extra .= file_tag_file_query('item',$category,'category');
114 $sql_extra .= " AND `contact`.`self` = 1 ";
117 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
119 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
120 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
121 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
122 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
123 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
124 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
125 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
126 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
127 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
128 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
129 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
131 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
138 // Will check further below if this actually returned results.
139 // We will provide an empty feed if that is the case.
143 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
147 $hubxml = feed_hublinks();
149 $salmon = feed_salmonlinks($owner_nick);
151 $atom .= replace_macros($feed_template, array(
152 '$version' => xmlify(FRIENDICA_VERSION),
153 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
154 '$feed_title' => xmlify($owner['name']),
155 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
157 '$salmon' => $salmon,
158 '$name' => xmlify($owner['name']),
159 '$profile_page' => xmlify($owner['url']),
160 '$photo' => xmlify($owner['photo']),
161 '$thumb' => xmlify($owner['thumb']),
162 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
163 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
164 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
165 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
166 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
169 call_hooks('atom_feed', $atom);
171 if(! count($items)) {
173 call_hooks('atom_feed_end', $atom);
175 $atom .= '</feed>' . "\r\n";
179 foreach($items as $item) {
181 // prevent private email from leaking.
182 if($item['network'] === NETWORK_MAIL)
185 // public feeds get html, our own nodes use bbcode
189 // catch any email that's in a public conversation and make sure it doesn't leak
197 $atom .= atom_entry($item,$type,null,$owner,true);
200 call_hooks('atom_feed_end', $atom);
202 $atom .= '</feed>' . "\r\n";
208 function construct_verb($item) {
210 return $item['verb'];
211 return ACTIVITY_POST;
214 function construct_activity_object($item) {
216 if($item['object']) {
217 $o = '<as:object>' . "\r\n";
218 $r = parse_xml_string($item['object'],false);
224 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
226 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
228 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
230 if(substr($r->link,0,1) === '<') {
231 // patch up some facebook "like" activity objects that got stored incorrectly
232 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
233 // we can probably remove this hack here and in the following function in a few months time.
234 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
235 $r->link = str_replace('&','&', $r->link);
236 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
240 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
243 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
244 $o .= '</as:object>' . "\r\n";
251 function construct_activity_target($item) {
253 if($item['target']) {
254 $o = '<as:target>' . "\r\n";
255 $r = parse_xml_string($item['target'],false);
259 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
261 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
263 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
265 if(substr($r->link,0,1) === '<') {
266 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
267 $r->link = str_replace('&','&', $r->link);
268 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
272 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
275 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
276 $o .= '</as:target>' . "\r\n";
286 function get_atom_elements($feed,$item) {
288 require_once('library/HTMLPurifier.auto.php');
289 require_once('include/html2bbcode.php');
291 $best_photo = array();
295 $author = $item->get_author();
297 $res['author-name'] = unxmlify($author->get_name());
298 $res['author-link'] = unxmlify($author->get_link());
301 $res['author-name'] = unxmlify($feed->get_title());
302 $res['author-link'] = unxmlify($feed->get_permalink());
304 $res['uri'] = unxmlify($item->get_id());
305 $res['title'] = unxmlify($item->get_title());
306 $res['body'] = unxmlify($item->get_content());
307 $res['plink'] = unxmlify($item->get_link(0));
310 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
314 // look for a photo. We should check media size and find the best one,
315 // but for now let's just find any author photo
317 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
319 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
320 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
321 foreach($base as $link) {
322 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
323 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
324 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
329 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
331 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
332 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
333 if($base && count($base)) {
334 foreach($base as $link) {
335 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
336 $res['author-link'] = unxmlify($link['attribs']['']['href']);
337 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
338 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
339 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
345 // No photo/profile-link on the item - look at the feed level
347 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
348 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
349 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
350 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
351 foreach($base as $link) {
352 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
353 $res['author-link'] = unxmlify($link['attribs']['']['href']);
354 if(! $res['author-avatar']) {
355 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
356 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
361 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
363 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
364 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
366 if($base && count($base)) {
367 foreach($base as $link) {
368 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
369 $res['author-link'] = unxmlify($link['attribs']['']['href']);
370 if(! (x($res,'author-avatar'))) {
371 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
372 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
379 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
380 if($apps && $apps[0]['attribs']['']['source']) {
381 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
382 if($res['app'] === 'web')
383 $res['app'] = 'OStatus';
386 // base64 encoded json structure representing Diaspora signature
388 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
390 $res['dsprsig'] = unxmlify($dsig[0]['data']);
393 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
395 $res['guid'] = unxmlify($dguid[0]['data']);
397 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
399 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
403 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
406 $have_real_body = false;
408 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
410 $have_real_body = true;
411 $res['body'] = $rawenv[0]['data'];
412 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
413 // make sure nobody is trying to sneak some html tags by us
414 $res['body'] = notags(base64url_decode($res['body']));
417 $maxlen = get_max_import_size();
418 if($maxlen && (strlen($res['body']) > $maxlen))
419 $res['body'] = substr($res['body'],0, $maxlen);
421 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
422 // the content type. Our own network only emits text normally, though it might have been converted to
423 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
424 // have to assume it is all html and needs to be purified.
426 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
427 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
428 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
431 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
433 $res['body'] = reltoabs($res['body'],$base_url);
435 $res['body'] = html2bb_video($res['body']);
437 $res['body'] = oembed_html2bbcode($res['body']);
439 $config = HTMLPurifier_Config::createDefault();
440 $config->set('Cache.DefinitionImpl', null);
442 // we shouldn't need a whitelist, because the bbcode converter
443 // will strip out any unsupported tags.
445 $purifier = new HTMLPurifier($config);
446 $res['body'] = $purifier->purify($res['body']);
448 $res['body'] = @html2bbcode($res['body']);
450 elseif(! $have_real_body) {
452 // it's not one of our messages and it has no tags
453 // so it's probably just text. We'll escape it just to be safe.
455 $res['body'] = escape_tags($res['body']);
458 // this tag is obsolete but we keep it for really old sites
460 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
461 if($allow && $allow[0]['data'] == 1)
462 $res['last-child'] = 1;
464 $res['last-child'] = 0;
466 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
467 if($private && $private[0]['data'] == 1)
472 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
473 if($extid && $extid[0]['data'])
474 $res['extid'] = $extid[0]['data'];
476 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
478 $res['location'] = unxmlify($rawlocation[0]['data']);
481 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
483 $res['created'] = unxmlify($rawcreated[0]['data']);
486 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
488 $res['edited'] = unxmlify($rawedited[0]['data']);
490 if((x($res,'edited')) && (! (x($res,'created'))))
491 $res['created'] = $res['edited'];
493 if(! $res['created'])
494 $res['created'] = $item->get_date('c');
497 $res['edited'] = $item->get_date('c');
500 // Disallow time travelling posts
502 $d1 = strtotime($res['created']);
503 $d2 = strtotime($res['edited']);
504 $d3 = strtotime('now');
507 $res['created'] = datetime_convert();
509 $res['edited'] = datetime_convert();
511 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
512 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
513 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
514 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
515 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
516 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
517 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
518 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
519 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
521 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
522 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
524 foreach($base as $link) {
525 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
526 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
527 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
532 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
534 $res['coord'] = unxmlify($rawgeo[0]['data']);
537 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
539 // select between supported verbs
542 $res['verb'] = unxmlify($rawverb[0]['data']);
545 // translate OStatus unfollow to activity streams if it happened to get selected
547 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
548 $res['verb'] = ACTIVITY_UNFOLLOW;
550 $cats = $item->get_categories();
553 foreach($cats as $cat) {
554 $term = $cat->get_term();
556 $term = $cat->get_label();
557 $scheme = $cat->get_scheme();
558 if($scheme && $term && stristr($scheme,'X-DFRN:'))
559 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
561 $tag_arr[] = notags(trim($term));
563 $res['tag'] = implode(',', $tag_arr);
566 $attach = $item->get_enclosures();
569 foreach($attach as $att) {
570 $len = intval($att->get_length());
571 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
572 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
573 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
574 if(strpos($type,';'))
575 $type = substr($type,0,strpos($type,';'));
576 if((! $link) || (strpos($link,'http') !== 0))
582 $type = 'application/octet-stream';
584 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
586 $res['attach'] = implode(',', $att_arr);
589 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
592 $res['object'] = '<object>' . "\n";
593 $child = $rawobj[0]['child'];
594 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
595 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
596 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
598 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
599 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
600 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
601 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
602 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
603 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
604 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
605 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
607 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
608 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
609 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
610 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
612 $body = html2bb_video($body);
614 $config = HTMLPurifier_Config::createDefault();
615 $config->set('Cache.DefinitionImpl', null);
617 $purifier = new HTMLPurifier($config);
618 $body = $purifier->purify($body);
619 $body = html2bbcode($body);
622 $res['object'] .= '<content>' . $body . '</content>' . "\n";
625 $res['object'] .= '</object>' . "\n";
628 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
631 $res['target'] = '<target>' . "\n";
632 $child = $rawobj[0]['child'];
633 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
634 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
636 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
637 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
638 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
639 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
640 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
641 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
642 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
643 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
645 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
646 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
647 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
648 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
650 $body = html2bb_video($body);
652 $config = HTMLPurifier_Config::createDefault();
653 $config->set('Cache.DefinitionImpl', null);
655 $purifier = new HTMLPurifier($config);
656 $body = $purifier->purify($body);
657 $body = html2bbcode($body);
660 $res['target'] .= '<content>' . $body . '</content>' . "\n";
663 $res['target'] .= '</target>' . "\n";
666 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
668 call_hooks('parse_atom', $arr);
673 function encode_rel_links($links) {
675 if(! ((is_array($links)) && (count($links))))
677 foreach($links as $link) {
679 if($link['attribs']['']['rel'])
680 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
681 if($link['attribs']['']['type'])
682 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
683 if($link['attribs']['']['href'])
684 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
685 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
686 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
687 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
688 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
696 function item_store($arr,$force_parent = false) {
698 // If a Diaspora signature structure was passed in, pull it out of the
699 // item array and set it aside for later storage.
702 if(x($arr,'dsprsig')) {
703 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
704 unset($arr['dsprsig']);
707 if(x($arr, 'gravity'))
708 $arr['gravity'] = intval($arr['gravity']);
709 elseif($arr['parent-uri'] === $arr['uri'])
711 elseif(activity_match($arr['verb'],ACTIVITY_POST))
714 $arr['gravity'] = 6; // extensible catchall
717 $arr['type'] = 'remote';
719 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
721 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
722 $arr['body'] = strip_tags($arr['body']);
725 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
726 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
727 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
728 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
729 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
730 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
731 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
732 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
733 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
734 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
735 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
736 $arr['commented'] = datetime_convert();
737 $arr['received'] = datetime_convert();
738 $arr['changed'] = datetime_convert();
739 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
740 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
741 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
742 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
743 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
745 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
746 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
747 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
748 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
749 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
750 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
751 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
752 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
753 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
754 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
755 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
756 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
757 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
758 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
759 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
760 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
761 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
762 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
763 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
765 if($arr['parent-uri'] === $arr['uri']) {
768 $allow_cid = $arr['allow_cid'];
769 $allow_gid = $arr['allow_gid'];
770 $deny_cid = $arr['deny_cid'];
771 $deny_gid = $arr['deny_gid'];
775 // find the parent and snarf the item id and ACL's
776 // and anything else we need to inherit
778 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
779 dbesc($arr['parent-uri']),
785 // is the new message multi-level threaded?
786 // even though we don't support it now, preserve the info
787 // and re-attach to the conversation parent.
789 if($r[0]['uri'] != $r[0]['parent-uri']) {
790 $arr['thr-parent'] = $arr['parent-uri'];
791 $arr['parent-uri'] = $r[0]['parent-uri'];
792 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
793 ORDER BY `id` ASC LIMIT 1",
794 dbesc($r[0]['parent-uri']),
795 dbesc($r[0]['parent-uri']),
802 $parent_id = $r[0]['id'];
803 $parent_deleted = $r[0]['deleted'];
804 $allow_cid = $r[0]['allow_cid'];
805 $allow_gid = $r[0]['allow_gid'];
806 $deny_cid = $r[0]['deny_cid'];
807 $deny_gid = $r[0]['deny_gid'];
808 $arr['wall'] = $r[0]['wall'];
810 // if the parent is private, force privacy for the entire conversation
811 // This differs from the above settings as it subtly allows comments from
812 // email correspondents to be private even if the overall thread is not.
820 // Allow one to see reply tweets from status.net even when
821 // we don't have or can't see the original post.
824 logger('item_store: $force_parent=true, reply converted to top-level post.');
826 $arr['thr-parent'] = $arr['parent-uri'];
827 $arr['parent-uri'] = $arr['uri'];
831 logger('item_store: item parent was not found - ignoring item');
839 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
843 if($r && count($r)) {
844 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
848 call_hooks('post_remote',$arr);
850 if(x($arr,'cancel')) {
851 logger('item_store: post cancelled by plugin.');
857 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
859 $r = dbq("INSERT INTO `item` (`"
860 . implode("`, `", array_keys($arr))
862 . implode("', '", array_values($arr))
865 // find the item we just created
867 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
868 $arr['uri'], // already dbesc'd
873 $current_post = $r[0]['id'];
874 logger('item_store: created item ' . $current_post);
877 logger('item_store: could not locate created item');
881 logger('item_store: duplicated post occurred. Removing duplicates.');
882 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
885 intval($current_post)
889 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
890 $parent_id = $current_post;
892 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
895 $private = $arr['private'];
897 // Set parent id - and also make sure to inherit the parent's ACL's.
899 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
900 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
907 intval($parent_deleted),
908 intval($current_post)
911 // update the commented timestamp on the parent
913 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
914 dbesc(datetime_convert()),
915 dbesc(datetime_convert()),
920 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
921 intval($current_post),
922 dbesc($dsprsig->signed_text),
923 dbesc($dsprsig->signature),
924 dbesc($dsprsig->signer)
930 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
933 if($arr['last-child']) {
934 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
937 intval($current_post)
941 tag_deliver($arr['uid'],$current_post);
943 return $current_post;
946 function get_item_contact($item,$contacts) {
947 if(! count($contacts) || (! is_array($item)))
949 foreach($contacts as $contact) {
950 if($contact['id'] == $item['contact-id']) {
959 function tag_deliver($uid,$item_id) {
961 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
967 $u = q("select * from user where uid = %d limit 1",
973 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
974 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
977 $i = q("select * from item where id = %d and uid = %d limit 1",
986 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
988 // Diaspora uses their own hardwired link URL in @-tags
989 // instead of the one we supply with webfinger
991 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
993 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
995 foreach($matches as $mtch) {
996 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
998 logger('tag_deliver: mention found: ' . $mtch[2]);
1006 // send a notification
1008 require_once('include/enotify.php');
1010 'type' => NOTIFY_TAGSELF,
1011 'notify_flags' => $u[0]['notify-flags'],
1012 'language' => $u[0]['language'],
1013 'to_name' => $u[0]['username'],
1014 'to_email' => $u[0]['email'],
1015 'uid' => $u[0]['uid'],
1017 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1018 'source_name' => $item['author-name'],
1019 'source_link' => $item['author-link'],
1020 'source_photo' => $item['author-avatar'],
1021 'verb' => ACTIVITY_TAG,
1025 if((! $community_page) && (! $prvgroup))
1029 // tgroup delivery - setup a second delivery chain
1030 // prevent delivery looping - only proceed
1031 // if the message originated elsewhere and is a top-level post
1033 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1036 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1039 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1040 intval($u[0]['uid'])
1045 // also reset all the privacy bits to the forum default permissions
1047 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1049 $forum_mode = (($prvgroup) ? 2 : 1);
1051 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1052 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1053 intval($forum_mode),
1054 dbesc($c[0]['name']),
1055 dbesc($c[0]['url']),
1056 dbesc($c[0]['thumb']),
1058 dbesc($u[0]['allow_cid']),
1059 dbesc($u[0]['allow_gid']),
1060 dbesc($u[0]['deny_cid']),
1061 dbesc($u[0]['deny_gid']),
1065 proc_run('php','include/notifier.php','tgroup',$item_id);
1074 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1078 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1080 if($contact['duplex'] && $contact['dfrn-id'])
1081 $idtosend = '0:' . $orig_id;
1082 if($contact['duplex'] && $contact['issued-id'])
1083 $idtosend = '1:' . $orig_id;
1085 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1087 $rino_enable = get_config('system','rino_encrypt');
1092 $ssl_val = intval(get_config('system','ssl_policy'));
1096 case SSL_POLICY_FULL:
1097 $ssl_policy = 'full';
1099 case SSL_POLICY_SELFSIGN:
1100 $ssl_policy = 'self';
1102 case SSL_POLICY_NONE:
1104 $ssl_policy = 'none';
1108 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1110 logger('dfrn_deliver: ' . $url);
1112 $xml = fetch_url($url);
1114 $curl_stat = $a->get_curl_code();
1116 return(-1); // timed out
1118 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1123 if(strpos($xml,'<?xml') === false) {
1124 logger('dfrn_deliver: no valid XML returned');
1125 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1129 $res = parse_xml_string($xml);
1131 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1132 return (($res->status) ? $res->status : 3);
1134 $postvars = array();
1135 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1136 $challenge = hex2bin((string) $res->challenge);
1137 $perm = (($res->perm) ? $res->perm : null);
1138 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1139 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1140 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1142 if($owner['page-flags'] == PAGE_PRVGROUP)
1145 $final_dfrn_id = '';
1148 if((($perm == 'rw') && (! intval($contact['writable'])))
1149 || (($perm == 'r') && (intval($contact['writable'])))) {
1150 q("update contact set writable = %d where id = %d limit 1",
1151 intval(($perm == 'rw') ? 1 : 0),
1152 intval($contact['id'])
1154 $contact['writable'] = (string) 1 - intval($contact['writable']);
1158 if(($contact['duplex'] && strlen($contact['pubkey']))
1159 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1160 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1161 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1162 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1165 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1166 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1169 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1171 if(strpos($final_dfrn_id,':') == 1)
1172 $final_dfrn_id = substr($final_dfrn_id,2);
1174 if($final_dfrn_id != $orig_id) {
1175 logger('dfrn_deliver: wrong dfrn_id.');
1176 // did not decode properly - cannot trust this site
1180 $postvars['dfrn_id'] = $idtosend;
1181 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1183 $postvars['dissolve'] = '1';
1186 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1187 $postvars['data'] = $atom;
1188 $postvars['perm'] = 'rw';
1191 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1192 $postvars['perm'] = 'r';
1195 $postvars['ssl_policy'] = $ssl_policy;
1198 $postvars['page'] = $page;
1200 if($rino && $rino_allowed && (! $dissolve)) {
1201 $key = substr(random_string(),0,16);
1202 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1203 $postvars['data'] = $data;
1204 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1207 if($dfrn_version >= 2.1) {
1208 if(($contact['duplex'] && strlen($contact['pubkey']))
1209 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1210 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1212 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1215 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1219 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1220 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1223 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1227 logger('md5 rawkey ' . md5($postvars['key']));
1229 $postvars['key'] = bin2hex($postvars['key']);
1232 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1234 $xml = post_url($contact['notify'],$postvars);
1236 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1238 $curl_stat = $a->get_curl_code();
1239 if((! $curl_stat) || (! strlen($xml)))
1240 return(-1); // timed out
1242 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1245 if(strpos($xml,'<?xml') === false) {
1246 logger('dfrn_deliver: phase 2: no valid XML returned');
1247 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1251 $res = parse_xml_string($xml);
1253 return $res->status;
1259 * consume_feed - process atom feed and update anything/everything we might need to update
1261 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1263 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1264 * It is this person's stuff that is going to be updated.
1265 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1266 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1267 * have a contact record.
1268 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1269 * might not) try and subscribe to it.
1270 * $datedir sorts in reverse order
1271 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1272 * imported prior to its children being seen in the stream unless we are certain
1273 * of how the feed is arranged/ordered.
1274 * With $pass = 1, we only pull parent items out of the stream.
1275 * With $pass = 2, we only pull children (comments/likes).
1277 * So running this twice, first with pass 1 and then with pass 2 will do the right
1278 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1279 * model where comments can have sub-threads. That would require some massive sorting
1280 * to get all the feed items into a mostly linear ordering, and might still require
1284 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1286 require_once('library/simplepie/simplepie.inc');
1288 if(! strlen($xml)) {
1289 logger('consume_feed: empty input');
1293 $feed = new SimplePie();
1294 $feed->set_raw_data($xml);
1296 $feed->enable_order_by_date(true);
1298 $feed->enable_order_by_date(false);
1302 logger('consume_feed: Error parsing XML: ' . $feed->error());
1304 $permalink = $feed->get_permalink();
1306 // Check at the feed level for updated contact name and/or photo
1310 $photo_timestamp = '';
1314 $hubs = $feed->get_links('hub');
1315 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1318 $hub = implode(',', $hubs);
1320 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1322 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1324 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1325 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1326 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1327 $new_name = $elems['name'][0]['data'];
1329 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1330 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1331 $photo_url = $elems['link'][0]['attribs']['']['href'];
1334 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1335 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1339 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1340 logger('consume_feed: Updating photo for ' . $contact['name']);
1341 require_once("Photo.php");
1342 $photo_failure = false;
1343 $have_photo = false;
1345 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1346 intval($contact['id']),
1347 intval($contact['uid'])
1350 $resource_id = $r[0]['resource-id'];
1354 $resource_id = photo_new_resource();
1357 $img_str = fetch_url($photo_url,true);
1358 // guess mimetype from headers or filename
1359 $type = guess_image_type($photo_url,true);
1362 $img = new Photo($img_str, $type);
1363 if($img->is_valid()) {
1365 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1366 dbesc($resource_id),
1367 intval($contact['id']),
1368 intval($contact['uid'])
1372 $img->scaleImageSquare(175);
1374 $hash = $resource_id;
1375 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1377 $img->scaleImage(80);
1378 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1380 $img->scaleImage(48);
1381 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1385 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1386 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1387 dbesc(datetime_convert()),
1388 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1389 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1390 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1391 intval($contact['uid']),
1392 intval($contact['id'])
1397 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1398 $r = q("select * from contact where uid = %d and id = %d limit 1",
1399 intval($contact['uid']),
1400 intval($contact['id'])
1403 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1404 dbesc(notags(trim($new_name))),
1405 dbesc(datetime_convert()),
1406 intval($contact['uid']),
1407 intval($contact['id'])
1410 // do our best to update the name on content items
1413 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1414 dbesc(notags(trim($new_name))),
1415 dbesc($r[0]['name']),
1416 dbesc($r[0]['url']),
1417 intval($contact['uid'])
1422 if(strlen($birthday)) {
1423 if(substr($birthday,0,4) != $contact['bdyear']) {
1424 logger('consume_feed: updating birthday: ' . $birthday);
1428 * Add new birthday event for this person
1430 * $bdtext is just a readable placeholder in case the event is shared
1431 * with others. We will replace it during presentation to our $importer
1432 * to contain a sparkle link and perhaps a photo.
1436 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1439 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1440 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1441 intval($contact['uid']),
1442 intval($contact['id']),
1443 dbesc(datetime_convert()),
1444 dbesc(datetime_convert()),
1445 dbesc(datetime_convert('UTC','UTC', $birthday)),
1446 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1454 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1455 dbesc(substr($birthday,0,4)),
1456 intval($contact['uid']),
1457 intval($contact['id'])
1460 // This function is called twice without reloading the contact
1461 // Make sure we only create one event. This is why &$contact
1462 // is a reference var in this function
1464 $contact['bdyear'] = substr($birthday,0,4);
1469 $community_page = 0;
1470 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1472 $community_page = intval($rawtags[0]['data']);
1474 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1475 q("update contact set forum = %d where id = %d limit 1",
1476 intval($community_page),
1477 intval($contact['id'])
1479 $contact['forum'] = (string) $community_page;
1483 // process any deleted entries
1485 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1486 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1487 foreach($del_entries as $dentry) {
1489 if(isset($dentry['attribs']['']['ref'])) {
1490 $uri = $dentry['attribs']['']['ref'];
1492 if(isset($dentry['attribs']['']['when'])) {
1493 $when = $dentry['attribs']['']['when'];
1494 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1497 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1499 if($deleted && is_array($contact)) {
1500 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1501 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1503 intval($importer['uid']),
1504 intval($contact['id'])
1509 if(! $item['deleted'])
1510 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1512 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1513 $xo = parse_xml_string($item['object'],false);
1514 $xt = parse_xml_string($item['target'],false);
1515 if($xt->type === ACTIVITY_OBJ_NOTE) {
1516 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1518 intval($importer['importer_uid'])
1522 // For tags, the owner cannot remove the tag on the author's copy of the post.
1524 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1525 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1526 $author_copy = (($item['origin']) ? true : false);
1528 if($owner_remove && $author_copy)
1530 if($author_remove || $owner_remove) {
1531 $tags = explode(',',$i[0]['tag']);
1534 foreach($tags as $tag)
1535 if(trim($tag) !== trim($xo->body))
1536 $newtags[] = trim($tag);
1538 q("update item set tag = '%s' where id = %d limit 1",
1539 dbesc(implode(',',$newtags)),
1547 if($item['uri'] == $item['parent-uri']) {
1548 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1549 `body` = '', `title` = ''
1550 WHERE `parent-uri` = '%s' AND `uid` = %d",
1552 dbesc(datetime_convert()),
1553 dbesc($item['uri']),
1554 intval($importer['uid'])
1558 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1559 `body` = '', `title` = ''
1560 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1562 dbesc(datetime_convert()),
1564 intval($importer['uid'])
1566 if($item['last-child']) {
1567 // ensure that last-child is set in case the comment that had it just got wiped.
1568 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1569 dbesc(datetime_convert()),
1570 dbesc($item['parent-uri']),
1571 intval($item['uid'])
1573 // who is the last child now?
1574 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1575 ORDER BY `created` DESC LIMIT 1",
1576 dbesc($item['parent-uri']),
1577 intval($importer['uid'])
1580 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1591 // Now process the feed
1593 if($feed->get_item_quantity()) {
1595 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1597 // in inverse date order
1599 $items = array_reverse($feed->get_items());
1601 $items = $feed->get_items();
1604 foreach($items as $item) {
1607 $item_id = $item->get_id();
1608 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1609 if(isset($rawthread[0]['attribs']['']['ref'])) {
1611 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1614 if(($is_reply) && is_array($contact)) {
1619 // Have we seen it? If not, import it.
1621 $item_id = $item->get_id();
1622 $datarray = get_atom_elements($feed,$item);
1625 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1626 $datarray['author-name'] = $contact['name'];
1627 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1628 $datarray['author-link'] = $contact['url'];
1629 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1630 $datarray['author-avatar'] = $contact['thumb'];
1632 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1633 logger('consume_feed: no author information! ' . print_r($datarray,true));
1637 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1639 intval($importer['uid'])
1642 // Update content if 'updated' changes
1645 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1647 // do not accept (ignore) an earlier edit than one we currently have.
1648 if(datetime_convert('UTC','UTC',$datarray['edited'] < $r[0]['edited']))
1651 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1652 dbesc($datarray['title']),
1653 dbesc($datarray['body']),
1654 dbesc($datarray['tag']),
1655 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1657 intval($importer['uid'])
1661 // update last-child if it changes
1663 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1664 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1665 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1666 dbesc(datetime_convert()),
1668 intval($importer['uid'])
1670 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1671 intval($allow[0]['data']),
1672 dbesc(datetime_convert()),
1674 intval($importer['uid'])
1680 $force_parent = false;
1681 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1682 if($contact['network'] === NETWORK_OSTATUS)
1683 $force_parent = true;
1684 if(strlen($datarray['title']))
1685 unset($datarray['title']);
1686 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1687 dbesc(datetime_convert()),
1689 intval($importer['uid'])
1691 $datarray['last-child'] = 1;
1694 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1695 // one way feed - no remote comment ability
1696 $datarray['last-child'] = 0;
1698 $datarray['parent-uri'] = $parent_uri;
1699 $datarray['uid'] = $importer['uid'];
1700 $datarray['contact-id'] = $contact['id'];
1701 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1702 $datarray['type'] = 'activity';
1703 $datarray['gravity'] = GRAVITY_LIKE;
1704 // only one like or dislike per person
1705 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1706 intval($datarray['uid']),
1707 intval($datarray['contact-id']),
1708 dbesc($datarray['verb'])
1714 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1715 $xo = parse_xml_string($datarray['object'],false);
1716 $xt = parse_xml_string($datarray['target'],false);
1718 if($xt->type == ACTIVITY_OBJ_NOTE) {
1719 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1721 intval($importer['importer_uid'])
1726 // extract tag, if not duplicate, add to parent item
1727 if($xo->id && $xo->content) {
1728 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1729 if(! (stristr($r[0]['tag'],$newtag))) {
1730 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1731 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1739 $r = item_store($datarray,$force_parent);
1745 // Head post of a conversation. Have we seen it? If not, import it.
1747 $item_id = $item->get_id();
1749 $datarray = get_atom_elements($feed,$item);
1751 if(is_array($contact)) {
1752 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1753 $datarray['author-name'] = $contact['name'];
1754 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1755 $datarray['author-link'] = $contact['url'];
1756 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1757 $datarray['author-avatar'] = $contact['thumb'];
1760 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1761 logger('consume_feed: no author information! ' . print_r($datarray,true));
1765 // special handling for events
1767 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1768 $ev = bbtoevent($datarray['body']);
1769 if(x($ev,'desc') && x($ev,'start')) {
1770 $ev['uid'] = $importer['uid'];
1771 $ev['uri'] = $item_id;
1772 $ev['edited'] = $datarray['edited'];
1773 $ev['private'] = $datarray['private'];
1775 if(is_array($contact))
1776 $ev['cid'] = $contact['id'];
1777 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1779 intval($importer['uid'])
1782 $ev['id'] = $r[0]['id'];
1783 $xyz = event_store($ev);
1788 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1790 intval($importer['uid'])
1793 // Update content if 'updated' changes
1796 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1798 // do not accept (ignore) an earlier edit than one we currently have.
1799 if(datetime_convert('UTC','UTC',$datarray['edited'] < $r[0]['edited']))
1802 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1803 dbesc($datarray['title']),
1804 dbesc($datarray['body']),
1805 dbesc($datarray['tag']),
1806 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1808 intval($importer['uid'])
1812 // update last-child if it changes
1814 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1815 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1816 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1817 intval($allow[0]['data']),
1818 dbesc(datetime_convert()),
1820 intval($importer['uid'])
1826 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1827 logger('consume-feed: New follower');
1828 new_follower($importer,$contact,$datarray,$item);
1831 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1832 lose_follower($importer,$contact,$datarray,$item);
1836 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1837 logger('consume-feed: New friend request');
1838 new_follower($importer,$contact,$datarray,$item,true);
1841 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1842 lose_sharer($importer,$contact,$datarray,$item);
1847 if(! is_array($contact))
1850 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1851 if(strlen($datarray['title']))
1852 unset($datarray['title']);
1853 $datarray['last-child'] = 1;
1856 if($contact['network'] === NETWORK_FEED) {
1857 if(! strlen($contact['notify'])) {
1858 // one way feed - no remote comment ability
1859 $datarray['last-child'] = 0;
1861 $datarray['private'] = 1;
1864 // This is my contact on another system, but it's really me.
1865 // Turn this into a wall post.
1867 if($contact['remote_self'])
1868 $datarray['wall'] = 1;
1870 $datarray['parent-uri'] = $item_id;
1871 $datarray['uid'] = $importer['uid'];
1872 $datarray['contact-id'] = $contact['id'];
1874 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1875 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1876 // but otherwise there's a possible data mixup on the sender's system.
1877 // the tgroup delivery code called from item_store will correct it if it's a forum,
1878 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1879 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1880 $datarray['owner-name'] = $contact['name'];
1881 $datarray['owner-link'] = $contact['url'];
1882 $datarray['owner-avatar'] = $contact['thumb'];
1885 $r = item_store($datarray);
1893 function local_delivery($importer,$data) {
1897 if($importer['readonly']) {
1898 // We aren't receiving stuff from this person. But we will quietly ignore them
1899 // rather than a blatant "go away" message.
1900 logger('local_delivery: ignoring');
1905 // Consume notification feed. This may differ from consuming a public feed in several ways
1906 // - might contain email or friend suggestions
1907 // - might contain remote followup to our message
1908 // - in which case we need to accept it and then notify other conversants
1909 // - we may need to send various email notifications
1911 $feed = new SimplePie();
1912 $feed->set_raw_data($data);
1913 $feed->enable_order_by_date(false);
1917 // Currently unsupported - needs a lot of work
1918 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1919 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1920 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1922 $newloc['uid'] = $importer['importer_uid'];
1923 $newloc['cid'] = $importer['id'];
1924 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1925 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1926 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1927 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1928 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1929 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1930 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1931 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1932 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1933 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1936 // merge with current record, current contents have priority
1937 // update record, set url-updated
1938 // update profile photos
1944 // handle friend suggestion notification
1946 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1947 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1948 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1950 $fsugg['uid'] = $importer['importer_uid'];
1951 $fsugg['cid'] = $importer['id'];
1952 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1953 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1954 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1955 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1956 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1958 // Does our member already have a friend matching this description?
1960 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1961 dbesc($fsugg['name']),
1962 dbesc(normalise_link($fsugg['url'])),
1963 intval($fsugg['uid'])
1968 // Do we already have an fcontact record for this person?
1971 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1972 dbesc($fsugg['url']),
1973 dbesc($fsugg['name']),
1974 dbesc($fsugg['request'])
1979 // OK, we do. Do we already have an introduction for this person ?
1980 $r = q("select id from intro where uid = %d and fid = %d limit 1",
1981 intval($fsugg['uid']),
1988 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1989 dbesc($fsugg['name']),
1990 dbesc($fsugg['url']),
1991 dbesc($fsugg['photo']),
1992 dbesc($fsugg['request'])
1994 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1995 dbesc($fsugg['url']),
1996 dbesc($fsugg['name']),
1997 dbesc($fsugg['request'])
2002 // database record did not get created. Quietly give up.
2007 $hash = random_string();
2009 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2010 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2011 intval($fsugg['uid']),
2013 intval($fsugg['cid']),
2014 dbesc($fsugg['body']),
2016 dbesc(datetime_convert()),
2021 'type' => NOTIFY_SUGGEST,
2022 'notify_flags' => $importer['notify-flags'],
2023 'language' => $importer['language'],
2024 'to_name' => $importer['username'],
2025 'to_email' => $importer['email'],
2026 'uid' => $importer['importer_uid'],
2028 'link' => $a->get_baseurl() . '/notifications/intros',
2029 'source_name' => $importer['name'],
2030 'source_link' => $importer['url'],
2031 'source_photo' => $importer['photo'],
2032 'verb' => ACTIVITY_REQ_FRIEND,
2041 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2042 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2044 logger('local_delivery: private message received');
2047 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2050 $msg['uid'] = $importer['importer_uid'];
2051 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2052 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2053 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2054 $msg['contact-id'] = $importer['id'];
2055 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2056 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2058 $msg['replied'] = 0;
2059 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2060 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2061 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2065 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2066 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2068 // send notifications.
2070 require_once('include/enotify.php');
2072 $notif_params = array(
2073 'type' => NOTIFY_MAIL,
2074 'notify_flags' => $importer['notify-flags'],
2075 'language' => $importer['language'],
2076 'to_name' => $importer['username'],
2077 'to_email' => $importer['email'],
2078 'uid' => $importer['importer_uid'],
2080 'source_name' => $msg['from-name'],
2081 'source_link' => $importer['url'],
2082 'source_photo' => $importer['thumb'],
2083 'verb' => ACTIVITY_POST,
2087 notification($notif_params);
2093 $community_page = 0;
2094 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2096 $community_page = intval($rawtags[0]['data']);
2098 if(intval($importer['forum']) != $community_page) {
2099 q("update contact set forum = %d where id = %d limit 1",
2100 intval($community_page),
2101 intval($importer['id'])
2103 $importer['forum'] = (string) $community_page;
2106 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2108 // process any deleted entries
2110 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2111 if(is_array($del_entries) && count($del_entries)) {
2112 foreach($del_entries as $dentry) {
2114 if(isset($dentry['attribs']['']['ref'])) {
2115 $uri = $dentry['attribs']['']['ref'];
2117 if(isset($dentry['attribs']['']['when'])) {
2118 $when = $dentry['attribs']['']['when'];
2119 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2122 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2126 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2127 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2129 intval($importer['importer_uid']),
2130 intval($importer['id'])
2136 if($item['deleted'])
2139 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2141 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2142 $xo = parse_xml_string($item['object'],false);
2143 $xt = parse_xml_string($item['target'],false);
2145 if($xt->type === ACTIVITY_OBJ_NOTE) {
2146 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2148 intval($importer['importer_uid'])
2152 // For tags, the owner cannot remove the tag on the author's copy of the post.
2154 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2155 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2156 $author_copy = (($item['origin']) ? true : false);
2158 if($owner_remove && $author_copy)
2160 if($author_remove || $owner_remove) {
2161 $tags = explode(',',$i[0]['tag']);
2164 foreach($tags as $tag)
2165 if(trim($tag) !== trim($xo->body))
2166 $newtags[] = trim($tag);
2168 q("update item set tag = '%s' where id = %d limit 1",
2169 dbesc(implode(',',$newtags)),
2177 if($item['uri'] == $item['parent-uri']) {
2178 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2179 WHERE `parent-uri` = '%s' AND `uid` = %d",
2181 dbesc(datetime_convert()),
2182 dbesc($item['uri']),
2183 intval($importer['importer_uid'])
2187 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2188 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2190 dbesc(datetime_convert()),
2192 intval($importer['importer_uid'])
2194 if($item['last-child']) {
2195 // ensure that last-child is set in case the comment that had it just got wiped.
2196 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2197 dbesc(datetime_convert()),
2198 dbesc($item['parent-uri']),
2199 intval($item['uid'])
2201 // who is the last child now?
2202 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2203 ORDER BY `created` DESC LIMIT 1",
2204 dbesc($item['parent-uri']),
2205 intval($importer['importer_uid'])
2208 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2220 foreach($feed->get_items() as $item) {
2223 $item_id = $item->get_id();
2224 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2225 if(isset($rawthread[0]['attribs']['']['ref'])) {
2227 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2233 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2236 logger('local_delivery: possible community reply');
2239 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2241 // was the top-level post for this reply written by somebody on this site?
2242 // Specifically, the recipient?
2244 $is_a_remote_comment = false;
2246 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2247 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2248 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2249 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2250 AND `item`.`uid` = %d
2255 intval($importer['importer_uid'])
2258 $is_a_remote_comment = true;
2260 // Does this have the characteristics of a community or private group comment?
2261 // If it's a reply to a wall post on a community/prvgroup page it's a
2262 // valid community comment. Also forum_mode makes it valid for sure.
2263 // If neither, it's not.
2265 if($is_a_remote_comment && $community) {
2266 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2267 $is_a_remote_comment = false;
2268 logger('local_delivery: not a community reply');
2272 if($is_a_remote_comment) {
2273 logger('local_delivery: received remote comment');
2275 // remote reply to our post. Import and then notify everybody else.
2277 $datarray = get_atom_elements($feed,$item);
2279 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2281 intval($importer['importer_uid'])
2284 // Update content if 'updated' changes
2288 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2290 // do not accept (ignore) an earlier edit than one we currently have.
2291 if(datetime_convert('UTC','UTC',$datarray['edited'] < $r[0]['edited']))
2294 logger('received updated comment' , LOGGER_DEBUG);
2295 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2296 dbesc($datarray['title']),
2297 dbesc($datarray['body']),
2298 dbesc($datarray['tag']),
2299 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2301 intval($importer['importer_uid'])
2304 proc_run('php',"include/notifier.php","comment-import",$iid);
2312 // TODO: make this next part work against both delivery threads of a community post
2314 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2315 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2316 // they won't know what to do so don't report an error. Just quietly die.
2320 // our user with $importer['importer_uid'] is the owner
2322 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2323 intval($importer['importer_uid'])
2327 $datarray['type'] = 'remote-comment';
2328 $datarray['wall'] = 1;
2329 $datarray['parent-uri'] = $parent_uri;
2330 $datarray['uid'] = $importer['importer_uid'];
2331 $datarray['owner-name'] = $own[0]['name'];
2332 $datarray['owner-link'] = $own[0]['url'];
2333 $datarray['owner-avatar'] = $own[0]['thumb'];
2334 $datarray['contact-id'] = $importer['id'];
2336 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2338 $datarray['type'] = 'activity';
2339 $datarray['gravity'] = GRAVITY_LIKE;
2340 $datarray['last-child'] = 0;
2341 // only one like or dislike per person
2342 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2343 intval($datarray['uid']),
2344 intval($datarray['contact-id']),
2345 dbesc($datarray['verb'])
2351 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2353 $xo = parse_xml_string($datarray['object'],false);
2354 $xt = parse_xml_string($datarray['target'],false);
2356 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2358 // fetch the parent item
2360 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2362 intval($importer['importer_uid'])
2367 // extract tag, if not duplicate, and this user allows tags, add to parent item
2369 if($xo->id && $xo->content) {
2370 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2371 if(! (stristr($tagp[0]['tag'],$newtag))) {
2372 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2373 intval($importer['importer_uid'])
2375 if(count($i) && ! intval($i[0]['blocktags'])) {
2376 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2377 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2378 intval($tagp[0]['id']),
2379 dbesc(datetime_convert())
2388 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2389 // if(! stristr($datarray['tag'],$newtag)) {
2390 // if(strlen($datarray['tag']))
2391 // $datarray['tag'] .= ',';
2392 // $datarray['tag'] .= $newtag;
2397 $posted_id = item_store($datarray);
2401 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2403 intval($importer['importer_uid'])
2406 $parent = $r[0]['parent'];
2409 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2410 dbesc(datetime_convert()),
2411 intval($importer['importer_uid']),
2412 intval($r[0]['parent'])
2415 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2416 dbesc(datetime_convert()),
2417 intval($importer['importer_uid']),
2422 if($posted_id && $parent) {
2424 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2426 if((! $is_like) && (! $importer['self'])) {
2428 require_once('include/enotify.php');
2431 'type' => NOTIFY_COMMENT,
2432 'notify_flags' => $importer['notify-flags'],
2433 'language' => $importer['language'],
2434 'to_name' => $importer['username'],
2435 'to_email' => $importer['email'],
2436 'uid' => $importer['importer_uid'],
2437 'item' => $datarray,
2438 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2439 'source_name' => stripslashes($datarray['author-name']),
2440 'source_link' => $datarray['author-link'],
2441 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2442 ? $importer['thumb'] : $datarray['author-avatar']),
2443 'verb' => ACTIVITY_POST,
2445 'parent' => $parent,
2458 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2460 $item_id = $item->get_id();
2461 $datarray = get_atom_elements($feed,$item);
2463 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2465 intval($importer['importer_uid'])
2468 // Update content if 'updated' changes
2471 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2473 // do not accept (ignore) an earlier edit than one we currently have.
2474 if(datetime_convert('UTC','UTC',$datarray['edited'] < $r[0]['edited']))
2477 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2478 dbesc($datarray['title']),
2479 dbesc($datarray['body']),
2480 dbesc($datarray['tag']),
2481 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2483 intval($importer['importer_uid'])
2487 // update last-child if it changes
2489 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2490 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2491 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2492 dbesc(datetime_convert()),
2494 intval($importer['importer_uid'])
2496 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2497 intval($allow[0]['data']),
2498 dbesc(datetime_convert()),
2500 intval($importer['importer_uid'])
2506 $datarray['parent-uri'] = $parent_uri;
2507 $datarray['uid'] = $importer['importer_uid'];
2508 $datarray['contact-id'] = $importer['id'];
2509 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2510 $datarray['type'] = 'activity';
2511 $datarray['gravity'] = GRAVITY_LIKE;
2512 // only one like or dislike per person
2513 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2514 intval($datarray['uid']),
2515 intval($datarray['contact-id']),
2516 dbesc($datarray['verb'])
2523 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2525 $xo = parse_xml_string($datarray['object'],false);
2526 $xt = parse_xml_string($datarray['target'],false);
2528 if($xt->type == ACTIVITY_OBJ_NOTE) {
2529 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2531 intval($importer['importer_uid'])
2536 // extract tag, if not duplicate, add to parent item
2538 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2539 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2540 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2548 $posted_id = item_store($datarray);
2550 // find out if our user is involved in this conversation and wants to be notified.
2552 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2554 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2556 intval($importer['importer_uid'])
2559 if(count($myconv)) {
2560 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2562 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2563 if(! link_compare($datarray['author-link'],$importer_url)) {
2566 foreach($myconv as $conv) {
2568 // now if we find a match, it means we're in this conversation
2570 if(! link_compare($conv['author-link'],$importer_url))
2573 require_once('include/enotify.php');
2575 $conv_parent = $conv['parent'];
2578 'type' => NOTIFY_COMMENT,
2579 'notify_flags' => $importer['notify-flags'],
2580 'language' => $importer['language'],
2581 'to_name' => $importer['username'],
2582 'to_email' => $importer['email'],
2583 'uid' => $importer['importer_uid'],
2584 'item' => $datarray,
2585 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2586 'source_name' => stripslashes($datarray['author-name']),
2587 'source_link' => $datarray['author-link'],
2588 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2589 ? $importer['thumb'] : $datarray['author-avatar']),
2590 'verb' => ACTIVITY_POST,
2592 'parent' => $conv_parent,
2596 // only send one notification
2608 // Head post of a conversation. Have we seen it? If not, import it.
2611 $item_id = $item->get_id();
2612 $datarray = get_atom_elements($feed,$item);
2614 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2615 $ev = bbtoevent($datarray['body']);
2616 if(x($ev,'desc') && x($ev,'start')) {
2617 $ev['cid'] = $importer['id'];
2618 $ev['uid'] = $importer['uid'];
2619 $ev['uri'] = $item_id;
2620 $ev['edited'] = $datarray['edited'];
2621 $ev['private'] = $datarray['private'];
2623 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2625 intval($importer['uid'])
2628 $ev['id'] = $r[0]['id'];
2629 $xyz = event_store($ev);
2634 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2636 intval($importer['importer_uid'])
2639 // Update content if 'updated' changes
2642 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2644 // do not accept (ignore) an earlier edit than one we currently have.
2645 if(datetime_convert('UTC','UTC',$datarray['edited'] < $r[0]['edited']))
2648 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2649 dbesc($datarray['title']),
2650 dbesc($datarray['body']),
2651 dbesc($datarray['tag']),
2652 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2654 intval($importer['importer_uid'])
2658 // update last-child if it changes
2660 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2661 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2662 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2663 intval($allow[0]['data']),
2664 dbesc(datetime_convert()),
2666 intval($importer['importer_uid'])
2672 // This is my contact on another system, but it's really me.
2673 // Turn this into a wall post.
2675 if($importer['remote_self'])
2676 $datarray['wall'] = 1;
2678 $datarray['parent-uri'] = $item_id;
2679 $datarray['uid'] = $importer['importer_uid'];
2680 $datarray['contact-id'] = $importer['id'];
2682 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2683 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2684 // but otherwise there's a possible data mixup on the sender's system.
2685 // the tgroup delivery code called from item_store will correct it if it's a forum,
2686 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2687 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2688 $datarray['owner-name'] = $importer['senderName'];
2689 $datarray['owner-link'] = $importer['url'];
2690 $datarray['owner-avatar'] = $importer['thumb'];
2693 $r = item_store($datarray);
2704 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2705 $url = notags(trim($datarray['author-link']));
2706 $name = notags(trim($datarray['author-name']));
2707 $photo = notags(trim($datarray['author-avatar']));
2709 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2710 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2711 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2713 if(is_array($contact)) {
2714 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2715 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2716 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2717 intval(CONTACT_IS_FRIEND),
2718 intval($contact['id']),
2719 intval($importer['uid'])
2722 // send email notification to owner?
2726 // create contact record
2728 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2729 `blocked`, `readonly`, `pending`, `writable` )
2730 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2731 intval($importer['uid']),
2732 dbesc(datetime_convert()),
2734 dbesc(normalise_link($url)),
2738 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2739 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2741 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2742 intval($importer['uid']),
2746 $contact_record = $r[0];
2748 // create notification
2749 $hash = random_string();
2751 if(is_array($contact_record)) {
2752 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2753 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2754 intval($importer['uid']),
2755 intval($contact_record['id']),
2757 dbesc(datetime_convert())
2760 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2761 intval($importer['uid'])
2766 if(intval($r[0]['def_gid'])) {
2767 require_once('include/group.php');
2768 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2771 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2772 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2773 $email = replace_macros($email_tpl, array(
2774 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2776 '$myname' => $r[0]['username'],
2777 '$siteurl' => $a->get_baseurl(),
2778 '$sitename' => $a->config['sitename']
2780 $res = mail($r[0]['email'],
2781 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2783 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2784 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2785 . 'Content-transfer-encoding: 8bit' );
2792 function lose_follower($importer,$contact,$datarray,$item) {
2794 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2795 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2796 intval(CONTACT_IS_SHARING),
2797 intval($contact['id'])
2801 contact_remove($contact['id']);
2805 function lose_sharer($importer,$contact,$datarray,$item) {
2807 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2808 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2809 intval(CONTACT_IS_FOLLOWER),
2810 intval($contact['id'])
2814 contact_remove($contact['id']);
2819 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2823 if(is_array($importer)) {
2824 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2825 intval($importer['uid'])
2829 // Diaspora has different message-ids in feeds than they do
2830 // through the direct Diaspora protocol. If we try and use
2831 // the feed, we'll get duplicates. So don't.
2833 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2836 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2838 // Use a single verify token, even if multiple hubs
2840 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2842 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2844 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2846 if(! strlen($contact['hub-verify'])) {
2847 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2848 dbesc($verify_token),
2849 intval($contact['id'])
2853 post_url($url,$params);
2855 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
2862 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2866 $name = xmlify($name);
2867 $uri = xmlify($uri);
2870 $photo = xmlify($photo);
2874 $o .= "<name>$name</name>\r\n";
2875 $o .= "<uri>$uri</uri>\r\n";
2876 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2877 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2879 call_hooks('atom_author', $o);
2881 $o .= "</$tag>\r\n";
2885 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
2889 if(! $item['parent'])
2892 if($item['deleted'])
2893 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2896 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2897 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
2899 $body = $item['body'];
2902 $o = "\r\n\r\n<entry>\r\n";
2904 if(is_array($author))
2905 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2907 $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']));
2908 if(strlen($item['owner-name']))
2909 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2911 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2912 $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";
2914 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2915 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2916 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2917 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2918 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2919 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2920 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2922 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2924 if($item['location']) {
2925 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2926 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2930 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2932 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2933 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2936 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2937 if($item['bookmark'])
2938 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2941 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2944 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2946 if($item['signed_text']) {
2947 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2948 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2951 $verb = construct_verb($item);
2952 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2953 $actobj = construct_activity_object($item);
2956 $actarg = construct_activity_target($item);
2960 $tags = item_getfeedtags($item);
2962 foreach($tags as $t) {
2963 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2967 $o .= item_getfeedattach($item);
2969 $mentioned = get_mentions($item);
2973 call_hooks('atom_entry', $o);
2975 $o .= '</entry>' . "\r\n";
2980 function fix_private_photos($s,$uid, $item = null, $cid = 0) {
2983 logger('fix_private_photos', LOGGER_DEBUG);
2984 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
2986 if(preg_match("/\[img(.*?)\](.*?)\[\/img\]/is",$s,$matches)) {
2987 $image = $matches[2];
2988 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
2989 if(stristr($image , $site . '/photo/')) {
2991 $i = basename($image);
2992 $i = str_replace(array('.jpg','.png'),array('',''),$i);
2993 $x = strpos($i,'-');
2995 $res = substr($i,$x+1);
2996 $i = substr($i,0,$x);
2997 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3004 // Check to see if we should replace this photo link with an embedded image
3005 // 1. No need to do so if the photo is public
3006 // 2. If there's a contact-id provided, see if they're in the access list
3007 // for the photo. If so, embed it.
3008 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3009 // permissions, regardless of order but first check to see if they're an exact
3010 // match to save some processing overhead.
3012 // Currently we only embed one private photo per message so as not to hit import
3013 // size limits at the receiving end.
3015 // To embed multiples, we would need to parse out the embedded photos on message
3016 // receipt and limit size based only on the text component. Would also need to
3017 // ignore all photos during bbcode translation and item localisation, as these
3018 // will hit internal regex backtrace limits.
3020 if(has_permissions($r[0])) {
3022 $recips = enumerate_permissions($r[0]);
3023 if(in_array($cid, $recips)) {
3028 if(compare_permissions($item,$r[0]))
3033 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3034 $s = str_replace($image, 'data:' . $r[0]['type'] . ';base64,' . base64_encode($r[0]['data']), $s);
3035 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
3045 function has_permissions($obj) {
3046 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3051 function compare_permissions($obj1,$obj2) {
3052 // first part is easy. Check that these are exactly the same.
3053 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3054 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3055 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3056 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3059 // This is harder. Parse all the permissions and compare the resulting set.
3061 $recipients1 = enumerate_permissions($obj1);
3062 $recipients2 = enumerate_permissions($obj2);
3065 if($recipients1 == $recipients2)
3070 // returns an array of contact-ids that are allowed to see this object
3072 function enumerate_permissions($obj) {
3073 require_once('include/group.php');
3074 $allow_people = expand_acl($obj['allow_cid']);
3075 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3076 $deny_people = expand_acl($obj['deny_cid']);
3077 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3078 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3079 $deny = array_unique(array_merge($deny_people,$deny_groups));
3080 $recipients = array_diff($recipients,$deny);
3084 function item_getfeedtags($item) {
3087 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3089 for($x = 0; $x < $cnt; $x ++) {
3091 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3095 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3097 for($x = 0; $x < $cnt; $x ++) {
3099 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3105 function item_getfeedattach($item) {
3107 $arr = explode(',',$item['attach']);
3109 foreach($arr as $r) {
3111 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3113 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3114 if(intval($matches[2]))
3115 $ret .= 'length="' . intval($matches[2]) . '" ';
3116 if($matches[4] !== ' ')
3117 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3118 $ret .= ' />' . "\r\n";
3127 function item_expire($uid,$days) {
3129 if((! $uid) || ($days < 1))
3132 // $expire_network_only = save your own wall posts
3133 // and just expire conversations started by others
3135 $expire_network_only = get_pconfig($uid,'expire','network_only');
3136 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3138 $r = q("SELECT * FROM `item`
3140 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3151 $expire_items = get_pconfig($uid, 'expire','items');
3152 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3154 $expire_notes = get_pconfig($uid, 'expire','notes');
3155 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3157 $expire_starred = get_pconfig($uid, 'expire','starred');
3158 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3160 $expire_photos = get_pconfig($uid, 'expire','photos');
3161 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3163 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3165 foreach($r as $item) {
3167 // don't expire filed items
3169 if(strpos($item['file'],'[') !== false)
3172 // Only expire posts, not photos and photo comments
3174 if($expire_photos==0 && strlen($item['resource-id']))
3176 if($expire_starred==0 && intval($item['starred']))
3178 if($expire_notes==0 && $item['type']=='note')
3180 if($expire_items==0 && $item['type']!='note')
3183 drop_item($item['id'],false);
3186 proc_run('php',"include/notifier.php","expire","$uid");
3191 function drop_items($items) {
3194 if(! local_user() && ! remote_user())
3198 foreach($items as $item) {
3199 $owner = drop_item($item,false);
3200 if($owner && ! $uid)
3205 // multiple threads may have been deleted, send an expire notification
3208 proc_run('php',"include/notifier.php","expire","$uid");
3212 function drop_item($id,$interactive = true) {
3216 // locate item to be deleted
3218 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3225 notice( t('Item not found.') . EOL);
3226 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3231 $owner = $item['uid'];
3233 // check if logged in user is either the author or owner of this item
3235 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3239 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3240 dbesc(datetime_convert()),
3241 dbesc(datetime_convert()),
3245 // clean up categories and tags so they don't end up as orphans
3248 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3250 foreach($matches as $mtch) {
3251 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3257 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3259 foreach($matches as $mtch) {
3260 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3264 // If item is a link to a photo resource, nuke all the associated photos
3265 // (visitors will not have photo resources)
3266 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3267 // generate a resource-id and therefore aren't intimately linked to the item.
3269 if(strlen($item['resource-id'])) {
3270 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3271 dbesc($item['resource-id']),
3272 intval($item['uid'])
3274 // ignore the result
3277 // If item is a link to an event, nuke the event record.
3279 if(intval($item['event-id'])) {
3280 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3281 intval($item['event-id']),
3282 intval($item['uid'])
3284 // ignore the result
3287 // clean up item_id and sign meta-data tables
3289 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3290 intval($item['id']),
3291 intval($item['uid'])
3294 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3295 intval($item['id']),
3296 intval($item['uid'])
3299 // If it's the parent of a comment thread, kill all the kids
3301 if($item['uri'] == $item['parent-uri']) {
3302 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3303 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3304 dbesc(datetime_convert()),
3305 dbesc(datetime_convert()),
3306 dbesc($item['parent-uri']),
3307 intval($item['uid'])
3309 // ignore the result
3312 // ensure that last-child is set in case the comment that had it just got wiped.
3313 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3314 dbesc(datetime_convert()),
3315 dbesc($item['parent-uri']),
3316 intval($item['uid'])
3318 // who is the last child now?
3319 $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",
3320 dbesc($item['parent-uri']),
3321 intval($item['uid'])
3324 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3329 // Add a relayable_retraction signature for Diaspora. Note that we can't add a target_author_signature
3330 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
3331 // the comment, that means we're the home of the post, and Diaspora will only
3332 // check the parent_author_signature of retractions that it doesn't have to relay further
3334 // I don't think this function gets called for an "unlike," but I'll check anyway
3335 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
3337 if(local_user() == $item['uid']) {
3339 $handle = $a->user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
3340 $authorsig = base64_encode(rsa_sign($signed_text,$a->user['prvkey'],'sha256'));
3343 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
3347 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
3348 // only handles DFRN deletes
3349 $handle_baseurl_start = strpos($r['url'],'://') + 3;
3350 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
3351 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
3357 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
3358 intval($item['id']),
3359 dbesc($signed_text),
3364 $drop_id = intval($item['id']);
3366 // send the notification upstream/downstream as the case may be
3371 proc_run('php',"include/notifier.php","drop","$drop_id");
3372 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3378 notice( t('Permission denied.') . EOL);
3379 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);