3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
8 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
10 // default permissions - anonymous user
12 if(! strlen($owner_nick))
15 $public_feed = (($dfrn_id) ? false : true);
19 if($public_feed && $a->argc > 2) {
20 for($x = 2; $x < $a->argc; $x++) {
21 if($a->argv[$x] == 'converse')
23 if($a->argv[$x] == 'starred')
29 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
31 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`
32 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
33 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
41 $owner_id = $owner['user_uid'];
42 $owner_nick = $owner['nickname'];
44 $birthday = feed_birthday($owner_id,$owner['timezone']);
51 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
55 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
56 $my_id = '1:' . $dfrn_id;
59 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
60 $my_id = '0:' . $dfrn_id;
67 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
75 $groups = init_groups_visitor($contact['id']);
78 for($x = 0; $x < count($groups); $x ++)
79 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
80 $gs = implode('|', $groups);
83 $gs = '<<>>' ; // Impossible to match
85 $sql_extra = sprintf("
86 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
87 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
88 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
89 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
91 intval($contact['id']),
92 intval($contact['id']),
103 if(! strlen($last_update))
104 $last_update = 'now -30 days';
108 $sql_extra .= " AND `contact`.`self` = 1 ";
111 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
113 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
114 `contact`.`name`, `contact`.`photo`, `contact`.`url`,
115 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
116 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
117 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
118 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
119 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
120 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
121 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
122 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
123 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
125 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
132 // Will check further below if this actually returned results.
133 // We will provide an empty feed if that is the case.
137 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
141 $hubxml = feed_hublinks();
143 $salmon = feed_salmonlinks($owner_nick);
145 $atom .= replace_macros($feed_template, array(
146 '$version' => xmlify(FRIENDICA_VERSION),
147 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
148 '$feed_title' => xmlify($owner['name']),
149 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
151 '$salmon' => $salmon,
152 '$name' => xmlify($owner['name']),
153 '$profile_page' => xmlify($owner['url']),
154 '$photo' => xmlify($owner['photo']),
155 '$thumb' => xmlify($owner['thumb']),
156 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
157 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
158 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
159 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : '')
162 call_hooks('atom_feed', $atom);
164 if(! count($items)) {
166 call_hooks('atom_feed_end', $atom);
168 $atom .= '</feed>' . "\r\n";
172 foreach($items as $item) {
174 // public feeds get html, our own nodes use bbcode
178 // catch any email that's in a public conversation and make sure it doesn't leak
186 $atom .= atom_entry($item,$type,null,$owner,true);
189 call_hooks('atom_feed_end', $atom);
191 $atom .= '</feed>' . "\r\n";
197 function construct_verb($item) {
199 return $item['verb'];
200 return ACTIVITY_POST;
203 function construct_activity_object($item) {
205 if($item['object']) {
206 $o = '<as:object>' . "\r\n";
207 $r = parse_xml_string($item['object'],false);
213 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
215 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
217 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
219 if(substr($r->link,0,1) === '<') {
220 // patch up some facebook "like" activity objects that got stored incorrectly
221 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
222 // we can probably remove this hack here and in the following function in a few months time.
223 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
224 $r->link = str_replace('&','&', $r->link);
225 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
229 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
232 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
233 $o .= '</as:object>' . "\r\n";
240 function construct_activity_target($item) {
242 if($item['target']) {
243 $o = '<as:target>' . "\r\n";
244 $r = parse_xml_string($item['target'],false);
248 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
250 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
252 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
254 if(substr($r->link,0,1) === '<') {
255 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
256 $r->link = str_replace('&','&', $r->link);
257 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
261 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
264 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
265 $o .= '</as:target>' . "\r\n";
275 function get_atom_elements($feed,$item) {
277 require_once('library/HTMLPurifier.auto.php');
278 require_once('include/html2bbcode.php');
280 $best_photo = array();
284 $author = $item->get_author();
286 $res['author-name'] = unxmlify($author->get_name());
287 $res['author-link'] = unxmlify($author->get_link());
290 $res['author-name'] = unxmlify($feed->get_title());
291 $res['author-link'] = unxmlify($feed->get_permalink());
293 $res['uri'] = unxmlify($item->get_id());
294 $res['title'] = unxmlify($item->get_title());
295 $res['body'] = unxmlify($item->get_content());
296 $res['plink'] = unxmlify($item->get_link(0));
299 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
303 // look for a photo. We should check media size and find the best one,
304 // but for now let's just find any author photo
306 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
308 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
309 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
310 foreach($base as $link) {
311 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
312 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
313 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
318 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
320 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
321 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
322 if($base && count($base)) {
323 foreach($base as $link) {
324 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
325 $res['author-link'] = unxmlify($link['attribs']['']['href']);
326 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
327 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
328 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
334 // No photo/profile-link on the item - look at the feed level
336 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
337 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
338 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
339 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
340 foreach($base as $link) {
341 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
342 $res['author-link'] = unxmlify($link['attribs']['']['href']);
343 if(! $res['author-avatar']) {
344 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
345 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
350 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
352 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
353 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
355 if($base && count($base)) {
356 foreach($base as $link) {
357 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
358 $res['author-link'] = unxmlify($link['attribs']['']['href']);
359 if(! (x($res,'author-avatar'))) {
360 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
361 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
368 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
369 if($apps && $apps[0]['attribs']['']['source']) {
370 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
371 if($res['app'] === 'web')
372 $res['app'] = 'OStatus';
375 // base64 encoded json structure representing Diaspora signature
377 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
379 $res['dsprsig'] = unxmlify($dsig[0]['data']);
382 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
384 $res['guid'] = unxmlify($dguid[0]['data']);
386 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
388 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
392 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
395 $have_real_body = false;
397 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
399 $have_real_body = true;
400 $res['body'] = $rawenv[0]['data'];
401 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
402 // make sure nobody is trying to sneak some html tags by us
403 $res['body'] = notags(base64url_decode($res['body']));
406 $maxlen = get_max_import_size();
407 if($maxlen && (strlen($res['body']) > $maxlen))
408 $res['body'] = substr($res['body'],0, $maxlen);
410 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
411 // the content type. Our own network only emits text normally, though it might have been converted to
412 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
413 // have to assume it is all html and needs to be purified.
415 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
416 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
417 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
420 if((strpos($res['body'],'<') !== false) || (strpos($res['body'],'>') !== false)) {
422 $res['body'] = reltoabs($res['body'],$base_url);
424 $res['body'] = html2bb_video($res['body']);
426 $res['body'] = oembed_html2bbcode($res['body']);
428 $config = HTMLPurifier_Config::createDefault();
429 $config->set('Cache.DefinitionImpl', null);
431 // we shouldn't need a whitelist, because the bbcode converter
432 // will strip out any unsupported tags.
433 // $config->set('HTML.Allowed', 'p,b,a[href],i');
435 $purifier = new HTMLPurifier($config);
436 $res['body'] = $purifier->purify($res['body']);
438 $res['body'] = html2bbcode($res['body']);
441 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
442 if($allow && $allow[0]['data'] == 1)
443 $res['last-child'] = 1;
445 $res['last-child'] = 0;
447 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
448 if($private && $private[0]['data'] == 1)
453 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
454 if($extid && $extid[0]['data'])
455 $res['extid'] = $extid[0]['data'];
457 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
459 $res['location'] = unxmlify($rawlocation[0]['data']);
462 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
464 $res['created'] = unxmlify($rawcreated[0]['data']);
467 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
469 $res['edited'] = unxmlify($rawedited[0]['data']);
471 if((x($res,'edited')) && (! (x($res,'created'))))
472 $res['created'] = $res['edited'];
474 if(! $res['created'])
475 $res['created'] = $item->get_date('c');
478 $res['edited'] = $item->get_date('c');
481 // Disallow time travelling posts
483 $d1 = strtotime($res['created']);
484 $d2 = strtotime($res['edited']);
485 $d3 = strtotime('now');
488 $res['created'] = datetime_convert();
490 $res['edited'] = datetime_convert();
492 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
493 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
494 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
495 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
496 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
497 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
498 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
499 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
500 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
502 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
503 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
505 foreach($base as $link) {
506 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
507 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
508 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
513 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
515 $res['coord'] = unxmlify($rawgeo[0]['data']);
518 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
520 // select between supported verbs
523 $res['verb'] = unxmlify($rawverb[0]['data']);
526 // translate OStatus unfollow to activity streams if it happened to get selected
528 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
529 $res['verb'] = ACTIVITY_UNFOLLOW;
531 $cats = $item->get_categories();
534 foreach($cats as $cat) {
535 $term = $cat->get_term();
537 $term = $cat->get_label();
538 $scheme = $cat->get_scheme();
539 if($scheme && $term && stristr($scheme,'X-DFRN:'))
540 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
542 $tag_arr[] = notags(trim($term));
544 $res['tag'] = implode(',', $tag_arr);
547 $attach = $item->get_enclosures();
550 foreach($attach as $att) {
551 $len = intval($att->get_length());
552 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
553 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
554 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
555 if(strpos($type,';'))
556 $type = substr($type,0,strpos($type,';'));
557 if((! $link) || (strpos($link,'http') !== 0))
563 $type = 'application/octet-stream';
565 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
567 $res['attach'] = implode(',', $att_arr);
570 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
573 $res['object'] = '<object>' . "\n";
574 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
575 $res['object-type'] = $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'];
576 $res['object'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
578 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
579 $res['object'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
580 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
581 $res['object'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
582 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
583 $res['object'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
584 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
585 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
587 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
588 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
589 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
590 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
592 $body = html2bb_video($body);
594 $config = HTMLPurifier_Config::createDefault();
595 $config->set('Cache.DefinitionImpl', null);
597 $purifier = new HTMLPurifier($config);
598 $body = $purifier->purify($body);
599 $body = html2bbcode($body);
602 $res['object'] .= '<content>' . $body . '</content>' . "\n";
605 $res['object'] .= '</object>' . "\n";
608 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
611 $res['target'] = '<target>' . "\n";
612 if($rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
613 $res['target'] .= '<type>' . $rawobj[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
615 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
616 $res['target'] .= '<id>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
618 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
619 $res['target'] .= '<link>' . encode_rel_links($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
620 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
621 $res['target'] .= '<title>' . $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
622 if($rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
623 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
625 $body = $rawobj[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
626 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
627 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
628 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
630 $body = html2bb_video($body);
632 $config = HTMLPurifier_Config::createDefault();
633 $config->set('Cache.DefinitionImpl', null);
635 $purifier = new HTMLPurifier($config);
636 $body = $purifier->purify($body);
637 $body = html2bbcode($body);
640 $res['target'] .= '<content>' . $body . '</content>' . "\n";
643 $res['target'] .= '</target>' . "\n";
646 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
648 call_hooks('parse_atom', $arr);
653 function encode_rel_links($links) {
655 if(! ((is_array($links)) && (count($links))))
657 foreach($links as $link) {
659 if($link['attribs']['']['rel'])
660 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
661 if($link['attribs']['']['type'])
662 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
663 if($link['attribs']['']['href'])
664 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
665 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
666 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
667 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
668 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
674 function item_store($arr,$force_parent = false) {
676 // If a Diaspora signature structure was passed in, pull it out of the
677 // item array and set it aside for later storage.
680 if(x($arr,'dsprsig')) {
681 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
682 unset($arr['dsprsig']);
685 if(x($arr, 'gravity'))
686 $arr['gravity'] = intval($arr['gravity']);
687 elseif($arr['parent-uri'] === $arr['uri'])
689 elseif(activity_match($arr['verb'],ACTIVITY_POST))
692 $arr['gravity'] = 6; // extensible catchall
695 $arr['type'] = 'remote';
697 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
699 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
700 $arr['body'] = strip_tags($arr['body']);
703 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
704 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
705 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
706 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
707 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
708 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
709 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
710 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
711 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
712 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
713 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
714 $arr['commented'] = datetime_convert();
715 $arr['received'] = datetime_convert();
716 $arr['changed'] = datetime_convert();
717 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
718 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
719 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
720 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
721 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
723 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
724 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
725 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
726 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
727 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
728 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
729 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
730 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
731 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
732 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
733 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
734 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
735 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
736 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
737 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
738 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
739 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
740 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
741 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
743 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 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1050 logger('dfrn_deliver: ' . $url);
1052 $xml = fetch_url($url);
1054 $curl_stat = $a->get_curl_code();
1056 return(-1); // timed out
1058 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1063 if(strpos($xml,'<?xml') === false) {
1064 logger('dfrn_deliver: no valid XML returned');
1065 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1069 $res = parse_xml_string($xml);
1071 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1072 return (($res->status) ? $res->status : 3);
1074 $postvars = array();
1075 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1076 $challenge = hex2bin((string) $res->challenge);
1077 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1078 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1080 $final_dfrn_id = '';
1083 if(($contact['duplex'] && strlen($contact['pubkey']))
1084 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1085 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1086 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1087 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1090 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1091 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1094 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1096 if(strpos($final_dfrn_id,':') == 1)
1097 $final_dfrn_id = substr($final_dfrn_id,2);
1099 if($final_dfrn_id != $orig_id) {
1100 logger('dfrn_deliver: wrong dfrn_id.');
1101 // did not decode properly - cannot trust this site
1105 $postvars['dfrn_id'] = $idtosend;
1106 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1108 $postvars['dissolve'] = '1';
1111 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1112 $postvars['data'] = $atom;
1113 $postvars['perm'] = 'rw';
1116 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1117 $postvars['perm'] = 'r';
1120 if($rino && $rino_allowed && (! $dissolve)) {
1121 $key = substr(random_string(),0,16);
1122 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1123 $postvars['data'] = $data;
1124 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1127 if($dfrn_version >= 2.1) {
1128 if(($contact['duplex'] && strlen($contact['pubkey']))
1129 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1130 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1132 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1135 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1139 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1140 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1143 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1147 logger('md5 rawkey ' . md5($postvars['key']));
1149 $postvars['key'] = bin2hex($postvars['key']);
1152 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1154 $xml = post_url($contact['notify'],$postvars);
1156 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1158 $curl_stat = $a->get_curl_code();
1159 if((! $curl_stat) || (! strlen($xml)))
1160 return(-1); // timed out
1162 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1165 if(strpos($xml,'<?xml') === false) {
1166 logger('dfrn_deliver: phase 2: no valid XML returned');
1167 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1171 $res = parse_xml_string($xml);
1173 return $res->status;
1179 * consume_feed - process atom feed and update anything/everything we might need to update
1181 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1183 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1184 * It is this person's stuff that is going to be updated.
1185 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1186 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1187 * have a contact record.
1188 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1189 * might not) try and subscribe to it.
1190 * $datedir sorts in reverse order
1191 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1192 * imported prior to its children being seen in the stream unless we are certain
1193 * of how the feed is arranged/ordered.
1194 * With $pass = 1, we only pull parent items out of the stream.
1195 * With $pass = 2, we only pull children (comments/likes).
1197 * So running this twice, first with pass 1 and then with pass 2 will do the right
1198 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1199 * model where comments can have sub-threads. That would require some massive sorting
1200 * to get all the feed items into a mostly linear ordering, and might still require
1204 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1206 require_once('library/simplepie/simplepie.inc');
1208 if(! strlen($xml)) {
1209 logger('consume_feed: empty input');
1213 $feed = new SimplePie();
1214 $feed->set_raw_data($xml);
1216 $feed->enable_order_by_date(true);
1218 $feed->enable_order_by_date(false);
1222 logger('consume_feed: Error parsing XML: ' . $feed->error());
1224 $permalink = $feed->get_permalink();
1226 // Check at the feed level for updated contact name and/or photo
1230 $photo_timestamp = '';
1234 $hubs = $feed->get_links('hub');
1237 $hub = implode(',', $hubs);
1239 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1241 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1243 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1244 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1245 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1246 $new_name = $elems['name'][0]['data'];
1248 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1249 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1250 $photo_url = $elems['link'][0]['attribs']['']['href'];
1253 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1254 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1258 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1259 logger('consume_feed: Updating photo for ' . $contact['name']);
1260 require_once("Photo.php");
1261 $photo_failure = false;
1262 $have_photo = false;
1264 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1265 intval($contact['id']),
1266 intval($contact['uid'])
1269 $resource_id = $r[0]['resource-id'];
1273 $resource_id = photo_new_resource();
1276 $img_str = fetch_url($photo_url,true);
1277 $img = new Photo($img_str);
1278 if($img->is_valid()) {
1280 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1281 dbesc($resource_id),
1282 intval($contact['id']),
1283 intval($contact['uid'])
1287 $img->scaleImageSquare(175);
1289 $hash = $resource_id;
1290 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1292 $img->scaleImage(80);
1293 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1295 $img->scaleImage(48);
1296 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1300 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1301 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1302 dbesc(datetime_convert()),
1303 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.jpg'),
1304 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.jpg'),
1305 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.jpg'),
1306 intval($contact['uid']),
1307 intval($contact['id'])
1312 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1313 $r = q("select * from contact where uid = %d and id = %d limit 1",
1314 intval($contact['uid']),
1315 intval($contact['id'])
1318 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1319 dbesc(notags(trim($new_name))),
1320 dbesc(datetime_convert()),
1321 intval($contact['uid']),
1322 intval($contact['id'])
1325 // do our best to update the name on content items
1328 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1329 dbesc(notags(trim($new_name))),
1330 dbesc($r[0]['name']),
1331 dbesc($r[0]['url']),
1332 intval($contact['uid'])
1337 if(strlen($birthday)) {
1338 if(substr($birthday,0,4) != $contact['bdyear']) {
1339 logger('consume_feed: updating birthday: ' . $birthday);
1343 * Add new birthday event for this person
1345 * $bdtext is just a readable placeholder in case the event is shared
1346 * with others. We will replace it during presentation to our $importer
1347 * to contain a sparkle link and perhaps a photo.
1351 $bdtext = t('Birthday:') . ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ;
1354 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`desc`,`type`)
1355 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1356 intval($contact['uid']),
1357 intval($contact['id']),
1358 dbesc(datetime_convert()),
1359 dbesc(datetime_convert()),
1360 dbesc(datetime_convert('UTC','UTC', $birthday)),
1361 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1369 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1370 dbesc(substr($birthday,0,4)),
1371 intval($contact['uid']),
1372 intval($contact['id'])
1375 // This function is called twice without reloading the contact
1376 // Make sure we only create one event. This is why &$contact
1377 // is a reference var in this function
1379 $contact['bdyear'] = substr($birthday,0,4);
1385 // process any deleted entries
1387 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1388 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1389 foreach($del_entries as $dentry) {
1391 if(isset($dentry['attribs']['']['ref'])) {
1392 $uri = $dentry['attribs']['']['ref'];
1394 if(isset($dentry['attribs']['']['when'])) {
1395 $when = $dentry['attribs']['']['when'];
1396 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1399 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1401 if($deleted && is_array($contact)) {
1402 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1403 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1405 intval($importer['uid']),
1406 intval($contact['id'])
1411 if(! $item['deleted'])
1412 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1414 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1415 $xo = parse_xml_string($item['object'],false);
1416 $xt = parse_xml_string($item['target'],false);
1417 if($xt->type === ACTIVITY_OBJ_NOTE) {
1418 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1420 intval($importer['importer_uid'])
1424 // For tags, the owner cannot remove the tag on the author's copy of the post.
1426 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1427 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1428 $author_copy = (($item['origin']) ? true : false);
1430 if($owner_remove && $author_copy)
1432 if($author_remove || $owner_remove) {
1433 $tags = explode(',',$i[0]['tag']);
1436 foreach($tags as $tag)
1437 if(trim($tag) !== trim($xo->body))
1438 $newtags[] = trim($tag);
1440 q("update item set tag = '%s' where id = %d limit 1",
1441 dbesc(implode(',',$newtags)),
1449 if($item['uri'] == $item['parent-uri']) {
1450 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1451 `body` = '', `title` = ''
1452 WHERE `parent-uri` = '%s' AND `uid` = %d",
1454 dbesc(datetime_convert()),
1455 dbesc($item['uri']),
1456 intval($importer['uid'])
1460 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1461 `body` = '', `title` = ''
1462 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1464 dbesc(datetime_convert()),
1466 intval($importer['uid'])
1468 if($item['last-child']) {
1469 // ensure that last-child is set in case the comment that had it just got wiped.
1470 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1471 dbesc(datetime_convert()),
1472 dbesc($item['parent-uri']),
1473 intval($item['uid'])
1475 // who is the last child now?
1476 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1477 ORDER BY `created` DESC LIMIT 1",
1478 dbesc($item['parent-uri']),
1479 intval($importer['uid'])
1482 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1493 // Now process the feed
1495 if($feed->get_item_quantity()) {
1497 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1499 // in inverse date order
1501 $items = array_reverse($feed->get_items());
1503 $items = $feed->get_items();
1506 foreach($items as $item) {
1509 $item_id = $item->get_id();
1510 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1511 if(isset($rawthread[0]['attribs']['']['ref'])) {
1513 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1516 if(($is_reply) && is_array($contact)) {
1521 // Have we seen it? If not, import it.
1523 $item_id = $item->get_id();
1524 $datarray = get_atom_elements($feed,$item);
1527 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1528 $datarray['author-name'] = $contact['name'];
1529 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1530 $datarray['author-link'] = $contact['url'];
1531 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1532 $datarray['author-avatar'] = $contact['thumb'];
1534 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1535 logger('consume_feed: no author information! ' . print_r($datarray,true));
1539 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1541 intval($importer['uid'])
1544 // Update content if 'updated' changes
1547 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1548 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1549 dbesc($datarray['title']),
1550 dbesc($datarray['body']),
1551 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1553 intval($importer['uid'])
1557 // update last-child if it changes
1559 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1560 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1561 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1562 dbesc(datetime_convert()),
1564 intval($importer['uid'])
1566 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1567 intval($allow[0]['data']),
1568 dbesc(datetime_convert()),
1570 intval($importer['uid'])
1576 $force_parent = false;
1577 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1578 if($contact['network'] === NETWORK_OSTATUS)
1579 $force_parent = true;
1580 if(strlen($datarray['title']))
1581 unset($datarray['title']);
1582 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1583 dbesc(datetime_convert()),
1585 intval($importer['uid'])
1587 $datarray['last-child'] = 1;
1590 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1591 // one way feed - no remote comment ability
1592 $datarray['last-child'] = 0;
1594 $datarray['parent-uri'] = $parent_uri;
1595 $datarray['uid'] = $importer['uid'];
1596 $datarray['contact-id'] = $contact['id'];
1597 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
1598 $datarray['type'] = 'activity';
1599 $datarray['gravity'] = GRAVITY_LIKE;
1602 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1603 $xo = parse_xml_string($datarray['object'],false);
1604 $xt = parse_xml_string($datarray['target'],false);
1606 if($xt->type == ACTIVITY_OBJ_NOTE) {
1607 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
1609 intval($importer['importer_uid'])
1614 // extract tag, if not duplicate, add to parent item
1615 if($xo->id && $xo->content) {
1616 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
1617 if(! (stristr($r[0]['tag'],$newtag))) {
1618 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
1619 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
1627 $r = item_store($datarray,$force_parent);
1633 // Head post of a conversation. Have we seen it? If not, import it.
1635 $item_id = $item->get_id();
1637 $datarray = get_atom_elements($feed,$item);
1639 if(is_array($contact)) {
1640 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1641 $datarray['author-name'] = $contact['name'];
1642 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1643 $datarray['author-link'] = $contact['url'];
1644 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1645 $datarray['author-avatar'] = $contact['thumb'];
1648 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1649 logger('consume_feed: no author information! ' . print_r($datarray,true));
1653 // special handling for events
1655 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
1656 $ev = bbtoevent($datarray['body']);
1657 if(x($ev,'desc') && x($ev,'start')) {
1658 $ev['uid'] = $importer['uid'];
1659 $ev['uri'] = $item_id;
1660 $ev['edited'] = $datarray['edited'];
1661 $ev['private'] = $datarray['private'];
1663 if(is_array($contact))
1664 $ev['cid'] = $contact['id'];
1665 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1667 intval($importer['uid'])
1670 $ev['id'] = $r[0]['id'];
1671 $xyz = event_store($ev);
1676 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1678 intval($importer['uid'])
1681 // Update content if 'updated' changes
1684 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1685 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1686 dbesc($datarray['title']),
1687 dbesc($datarray['body']),
1688 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1690 intval($importer['uid'])
1694 // update last-child if it changes
1696 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1697 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
1698 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1699 intval($allow[0]['data']),
1700 dbesc(datetime_convert()),
1702 intval($importer['uid'])
1708 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
1709 logger('consume-feed: New follower');
1710 new_follower($importer,$contact,$datarray,$item);
1713 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
1714 lose_follower($importer,$contact,$datarray,$item);
1718 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
1719 logger('consume-feed: New friend request');
1720 new_follower($importer,$contact,$datarray,$item,true);
1723 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
1724 lose_sharer($importer,$contact,$datarray,$item);
1729 if(! is_array($contact))
1732 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1733 if(strlen($datarray['title']))
1734 unset($datarray['title']);
1735 $datarray['last-child'] = 1;
1738 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
1739 // one way feed - no remote comment ability
1740 $datarray['last-child'] = 0;
1743 // This is my contact on another system, but it's really me.
1744 // Turn this into a wall post.
1746 if($contact['remote_self'])
1747 $datarray['wall'] = 1;
1749 $datarray['parent-uri'] = $item_id;
1750 $datarray['uid'] = $importer['uid'];
1751 $datarray['contact-id'] = $contact['id'];
1752 $r = item_store($datarray);
1760 function local_delivery($importer,$data) {
1764 if($importer['readonly']) {
1765 // We aren't receiving stuff from this person. But we will quietly ignore them
1766 // rather than a blatant "go away" message.
1767 logger('local_delivery: ignoring');
1772 // Consume notification feed. This may differ from consuming a public feed in several ways
1773 // - might contain email or friend suggestions
1774 // - might contain remote followup to our message
1775 // - in which case we need to accept it and then notify other conversants
1776 // - we may need to send various email notifications
1778 $feed = new SimplePie();
1779 $feed->set_raw_data($data);
1780 $feed->enable_order_by_date(false);
1783 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
1784 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
1785 $base = $reloc[0]['child'][NAMESPACE_DFRN];
1787 $newloc['uid'] = $importer['importer_uid'];
1788 $newloc['cid'] = $importer['id'];
1789 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
1790 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
1791 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
1792 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
1793 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
1794 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
1795 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
1796 $newloc['site-pubkey'] = notags(unxmlify($base['site-pubkey'][0]['data']));
1797 $newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
1798 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));
1801 // merge with current record, current contents have priority
1802 // update record, set url-updated
1803 // update profile photos
1808 // handle friend suggestion notification
1810 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
1811 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
1812 $base = $sugg[0]['child'][NAMESPACE_DFRN];
1814 $fsugg['uid'] = $importer['importer_uid'];
1815 $fsugg['cid'] = $importer['id'];
1816 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
1817 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
1818 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
1819 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
1820 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
1822 // Does our member already have a friend matching this description?
1824 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1825 dbesc($fsugg['name']),
1826 dbesc(normalise_link($fsugg['url'])),
1827 intval($fsugg['uid'])
1832 // Do we already have an fcontact record for this person?
1835 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1836 dbesc($fsugg['url']),
1837 dbesc($fsugg['name']),
1838 dbesc($fsugg['request'])
1844 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
1845 dbesc($fsugg['name']),
1846 dbesc($fsugg['url']),
1847 dbesc($fsugg['photo']),
1848 dbesc($fsugg['request'])
1850 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1851 dbesc($fsugg['url']),
1852 dbesc($fsugg['name']),
1853 dbesc($fsugg['request'])
1858 // database record did not get created. Quietly give up.
1862 $hash = random_string();
1864 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
1865 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
1866 intval($fsugg['uid']),
1868 intval($fsugg['cid']),
1869 dbesc($fsugg['body']),
1871 dbesc(datetime_convert()),
1876 'type' => NOTIFY_SUGGEST,
1877 'notify_flags' => $importer['notify-flags'],
1878 'language' => $importer['language'],
1879 'to_name' => $importer['username'],
1880 'to_email' => $importer['email'],
1881 'uid' => $importer['importer_uid'],
1883 'link' => $a->get_baseurl() . '/notifications/intros',
1884 'source_name' => $importer['name'],
1885 'source_link' => $importer['url'],
1886 'source_photo' => $importer['photo'],
1887 'verb' => ACTIVITY_REQ_FRIEND,
1896 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
1897 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
1899 logger('local_delivery: private message received');
1902 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
1905 $msg['uid'] = $importer['importer_uid'];
1906 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
1907 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
1908 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
1909 $msg['contact-id'] = $importer['id'];
1910 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
1911 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
1913 $msg['replied'] = 0;
1914 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
1915 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
1916 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
1920 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
1921 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
1923 // send notifications.
1925 require_once('include/enotify.php');
1927 $notif_params = array(
1928 'type' => NOTIFY_MAIL,
1929 'notify_flags' => $importer['notify-flags'],
1930 'language' => $importer['language'],
1931 'to_name' => $importer['username'],
1932 'to_email' => $importer['email'],
1933 'uid' => $importer['importer_uid'],
1935 'source_name' => $msg['from-name'],
1936 'source_link' => $importer['url'],
1937 'source_photo' => $importer['thumb'],
1938 'verb' => ACTIVITY_POST,
1942 notification($notif_params);
1948 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
1950 // process any deleted entries
1952 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1953 if(is_array($del_entries) && count($del_entries)) {
1954 foreach($del_entries as $dentry) {
1956 if(isset($dentry['attribs']['']['ref'])) {
1957 $uri = $dentry['attribs']['']['ref'];
1959 if(isset($dentry['attribs']['']['when'])) {
1960 $when = $dentry['attribs']['']['when'];
1961 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1964 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1968 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
1969 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d LIMIT 1",
1971 intval($importer['importer_uid']),
1972 intval($importer['id'])
1978 if($item['deleted'])
1981 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1983 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTVITY_OBJ_TAGTERM)) {
1984 $xo = parse_xml_string($item['object'],false);
1985 $xt = parse_xml_string($item['target'],false);
1986 if($xt->type === ACTIVITY_OBJ_NOTE) {
1987 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1989 intval($importer['importer_uid'])
1993 // For tags, the owner cannot remove the tag on the author's copy of the post.
1995 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1996 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1997 $author_copy = (($item['origin']) ? true : false);
1999 if($owner_remove && $author_copy)
2001 if($author_remove || $owner_remove) {
2002 $tags = explode(',',$i[0]['tag']);
2005 foreach($tags as $tag)
2006 if(trim($tag) !== trim($xo->body))
2007 $newtags[] = trim($tag);
2009 q("update item set tag = '%s' where id = %d limit 1",
2010 dbesc(implode(',',$newtags)),
2018 if($item['uri'] == $item['parent-uri']) {
2019 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2020 WHERE `parent-uri` = '%s' AND `uid` = %d",
2022 dbesc(datetime_convert()),
2023 dbesc($item['uri']),
2024 intval($importer['importer_uid'])
2028 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s'
2029 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2031 dbesc(datetime_convert()),
2033 intval($importer['importer_uid'])
2035 if($item['last-child']) {
2036 // ensure that last-child is set in case the comment that had it just got wiped.
2037 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2038 dbesc(datetime_convert()),
2039 dbesc($item['parent-uri']),
2040 intval($item['uid'])
2042 // who is the last child now?
2043 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2044 ORDER BY `created` DESC LIMIT 1",
2045 dbesc($item['parent-uri']),
2046 intval($importer['importer_uid'])
2049 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2061 foreach($feed->get_items() as $item) {
2064 $item_id = $item->get_id();
2065 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2066 if(isset($rawthread[0]['attribs']['']['ref'])) {
2068 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2074 if($importer['page-flags'] == PAGE_COMMUNITY) {
2077 logger('local_delivery: possible community reply');
2080 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2082 // was the top-level post for this reply written by somebody on this site?
2083 // Specifically, the recipient?
2085 $is_a_remote_comment = false;
2087 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2088 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2089 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2090 WHERE `item`.`uri` = '%s' AND `item`.`parent-uri` = '%s'
2091 AND `item`.`uid` = %d
2096 intval($importer['importer_uid'])
2099 $is_a_remote_comment = true;
2101 // Does this have the characteristics of a community comment?
2102 // If it's a reply to a wall post on a community page it's a
2103 // valid community comment. Also forum_mode makes it valid for sure.
2104 // If neither, it's not.
2106 if($is_a_remote_comment && $community) {
2107 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2108 $is_a_remote_comment = false;
2109 logger('local_delivery: not a community reply');
2113 if($is_a_remote_comment) {
2114 logger('local_delivery: received remote comment');
2116 // remote reply to our post. Import and then notify everybody else.
2117 $datarray = get_atom_elements($feed,$item);
2120 // TODO: make this next part work against both delivery threads of a community post
2122 // if((! link_compare($datarray['author-link'],$importer['url'])) && (! $community)) {
2123 // logger('local_delivery: received relay claiming to be from ' . $importer['url'] . ' however comment author url is ' . $datarray['author-link'] );
2124 // they won't know what to do so don't report an error. Just quietly die.
2128 $datarray['type'] = 'remote-comment';
2129 $datarray['wall'] = 1;
2130 $datarray['parent-uri'] = $parent_uri;
2131 $datarray['uid'] = $importer['importer_uid'];
2132 $datarray['owner-name'] = $r[0]['name'];
2133 $datarray['owner-link'] = $r[0]['url'];
2134 $datarray['owner-avatar'] = $r[0]['thumb'];
2135 $datarray['contact-id'] = $importer['id'];
2136 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2138 $datarray['type'] = 'activity';
2139 $datarray['gravity'] = GRAVITY_LIKE;
2140 $datarray['last-child'] = 0;
2143 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2146 $xo = parse_xml_string($datarray['object'],false);
2147 $xt = parse_xml_string($datarray['target'],false);
2149 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id == $r[0]['uri'])) {
2151 // extract tag, if not duplicate, and this user allows tags, add to parent item
2153 if($xo->id && $xo->content) {
2154 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2156 if(! (stristr($r[0]['tag'],$newtag))) {
2157 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2158 intval($importer['importer_uid'])
2160 if(count($i) && ! ($i[0]['blocktags'])) {
2161 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2162 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2172 // $newtag = '@[url=' . $a->get_baseurl() . '/profile/' . $importer['nickname'] . ']' . $importer['username'] . '[/url]';
2173 // if(! stristr($datarray['tag'],$newtag)) {
2174 // if(strlen($datarray['tag']))
2175 // $datarray['tag'] .= ',';
2176 // $datarray['tag'] .= $newtag;
2181 $posted_id = item_store($datarray);
2185 $r = q("SELECT `parent` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2187 intval($importer['importer_uid'])
2190 $parent = $r[0]['parent'];
2193 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2194 dbesc(datetime_convert()),
2195 intval($importer['importer_uid']),
2196 intval($r[0]['parent'])
2199 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2200 dbesc(datetime_convert()),
2201 intval($importer['importer_uid']),
2206 if($posted_id && $parent) {
2208 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2210 if((! $is_like) && (! $importer['self'])) {
2212 require_once('include/enotify.php');
2215 'type' => NOTIFY_COMMENT,
2216 'notify_flags' => $importer['notify-flags'],
2217 'language' => $importer['language'],
2218 'to_name' => $importer['username'],
2219 'to_email' => $importer['email'],
2220 'uid' => $importer['importer_uid'],
2221 'item' => $datarray,
2222 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2223 'source_name' => stripslashes($datarray['author-name']),
2224 'source_link' => $datarray['author-link'],
2225 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2226 ? $importer['thumb'] : $datarray['author-avatar']),
2227 'verb' => ACTIVITY_POST,
2229 'parent' => $parent,
2242 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
2244 $item_id = $item->get_id();
2245 $datarray = get_atom_elements($feed,$item);
2247 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2249 intval($importer['importer_uid'])
2252 // Update content if 'updated' changes
2255 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2256 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2257 dbesc($datarray['title']),
2258 dbesc($datarray['body']),
2259 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2261 intval($importer['importer_uid'])
2265 // update last-child if it changes
2267 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2268 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2269 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2270 dbesc(datetime_convert()),
2272 intval($importer['importer_uid'])
2274 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2275 intval($allow[0]['data']),
2276 dbesc(datetime_convert()),
2278 intval($importer['importer_uid'])
2284 $datarray['parent-uri'] = $parent_uri;
2285 $datarray['uid'] = $importer['importer_uid'];
2286 $datarray['contact-id'] = $importer['id'];
2287 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
2288 $datarray['type'] = 'activity';
2289 $datarray['gravity'] = GRAVITY_LIKE;
2292 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2294 $xo = parse_xml_string($datarray['object'],false);
2295 $xt = parse_xml_string($datarray['target'],false);
2297 if($xt->type == ACTIVITY_OBJ_NOTE) {
2298 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2300 intval($importer['importer_uid'])
2305 // extract tag, if not duplicate, add to parent item
2307 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
2308 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2309 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2317 $posted_id = item_store($datarray);
2319 // find out if our user is involved in this conversation and wants to be notified.
2321 if($datarray['type'] != 'activity') {
2323 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 ",
2325 intval($importer['importer_uid'])
2328 if(count($myconv)) {
2329 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
2330 foreach($myconv as $conv) {
2332 if(! link_compare($conv['author-link'],$importer_url))
2335 require_once('include/enotify.php');
2337 $conv_parent = $conv['parent'];
2340 'type' => NOTIFY_COMMENT,
2341 'notify_flags' => $importer['notify-flags'],
2342 'language' => $importer['language'],
2343 'to_name' => $importer['username'],
2344 'to_email' => $importer['email'],
2345 'uid' => $importer['importer_uid'],
2346 'item' => $datarray,
2347 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
2348 'source_name' => stripslashes($datarray['author-name']),
2349 'source_link' => $datarray['author-link'],
2350 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
2351 ? $importer['thumb'] : $datarray['author-avatar']),
2352 'verb' => ACTIVITY_POST,
2354 'parent' => $conv_parent,
2368 // Head post of a conversation. Have we seen it? If not, import it.
2371 $item_id = $item->get_id();
2372 $datarray = get_atom_elements($feed,$item);
2374 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2375 $ev = bbtoevent($datarray['body']);
2376 if(x($ev,'desc') && x($ev,'start')) {
2377 $ev['cid'] = $importer['id'];
2378 $ev['uid'] = $importer['uid'];
2379 $ev['uri'] = $item_id;
2380 $ev['edited'] = $datarray['edited'];
2381 $ev['private'] = $datarray['private'];
2383 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2385 intval($importer['uid'])
2388 $ev['id'] = $r[0]['id'];
2389 $xyz = event_store($ev);
2394 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2396 intval($importer['importer_uid'])
2399 // Update content if 'updated' changes
2402 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2403 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2404 dbesc($datarray['title']),
2405 dbesc($datarray['body']),
2406 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2408 intval($importer['importer_uid'])
2412 // update last-child if it changes
2414 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2415 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2416 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2417 intval($allow[0]['data']),
2418 dbesc(datetime_convert()),
2420 intval($importer['importer_uid'])
2426 // This is my contact on another system, but it's really me.
2427 // Turn this into a wall post.
2429 if($contact['remote_self'])
2430 $datarray['wall'] = 1;
2432 $datarray['parent-uri'] = $item_id;
2433 $datarray['uid'] = $importer['importer_uid'];
2434 $datarray['contact-id'] = $importer['id'];
2435 $r = item_store($datarray);
2446 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
2447 $url = notags(trim($datarray['author-link']));
2448 $name = notags(trim($datarray['author-name']));
2449 $photo = notags(trim($datarray['author-avatar']));
2451 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
2452 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
2453 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
2455 if(is_array($contact)) {
2456 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
2457 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
2458 $r = q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
2459 intval(CONTACT_IS_FRIEND),
2460 intval($contact['id']),
2461 intval($importer['uid'])
2464 // send email notification to owner?
2468 // create contact record
2470 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2471 `blocked`, `readonly`, `pending`, `writable` )
2472 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
2473 intval($importer['uid']),
2474 dbesc(datetime_convert()),
2476 dbesc(normalise_link($url)),
2480 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
2481 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
2483 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
2484 intval($importer['uid']),
2488 $contact_record = $r[0];
2490 // create notification
2491 $hash = random_string();
2493 if(is_array($contact_record)) {
2494 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
2495 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
2496 intval($importer['uid']),
2497 intval($contact_record['id']),
2499 dbesc(datetime_convert())
2502 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
2503 intval($importer['uid'])
2507 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
2508 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
2509 $email = replace_macros($email_tpl, array(
2510 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
2512 '$myname' => $r[0]['username'],
2513 '$siteurl' => $a->get_baseurl(),
2514 '$sitename' => $a->config['sitename']
2516 $res = mail($r[0]['email'],
2517 (($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],
2519 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
2520 . 'Content-type: text/plain; charset=UTF-8' . "\n"
2521 . 'Content-transfer-encoding: 8bit' );
2528 function lose_follower($importer,$contact,$datarray,$item) {
2530 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
2531 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2532 intval(CONTACT_IS_SHARING),
2533 intval($contact['id'])
2537 contact_remove($contact['id']);
2541 function lose_sharer($importer,$contact,$datarray,$item) {
2543 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
2544 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
2545 intval(CONTACT_IS_FOLLOWER),
2546 intval($contact['id'])
2550 contact_remove($contact['id']);
2555 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
2557 if(is_array($importer)) {
2558 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
2559 intval($importer['uid'])
2563 // Diaspora has different message-ids in feeds than they do
2564 // through the direct Diaspora protocol. If we try and use
2565 // the feed, we'll get duplicates. So don't.
2567 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
2570 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
2572 // Use a single verify token, even if multiple hubs
2574 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
2576 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
2578 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
2580 if(! strlen($contact['hub-verify'])) {
2581 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
2582 dbesc($verify_token),
2583 intval($contact['id'])
2587 post_url($url,$params);
2593 function atom_author($tag,$name,$uri,$h,$w,$photo) {
2597 $name = xmlify($name);
2598 $uri = xmlify($uri);
2601 $photo = xmlify($photo);
2605 $o .= "<name>$name</name>\r\n";
2606 $o .= "<uri>$uri</uri>\r\n";
2607 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2608 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
2610 call_hooks('atom_author', $o);
2612 $o .= "</$tag>\r\n";
2616 function atom_entry($item,$type,$author,$owner,$comment = false) {
2620 if(! $item['parent'])
2623 if($item['deleted'])
2624 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
2627 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
2628 $body = fix_private_photos($item['body'],$owner['uid']);
2630 $body = $item['body'];
2633 $o = "\r\n\r\n<entry>\r\n";
2635 if(is_array($author))
2636 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
2638 $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']));
2639 if(strlen($item['owner-name']))
2640 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
2642 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']))
2643 $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";
2645 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
2646 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
2647 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
2648 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
2649 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
2650 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
2651 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
2653 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
2655 if($item['location']) {
2656 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
2657 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
2661 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
2663 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
2664 $o .= '<dfrn:private>1</dfrn:private>' . "\r\n";
2667 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
2668 if($item['bookmark'])
2669 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
2672 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
2675 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
2677 if($item['signed_text']) {
2678 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
2679 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
2682 $verb = construct_verb($item);
2683 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
2684 $actobj = construct_activity_object($item);
2687 $actarg = construct_activity_target($item);
2691 $tags = item_getfeedtags($item);
2693 foreach($tags as $t) {
2694 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
2698 $o .= item_getfeedattach($item);
2700 $mentioned = get_mentions($item);
2704 call_hooks('atom_entry', $o);
2706 $o .= '</entry>' . "\r\n";
2711 function fix_private_photos($s,$uid) {
2713 logger('fix_private_photos');
2715 if(preg_match("/\[img\](.*?)\[\/img\]/is",$s,$matches)) {
2716 $image = $matches[1];
2717 logger('fix_private_photos: found photo ' . $image);
2718 if(stristr($image ,$a->get_baseurl() . '/photo/')) {
2719 $i = basename($image);
2720 $i = str_replace('.jpg','',$i);
2721 $x = strpos($i,'-');
2723 $res = substr($i,$x+1);
2724 $i = substr($i,0,$x);
2725 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
2731 logger('replacing photo');
2732 $s = str_replace($image, 'data:image/jpg;base64,' . base64_encode($r[0]['data']), $s);
2735 logger('fix_private_photos: replaced: ' . $s, LOGGER_DATA);
2743 function item_getfeedtags($item) {
2746 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2748 for($x = 0; $x < $cnt; $x ++) {
2750 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
2754 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
2756 for($x = 0; $x < $cnt; $x ++) {
2758 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
2764 function item_getfeedattach($item) {
2766 $arr = explode(',',$item['attach']);
2768 foreach($arr as $r) {
2770 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"\[\/attach\]|',$r,$matches);
2772 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
2773 if(intval($matches[2]))
2774 $ret .= 'length="' . intval($matches[2]) . '" ';
2775 if($matches[4] !== ' ')
2776 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
2777 $ret .= ' />' . "\r\n";
2786 function item_expire($uid,$days) {
2788 if((! $uid) || (! $days))
2791 $r = q("SELECT * FROM `item`
2793 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
2803 $expire_items = get_pconfig($uid, 'expire','items');
2804 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
2806 $expire_notes = get_pconfig($uid, 'expire','notes');
2807 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
2809 $expire_starred = get_pconfig($uid, 'expire','starred');
2810 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
2812 $expire_photos = get_pconfig($uid, 'expire','photos');
2813 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
2815 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2817 foreach($r as $item) {
2819 // Only expire posts, not photos and photo comments
2821 if($expire_photos==0 && strlen($item['resource-id']))
2823 if($expire_starred==0 && intval($item['starred']))
2825 if($expire_notes==0 && $item['type']=='note')
2827 if($expire_items==0 && $item['type']!='note')
2830 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2831 dbesc(datetime_convert()),
2832 dbesc(datetime_convert()),
2838 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2839 dbesc(datetime_convert()),
2840 dbesc(datetime_convert()),
2841 dbesc($item['parent-uri']),
2842 intval($item['uid'])
2847 proc_run('php',"include/notifier.php","expire","$uid");
2852 function drop_items($items) {
2855 if((! local_user()) && (! $remote_user()))
2859 foreach($items as $item) {
2860 $owner = drop_item($item,false);
2861 if($owner && ! $uid)
2866 // multiple threads may have been deleted, send an expire notification
2869 proc_run('php',"include/notifier.php","expire","$uid");
2873 function drop_item($id,$interactive = true) {
2877 // locate item to be deleted
2879 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
2886 notice( t('Item not found.') . EOL);
2887 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2892 $owner = $item['uid'];
2894 // check if logged in user is either the author or owner of this item
2896 if((local_user() == $item['uid']) || (remote_user() == $item['contact-id'])) {
2900 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
2901 dbesc(datetime_convert()),
2902 dbesc(datetime_convert()),
2906 // If item is a link to a photo resource, nuke all the associated photos
2907 // (visitors will not have photo resources)
2908 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
2909 // generate a resource-id and therefore aren't intimately linked to the item.
2911 if(strlen($item['resource-id'])) {
2912 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
2913 dbesc($item['resource-id']),
2914 intval($item['uid'])
2916 // ignore the result
2919 // If item is a link to an event, nuke the event record.
2921 if(intval($item['event-id'])) {
2922 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2923 intval($item['event-id']),
2924 intval($item['uid'])
2926 // ignore the result
2930 // If it's the parent of a comment thread, kill all the kids
2932 if($item['uri'] == $item['parent-uri']) {
2933 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
2934 WHERE `parent-uri` = '%s' AND `uid` = %d ",
2935 dbesc(datetime_convert()),
2936 dbesc(datetime_convert()),
2937 dbesc($item['parent-uri']),
2938 intval($item['uid'])
2940 // ignore the result
2943 // ensure that last-child is set in case the comment that had it just got wiped.
2944 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2945 dbesc(datetime_convert()),
2946 dbesc($item['parent-uri']),
2947 intval($item['uid'])
2949 // who is the last child now?
2950 $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",
2951 dbesc($item['parent-uri']),
2952 intval($item['uid'])
2955 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2960 $drop_id = intval($item['id']);
2962 // send the notification upstream/downstream as the case may be
2967 proc_run('php',"include/notifier.php","drop","$drop_id");
2968 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
2974 notice( t('Permission denied.') . EOL);
2975 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);