3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
8 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
11 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
12 $public_feed = (($dfrn_id) ? false : true);
13 $starred = false; // not yet implemented, possible security issues
16 if($public_feed && $a->argc > 2) {
17 for($x = 2; $x < $a->argc; $x++) {
18 if($a->argv[$x] == 'converse')
20 if($a->argv[$x] == 'starred')
22 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
23 $category = $a->argv[$x+1];
31 // default permissions - anonymous user
33 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
35 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
36 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
37 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
45 $owner_id = $owner['user_uid'];
46 $owner_nick = $owner['nickname'];
48 $birthday = feed_birthday($owner_id,$owner['timezone']);
55 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
59 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60 $my_id = '1:' . $dfrn_id;
63 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
64 $my_id = '0:' . $dfrn_id;
71 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
79 $groups = init_groups_visitor($contact['id']);
82 for($x = 0; $x < count($groups); $x ++)
83 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
84 $gs = implode('|', $groups);
87 $gs = '<<>>' ; // Impossible to match
89 $sql_extra = sprintf("
90 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
91 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
92 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
93 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
95 intval($contact['id']),
96 intval($contact['id']),
107 if(! strlen($last_update))
108 $last_update = 'now -30 days';
110 if(isset($category)) {
111 $sql_extra .= file_tag_file_query('item',$category,'category');
116 $sql_extra .= " AND `contact`.`self` = 1 ";
119 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
121 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
122 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
123 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
124 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
125 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
126 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
127 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
128 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
129 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
130 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
131 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
133 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
140 // Will check further below if this actually returned results.
141 // We will provide an empty feed if that is the case.
145 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
149 $hubxml = feed_hublinks();
151 $salmon = feed_salmonlinks($owner_nick);
153 $atom .= replace_macros($feed_template, array(
154 '$version' => xmlify(FRIENDICA_VERSION),
155 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
156 '$feed_title' => xmlify($owner['name']),
157 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
159 '$salmon' => $salmon,
160 '$name' => xmlify($owner['name']),
161 '$profile_page' => xmlify($owner['url']),
162 '$photo' => xmlify($owner['photo']),
163 '$thumb' => xmlify($owner['thumb']),
164 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
165 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
166 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
167 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
168 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
171 call_hooks('atom_feed', $atom);
173 if(! count($items)) {
175 call_hooks('atom_feed_end', $atom);
177 $atom .= '</feed>' . "\r\n";
181 foreach($items as $item) {
183 // prevent private email from leaking.
184 if($item['network'] === NETWORK_MAIL)
187 // public feeds get html, our own nodes use bbcode
191 // catch any email that's in a public conversation and make sure it doesn't leak
199 $atom .= atom_entry($item,$type,null,$owner,true);
202 call_hooks('atom_feed_end', $atom);
204 $atom .= '</feed>' . "\r\n";
210 function construct_verb($item) {
212 return $item['verb'];
213 return ACTIVITY_POST;
216 function construct_activity_object($item) {
218 if($item['object']) {
219 $o = '<as:object>' . "\r\n";
220 $r = parse_xml_string($item['object'],false);
226 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
228 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
230 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
232 if(substr($r->link,0,1) === '<') {
233 // patch up some facebook "like" activity objects that got stored incorrectly
234 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
235 // we can probably remove this hack here and in the following function in a few months time.
236 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
237 $r->link = str_replace('&','&', $r->link);
238 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
242 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
245 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
246 $o .= '</as:object>' . "\r\n";
253 function construct_activity_target($item) {
255 if($item['target']) {
256 $o = '<as:target>' . "\r\n";
257 $r = parse_xml_string($item['target'],false);
261 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
263 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
265 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
267 if(substr($r->link,0,1) === '<') {
268 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
269 $r->link = str_replace('&','&', $r->link);
270 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
274 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
277 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
278 $o .= '</as:target>' . "\r\n";
288 function get_atom_elements($feed,$item) {
290 require_once('library/HTMLPurifier.auto.php');
291 require_once('include/html2bbcode.php');
293 $best_photo = array();
297 $author = $item->get_author();
299 $res['author-name'] = unxmlify($author->get_name());
300 $res['author-link'] = unxmlify($author->get_link());
303 $res['author-name'] = unxmlify($feed->get_title());
304 $res['author-link'] = unxmlify($feed->get_permalink());
306 $res['uri'] = unxmlify($item->get_id());
307 $res['title'] = unxmlify($item->get_title());
308 $res['body'] = unxmlify($item->get_content());
309 $res['plink'] = unxmlify($item->get_link(0));
312 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
316 // look for a photo. We should check media size and find the best one,
317 // but for now let's just find any author photo
319 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
321 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
322 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
323 foreach($base as $link) {
324 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
325 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
326 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
331 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
333 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
334 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
335 if($base && count($base)) {
336 foreach($base as $link) {
337 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
338 $res['author-link'] = unxmlify($link['attribs']['']['href']);
339 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
340 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
341 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
347 // No photo/profile-link on the item - look at the feed level
349 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
350 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
351 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
352 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
353 foreach($base as $link) {
354 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
355 $res['author-link'] = unxmlify($link['attribs']['']['href']);
356 if(! $res['author-avatar']) {
357 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
358 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
363 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
365 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
366 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
368 if($base && count($base)) {
369 foreach($base as $link) {
370 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
371 $res['author-link'] = unxmlify($link['attribs']['']['href']);
372 if(! (x($res,'author-avatar'))) {
373 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
374 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
381 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
382 if($apps && $apps[0]['attribs']['']['source']) {
383 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
384 if($res['app'] === 'web')
385 $res['app'] = 'OStatus';
388 // base64 encoded json structure representing Diaspora signature
390 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
392 $res['dsprsig'] = unxmlify($dsig[0]['data']);
395 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
397 $res['guid'] = unxmlify($dguid[0]['data']);
399 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
401 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
405 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
408 $have_real_body = false;
410 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
412 $have_real_body = true;
413 $res['body'] = $rawenv[0]['data'];
414 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
415 // make sure nobody is trying to sneak some html tags by us
416 $res['body'] = notags(base64url_decode($res['body']));
419 $maxlen = get_max_import_size();
420 if($maxlen && (strlen($res['body']) > $maxlen))
421 $res['body'] = substr($res['body'],0, $maxlen);
423 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
424 // the content type. Our own network only emits text normally, though it might have been converted to
425 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
426 // have to assume it is all html and needs to be purified.
428 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
429 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
430 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
433 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
435 $res['body'] = reltoabs($res['body'],$base_url);
437 $res['body'] = html2bb_video($res['body']);
439 $res['body'] = oembed_html2bbcode($res['body']);
441 $config = HTMLPurifier_Config::createDefault();
442 $config->set('Cache.DefinitionImpl', null);
444 // we shouldn't need a whitelist, because the bbcode converter
445 // will strip out any unsupported tags.
447 $purifier = new HTMLPurifier($config);
448 $res['body'] = $purifier->purify($res['body']);
450 $res['body'] = @html2bbcode($res['body']);
452 elseif(! $have_real_body) {
454 // it's not one of our messages and it has no tags
455 // so it's probably just text. We'll escape it just to be safe.
457 $res['body'] = escape_tags($res['body']);
460 // this tag is obsolete but we keep it for really old sites
462 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
463 if($allow && $allow[0]['data'] == 1)
464 $res['last-child'] = 1;
466 $res['last-child'] = 0;
468 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
469 if($private && $private[0]['data'] == 1)
474 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
475 if($extid && $extid[0]['data'])
476 $res['extid'] = $extid[0]['data'];
478 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
480 $res['location'] = unxmlify($rawlocation[0]['data']);
483 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
485 $res['created'] = unxmlify($rawcreated[0]['data']);
488 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
490 $res['edited'] = unxmlify($rawedited[0]['data']);
492 if((x($res,'edited')) && (! (x($res,'created'))))
493 $res['created'] = $res['edited'];
495 if(! $res['created'])
496 $res['created'] = $item->get_date('c');
499 $res['edited'] = $item->get_date('c');
502 // Disallow time travelling posts
504 $d1 = strtotime($res['created']);
505 $d2 = strtotime($res['edited']);
506 $d3 = strtotime('now');
509 $res['created'] = datetime_convert();
511 $res['edited'] = datetime_convert();
513 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
514 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
515 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
516 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
517 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
518 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
519 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
520 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
521 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
523 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
524 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
526 foreach($base as $link) {
527 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
528 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
529 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
534 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
536 $res['coord'] = unxmlify($rawgeo[0]['data']);
539 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
541 // select between supported verbs
544 $res['verb'] = unxmlify($rawverb[0]['data']);
547 // translate OStatus unfollow to activity streams if it happened to get selected
549 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
550 $res['verb'] = ACTIVITY_UNFOLLOW;
552 $cats = $item->get_categories();
555 foreach($cats as $cat) {
556 $term = $cat->get_term();
558 $term = $cat->get_label();
559 $scheme = $cat->get_scheme();
560 if($scheme && $term && stristr($scheme,'X-DFRN:'))
561 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
563 $tag_arr[] = notags(trim($term));
565 $res['tag'] = implode(',', $tag_arr);
568 $attach = $item->get_enclosures();
571 foreach($attach as $att) {
572 $len = intval($att->get_length());
573 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
574 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
575 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
576 if(strpos($type,';'))
577 $type = substr($type,0,strpos($type,';'));
578 if((! $link) || (strpos($link,'http') !== 0))
584 $type = 'application/octet-stream';
586 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
588 $res['attach'] = implode(',', $att_arr);
591 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
594 $res['object'] = '<object>' . "\n";
595 $child = $rawobj[0]['child'];
596 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
597 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
598 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
600 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
601 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
602 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
603 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
604 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
605 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
606 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
607 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
609 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
610 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
611 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
612 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
614 $body = html2bb_video($body);
616 $config = HTMLPurifier_Config::createDefault();
617 $config->set('Cache.DefinitionImpl', null);
619 $purifier = new HTMLPurifier($config);
620 $body = $purifier->purify($body);
621 $body = html2bbcode($body);
624 $res['object'] .= '<content>' . $body . '</content>' . "\n";
627 $res['object'] .= '</object>' . "\n";
630 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
633 $res['target'] = '<target>' . "\n";
634 $child = $rawobj[0]['child'];
635 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
636 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
638 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
639 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
640 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
641 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
642 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
643 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
644 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
645 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
647 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
648 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
649 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
650 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
652 $body = html2bb_video($body);
654 $config = HTMLPurifier_Config::createDefault();
655 $config->set('Cache.DefinitionImpl', null);
657 $purifier = new HTMLPurifier($config);
658 $body = $purifier->purify($body);
659 $body = html2bbcode($body);
662 $res['target'] .= '<content>' . $body . '</content>' . "\n";
665 $res['target'] .= '</target>' . "\n";
668 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
670 call_hooks('parse_atom', $arr);
675 function encode_rel_links($links) {
677 if(! ((is_array($links)) && (count($links))))
679 foreach($links as $link) {
681 if($link['attribs']['']['rel'])
682 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
683 if($link['attribs']['']['type'])
684 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
685 if($link['attribs']['']['href'])
686 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
687 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
688 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
689 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
690 $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'];
812 // Allow one to see reply tweets from status.net even when
813 // we don't have or can't see the original post.
816 logger('item_store: $force_parent=true, reply converted to top-level post.');
818 $arr['thr-parent'] = $arr['parent-uri'];
819 $arr['parent-uri'] = $arr['uri'];
823 logger('item_store: item parent was not found - ignoring item');
831 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
835 if($r && count($r)) {
836 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
840 call_hooks('post_remote',$arr);
842 if(x($arr,'cancel')) {
843 logger('item_store: post cancelled by plugin.');
849 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
851 $r = dbq("INSERT INTO `item` (`"
852 . implode("`, `", array_keys($arr))
854 . implode("', '", array_values($arr))
857 // find the item we just created
859 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
860 $arr['uri'], // already dbesc'd
865 $current_post = $r[0]['id'];
866 logger('item_store: created item ' . $current_post);
869 logger('item_store: could not locate created item');
873 logger('item_store: duplicated post occurred. Removing duplicates.');
874 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
877 intval($current_post)
881 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
882 $parent_id = $current_post;
884 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
887 $private = $arr['private'];
889 // Set parent id - and also make sure to inherit the parent's ACL's.
891 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
892 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
899 intval($parent_deleted),
900 intval($current_post)
903 // update the commented timestamp on the parent
905 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
906 dbesc(datetime_convert()),
907 dbesc(datetime_convert()),
912 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
913 intval($current_post),
914 dbesc($dsprsig->signed_text),
915 dbesc($dsprsig->signature),
916 dbesc($dsprsig->signer)
922 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
925 if($arr['last-child']) {
926 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
929 intval($current_post)
933 tag_deliver($arr['uid'],$current_post);
935 return $current_post;
938 function get_item_contact($item,$contacts) {
939 if(! count($contacts) || (! is_array($item)))
941 foreach($contacts as $contact) {
942 if($contact['id'] == $item['contact-id']) {
951 function tag_deliver($uid,$item_id) {
953 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
959 $u = q("select * from user where uid = %d limit 1",
965 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
966 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
969 $i = q("select * from item where id = %d and uid = %d limit 1",
978 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
980 // Diaspora uses their own hardwired link URL in @-tags
981 // instead of the one we supply with webfinger
983 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
985 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
987 foreach($matches as $mtch) {
988 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
990 logger('tag_deliver: mention found: ' . $mtch[2]);
998 // send a notification
1000 require_once('include/enotify.php');
1002 'type' => NOTIFY_TAGSELF,
1003 'notify_flags' => $u[0]['notify-flags'],
1004 'language' => $u[0]['language'],
1005 'to_name' => $u[0]['username'],
1006 'to_email' => $u[0]['email'],
1007 'uid' => $u[0]['uid'],
1009 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1010 'source_name' => $item['author-name'],
1011 'source_link' => $item['author-link'],
1012 'source_photo' => $item['author-avatar'],
1013 'verb' => ACTIVITY_TAG,
1017 if((! $community_page) && (! $prvgroup))
1021 // tgroup delivery - setup a second delivery chain
1022 // prevent delivery looping - only proceed
1023 // if the message originated elsewhere and is a top-level post
1025 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1028 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1031 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1032 intval($u[0]['uid'])
1037 // also reset all the privacy bits to the forum default permissions
1039 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1041 $forum_mode = (($prvgroup) ? 2 : 1);
1043 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1044 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1045 intval($forum_mode),
1046 dbesc($c[0]['name']),
1047 dbesc($c[0]['url']),
1048 dbesc($c[0]['thumb']),
1050 dbesc($u[0]['allow_cid']),
1051 dbesc($u[0]['allow_gid']),
1052 dbesc($u[0]['deny_cid']),
1053 dbesc($u[0]['deny_gid']),
1057 proc_run('php','include/notifier.php','tgroup',$item_id);
1066 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1070 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1072 if($contact['duplex'] && $contact['dfrn-id'])
1073 $idtosend = '0:' . $orig_id;
1074 if($contact['duplex'] && $contact['issued-id'])
1075 $idtosend = '1:' . $orig_id;
1077 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1079 $rino_enable = get_config('system','rino_encrypt');
1084 $ssl_val = intval(get_config('system','ssl_policy'));
1088 case SSL_POLICY_FULL:
1089 $ssl_policy = 'full';
1091 case SSL_POLICY_SELFSIGN:
1092 $ssl_policy = 'self';
1094 case SSL_POLICY_NONE:
1096 $ssl_policy = 'none';
1100 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1102 logger('dfrn_deliver: ' . $url);
1104 $xml = fetch_url($url);
1106 $curl_stat = $a->get_curl_code();
1108 return(-1); // timed out
1110 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1115 if(strpos($xml,'<?xml') === false) {
1116 logger('dfrn_deliver: no valid XML returned');
1117 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1121 $res = parse_xml_string($xml);
1123 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1124 return (($res->status) ? $res->status : 3);
1126 $postvars = array();
1127 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1128 $challenge = hex2bin((string) $res->challenge);
1129 $perm = (($res->perm) ? $res->perm : null);
1130 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1131 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1132 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1134 if($owner['page-flags'] == PAGE_PRVGROUP)
1137 $final_dfrn_id = '';
1140 if((($perm == 'rw') && (! intval($contact['writable'])))
1141 || (($perm == 'r') && (intval($contact['writable'])))) {
1142 q("update contact set writable = %d where id = %d limit 1",
1143 intval(($perm == 'rw') ? 1 : 0),
1144 intval($contact['id'])
1146 $contact['writable'] = (string) 1 - intval($contact['writable']);
1150 if(($contact['duplex'] && strlen($contact['pubkey']))
1151 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1152 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1153 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1154 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1157 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1158 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1161 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1163 if(strpos($final_dfrn_id,':') == 1)
1164 $final_dfrn_id = substr($final_dfrn_id,2);
1166 if($final_dfrn_id != $orig_id) {
1167 logger('dfrn_deliver: wrong dfrn_id.');
1168 // did not decode properly - cannot trust this site
1172 $postvars['dfrn_id'] = $idtosend;
1173 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1175 $postvars['dissolve'] = '1';
1178 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1179 $postvars['data'] = $atom;
1180 $postvars['perm'] = 'rw';
1183 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1184 $postvars['perm'] = 'r';
1187 $postvars['ssl_policy'] = $ssl_policy;
1190 $postvars['page'] = $page;
1192 if($rino && $rino_allowed && (! $dissolve)) {
1193 $key = substr(random_string(),0,16);
1194 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1195 $postvars['data'] = $data;
1196 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1199 if($dfrn_version >= 2.1) {
1200 if(($contact['duplex'] && strlen($contact['pubkey']))
1201 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1202 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1204 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1207 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1211 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1212 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1215 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1219 logger('md5 rawkey ' . md5($postvars['key']));
1221 $postvars['key'] = bin2hex($postvars['key']);
1224 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1226 $xml = post_url($contact['notify'],$postvars);
1228 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1230 $curl_stat = $a->get_curl_code();
1231 if((! $curl_stat) || (! strlen($xml)))
1232 return(-1); // timed out
1234 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1237 if(strpos($xml,'<?xml') === false) {
1238 logger('dfrn_deliver: phase 2: no valid XML returned');
1239 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1243 $res = parse_xml_string($xml);
1245 return $res->status;
1251 * consume_feed - process atom feed and update anything/everything we might need to update
1253 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1255 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1256 * It is this person's stuff that is going to be updated.
1257 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1258 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1259 * have a contact record.
1260 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1261 * might not) try and subscribe to it.
1262 * $datedir sorts in reverse order
1263 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1264 * imported prior to its children being seen in the stream unless we are certain
1265 * of how the feed is arranged/ordered.
1266 * With $pass = 1, we only pull parent items out of the stream.
1267 * With $pass = 2, we only pull children (comments/likes).
1269 * So running this twice, first with pass 1 and then with pass 2 will do the right
1270 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1271 * model where comments can have sub-threads. That would require some massive sorting
1272 * to get all the feed items into a mostly linear ordering, and might still require
1276 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1278 require_once('library/simplepie/simplepie.inc');
1280 if(! strlen($xml)) {
1281 logger('consume_feed: empty input');
1285 $feed = new SimplePie();
1286 $feed->set_raw_data($xml);
1288 $feed->enable_order_by_date(true);
1290 $feed->enable_order_by_date(false);
1294 logger('consume_feed: Error parsing XML: ' . $feed->error());
1296 $permalink = $feed->get_permalink();
1298 // Check at the feed level for updated contact name and/or photo
1302 $photo_timestamp = '';
1306 $hubs = $feed->get_links('hub');
1309 $hub = implode(',', $hubs);
1311 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1313 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1315 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1316 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1317 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1318 $new_name = $elems['name'][0]['data'];
1320 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1321 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1322 $photo_url = $elems['link'][0]['attribs']['']['href'];
1325 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1326 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1330 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1331 logger('consume_feed: Updating photo for ' . $contact['name']);
1332 require_once("Photo.php");
1333 $photo_failure = false;
1334 $have_photo = false;
1336 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1337 intval($contact['id']),
1338 intval($contact['uid'])
1341 $resource_id = $r[0]['resource-id'];
1345 $resource_id = photo_new_resource();
1348 $img_str = fetch_url($photo_url,true);
1349 $img = new Photo($img_str);
1350 if($img->is_valid()) {
1352 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1353 dbesc($resource_id),
1354 intval($contact['id']),
1355 intval($contact['uid'])
1359 $img->scaleImageSquare(175);
1361 $hash = $resource_id;
1362 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1364 $img->scaleImage(80);
1365 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1367 $img->scaleImage(48);
1368 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1372 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1373 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1374 dbesc(datetime_convert()),
1375 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1376 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1377 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1378 intval($contact['uid']),
1379 intval($contact['id'])
1384 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1385 $r = q("select * from contact where uid = %d and id = %d limit 1",
1386 intval($contact['uid']),
1387 intval($contact['id'])
1390 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1391 dbesc(notags(trim($new_name))),
1392 dbesc(datetime_convert()),
1393 intval($contact['uid']),
1394 intval($contact['id'])
1397 // do our best to update the name on content items
1400 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1401 dbesc(notags(trim($new_name))),
1402 dbesc($r[0]['name']),
1403 dbesc($r[0]['url']),
1404 intval($contact['uid'])
1409 if(strlen($birthday)) {
1410 if(substr($birthday,0,4) != $contact['bdyear']) {
1411 logger('consume_feed: updating birthday: ' . $birthday);
1415 * Add new birthday event for this person
1417 * $bdtext is just a readable placeholder in case the event is shared
1418 * with others. We will replace it during presentation to our $importer
1419 * to contain a sparkle link and perhaps a photo.
1423 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1426 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1427 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1428 intval($contact['uid']),
1429 intval($contact['id']),
1430 dbesc(datetime_convert()),
1431 dbesc(datetime_convert()),
1432 dbesc(datetime_convert('UTC','UTC', $birthday)),
1433 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1441 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1442 dbesc(substr($birthday,0,4)),
1443 intval($contact['uid']),
1444 intval($contact['id'])
1447 // This function is called twice without reloading the contact
1448 // Make sure we only create one event. This is why &$contact
1449 // is a reference var in this function
1451 $contact['bdyear'] = substr($birthday,0,4);
1456 $community_page = 0;
1457 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1459 $community_page = intval($rawtags[0]['data']);
1461 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1462 q("update contact set forum = %d where id = %d limit 1",
1463 intval($community_page),
1464 intval($contact['id'])
1466 $contact['forum'] = (string) $community_page;
1470 // process any deleted entries
1472 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1473 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1474 foreach($del_entries as $dentry) {
1476 if(isset($dentry['attribs']['']['ref'])) {
1477 $uri = $dentry['attribs']['']['ref'];
1479 if(isset($dentry['attribs']['']['when'])) {
1480 $when = $dentry['attribs']['']['when'];
1481 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1484 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1486 if($deleted && is_array($contact)) {
1487 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1488 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1490 intval($importer['uid']),
1491 intval($contact['id'])
1496 if(! $item['deleted'])
1497 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1499 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1500 $xo = parse_xml_string($item['object'],false);
1501 $xt = parse_xml_string($item['target'],false);
1502 if($xt->type === ACTIVITY_OBJ_NOTE) {
1503 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1505 intval($importer['importer_uid'])
1509 // For tags, the owner cannot remove the tag on the author's copy of the post.
1511 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1512 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1513 $author_copy = (($item['origin']) ? true : false);
1515 if($owner_remove && $author_copy)
1517 if($author_remove || $owner_remove) {
1518 $tags = explode(',',$i[0]['tag']);
1521 foreach($tags as $tag)
1522 if(trim($tag) !== trim($xo->body))
1523 $newtags[] = trim($tag);
1525 q("update item set tag = '%s' where id = %d limit 1",
1526 dbesc(implode(',',$newtags)),
1534 if($item['uri'] == $item['parent-uri']) {
1535 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1536 `body` = '', `title` = ''
1537 WHERE `parent-uri` = '%s' AND `uid` = %d",
1539 dbesc(datetime_convert()),
1540 dbesc($item['uri']),
1541 intval($importer['uid'])
1545 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1546 `body` = '', `title` = ''
1547 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1549 dbesc(datetime_convert()),
1551 intval($importer['uid'])
1553 if($item['last-child']) {
1554 // ensure that last-child is set in case the comment that had it just got wiped.
1555 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1556 dbesc(datetime_convert()),
1557 dbesc($item['parent-uri']),
1558 intval($item['uid'])
1560 // who is the last child now?
1561 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1562 ORDER BY `created` DESC LIMIT 1",
1563 dbesc($item['parent-uri']),
1564 intval($importer['uid'])
1567 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1578 // Now process the feed
1580 if($feed->get_item_quantity()) {
1582 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1584 // in inverse date order
1586 $items = array_reverse($feed->get_items());
1588 $items = $feed->get_items();
1591 foreach($items as $item) {
1594 $item_id = $item->get_id();
1595 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1596 if(isset($rawthread[0]['attribs']['']['ref'])) {
1598 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1601 if(($is_reply) && is_array($contact)) {
1606 // Have we seen it? If not, import it.
1608 $item_id = $item->get_id();
1609 $datarray = get_atom_elements($feed,$item);
1612 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1613 $datarray['author-name'] = $contact['name'];
1614 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1615 $datarray['author-link'] = $contact['url'];
1616 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1617 $datarray['author-avatar'] = $contact['thumb'];
1619 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1620 logger('consume_feed: no author information! ' . print_r($datarray,true));
1624 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1626 intval($importer['uid'])
1629 // Update content if 'updated' changes
1632 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1633 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1634 dbesc($datarray['title']),
1635 dbesc($datarray['body']),
1636 dbesc($datarray['tag']),
1637 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1639 intval($importer['uid'])
1643 // update last-child if it changes
1645 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1646 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1647 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1648 dbesc(datetime_convert()),
1650 intval($importer['uid'])
1652 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1653 intval($allow[0]['data']),
1654 dbesc(datetime_convert()),
1656 intval($importer['uid'])
1662 $force_parent = false;
1663 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1664 if($contact['network'] === NETWORK_OSTATUS)
1665 $force_parent = true;
1666 if(strlen($datarray['title']))
1667 unset($datarray['title']);
1668 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1669 dbesc(datetime_convert()),
1671 intval($importer['uid'])
1673 $datarray['last-child'] = 1;
1676 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1677 // one way feed - no remote comment ability
1678 $datarray['last-child'] = 0;
1680 $datarray['parent-uri'] = $parent_uri;
1681 $datarray['uid'] = $importer['uid'];
1682 $datarray['contact-id'] = $contact['id'];
1683 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1684 $datarray['type'] = 'activity';
1685 $datarray['gravity'] = GRAVITY_LIKE;
1686 // only one like or dislike per person
1687 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1688 intval($datarray['uid']),
1689 intval($datarray['contact-id']),
1690 dbesc($datarray['verb'])
1696 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1697 $xo = parse_xml_string($datarray['object'],false);
1698 $xt = parse_xml_string($datarray['target'],false);
1700 if($xt->type == ACTIVITY_OBJ_NOTE) {
1701 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1703 intval($importer['importer_uid'])
1708 // extract tag, if not duplicate, add to parent item
1709 if($xo->id && $xo->content) {
1710 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1711 if(! (stristr($r[0]['tag'],$newtag))) {
1712 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1713 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1721 $r = item_store($datarray,$force_parent);
1727 // Head post of a conversation. Have we seen it? If not, import it.
1729 $item_id = $item->get_id();
1731 $datarray = get_atom_elements($feed,$item);
1733 if(is_array($contact)) {
1734 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1735 $datarray['author-name'] = $contact['name'];
1736 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1737 $datarray['author-link'] = $contact['url'];
1738 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1739 $datarray['author-avatar'] = $contact['thumb'];
1742 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1743 logger('consume_feed: no author information! ' . print_r($datarray,true));
1747 // special handling for events
1749 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1750 $ev = bbtoevent($datarray['body']);
1751 if(x($ev,'desc') && x($ev,'start')) {
1752 $ev['uid'] = $importer['uid'];
1753 $ev['uri'] = $item_id;
1754 $ev['edited'] = $datarray['edited'];
1755 $ev['private'] = $datarray['private'];
1757 if(is_array($contact))
1758 $ev['cid'] = $contact['id'];
1759 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1761 intval($importer['uid'])
1764 $ev['id'] = $r[0]['id'];
1765 $xyz = event_store($ev);
1770 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1772 intval($importer['uid'])
1775 // Update content if 'updated' changes
1778 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1779 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1780 dbesc($datarray['title']),
1781 dbesc($datarray['body']),
1782 dbesc($datarray['tag']),
1783 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1785 intval($importer['uid'])
1789 // update last-child if it changes
1791 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1792 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1793 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1794 intval($allow[0]['data']),
1795 dbesc(datetime_convert()),
1797 intval($importer['uid'])
1803 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1804 logger('consume-feed: New follower');
1805 new_follower($importer,$contact,$datarray,$item);
1808 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1809 lose_follower($importer,$contact,$datarray,$item);
1813 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1814 logger('consume-feed: New friend request');
1815 new_follower($importer,$contact,$datarray,$item,true);
1818 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1819 lose_sharer($importer,$contact,$datarray,$item);
1824 if(! is_array($contact))
1827 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1828 if(strlen($datarray['title']))
1829 unset($datarray['title']);
1830 $datarray['last-child'] = 1;
1833 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1834 // one way feed - no remote comment ability
1835 $datarray['last-child'] = 0;
1838 // This is my contact on another system, but it's really me.
1839 // Turn this into a wall post.
1841 if($contact['remote_self'])
1842 $datarray['wall'] = 1;
1844 $datarray['parent-uri'] = $item_id;
1845 $datarray['uid'] = $importer['uid'];
1846 $datarray['contact-id'] = $contact['id'];
1848 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1849 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1850 // but otherwise there's a possible data mixup on the sender's system.
1851 // the tgroup delivery code called from item_store will correct it if it's a forum,
1852 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1853 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1854 $datarray['owner-name'] = $contact['name'];
1855 $datarray['owner-link'] = $contact['url'];
1856 $datarray['owner-avatar'] = $contact['thumb'];
1859 $r = item_store($datarray);
1867 function local_delivery($importer,$data) {
1871 if($importer['readonly']) {
1872 // We aren't receiving stuff from this person. But we will quietly ignore them
1873 // rather than a blatant "go away" message.
1874 logger('local_delivery: ignoring');
1879 // Consume notification feed. This may differ from consuming a public feed in several ways
1880 // - might contain email or friend suggestions
1881 // - might contain remote followup to our message
1882 // - in which case we need to accept it and then notify other conversants
1883 // - we may need to send various email notifications
1885 $feed = new SimplePie();
1886 $feed->set_raw_data($data);
1887 $feed->enable_order_by_date(false);
1891 // Currently unsupported - needs a lot of work
1892 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1893 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1894 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1896 $newloc['uid'] = $importer['importer_uid'];
1897 $newloc['cid'] = $importer['id'];
1898 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1899 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1900 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1901 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1902 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1903 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1904 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1905 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1906 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1907 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1910 // merge with current record, current contents have priority
1911 // update record, set url-updated
1912 // update profile photos
1918 // handle friend suggestion notification
1920 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1921 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1922 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1924 $fsugg['uid'] = $importer['importer_uid'];
1925 $fsugg['cid'] = $importer['id'];
1926 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1927 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1928 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1929 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1930 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1932 // Does our member already have a friend matching this description?
1934 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1935 dbesc($fsugg['name']),
1936 dbesc(normalise_link($fsugg['url'])),
1937 intval($fsugg['uid'])
1942 // Do we already have an fcontact record for this person?
1945 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1946 dbesc($fsugg['url']),
1947 dbesc($fsugg['name']),
1948 dbesc($fsugg['request'])
1953 // OK, we do. Do we already have an introduction for this person ?
1954 $r = q("select id from intro where uid = %d and fid = %d limit 1",
1955 intval($fsugg['uid']),
1962 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1963 dbesc($fsugg['name']),
1964 dbesc($fsugg['url']),
1965 dbesc($fsugg['photo']),
1966 dbesc($fsugg['request'])
1968 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1969 dbesc($fsugg['url']),
1970 dbesc($fsugg['name']),
1971 dbesc($fsugg['request'])
1976 // database record did not get created. Quietly give up.
1981 $hash = random_string();
1983 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1984 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1985 intval($fsugg['uid']),
1987 intval($fsugg['cid']),
1988 dbesc($fsugg['body']),
1990 dbesc(datetime_convert()),
1995 'type' => NOTIFY_SUGGEST,
1996 'notify_flags' => $importer['notify-flags'],
1997 'language' => $importer['language'],
1998 'to_name' => $importer['username'],
1999 'to_email' => $importer['email'],
2000 'uid' => $importer['importer_uid'],
2002 'link' => $a->get_baseurl() . '/notifications/intros',
2003 'source_name' => $importer['name'],
2004 'source_link' => $importer['url'],
2005 'source_photo' => $importer['photo'],
2006 'verb' => ACTIVITY_REQ_FRIEND,
2015 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2016 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2018 logger('local_delivery: private message received');
2021 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2024 $msg['uid'] = $importer['importer_uid'];
2025 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2026 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2027 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2028 $msg['contact-id'] = $importer['id'];
2029 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2030 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2032 $msg['replied'] = 0;
2033 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2034 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2035 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2039 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2040 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2042 // send notifications.
2044 require_once('include/enotify.php');
2046 $notif_params = array(
2047 'type' => NOTIFY_MAIL,
2048 'notify_flags' => $importer['notify-flags'],
2049 'language' => $importer['language'],
2050 'to_name' => $importer['username'],
2051 'to_email' => $importer['email'],
2052 'uid' => $importer['importer_uid'],
2054 'source_name' => $msg['from-name'],
2055 'source_link' => $importer['url'],
2056 'source_photo' => $importer['thumb'],
2057 'verb' => ACTIVITY_POST,
2061 notification($notif_params);
2067 $community_page = 0;
2068 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2070 $community_page = intval($rawtags[0]['data']);
2072 if(intval($importer['forum']) != $community_page) {
2073 q("update contact set forum = %d where id = %d limit 1",
2074 intval($community_page),
2075 intval($importer['id'])
2077 $importer['forum'] = (string) $community_page;
2080 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2082 // process any deleted entries
2084 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2085 if(is_array($del_entries) && count($del_entries)) {
2086 foreach($del_entries as $dentry) {
2088 if(isset($dentry['attribs']['']['ref'])) {
2089 $uri = $dentry['attribs']['']['ref'];
2091 if(isset($dentry['attribs']['']['when'])) {
2092 $when = $dentry['attribs']['']['when'];
2093 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2096 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2100 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2101 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2103 intval($importer['importer_uid']),
2104 intval($importer['id'])
2110 if($item['deleted'])
2113 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2115 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2116 $xo = parse_xml_string($item['object'],false);
2117 $xt = parse_xml_string($item['target'],false);
2119 if($xt->type === ACTIVITY_OBJ_NOTE) {
2120 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2122 intval($importer['importer_uid'])
2126 // For tags, the owner cannot remove the tag on the author's copy of the post.
2128 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2129 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2130 $author_copy = (($item['origin']) ? true : false);
2132 if($owner_remove && $author_copy)
2134 if($author_remove || $owner_remove) {
2135 $tags = explode(',',$i[0]['tag']);
2138 foreach($tags as $tag)
2139 if(trim($tag) !== trim($xo->body))
2140 $newtags[] = trim($tag);
2142 q("update item set tag = '%s' where id = %d limit 1",
2143 dbesc(implode(',',$newtags)),
2151 if($item['uri'] == $item['parent-uri']) {
2152 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2153 WHERE `parent-uri` = '%s' AND `uid` = %d",
2155 dbesc(datetime_convert()),
2156 dbesc($item['uri']),
2157 intval($importer['importer_uid'])
2161 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2162 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2164 dbesc(datetime_convert()),
2166 intval($importer['importer_uid'])
2168 if($item['last-child']) {
2169 // ensure that last-child is set in case the comment that had it just got wiped.
2170 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2171 dbesc(datetime_convert()),
2172 dbesc($item['parent-uri']),
2173 intval($item['uid'])
2175 // who is the last child now?
2176 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2177 ORDER BY `created` DESC LIMIT 1",
2178 dbesc($item['parent-uri']),
2179 intval($importer['importer_uid'])
2182 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2194 foreach($feed->get_items() as $item) {
2197 $item_id = $item->get_id();
2198 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2199 if(isset($rawthread[0]['attribs']['']['ref'])) {
2201 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2207 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2210 logger('local_delivery: possible community reply');
2213 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2215 // was the top-level post for this reply written by somebody on this site?
2216 // Specifically, the recipient?
2218 $is_a_remote_comment = false;
2220 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2221 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2222 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2223 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2224 AND `item`.`uid` = %d
2229 intval($importer['importer_uid'])
2232 $is_a_remote_comment = true;
2234 // Does this have the characteristics of a community or private group comment?
2235 // If it's a reply to a wall post on a community/prvgroup page it's a
2236 // valid community comment. Also forum_mode makes it valid for sure.
2237 // If neither, it's not.
2239 if($is_a_remote_comment && $community) {
2240 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2241 $is_a_remote_comment = false;
2242 logger('local_delivery: not a community reply');
2246 if($is_a_remote_comment) {
2247 logger('local_delivery: received remote comment');
2249 // remote reply to our post. Import and then notify everybody else.
2251 $datarray = get_atom_elements($feed,$item);
2253 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2255 intval($importer['importer_uid'])
2258 // Update content if 'updated' changes
2262 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2263 logger('received updated comment' , LOGGER_DEBUG);
2264 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2265 dbesc($datarray['title']),
2266 dbesc($datarray['body']),
2267 dbesc($datarray['tag']),
2268 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2270 intval($importer['importer_uid'])
2273 proc_run('php',"include/notifier.php","comment-import",$iid);
2281 // TODO: make this next part work against both delivery threads of a community post
2283 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2284 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2285 // they won't know what to do so don't report an error. Just quietly die.
2289 // our user with $importer['importer_uid'] is the owner
2291 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2292 intval($importer['importer_uid'])
2296 $datarray['type'] = 'remote-comment';
2297 $datarray['wall'] = 1;
2298 $datarray['parent-uri'] = $parent_uri;
2299 $datarray['uid'] = $importer['importer_uid'];
2300 $datarray['owner-name'] = $own[0]['name'];
2301 $datarray['owner-link'] = $own[0]['url'];
2302 $datarray['owner-avatar'] = $own[0]['thumb'];
2303 $datarray['contact-id'] = $importer['id'];
2305 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2307 $datarray['type'] = 'activity';
2308 $datarray['gravity'] = GRAVITY_LIKE;
2309 $datarray['last-child'] = 0;
2310 // only one like or dislike per person
2311 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2312 intval($datarray['uid']),
2313 intval($datarray['contact-id']),
2314 dbesc($datarray['verb'])
2320 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2322 $xo = parse_xml_string($datarray['object'],false);
2323 $xt = parse_xml_string($datarray['target'],false);
2325 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2327 // fetch the parent item
2329 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2331 intval($importer['importer_uid'])
2336 // extract tag, if not duplicate, and this user allows tags, add to parent item
2338 if($xo->id && $xo->content) {
2339 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2340 if(! (stristr($tagp[0]['tag'],$newtag))) {
2341 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2342 intval($importer['importer_uid'])
2344 if(count($i) && ! intval($i[0]['blocktags'])) {
2345 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2346 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2347 intval($tagp[0]['id']),
2348 dbesc(datetime_convert())
2357 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2358 // if(! stristr($datarray['tag'],$newtag)) {
2359 // if(strlen($datarray['tag']))
2360 // $datarray['tag'] .= ',';
2361 // $datarray['tag'] .= $newtag;
2366 $posted_id = item_store($datarray);
2370 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2372 intval($importer['importer_uid'])
2375 $parent = $r[0]['parent'];
2378 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2379 dbesc(datetime_convert()),
2380 intval($importer['importer_uid']),
2381 intval($r[0]['parent'])
2384 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2385 dbesc(datetime_convert()),
2386 intval($importer['importer_uid']),
2391 if($posted_id && $parent) {
2393 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2395 if((! $is_like) && (! $importer['self'])) {
2397 require_once('include/enotify.php');
2400 'type' => NOTIFY_COMMENT,
2401 'notify_flags' => $importer['notify-flags'],
2402 'language' => $importer['language'],
2403 'to_name' => $importer['username'],
2404 'to_email' => $importer['email'],
2405 'uid' => $importer['importer_uid'],
2406 'item' => $datarray,
2407 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2408 'source_name' => stripslashes($datarray['author-name']),
2409 'source_link' => $datarray['author-link'],
2410 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2411 ? $importer['thumb'] : $datarray['author-avatar']),
2412 'verb' => ACTIVITY_POST,
2414 'parent' => $parent,
2427 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2429 $item_id = $item->get_id();
2430 $datarray = get_atom_elements($feed,$item);
2432 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2434 intval($importer['importer_uid'])
2437 // Update content if 'updated' changes
2440 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2441 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2442 dbesc($datarray['title']),
2443 dbesc($datarray['body']),
2444 dbesc($datarray['tag']),
2445 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2447 intval($importer['importer_uid'])
2451 // update last-child if it changes
2453 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2454 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2455 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2456 dbesc(datetime_convert()),
2458 intval($importer['importer_uid'])
2460 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2461 intval($allow[0]['data']),
2462 dbesc(datetime_convert()),
2464 intval($importer['importer_uid'])
2470 $datarray['parent-uri'] = $parent_uri;
2471 $datarray['uid'] = $importer['importer_uid'];
2472 $datarray['contact-id'] = $importer['id'];
2473 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2474 $datarray['type'] = 'activity';
2475 $datarray['gravity'] = GRAVITY_LIKE;
2476 // only one like or dislike per person
2477 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2478 intval($datarray['uid']),
2479 intval($datarray['contact-id']),
2480 dbesc($datarray['verb'])
2487 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2489 $xo = parse_xml_string($datarray['object'],false);
2490 $xt = parse_xml_string($datarray['target'],false);
2492 if($xt->type == ACTIVITY_OBJ_NOTE) {
2493 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2495 intval($importer['importer_uid'])
2500 // extract tag, if not duplicate, add to parent item
2502 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2503 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2504 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2512 $posted_id = item_store($datarray);
2514 // find out if our user is involved in this conversation and wants to be notified.
2516 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
2518 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
2520 intval($importer['importer_uid'])
2523 if(count($myconv)) {
2524 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2526 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2527 if(! link_compare($datarray['author-link'],$importer_url)) {
2530 foreach($myconv as $conv) {
2532 // now if we find a match, it means we're in this conversation
2534 if(! link_compare($conv['author-link'],$importer_url))
2537 require_once('include/enotify.php');
2539 $conv_parent = $conv['parent'];
2542 'type' => NOTIFY_COMMENT,
2543 'notify_flags' => $importer['notify-flags'],
2544 'language' => $importer['language'],
2545 'to_name' => $importer['username'],
2546 'to_email' => $importer['email'],
2547 'uid' => $importer['importer_uid'],
2548 'item' => $datarray,
2549 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2550 'source_name' => stripslashes($datarray['author-name']),
2551 'source_link' => $datarray['author-link'],
2552 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2553 ? $importer['thumb'] : $datarray['author-avatar']),
2554 'verb' => ACTIVITY_POST,
2556 'parent' => $conv_parent,
2560 // only send one notification
2572 // Head post of a conversation. Have we seen it? If not, import it.
2575 $item_id = $item->get_id();
2576 $datarray = get_atom_elements($feed,$item);
2578 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2579 $ev = bbtoevent($datarray['body']);
2580 if(x($ev,'desc') && x($ev,'start')) {
2581 $ev['cid'] = $importer['id'];
2582 $ev['uid'] = $importer['uid'];
2583 $ev['uri'] = $item_id;
2584 $ev['edited'] = $datarray['edited'];
2585 $ev['private'] = $datarray['private'];
2587 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2589 intval($importer['uid'])
2592 $ev['id'] = $r[0]['id'];
2593 $xyz = event_store($ev);
2598 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2600 intval($importer['importer_uid'])
2603 // Update content if 'updated' changes
2606 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2607 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2608 dbesc($datarray['title']),
2609 dbesc($datarray['body']),
2610 dbesc($datarray['tag']),
2611 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2613 intval($importer['importer_uid'])
2617 // update last-child if it changes
2619 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2620 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2621 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2622 intval($allow[0]['data']),
2623 dbesc(datetime_convert()),
2625 intval($importer['importer_uid'])
2631 // This is my contact on another system, but it's really me.
2632 // Turn this into a wall post.
2634 if($importer['remote_self'])
2635 $datarray['wall'] = 1;
2637 $datarray['parent-uri'] = $item_id;
2638 $datarray['uid'] = $importer['importer_uid'];
2639 $datarray['contact-id'] = $importer['id'];
2641 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2642 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2643 // but otherwise there's a possible data mixup on the sender's system.
2644 // the tgroup delivery code called from item_store will correct it if it's a forum,
2645 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2646 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2647 $datarray['owner-name'] = $importer['senderName'];
2648 $datarray['owner-link'] = $importer['url'];
2649 $datarray['owner-avatar'] = $importer['thumb'];
2652 $r = item_store($datarray);
2663 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2664 $url = notags(trim($datarray['author-link']));
2665 $name = notags(trim($datarray['author-name']));
2666 $photo = notags(trim($datarray['author-avatar']));
2668 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2669 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2670 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2672 if(is_array($contact)) {
2673 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2674 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2675 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2676 intval(CONTACT_IS_FRIEND),
2677 intval($contact['id']),
2678 intval($importer['uid'])
2681 // send email notification to owner?
2685 // create contact record
2687 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2688 `blocked`, `readonly`, `pending`, `writable` )
2689 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2690 intval($importer['uid']),
2691 dbesc(datetime_convert()),
2693 dbesc(normalise_link($url)),
2697 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2698 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2700 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2701 intval($importer['uid']),
2705 $contact_record = $r[0];
2707 // create notification
2708 $hash = random_string();
2710 if(is_array($contact_record)) {
2711 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2712 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2713 intval($importer['uid']),
2714 intval($contact_record['id']),
2716 dbesc(datetime_convert())
2719 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2720 intval($importer['uid'])
2725 if(intval($r[0]['def_gid'])) {
2726 require_once('include/group.php');
2727 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
2730 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2731 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2732 $email = replace_macros($email_tpl, array(
2733 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2735 '$myname' => $r[0]['username'],
2736 '$siteurl' => $a->get_baseurl(),
2737 '$sitename' => $a->config['sitename']
2739 $res = mail($r[0]['email'],
2740 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2742 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2743 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2744 . 'Content-transfer-encoding: 8bit' );
2751 function lose_follower($importer,$contact,$datarray,$item) {
2753 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2754 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2755 intval(CONTACT_IS_SHARING),
2756 intval($contact['id'])
2760 contact_remove($contact['id']);
2764 function lose_sharer($importer,$contact,$datarray,$item) {
2766 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2767 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2768 intval(CONTACT_IS_FOLLOWER),
2769 intval($contact['id'])
2773 contact_remove($contact['id']);
2778 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2780 if(is_array($importer)) {
2781 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2782 intval($importer['uid'])
2786 // Diaspora has different message-ids in feeds than they do
2787 // through the direct Diaspora protocol. If we try and use
2788 // the feed, we'll get duplicates. So don't.
2790 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2793 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2795 // Use a single verify token, even if multiple hubs
2797 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2799 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2801 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2803 if(! strlen($contact['hub-verify'])) {
2804 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2805 dbesc($verify_token),
2806 intval($contact['id'])
2810 post_url($url,$params);
2816 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2820 $name = xmlify($name);
2821 $uri = xmlify($uri);
2824 $photo = xmlify($photo);
2828 $o .= "<name>$name</name>\r\n";
2829 $o .= "<uri>$uri</uri>\r\n";
2830 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2831 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2833 call_hooks('atom_author', $o);
2835 $o .= "</$tag>\r\n";
2839 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
2843 if(! $item['parent'])
2846 if($item['deleted'])
2847 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2850 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2851 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
2853 $body = $item['body'];
2856 $o = "\r\n\r\n<entry>\r\n";
2858 if(is_array($author))
2859 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2861 $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']));
2862 if(strlen($item['owner-name']))
2863 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2865 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2866 $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";
2868 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2869 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2870 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2871 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2872 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2873 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2874 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2876 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2878 if($item['location']) {
2879 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2880 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2884 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2886 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2887 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2890 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2891 if($item['bookmark'])
2892 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2895 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2898 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2900 if($item['signed_text']) {
2901 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2902 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2905 $verb = construct_verb($item);
2906 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2907 $actobj = construct_activity_object($item);
2910 $actarg = construct_activity_target($item);
2914 $tags = item_getfeedtags($item);
2916 foreach($tags as $t) {
2917 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2921 $o .= item_getfeedattach($item);
2923 $mentioned = get_mentions($item);
2927 call_hooks('atom_entry', $o);
2929 $o .= '</entry>' . "\r\n";
2934 function fix_private_photos($s,$uid, $item = null, $cid = 0) {
2937 logger('fix_private_photos', LOGGER_DEBUG);
2938 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
2940 if(preg_match("/\[img(.*?)\](.*?)\[\/img\]/is",$s,$matches)) {
2941 $image = $matches[2];
2942 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
2943 if(stristr($image , $site . '/photo/')) {
2945 $i = basename($image);
2946 $i = str_replace('.jpg','',$i);
2947 $x = strpos($i,'-');
2949 $res = substr($i,$x+1);
2950 $i = substr($i,0,$x);
2951 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2958 // Check to see if we should replace this photo link with an embedded image
2959 // 1. No need to do so if the photo is public
2960 // 2. If there's a contact-id provided, see if they're in the access list
2961 // for the photo. If so, embed it.
2962 // 3. Otherwise, if we have an item, see if the item permissions match the photo
2963 // permissions, regardless of order but first check to see if they're an exact
2964 // match to save some processing overhead.
2966 // Currently we only embed one private photo per message so as not to hit import
2967 // size limits at the receiving end.
2969 // To embed multiples, we would need to parse out the embedded photos on message
2970 // receipt and limit size based only on the text component. Would also need to
2971 // ignore all photos during bbcode translation and item localisation, as these
2972 // will hit internal regex backtrace limits.
2974 if(has_permissions($r[0])) {
2976 $recips = enumerate_permissions($r[0]);
2977 if(in_array($cid, $recips)) {
2982 if(compare_permissions($item,$r[0]))
2987 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
2988 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2989 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2999 function has_permissions($obj) {
3000 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3005 function compare_permissions($obj1,$obj2) {
3006 // first part is easy. Check that these are exactly the same.
3007 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3008 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3009 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3010 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3013 // This is harder. Parse all the permissions and compare the resulting set.
3015 $recipients1 = enumerate_permissions($obj1);
3016 $recipients2 = enumerate_permissions($obj2);
3019 if($recipients1 == $recipients2)
3024 // returns an array of contact-ids that are allowed to see this object
3026 function enumerate_permissions($obj) {
3027 require_once('include/group.php');
3028 $allow_people = expand_acl($obj['allow_cid']);
3029 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3030 $deny_people = expand_acl($obj['deny_cid']);
3031 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3032 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3033 $deny = array_unique(array_merge($deny_people,$deny_groups));
3034 $recipients = array_diff($recipients,$deny);
3038 function item_getfeedtags($item) {
3041 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3043 for($x = 0; $x < $cnt; $x ++) {
3045 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3049 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3051 for($x = 0; $x < $cnt; $x ++) {
3053 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3059 function item_getfeedattach($item) {
3061 $arr = explode(',',$item['attach']);
3063 foreach($arr as $r) {
3065 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
3067 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3068 if(intval($matches[2]))
3069 $ret .= 'length="' . intval($matches[2]) . '" ';
3070 if($matches[4] !== ' ')
3071 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3072 $ret .= ' />' . "\r\n";
3081 function item_expire($uid,$days) {
3083 if((! $uid) || ($days < 1))
3086 // $expire_network_only = save your own wall posts
3087 // and just expire conversations started by others
3089 $expire_network_only = get_pconfig($uid,'expire','network_only');
3090 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3092 $r = q("SELECT * FROM `item`
3094 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3105 $expire_items = get_pconfig($uid, 'expire','items');
3106 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3108 $expire_notes = get_pconfig($uid, 'expire','notes');
3109 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3111 $expire_starred = get_pconfig($uid, 'expire','starred');
3112 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3114 $expire_photos = get_pconfig($uid, 'expire','photos');
3115 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3117 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3119 foreach($r as $item) {
3121 // don't expire filed items
3123 if(strpos($item['file'],'[') !== false)
3126 // Only expire posts, not photos and photo comments
3128 if($expire_photos==0 && strlen($item['resource-id']))
3130 if($expire_starred==0 && intval($item['starred']))
3132 if($expire_notes==0 && $item['type']=='note')
3134 if($expire_items==0 && $item['type']!='note')
3137 drop_item($item['id'],false);
3140 proc_run('php',"include/notifier.php","expire","$uid");
3145 function drop_items($items) {
3148 if(! local_user() && ! remote_user())
3152 foreach($items as $item) {
3153 $owner = drop_item($item,false);
3154 if($owner && ! $uid)
3159 // multiple threads may have been deleted, send an expire notification
3162 proc_run('php',"include/notifier.php","expire","$uid");
3166 function drop_item($id,$interactive = true) {
3170 // locate item to be deleted
3172 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3179 notice( t('Item not found.') . EOL);
3180 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3185 $owner = $item['uid'];
3187 // check if logged in user is either the author or owner of this item
3189 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3193 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3194 dbesc(datetime_convert()),
3195 dbesc(datetime_convert()),
3199 // clean up categories and tags so they don't end up as orphans
3202 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3204 foreach($matches as $mtch) {
3205 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3211 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3213 foreach($matches as $mtch) {
3214 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3218 // If item is a link to a photo resource, nuke all the associated photos
3219 // (visitors will not have photo resources)
3220 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3221 // generate a resource-id and therefore aren't intimately linked to the item.
3223 if(strlen($item['resource-id'])) {
3224 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3225 dbesc($item['resource-id']),
3226 intval($item['uid'])
3228 // ignore the result
3231 // If item is a link to an event, nuke the event record.
3233 if(intval($item['event-id'])) {
3234 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3235 intval($item['event-id']),
3236 intval($item['uid'])
3238 // ignore the result
3241 // clean up item_id and sign meta-data tables
3243 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3244 intval($item['id']),
3245 intval($item['uid'])
3248 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3249 intval($item['id']),
3250 intval($item['uid'])
3253 // If it's the parent of a comment thread, kill all the kids
3255 if($item['uri'] == $item['parent-uri']) {
3256 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3257 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3258 dbesc(datetime_convert()),
3259 dbesc(datetime_convert()),
3260 dbesc($item['parent-uri']),
3261 intval($item['uid'])
3263 // ignore the result
3266 // ensure that last-child is set in case the comment that had it just got wiped.
3267 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3268 dbesc(datetime_convert()),
3269 dbesc($item['parent-uri']),
3270 intval($item['uid'])
3272 // who is the last child now?
3273 $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",
3274 dbesc($item['parent-uri']),
3275 intval($item['uid'])
3278 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3283 $drop_id = intval($item['id']);
3285 // send the notification upstream/downstream as the case may be
3290 proc_run('php',"include/notifier.php","drop","$drop_id");
3291 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3297 notice( t('Permission denied.') . EOL);
3298 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);