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')
25 // default permissions - anonymous user
27 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
29 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
30 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
31 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
39 $owner_id = $owner['user_uid'];
40 $owner_nick = $owner['nickname'];
42 $birthday = feed_birthday($owner_id,$owner['timezone']);
49 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
53 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
54 $my_id = '1:' . $dfrn_id;
57 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
58 $my_id = '0:' . $dfrn_id;
65 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
73 $groups = init_groups_visitor($contact['id']);
76 for($x = 0; $x < count($groups); $x ++)
77 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
78 $gs = implode('|', $groups);
81 $gs = '<<>>' ; // Impossible to match
83 $sql_extra = sprintf("
84 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
85 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
86 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
87 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
89 intval($contact['id']),
90 intval($contact['id']),
101 if(! strlen($last_update))
102 $last_update = 'now -30 days';
106 $sql_extra .= " AND `contact`.`self` = 1 ";
109 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
111 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
112 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
113 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
114 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
115 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
116 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
117 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
118 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
119 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
120 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
121 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
123 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
130 // Will check further below if this actually returned results.
131 // We will provide an empty feed if that is the case.
135 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
139 $hubxml = feed_hublinks();
141 $salmon = feed_salmonlinks($owner_nick);
143 $atom .= replace_macros($feed_template, array(
144 '$version' => xmlify(FRIENDICA_VERSION),
145 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
146 '$feed_title' => xmlify($owner['name']),
147 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
149 '$salmon' => $salmon,
150 '$name' => xmlify($owner['name']),
151 '$profile_page' => xmlify($owner['url']),
152 '$photo' => xmlify($owner['photo']),
153 '$thumb' => xmlify($owner['thumb']),
154 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
155 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
156 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
157 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
158 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
161 call_hooks('atom_feed', $atom);
163 if(! count($items)) {
165 call_hooks('atom_feed_end', $atom);
167 $atom .= '</feed>' . "\r\n";
171 foreach($items as $item) {
173 // public feeds get html, our own nodes use bbcode
177 // catch any email that's in a public conversation and make sure it doesn't leak
185 $atom .= atom_entry($item,$type,null,$owner,true);
188 call_hooks('atom_feed_end', $atom);
190 $atom .= '</feed>' . "\r\n";
196 function construct_verb($item) {
198 return $item['verb'];
199 return ACTIVITY_POST;
202 function construct_activity_object($item) {
204 if($item['object']) {
205 $o = '<as:object>' . "\r\n";
206 $r = parse_xml_string($item['object'],false);
212 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
214 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
216 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
218 if(substr($r->link,0,1) === '<') {
219 // patch up some facebook "like" activity objects that got stored incorrectly
220 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
221 // we can probably remove this hack here and in the following function in a few months time.
222 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
223 $r->link = str_replace('&','&', $r->link);
224 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
228 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
231 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
232 $o .= '</as:object>' . "\r\n";
239 function construct_activity_target($item) {
241 if($item['target']) {
242 $o = '<as:target>' . "\r\n";
243 $r = parse_xml_string($item['target'],false);
247 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
249 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
251 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
253 if(substr($r->link,0,1) === '<') {
254 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
255 $r->link = str_replace('&','&', $r->link);
256 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
260 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
263 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
264 $o .= '</as:target>' . "\r\n";
274 function get_atom_elements($feed,$item) {
276 require_once('library/HTMLPurifier.auto.php');
277 require_once('include/html2bbcode.php');
279 $best_photo = array();
283 $author = $item->get_author();
285 $res['author-name'] = unxmlify($author->get_name());
286 $res['author-link'] = unxmlify($author->get_link());
289 $res['author-name'] = unxmlify($feed->get_title());
290 $res['author-link'] = unxmlify($feed->get_permalink());
292 $res['uri'] = unxmlify($item->get_id());
293 $res['title'] = unxmlify($item->get_title());
294 $res['body'] = unxmlify($item->get_content());
295 $res['plink'] = unxmlify($item->get_link(0));
298 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
302 // look for a photo. We should check media size and find the best one,
303 // but for now let's just find any author photo
305 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
307 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
308 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
309 foreach($base as $link) {
310 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
311 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
312 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
317 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
319 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
320 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
321 if($base && count($base)) {
322 foreach($base as $link) {
323 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
324 $res['author-link'] = unxmlify($link['attribs']['']['href']);
325 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
326 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
327 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
333 // No photo/profile-link on the item - look at the feed level
335 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
336 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
337 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
338 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
339 foreach($base as $link) {
340 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
341 $res['author-link'] = unxmlify($link['attribs']['']['href']);
342 if(! $res['author-avatar']) {
343 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
344 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
349 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
351 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
352 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
354 if($base && count($base)) {
355 foreach($base as $link) {
356 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
357 $res['author-link'] = unxmlify($link['attribs']['']['href']);
358 if(! (x($res,'author-avatar'))) {
359 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
360 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
367 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
368 if($apps && $apps[0]['attribs']['']['source']) {
369 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
370 if($res['app'] === 'web')
371 $res['app'] = 'OStatus';
374 // base64 encoded json structure representing Diaspora signature
376 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
378 $res['dsprsig'] = unxmlify($dsig[0]['data']);
381 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
383 $res['guid'] = unxmlify($dguid[0]['data']);
385 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
387 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
391 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
394 $have_real_body = false;
396 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
398 $have_real_body = true;
399 $res['body'] = $rawenv[0]['data'];
400 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
401 // make sure nobody is trying to sneak some html tags by us
402 $res['body'] = notags(base64url_decode($res['body']));
405 $maxlen = get_max_import_size();
406 if($maxlen && (strlen($res['body']) > $maxlen))
407 $res['body'] = substr($res['body'],0, $maxlen);
409 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
410 // the content type. Our own network only emits text normally, though it might have been converted to
411 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
412 // have to assume it is all html and needs to be purified.
414 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
415 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
416 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
419 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
421 $res['body'] = reltoabs($res['body'],$base_url);
423 $res['body'] = html2bb_video($res['body']);
425 $res['body'] = oembed_html2bbcode($res['body']);
427 $config = HTMLPurifier_Config::createDefault();
428 $config->set('Cache.DefinitionImpl', null);
430 // we shouldn't need a whitelist, because the bbcode converter
431 // will strip out any unsupported tags.
432 // $config->set('HTML.Allowed', 'p,b,a[href],i');
434 $purifier = new HTMLPurifier($config);
435 $res['body'] = $purifier->purify($res['body']);
437 $res['body'] = html2bbcode($res['body']);
440 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
441 if($allow && $allow[0]['data'] == 1)
442 $res['last-child'] = 1;
444 $res['last-child'] = 0;
446 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
447 if($private && $private[0]['data'] == 1)
452 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
453 if($extid && $extid[0]['data'])
454 $res['extid'] = $extid[0]['data'];
456 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
458 $res['location'] = unxmlify($rawlocation[0]['data']);
461 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
463 $res['created'] = unxmlify($rawcreated[0]['data']);
466 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
468 $res['edited'] = unxmlify($rawedited[0]['data']);
470 if((x($res,'edited')) && (! (x($res,'created'))))
471 $res['created'] = $res['edited'];
473 if(! $res['created'])
474 $res['created'] = $item->get_date('c');
477 $res['edited'] = $item->get_date('c');
480 // Disallow time travelling posts
482 $d1 = strtotime($res['created']);
483 $d2 = strtotime($res['edited']);
484 $d3 = strtotime('now');
487 $res['created'] = datetime_convert();
489 $res['edited'] = datetime_convert();
491 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
492 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
493 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
494 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
495 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
496 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
497 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
498 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
499 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
501 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
502 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
504 foreach($base as $link) {
505 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
506 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
507 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
512 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
514 $res['coord'] = unxmlify($rawgeo[0]['data']);
517 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
519 // select between supported verbs
522 $res['verb'] = unxmlify($rawverb[0]['data']);
525 // translate OStatus unfollow to activity streams if it happened to get selected
527 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
528 $res['verb'] = ACTIVITY_UNFOLLOW;
530 $cats = $item->get_categories();
533 foreach($cats as $cat) {
534 $term = $cat->get_term();
536 $term = $cat->get_label();
537 $scheme = $cat->get_scheme();
538 if($scheme && $term && stristr($scheme,'X-DFRN:'))
539 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
541 $tag_arr[] = notags(trim($term));
543 $res['tag'] = implode(',', $tag_arr);
546 $attach = $item->get_enclosures();
549 foreach($attach as $att) {
550 $len = intval($att->get_length());
551 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
552 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
553 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
554 if(strpos($type,';'))
555 $type = substr($type,0,strpos($type,';'));
556 if((! $link) || (strpos($link,'http') !== 0))
562 $type = 'application/octet-stream';
564 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
566 $res['attach'] = implode(',', $att_arr);
569 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
572 $res['object'] = '<object>' . "\n";
573 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
574 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
575 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
577 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
578 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
579 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
580 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
581 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
582 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
583 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
584 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
586 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
587 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
588 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
589 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
591 $body = html2bb_video($body);
593 $config = HTMLPurifier_Config::createDefault();
594 $config->set('Cache.DefinitionImpl', null);
596 $purifier = new HTMLPurifier($config);
597 $body = $purifier->purify($body);
598 $body = html2bbcode($body);
601 $res['object'] .= '<content>' . $body . '</content>' . "\n";
604 $res['object'] .= '</object>' . "\n";
607 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
610 $res['target'] = '<target>' . "\n";
611 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
612 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
614 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
615 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
617 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
618 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
619 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
620 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
621 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
622 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
624 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
625 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
626 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
627 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
629 $body = html2bb_video($body);
631 $config = HTMLPurifier_Config::createDefault();
632 $config->set('Cache.DefinitionImpl', null);
634 $purifier = new HTMLPurifier($config);
635 $body = $purifier->purify($body);
636 $body = html2bbcode($body);
639 $res['target'] .= '<content>' . $body . '</content>' . "\n";
642 $res['target'] .= '</target>' . "\n";
645 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
647 call_hooks('parse_atom', $arr);
652 function encode_rel_links($links) {
654 if(! ((is_array($links)) && (count($links))))
656 foreach($links as $link) {
658 if($link['attribs']['']['rel'])
659 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
660 if($link['attribs']['']['type'])
661 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
662 if($link['attribs']['']['href'])
663 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
664 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
665 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
666 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
667 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
673 function item_store($arr,$force_parent = false) {
675 // If a Diaspora signature structure was passed in, pull it out of the
676 // item array and set it aside for later storage.
679 if(x($arr,'dsprsig')) {
680 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
681 unset($arr['dsprsig']);
684 if(x($arr, 'gravity'))
685 $arr['gravity'] = intval($arr['gravity']);
686 elseif($arr['parent-uri'] === $arr['uri'])
688 elseif(activity_match($arr['verb'],ACTIVITY_POST))
691 $arr['gravity'] = 6; // extensible catchall
694 $arr['type'] = 'remote';
696 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
698 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
699 $arr['body'] = strip_tags($arr['body']);
702 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
703 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
704 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
705 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
706 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
707 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
708 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
709 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
710 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
711 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
712 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
713 $arr['commented'] = datetime_convert();
714 $arr['received'] = datetime_convert();
715 $arr['changed'] = datetime_convert();
716 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
717 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
718 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
719 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
720 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
722 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
723 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
724 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
725 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
726 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
727 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
728 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
729 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
730 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
731 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
732 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
733 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
734 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
735 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
736 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
737 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
738 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
739 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
740 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
742 if($arr['parent-uri'] === $arr['uri']) {
745 $allow_cid = $arr['allow_cid'];
746 $allow_gid = $arr['allow_gid'];
747 $deny_cid = $arr['deny_cid'];
748 $deny_gid = $arr['deny_gid'];
752 // find the parent and snarf the item id and ACL's
753 // and anything else we need to inherit
755 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
756 dbesc($arr['parent-uri']),
762 // is the new message multi-level threaded?
763 // even though we don't support it now, preserve the info
764 // and re-attach to the conversation parent.
766 if($r[0]['uri'] != $r[0]['parent-uri']) {
767 $arr['thr-parent'] = $arr['parent-uri'];
768 $arr['parent-uri'] = $r[0]['parent-uri'];
769 $z = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
770 ORDER BY `id` ASC LIMIT 1",
771 dbesc($r[0]['parent-uri']),
772 dbesc($r[0]['parent-uri']),
779 $parent_id = $r[0]['id'];
780 $parent_deleted = $r[0]['deleted'];
781 $allow_cid = $r[0]['allow_cid'];
782 $allow_gid = $r[0]['allow_gid'];
783 $deny_cid = $r[0]['deny_cid'];
784 $deny_gid = $r[0]['deny_gid'];
785 $arr['wall'] = $r[0]['wall'];
789 // Allow one to see reply tweets from status.net even when
790 // we don't have or can't see the original post.
793 logger('item_store: $force_parent=true, reply converted to top-level post.');
795 $arr['thr-parent'] = $arr['parent-uri'];
796 $arr['parent-uri'] = $arr['uri'];
800 logger('item_store: item parent was not found - ignoring item');
808 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
812 if($r && count($r)) {
813 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
817 call_hooks('post_remote',$arr);
819 if(x($arr,'cancel')) {
820 logger('item_store: post cancelled by plugin.');
826 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
828 $r = dbq("INSERT INTO `item` (`"
829 . implode("`, `", array_keys($arr))
831 . implode("', '", array_values($arr))
834 // find the item we just created
836 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
837 $arr['uri'], // already dbesc'd
842 $current_post = $r[0]['id'];
843 logger('item_store: created item ' . $current_post);
846 logger('item_store: could not locate created item');
850 logger('item_store: duplicated post occurred. Removing duplicates.');
851 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
854 intval($current_post)
858 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
859 $parent_id = $current_post;
861 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
864 $private = $arr['private'];
866 // Set parent id - and also make sure to inherit the parent's ACL's.
868 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
869 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
876 intval($parent_deleted),
877 intval($current_post)
880 // update the commented timestamp on the parent
882 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
883 dbesc(datetime_convert()),
884 dbesc(datetime_convert()),
889 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
890 intval($current_post),
891 dbesc($dsprsig->signed_text),
892 dbesc($dsprsig->signature),
893 dbesc($dsprsig->signer)
899 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
902 if($arr['last-child']) {
903 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
906 intval($current_post)
910 tag_deliver($arr['uid'],$current_post);
912 return $current_post;
915 function get_item_contact($item,$contacts) {
916 if(! count($contacts) || (! is_array($item)))
918 foreach($contacts as $contact) {
919 if($contact['id'] == $item['contact-id']) {
928 function tag_deliver($uid,$item_id) {
930 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
936 $u = q("select uid, nickname, language, username, email, `page-flags`, `notify-flags` from user where uid = %d limit 1",
942 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
944 $i = q("select * from item where id = %d and uid = %d limit 1",
953 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
955 // Diaspora uses their own hardwired link URL in @-tags
956 // instead of the one we supply with webfinger
958 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
960 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
962 foreach($matches as $mtch) {
963 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
965 logger('tag_deliver: mention found: ' . $mtch[2]);
973 // send a notification
975 require_once('include/enotify.php');
977 'type' => NOTIFY_TAGSELF,
978 'notify_flags' => $u[0]['notify-flags'],
979 'language' => $u[0]['language'],
980 'to_name' => $u[0]['username'],
981 'to_email' => $u[0]['email'],
982 'uid' => $u[0]['uid'],
984 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
985 'source_name' => $item['author-name'],
986 'source_link' => $item['author-link'],
987 'source_photo' => $item['author-avatar'],
988 'verb' => ACTIVITY_TAG,
992 if(! $community_page)
995 // tgroup delivery - setup a second delivery chain
996 // prevent delivery looping - only proceed
997 // if the message originated elsewhere and is a top-level post
999 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1002 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1005 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1006 intval($u[0]['uid'])
1011 q("update item set wall = 1, origin = 1, forum_mode = 1, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s' where id = %d limit 1",
1012 dbesc($c[0]['name']),
1013 dbesc($c[0]['url']),
1014 dbesc($c[0]['thumb']),
1018 proc_run('php','include/notifier.php','tgroup',$item_id);
1027 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1031 // if((! strlen($contact['issued-id'])) && (! $contact['duplex']) && (! ($owner['page-flags'] == PAGE_COMMUNITY)))
1034 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1036 if($contact['duplex'] && $contact['dfrn-id'])
1037 $idtosend = '0:' . $orig_id;
1038 if($contact['duplex'] && $contact['issued-id'])
1039 $idtosend = '1:' . $orig_id;
1041 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1043 $rino_enable = get_config('system','rino_encrypt');
1048 $ssl_val = intval(get_config('system','ssl_policy'));
1052 case SSL_POLICY_FULL:
1053 $ssl_policy = 'full';
1055 case SSL_POLICY_SELFSIGN:
1056 $ssl_policy = 'self';
1058 case SSL_POLICY_NONE:
1060 $ssl_policy = 'none';
1064 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1066 logger('dfrn_deliver: ' . $url);
1068 $xml = fetch_url($url);
1070 $curl_stat = $a->get_curl_code();
1072 return(-1); // timed out
1074 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1079 if(strpos($xml,'<?xml') === false) {
1080 logger('dfrn_deliver: no valid XML returned');
1081 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1085 $res = parse_xml_string($xml);
1087 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1088 return (($res->status) ? $res->status : 3);
1090 $postvars = array();
1091 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1092 $challenge = hex2bin((string) $res->challenge);
1093 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1094 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1095 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1097 $final_dfrn_id = '';
1100 if(($contact['duplex'] && strlen($contact['pubkey']))
1101 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1102 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1103 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1104 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1107 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1108 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1111 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1113 if(strpos($final_dfrn_id,':') == 1)
1114 $final_dfrn_id = substr($final_dfrn_id,2);
1116 if($final_dfrn_id != $orig_id) {
1117 logger('dfrn_deliver: wrong dfrn_id.');
1118 // did not decode properly - cannot trust this site
1122 $postvars['dfrn_id'] = $idtosend;
1123 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1125 $postvars['dissolve'] = '1';
1128 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1129 $postvars['data'] = $atom;
1130 $postvars['perm'] = 'rw';
1133 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1134 $postvars['perm'] = 'r';
1137 $postvars['ssl_policy'] = $ssl_policy;
1140 $postvars['page'] = '1';
1142 if($rino && $rino_allowed && (! $dissolve)) {
1143 $key = substr(random_string(),0,16);
1144 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1145 $postvars['data'] = $data;
1146 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1149 if($dfrn_version >= 2.1) {
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']))) {
1154 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1157 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1161 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1162 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1165 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1169 logger('md5 rawkey ' . md5($postvars['key']));
1171 $postvars['key'] = bin2hex($postvars['key']);
1174 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1176 $xml = post_url($contact['notify'],$postvars);
1178 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1180 $curl_stat = $a->get_curl_code();
1181 if((! $curl_stat) || (! strlen($xml)))
1182 return(-1); // timed out
1184 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1187 if(strpos($xml,'<?xml') === false) {
1188 logger('dfrn_deliver: phase 2: no valid XML returned');
1189 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1193 $res = parse_xml_string($xml);
1195 return $res->status;
1201 * consume_feed - process atom feed and update anything/everything we might need to update
1203 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1205 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1206 * It is this person's stuff that is going to be updated.
1207 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1208 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1209 * have a contact record.
1210 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1211 * might not) try and subscribe to it.
1212 * $datedir sorts in reverse order
1213 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1214 * imported prior to its children being seen in the stream unless we are certain
1215 * of how the feed is arranged/ordered.
1216 * With $pass = 1, we only pull parent items out of the stream.
1217 * With $pass = 2, we only pull children (comments/likes).
1219 * So running this twice, first with pass 1 and then with pass 2 will do the right
1220 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1221 * model where comments can have sub-threads. That would require some massive sorting
1222 * to get all the feed items into a mostly linear ordering, and might still require
1226 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1228 require_once('library/simplepie/simplepie.inc');
1230 if(! strlen($xml)) {
1231 logger('consume_feed: empty input');
1235 $feed = new SimplePie();
1236 $feed->set_raw_data($xml);
1238 $feed->enable_order_by_date(true);
1240 $feed->enable_order_by_date(false);
1244 logger('consume_feed: Error parsing XML: ' . $feed->error());
1246 $permalink = $feed->get_permalink();
1248 // Check at the feed level for updated contact name and/or photo
1252 $photo_timestamp = '';
1256 $hubs = $feed->get_links('hub');
1259 $hub = implode(',', $hubs);
1261 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1263 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1265 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1266 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1267 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1268 $new_name = $elems['name'][0]['data'];
1270 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1271 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1272 $photo_url = $elems['link'][0]['attribs']['']['href'];
1275 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1276 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1280 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1281 logger('consume_feed: Updating photo for ' . $contact['name']);
1282 require_once("Photo.php");
1283 $photo_failure = false;
1284 $have_photo = false;
1286 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1287 intval($contact['id']),
1288 intval($contact['uid'])
1291 $resource_id = $r[0]['resource-id'];
1295 $resource_id = photo_new_resource();
1298 $img_str = fetch_url($photo_url,true);
1299 $img = new Photo($img_str);
1300 if($img->is_valid()) {
1302 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1303 dbesc($resource_id),
1304 intval($contact['id']),
1305 intval($contact['uid'])
1309 $img->scaleImageSquare(175);
1311 $hash = $resource_id;
1312 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1314 $img->scaleImage(80);
1315 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1317 $img->scaleImage(48);
1318 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1322 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1323 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1324 dbesc(datetime_convert()),
1325 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1326 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1327 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1328 intval($contact['uid']),
1329 intval($contact['id'])
1334 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1335 $r = q("select * from contact where uid = %d and id = %d limit 1",
1336 intval($contact['uid']),
1337 intval($contact['id'])
1340 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1341 dbesc(notags(trim($new_name))),
1342 dbesc(datetime_convert()),
1343 intval($contact['uid']),
1344 intval($contact['id'])
1347 // do our best to update the name on content items
1350 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1351 dbesc(notags(trim($new_name))),
1352 dbesc($r[0]['name']),
1353 dbesc($r[0]['url']),
1354 intval($contact['uid'])
1359 if(strlen($birthday)) {
1360 if(substr($birthday,0,4) != $contact['bdyear']) {
1361 logger('consume_feed: updating birthday: ' . $birthday);
1365 * Add new birthday event for this person
1367 * $bdtext is just a readable placeholder in case the event is shared
1368 * with others. We will replace it during presentation to our $importer
1369 * to contain a sparkle link and perhaps a photo.
1373 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1376 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1377 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1378 intval($contact['uid']),
1379 intval($contact['id']),
1380 dbesc(datetime_convert()),
1381 dbesc(datetime_convert()),
1382 dbesc(datetime_convert('UTC','UTC', $birthday)),
1383 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1391 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1392 dbesc(substr($birthday,0,4)),
1393 intval($contact['uid']),
1394 intval($contact['id'])
1397 // This function is called twice without reloading the contact
1398 // Make sure we only create one event. This is why &$contact
1399 // is a reference var in this function
1401 $contact['bdyear'] = substr($birthday,0,4);
1406 $community_page = 0;
1407 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1409 $community_page = intval($rawtags[0]['data']);
1411 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1412 q("update contact set forum = %d where id = %d limit 1",
1413 intval($community_page),
1414 intval($contact['id'])
1416 $contact['forum'] = (string) $community_page;
1420 // process any deleted entries
1422 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1423 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1424 foreach($del_entries as $dentry) {
1426 if(isset($dentry['attribs']['']['ref'])) {
1427 $uri = $dentry['attribs']['']['ref'];
1429 if(isset($dentry['attribs']['']['when'])) {
1430 $when = $dentry['attribs']['']['when'];
1431 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1434 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1436 if($deleted && is_array($contact)) {
1437 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1438 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1440 intval($importer['uid']),
1441 intval($contact['id'])
1446 if(! $item['deleted'])
1447 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1449 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1450 $xo = parse_xml_string($item['object'],false);
1451 $xt = parse_xml_string($item['target'],false);
1452 if($xt->type === ACTIVITY_OBJ_NOTE) {
1453 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1455 intval($importer['importer_uid'])
1459 // For tags, the owner cannot remove the tag on the author's copy of the post.
1461 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1462 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1463 $author_copy = (($item['origin']) ? true : false);
1465 if($owner_remove && $author_copy)
1467 if($author_remove || $owner_remove) {
1468 $tags = explode(',',$i[0]['tag']);
1471 foreach($tags as $tag)
1472 if(trim($tag) !== trim($xo->body))
1473 $newtags[] = trim($tag);
1475 q("update item set tag = '%s' where id = %d limit 1",
1476 dbesc(implode(',',$newtags)),
1484 if($item['uri'] == $item['parent-uri']) {
1485 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1486 `body` = '', `title` = ''
1487 WHERE `parent-uri` = '%s' AND `uid` = %d",
1489 dbesc(datetime_convert()),
1490 dbesc($item['uri']),
1491 intval($importer['uid'])
1495 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1496 `body` = '', `title` = ''
1497 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1499 dbesc(datetime_convert()),
1501 intval($importer['uid'])
1503 if($item['last-child']) {
1504 // ensure that last-child is set in case the comment that had it just got wiped.
1505 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1506 dbesc(datetime_convert()),
1507 dbesc($item['parent-uri']),
1508 intval($item['uid'])
1510 // who is the last child now?
1511 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1512 ORDER BY `created` DESC LIMIT 1",
1513 dbesc($item['parent-uri']),
1514 intval($importer['uid'])
1517 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1528 // Now process the feed
1530 if($feed->get_item_quantity()) {
1532 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1534 // in inverse date order
1536 $items = array_reverse($feed->get_items());
1538 $items = $feed->get_items();
1541 foreach($items as $item) {
1544 $item_id = $item->get_id();
1545 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1546 if(isset($rawthread[0]['attribs']['']['ref'])) {
1548 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1551 if(($is_reply) && is_array($contact)) {
1556 // Have we seen it? If not, import it.
1558 $item_id = $item->get_id();
1559 $datarray = get_atom_elements($feed,$item);
1562 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1563 $datarray['author-name'] = $contact['name'];
1564 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1565 $datarray['author-link'] = $contact['url'];
1566 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1567 $datarray['author-avatar'] = $contact['thumb'];
1569 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1570 logger('consume_feed: no author information! ' . print_r($datarray,true));
1574 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1576 intval($importer['uid'])
1579 // Update content if 'updated' changes
1582 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1583 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1584 dbesc($datarray['title']),
1585 dbesc($datarray['body']),
1586 dbesc($datarray['tag']),
1587 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1589 intval($importer['uid'])
1593 // update last-child if it changes
1595 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1596 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1597 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1598 dbesc(datetime_convert()),
1600 intval($importer['uid'])
1602 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1603 intval($allow[0]['data']),
1604 dbesc(datetime_convert()),
1606 intval($importer['uid'])
1612 $force_parent = false;
1613 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1614 if($contact['network'] === NETWORK_OSTATUS)
1615 $force_parent = true;
1616 if(strlen($datarray['title']))
1617 unset($datarray['title']);
1618 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1619 dbesc(datetime_convert()),
1621 intval($importer['uid'])
1623 $datarray['last-child'] = 1;
1626 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1627 // one way feed - no remote comment ability
1628 $datarray['last-child'] = 0;
1630 $datarray['parent-uri'] = $parent_uri;
1631 $datarray['uid'] = $importer['uid'];
1632 $datarray['contact-id'] = $contact['id'];
1633 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1634 $datarray['type'] = 'activity';
1635 $datarray['gravity'] = GRAVITY_LIKE;
1636 // only one like or dislike per person
1637 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
1638 intval($datarray['uid']),
1639 intval($datarray['contact-id']),
1640 dbesc($datarray['verb'])
1646 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1647 $xo = parse_xml_string($datarray['object'],false);
1648 $xt = parse_xml_string($datarray['target'],false);
1650 if($xt->type == ACTIVITY_OBJ_NOTE) {
1651 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1653 intval($importer['importer_uid'])
1658 // extract tag, if not duplicate, add to parent item
1659 if($xo->id && $xo->content) {
1660 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1661 if(! (stristr($r[0]['tag'],$newtag))) {
1662 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1663 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1671 $r = item_store($datarray,$force_parent);
1677 // Head post of a conversation. Have we seen it? If not, import it.
1679 $item_id = $item->get_id();
1681 $datarray = get_atom_elements($feed,$item);
1683 if(is_array($contact)) {
1684 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1685 $datarray['author-name'] = $contact['name'];
1686 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1687 $datarray['author-link'] = $contact['url'];
1688 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1689 $datarray['author-avatar'] = $contact['thumb'];
1692 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1693 logger('consume_feed: no author information! ' . print_r($datarray,true));
1697 // special handling for events
1699 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1700 $ev = bbtoevent($datarray['body']);
1701 if(x($ev,'desc') && x($ev,'start')) {
1702 $ev['uid'] = $importer['uid'];
1703 $ev['uri'] = $item_id;
1704 $ev['edited'] = $datarray['edited'];
1705 $ev['private'] = $datarray['private'];
1707 if(is_array($contact))
1708 $ev['cid'] = $contact['id'];
1709 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1711 intval($importer['uid'])
1714 $ev['id'] = $r[0]['id'];
1715 $xyz = event_store($ev);
1720 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1722 intval($importer['uid'])
1725 // Update content if 'updated' changes
1728 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1729 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1730 dbesc($datarray['title']),
1731 dbesc($datarray['body']),
1732 dbesc($datarray['tag']),
1733 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1735 intval($importer['uid'])
1739 // update last-child if it changes
1741 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1742 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1743 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1744 intval($allow[0]['data']),
1745 dbesc(datetime_convert()),
1747 intval($importer['uid'])
1753 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1754 logger('consume-feed: New follower');
1755 new_follower($importer,$contact,$datarray,$item);
1758 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1759 lose_follower($importer,$contact,$datarray,$item);
1763 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1764 logger('consume-feed: New friend request');
1765 new_follower($importer,$contact,$datarray,$item,true);
1768 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1769 lose_sharer($importer,$contact,$datarray,$item);
1774 if(! is_array($contact))
1777 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1778 if(strlen($datarray['title']))
1779 unset($datarray['title']);
1780 $datarray['last-child'] = 1;
1783 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1784 // one way feed - no remote comment ability
1785 $datarray['last-child'] = 0;
1788 // This is my contact on another system, but it's really me.
1789 // Turn this into a wall post.
1791 if($contact['remote_self'])
1792 $datarray['wall'] = 1;
1794 $datarray['parent-uri'] = $item_id;
1795 $datarray['uid'] = $importer['uid'];
1796 $datarray['contact-id'] = $contact['id'];
1798 if(! link_compare($datarray['owner-link'],$contact['url'])) {
1799 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
1800 // but otherwise there's a possible data mixup on the sender's system.
1801 // the tgroup delivery code called from item_store will correct it if it's a forum,
1802 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
1803 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
1804 $datarray['owner-name'] = $contact['name'];
1805 $datarray['owner-link'] = $contact['url'];
1806 $datarray['owner-avatar'] = $contact['thumb'];
1809 $r = item_store($datarray);
1817 function local_delivery($importer,$data) {
1821 if($importer['readonly']) {
1822 // We aren't receiving stuff from this person. But we will quietly ignore them
1823 // rather than a blatant "go away" message.
1824 logger('local_delivery: ignoring');
1829 // Consume notification feed. This may differ from consuming a public feed in several ways
1830 // - might contain email or friend suggestions
1831 // - might contain remote followup to our message
1832 // - in which case we need to accept it and then notify other conversants
1833 // - we may need to send various email notifications
1835 $feed = new SimplePie();
1836 $feed->set_raw_data($data);
1837 $feed->enable_order_by_date(false);
1840 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1841 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1842 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1844 $newloc['uid'] = $importer['importer_uid'];
1845 $newloc['cid'] = $importer['id'];
1846 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1847 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1848 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1849 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1850 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1851 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1852 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1853 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1854 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1855 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1858 // merge with current record, current contents have priority
1859 // update record, set url-updated
1860 // update profile photos
1865 // handle friend suggestion notification
1867 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1868 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1869 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1871 $fsugg['uid'] = $importer['importer_uid'];
1872 $fsugg['cid'] = $importer['id'];
1873 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1874 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1875 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1876 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1877 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1879 // Does our member already have a friend matching this description?
1881 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1882 dbesc($fsugg['name']),
1883 dbesc(normalise_link($fsugg['url'])),
1884 intval($fsugg['uid'])
1889 // Do we already have an fcontact record for this person?
1892 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1893 dbesc($fsugg['url']),
1894 dbesc($fsugg['name']),
1895 dbesc($fsugg['request'])
1900 // OK, we do. Do we already have an introduction for this person ?
1901 $r = q("select id from intro where uid = %d and fid = %d limit 1",
1902 intval($fsugg['uid']),
1909 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1910 dbesc($fsugg['name']),
1911 dbesc($fsugg['url']),
1912 dbesc($fsugg['photo']),
1913 dbesc($fsugg['request'])
1915 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1916 dbesc($fsugg['url']),
1917 dbesc($fsugg['name']),
1918 dbesc($fsugg['request'])
1923 // database record did not get created. Quietly give up.
1928 $hash = random_string();
1930 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1931 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1932 intval($fsugg['uid']),
1934 intval($fsugg['cid']),
1935 dbesc($fsugg['body']),
1937 dbesc(datetime_convert()),
1942 'type' => NOTIFY_SUGGEST,
1943 'notify_flags' => $importer['notify-flags'],
1944 'language' => $importer['language'],
1945 'to_name' => $importer['username'],
1946 'to_email' => $importer['email'],
1947 'uid' => $importer['importer_uid'],
1949 'link' => $a->get_baseurl() . '/notifications/intros',
1950 'source_name' => $importer['name'],
1951 'source_link' => $importer['url'],
1952 'source_photo' => $importer['photo'],
1953 'verb' => ACTIVITY_REQ_FRIEND,
1962 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1963 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1965 logger('local_delivery: private message received');
1968 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1971 $msg['uid'] = $importer['importer_uid'];
1972 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1973 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1974 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1975 $msg['contact-id'] = $importer['id'];
1976 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1977 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1979 $msg['replied'] = 0;
1980 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1981 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1982 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1986 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
1987 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1989 // send notifications.
1991 require_once('include/enotify.php');
1993 $notif_params = array(
1994 'type' => NOTIFY_MAIL,
1995 'notify_flags' => $importer['notify-flags'],
1996 'language' => $importer['language'],
1997 'to_name' => $importer['username'],
1998 'to_email' => $importer['email'],
1999 'uid' => $importer['importer_uid'],
2001 'source_name' => $msg['from-name'],
2002 'source_link' => $importer['url'],
2003 'source_photo' => $importer['thumb'],
2004 'verb' => ACTIVITY_POST,
2008 notification($notif_params);
2014 $community_page = 0;
2015 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2017 $community_page = intval($rawtags[0]['data']);
2019 if(intval($importer['forum']) != $community_page) {
2020 q("update contact set forum = %d where id = %d limit 1",
2021 intval($community_page),
2022 intval($importer['id'])
2024 $importer['forum'] = (string) $community_page;
2027 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2029 // process any deleted entries
2031 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2032 if(is_array($del_entries) && count($del_entries)) {
2033 foreach($del_entries as $dentry) {
2035 if(isset($dentry['attribs']['']['ref'])) {
2036 $uri = $dentry['attribs']['']['ref'];
2038 if(isset($dentry['attribs']['']['when'])) {
2039 $when = $dentry['attribs']['']['when'];
2040 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2043 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2047 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2048 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2050 intval($importer['importer_uid']),
2051 intval($importer['id'])
2057 if($item['deleted'])
2060 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2062 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
2063 $xo = parse_xml_string($item['object'],false);
2064 $xt = parse_xml_string($item['target'],false);
2066 if($xt->type === ACTIVITY_OBJ_NOTE) {
2067 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2069 intval($importer['importer_uid'])
2073 // For tags, the owner cannot remove the tag on the author's copy of the post.
2075 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2076 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2077 $author_copy = (($item['origin']) ? true : false);
2079 if($owner_remove && $author_copy)
2081 if($author_remove || $owner_remove) {
2082 $tags = explode(',',$i[0]['tag']);
2085 foreach($tags as $tag)
2086 if(trim($tag) !== trim($xo->body))
2087 $newtags[] = trim($tag);
2089 q("update item set tag = '%s' where id = %d limit 1",
2090 dbesc(implode(',',$newtags)),
2098 if($item['uri'] == $item['parent-uri']) {
2099 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2100 WHERE `parent-uri` = '%s' AND `uid` = %d",
2102 dbesc(datetime_convert()),
2103 dbesc($item['uri']),
2104 intval($importer['importer_uid'])
2108 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2109 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2111 dbesc(datetime_convert()),
2113 intval($importer['importer_uid'])
2115 if($item['last-child']) {
2116 // ensure that last-child is set in case the comment that had it just got wiped.
2117 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2118 dbesc(datetime_convert()),
2119 dbesc($item['parent-uri']),
2120 intval($item['uid'])
2122 // who is the last child now?
2123 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2124 ORDER BY `created` DESC LIMIT 1",
2125 dbesc($item['parent-uri']),
2126 intval($importer['importer_uid'])
2129 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2141 foreach($feed->get_items() as $item) {
2144 $item_id = $item->get_id();
2145 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2146 if(isset($rawthread[0]['attribs']['']['ref'])) {
2148 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2154 if($importer['page-flags'] == PAGE_COMMUNITY) {
2157 logger('local_delivery: possible community reply');
2160 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2162 // was the top-level post for this reply written by somebody on this site?
2163 // Specifically, the recipient?
2165 $is_a_remote_comment = false;
2167 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2168 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2169 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2170 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2171 AND `item`.`uid` = %d
2176 intval($importer['importer_uid'])
2179 $is_a_remote_comment = true;
2181 // Does this have the characteristics of a community comment?
2182 // If it's a reply to a wall post on a community page it's a
2183 // valid community comment. Also forum_mode makes it valid for sure.
2184 // If neither, it's not.
2186 if($is_a_remote_comment && $community) {
2187 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2188 $is_a_remote_comment = false;
2189 logger('local_delivery: not a community reply');
2193 if($is_a_remote_comment) {
2194 logger('local_delivery: received remote comment');
2196 // remote reply to our post. Import and then notify everybody else.
2197 $datarray = get_atom_elements($feed,$item);
2200 // TODO: make this next part work against both delivery threads of a community post
2202 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2203 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2204 // they won't know what to do so don't report an error. Just quietly die.
2208 $datarray['type'] = 'remote-comment';
2209 $datarray['wall'] = 1;
2210 $datarray['parent-uri'] = $parent_uri;
2211 $datarray['uid'] = $importer['importer_uid'];
2212 $datarray['owner-name'] = $r[0]['name'];
2213 $datarray['owner-link'] = $r[0]['url'];
2214 $datarray['owner-avatar'] = $r[0]['thumb'];
2215 $datarray['contact-id'] = $importer['id'];
2216 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2218 $datarray['type'] = 'activity';
2219 $datarray['gravity'] = GRAVITY_LIKE;
2220 $datarray['last-child'] = 0;
2221 // only one like or dislike per person
2222 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2223 intval($datarray['uid']),
2224 intval($datarray['contact-id']),
2225 dbesc($datarray['verb'])
2231 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2234 $xo = parse_xml_string($datarray['object'],false);
2235 $xt = parse_xml_string($datarray['target'],false);
2237 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2239 // extract tag, if not duplicate, and this user allows tags, add to parent item
2241 if($xo->id && $xo->content) {
2242 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2244 if(! (stristr($r[0]['tag'],$newtag))) {
2245 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2246 intval($importer['importer_uid'])
2248 if(count($i) && ! ($i[0]['blocktags'])) {
2249 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2250 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2260 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2261 // if(! stristr($datarray['tag'],$newtag)) {
2262 // if(strlen($datarray['tag']))
2263 // $datarray['tag'] .= ',';
2264 // $datarray['tag'] .= $newtag;
2269 $posted_id = item_store($datarray);
2273 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2275 intval($importer['importer_uid'])
2278 $parent = $r[0]['parent'];
2281 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2282 dbesc(datetime_convert()),
2283 intval($importer['importer_uid']),
2284 intval($r[0]['parent'])
2287 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2288 dbesc(datetime_convert()),
2289 intval($importer['importer_uid']),
2294 if($posted_id && $parent) {
2296 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2298 if((! $is_like) && (! $importer['self'])) {
2300 require_once('include/enotify.php');
2303 'type' => NOTIFY_COMMENT,
2304 'notify_flags' => $importer['notify-flags'],
2305 'language' => $importer['language'],
2306 'to_name' => $importer['username'],
2307 'to_email' => $importer['email'],
2308 'uid' => $importer['importer_uid'],
2309 'item' => $datarray,
2310 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2311 'source_name' => stripslashes($datarray['author-name']),
2312 'source_link' => $datarray['author-link'],
2313 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2314 ? $importer['thumb'] : $datarray['author-avatar']),
2315 'verb' => ACTIVITY_POST,
2317 'parent' => $parent,
2330 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2332 $item_id = $item->get_id();
2333 $datarray = get_atom_elements($feed,$item);
2335 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2337 intval($importer['importer_uid'])
2340 // Update content if 'updated' changes
2343 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2344 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2345 dbesc($datarray['title']),
2346 dbesc($datarray['body']),
2347 dbesc($datarray['tag']),
2348 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2350 intval($importer['importer_uid'])
2354 // update last-child if it changes
2356 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2357 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2358 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2359 dbesc(datetime_convert()),
2361 intval($importer['importer_uid'])
2363 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2364 intval($allow[0]['data']),
2365 dbesc(datetime_convert()),
2367 intval($importer['importer_uid'])
2373 $datarray['parent-uri'] = $parent_uri;
2374 $datarray['uid'] = $importer['importer_uid'];
2375 $datarray['contact-id'] = $importer['id'];
2376 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2377 $datarray['type'] = 'activity';
2378 $datarray['gravity'] = GRAVITY_LIKE;
2379 // only one like or dislike per person
2380 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 limit 1",
2381 intval($datarray['uid']),
2382 intval($datarray['contact-id']),
2383 dbesc($datarray['verb'])
2390 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2392 $xo = parse_xml_string($datarray['object'],false);
2393 $xt = parse_xml_string($datarray['target'],false);
2395 if($xt->type == ACTIVITY_OBJ_NOTE) {
2396 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2398 intval($importer['importer_uid'])
2403 // extract tag, if not duplicate, add to parent item
2405 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2406 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2407 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2415 $posted_id = item_store($datarray);
2417 // find out if our user is involved in this conversation and wants to be notified.
2419 if($datarray['type'] != 'activity') {
2421 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2423 intval($importer['importer_uid'])
2426 if(count($myconv)) {
2427 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2429 // first make sure this isn't our own post coming back to us from a wall-to-wall event
2430 if(! link_compare($datarray['author-link'],$importer_url)) {
2433 foreach($myconv as $conv) {
2435 // now if we find a match, it means we're in this conversation
2437 if(! link_compare($conv['author-link'],$importer_url))
2440 require_once('include/enotify.php');
2442 $conv_parent = $conv['parent'];
2445 'type' => NOTIFY_COMMENT,
2446 'notify_flags' => $importer['notify-flags'],
2447 'language' => $importer['language'],
2448 'to_name' => $importer['username'],
2449 'to_email' => $importer['email'],
2450 'uid' => $importer['importer_uid'],
2451 'item' => $datarray,
2452 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2453 'source_name' => stripslashes($datarray['author-name']),
2454 'source_link' => $datarray['author-link'],
2455 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2456 ? $importer['thumb'] : $datarray['author-avatar']),
2457 'verb' => ACTIVITY_POST,
2459 'parent' => $conv_parent,
2463 // only send one notification
2475 // Head post of a conversation. Have we seen it? If not, import it.
2478 $item_id = $item->get_id();
2479 $datarray = get_atom_elements($feed,$item);
2481 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2482 $ev = bbtoevent($datarray['body']);
2483 if(x($ev,'desc') && x($ev,'start')) {
2484 $ev['cid'] = $importer['id'];
2485 $ev['uid'] = $importer['uid'];
2486 $ev['uri'] = $item_id;
2487 $ev['edited'] = $datarray['edited'];
2488 $ev['private'] = $datarray['private'];
2490 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2492 intval($importer['uid'])
2495 $ev['id'] = $r[0]['id'];
2496 $xyz = event_store($ev);
2501 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2503 intval($importer['importer_uid'])
2506 // Update content if 'updated' changes
2509 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2510 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2511 dbesc($datarray['title']),
2512 dbesc($datarray['body']),
2513 dbesc($datarray['tag']),
2514 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2516 intval($importer['importer_uid'])
2520 // update last-child if it changes
2522 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2523 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2524 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2525 intval($allow[0]['data']),
2526 dbesc(datetime_convert()),
2528 intval($importer['importer_uid'])
2534 // This is my contact on another system, but it's really me.
2535 // Turn this into a wall post.
2537 if($importer['remote_self'])
2538 $datarray['wall'] = 1;
2540 $datarray['parent-uri'] = $item_id;
2541 $datarray['uid'] = $importer['importer_uid'];
2542 $datarray['contact-id'] = $importer['id'];
2544 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2545 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2546 // but otherwise there's a possible data mixup on the sender's system.
2547 // the tgroup delivery code called from item_store will correct it if it's a forum,
2548 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2549 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
2550 $datarray['owner-name'] = $importer['senderName'];
2551 $datarray['owner-link'] = $importer['url'];
2552 $datarray['owner-avatar'] = $importer['thumb'];
2555 $r = item_store($datarray);
2566 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2567 $url = notags(trim($datarray['author-link']));
2568 $name = notags(trim($datarray['author-name']));
2569 $photo = notags(trim($datarray['author-avatar']));
2571 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2572 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2573 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2575 if(is_array($contact)) {
2576 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2577 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2578 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2579 intval(CONTACT_IS_FRIEND),
2580 intval($contact['id']),
2581 intval($importer['uid'])
2584 // send email notification to owner?
2588 // create contact record
2590 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2591 `blocked`, `readonly`, `pending`, `writable` )
2592 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2593 intval($importer['uid']),
2594 dbesc(datetime_convert()),
2596 dbesc(normalise_link($url)),
2600 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2601 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2603 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2604 intval($importer['uid']),
2608 $contact_record = $r[0];
2610 // create notification
2611 $hash = random_string();
2613 if(is_array($contact_record)) {
2614 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2615 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2616 intval($importer['uid']),
2617 intval($contact_record['id']),
2619 dbesc(datetime_convert())
2622 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2623 intval($importer['uid'])
2627 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2628 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2629 $email = replace_macros($email_tpl, array(
2630 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2632 '$myname' => $r[0]['username'],
2633 '$siteurl' => $a->get_baseurl(),
2634 '$sitename' => $a->config['sitename']
2636 $res = mail($r[0]['email'],
2637 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2639 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2640 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2641 . 'Content-transfer-encoding: 8bit' );
2648 function lose_follower($importer,$contact,$datarray,$item) {
2650 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2651 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2652 intval(CONTACT_IS_SHARING),
2653 intval($contact['id'])
2657 contact_remove($contact['id']);
2661 function lose_sharer($importer,$contact,$datarray,$item) {
2663 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2664 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2665 intval(CONTACT_IS_FOLLOWER),
2666 intval($contact['id'])
2670 contact_remove($contact['id']);
2675 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2677 if(is_array($importer)) {
2678 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2679 intval($importer['uid'])
2683 // Diaspora has different message-ids in feeds than they do
2684 // through the direct Diaspora protocol. If we try and use
2685 // the feed, we'll get duplicates. So don't.
2687 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2690 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2692 // Use a single verify token, even if multiple hubs
2694 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2696 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2698 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2700 if(! strlen($contact['hub-verify'])) {
2701 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2702 dbesc($verify_token),
2703 intval($contact['id'])
2707 post_url($url,$params);
2713 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2717 $name = xmlify($name);
2718 $uri = xmlify($uri);
2721 $photo = xmlify($photo);
2725 $o .= "<name>$name</name>\r\n";
2726 $o .= "<uri>$uri</uri>\r\n";
2727 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2728 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2730 call_hooks('atom_author', $o);
2732 $o .= "</$tag>\r\n";
2736 function atom_entry($item,$type,$author,$owner,$comment = false) {
2740 if(! $item['parent'])
2743 if($item['deleted'])
2744 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2747 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2748 $body = fix_private_photos($item['body'],$owner['uid']);
2750 $body = $item['body'];
2753 $o = "\r\n\r\n<entry>\r\n";
2755 if(is_array($author))
2756 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2758 $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']));
2759 if(strlen($item['owner-name']))
2760 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2762 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2763 $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";
2765 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2766 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2767 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2768 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2769 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2770 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2771 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2773 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2775 if($item['location']) {
2776 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2777 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2781 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2783 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2784 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2787 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2788 if($item['bookmark'])
2789 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2792 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2795 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2797 if($item['signed_text']) {
2798 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2799 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2802 $verb = construct_verb($item);
2803 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2804 $actobj = construct_activity_object($item);
2807 $actarg = construct_activity_target($item);
2811 $tags = item_getfeedtags($item);
2813 foreach($tags as $t) {
2814 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2818 $o .= item_getfeedattach($item);
2820 $mentioned = get_mentions($item);
2824 call_hooks('atom_entry', $o);
2826 $o .= '</entry>' . "\r\n";
2831 function fix_private_photos($s,$uid) {
2833 logger('fix_private_photos');
2835 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2836 $image = $matches[1];
2837 logger('fix_private_photos: found photo ' . $image);
2838 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2839 $i = basename($image);
2840 $i = str_replace('.jpg','',$i);
2841 $x = strpos($i,'-');
2843 $res = substr($i,$x+1);
2844 $i = substr($i,0,$x);
2845 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2851 logger('replacing photo');
2852 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2855 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2863 function item_getfeedtags($item) {
2866 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2868 for($x = 0; $x < $cnt; $x ++) {
2870 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2874 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2876 for($x = 0; $x < $cnt; $x ++) {
2878 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2884 function item_getfeedattach($item) {
2886 $arr = explode(',',$item['attach']);
2888 foreach($arr as $r) {
2890 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2892 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2893 if(intval($matches[2]))
2894 $ret .= 'length="' . intval($matches[2]) . '" ';
2895 if($matches[4] !== ' ')
2896 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2897 $ret .= ' />' . "\r\n";
2906 function item_expire($uid,$days) {
2908 if((! $uid) || (! $days))
2911 $r = q("SELECT * FROM `item`
2913 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
2923 $expire_items = get_pconfig($uid, 'expire','items');
2924 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2926 $expire_notes = get_pconfig($uid, 'expire','notes');
2927 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2929 $expire_starred = get_pconfig($uid, 'expire','starred');
2930 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2932 $expire_photos = get_pconfig($uid, 'expire','photos');
2933 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2935 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2937 foreach($r as $item) {
2939 // don't expire filed items
2941 if(strpos($item['file'],'[') !== false)
2944 // Only expire posts, not photos and photo comments
2946 if($expire_photos==0 && strlen($item['resource-id']))
2948 if($expire_starred==0 && intval($item['starred']))
2950 if($expire_notes==0 && $item['type']=='note')
2952 if($expire_items==0 && $item['type']!='note')
2955 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2956 dbesc(datetime_convert()),
2957 dbesc(datetime_convert()),
2963 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2964 dbesc(datetime_convert()),
2965 dbesc(datetime_convert()),
2966 dbesc($item['parent-uri']),
2967 intval($item['uid'])
2972 proc_run('php',"include/notifier.php","expire","$uid");
2977 function drop_items($items) {
2980 if((! local_user()) && (! $remote_user()))
2984 foreach($items as $item) {
2985 $owner = drop_item($item,false);
2986 if($owner && ! $uid)
2991 // multiple threads may have been deleted, send an expire notification
2994 proc_run('php',"include/notifier.php","expire","$uid");
2998 function drop_item($id,$interactive = true) {
3002 // locate item to be deleted
3004 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3011 notice( t('Item not found.') . EOL);
3012 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3017 $owner = $item['uid'];
3019 // check if logged in user is either the author or owner of this item
3021 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
3025 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3026 dbesc(datetime_convert()),
3027 dbesc(datetime_convert()),
3031 // If item is a link to a photo resource, nuke all the associated photos
3032 // (visitors will not have photo resources)
3033 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3034 // generate a resource-id and therefore aren't intimately linked to the item.
3036 if(strlen($item['resource-id'])) {
3037 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3038 dbesc($item['resource-id']),
3039 intval($item['uid'])
3041 // ignore the result
3044 // If item is a link to an event, nuke the event record.
3046 if(intval($item['event-id'])) {
3047 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3048 intval($item['event-id']),
3049 intval($item['uid'])
3051 // ignore the result
3055 // If it's the parent of a comment thread, kill all the kids
3057 if($item['uri'] == $item['parent-uri']) {
3058 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3059 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3060 dbesc(datetime_convert()),
3061 dbesc(datetime_convert()),
3062 dbesc($item['parent-uri']),
3063 intval($item['uid'])
3065 // ignore the result
3068 // ensure that last-child is set in case the comment that had it just got wiped.
3069 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3070 dbesc(datetime_convert()),
3071 dbesc($item['parent-uri']),
3072 intval($item['uid'])
3074 // who is the last child now?
3075 $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",
3076 dbesc($item['parent-uri']),
3077 intval($item['uid'])
3080 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
3085 $drop_id = intval($item['id']);
3087 // send the notification upstream/downstream as the case may be
3092 proc_run('php',"include/notifier.php","drop","$drop_id");
3093 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3099 notice( t('Permission denied.') . EOL);
3100 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);