3 require_once('include/bbcode.php');
4 require_once('include/oembed.php');
5 require_once('include/salmon.php');
6 require_once('include/crypto.php');
7 require_once('include/Photo.php');
8 require_once('include/tags.php');
9 require_once('include/text.php');
10 require_once('include/email.php');
12 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
15 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
16 $public_feed = (($dfrn_id) ? false : true);
17 $starred = false; // not yet implemented, possible security issues
20 if($public_feed && $a->argc > 2) {
21 for($x = 2; $x < $a->argc; $x++) {
22 if($a->argv[$x] == 'converse')
24 if($a->argv[$x] == 'starred')
26 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
27 $category = $a->argv[$x+1];
33 // default permissions - anonymous user
35 $sql_extra = " AND `allow_cid` = '' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = '' ";
37 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
38 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
39 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
47 $owner_id = $owner['user_uid'];
48 $owner_nick = $owner['nickname'];
50 $birthday = feed_birthday($owner_id,$owner['timezone']);
57 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
61 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
62 $my_id = '1:' . $dfrn_id;
65 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
66 $my_id = '0:' . $dfrn_id;
73 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
81 require_once('include/security.php');
82 $groups = init_groups_visitor($contact['id']);
85 for($x = 0; $x < count($groups); $x ++)
86 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
87 $gs = implode('|', $groups);
90 $gs = '<<>>' ; // Impossible to match
92 $sql_extra = sprintf("
93 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
94 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
95 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
96 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
98 intval($contact['id']),
99 intval($contact['id']),
110 if(! strlen($last_update))
111 $last_update = 'now -30 days';
113 if(isset($category)) {
114 $sql_extra .= file_tag_file_query('item',$category,'category');
119 $sql_extra .= " AND `contact`.`self` = 1 ";
122 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
124 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
125 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
126 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
127 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
128 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
129 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
130 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
131 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
132 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
133 AND `item`.`wall` = 1 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
134 AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
136 ORDER BY `parent` %s, `created` ASC LIMIT 0, 300",
143 // Will check further below if this actually returned results.
144 // We will provide an empty feed if that is the case.
148 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
152 $hubxml = feed_hublinks();
154 $salmon = feed_salmonlinks($owner_nick);
156 $atom .= replace_macros($feed_template, array(
157 '$version' => xmlify(FRIENDICA_VERSION),
158 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
159 '$feed_title' => xmlify($owner['name']),
160 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
162 '$salmon' => $salmon,
163 '$name' => xmlify($owner['name']),
164 '$profile_page' => xmlify($owner['url']),
165 '$photo' => xmlify($owner['photo']),
166 '$thumb' => xmlify($owner['thumb']),
167 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
168 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
169 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
170 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
171 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
174 call_hooks('atom_feed', $atom);
176 if(! count($items)) {
178 call_hooks('atom_feed_end', $atom);
180 $atom .= '</feed>' . "\r\n";
184 foreach($items as $item) {
186 // prevent private email from leaking.
187 if($item['network'] === NETWORK_MAIL)
190 // public feeds get html, our own nodes use bbcode
194 // catch any email that's in a public conversation and make sure it doesn't leak
202 $atom .= atom_entry($item,$type,null,$owner,true);
205 call_hooks('atom_feed_end', $atom);
207 $atom .= '</feed>' . "\r\n";
213 function construct_verb($item) {
215 return $item['verb'];
216 return ACTIVITY_POST;
219 function construct_activity_object($item) {
221 if($item['object']) {
222 $o = '<as:object>' . "\r\n";
223 $r = parse_xml_string($item['object'],false);
229 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
231 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
233 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
235 if(substr($r->link,0,1) === '<') {
236 // patch up some facebook "like" activity objects that got stored incorrectly
237 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
238 // we can probably remove this hack here and in the following function in a few months time.
239 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
240 $r->link = str_replace('&','&', $r->link);
241 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
245 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
248 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
249 $o .= '</as:object>' . "\r\n";
256 function construct_activity_target($item) {
258 if($item['target']) {
259 $o = '<as:target>' . "\r\n";
260 $r = parse_xml_string($item['target'],false);
264 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
266 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
268 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
270 if(substr($r->link,0,1) === '<') {
271 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
272 $r->link = str_replace('&','&', $r->link);
273 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
277 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
280 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
281 $o .= '</as:target>' . "\r\n";
290 * The purpose of this function is to apply system message length limits to
291 * imported messages without including any embedded photos in the length
293 if(! function_exists('limit_body_size')) {
294 function limit_body_size($body) {
296 logger('limit_body_size: start', LOGGER_DEBUG);
298 $maxlen = get_max_import_size();
300 // If the length of the body, including the embedded images, is smaller
301 // than the maximum, then don't waste time looking for the images
302 if($maxlen && (strlen($body) > $maxlen)) {
304 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
311 $img_start = strpos($orig_body, '[img');
312 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
313 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
314 while(($img_st_close !== false) && ($img_end !== false)) {
316 $img_st_close++; // make it point to AFTER the closing bracket
317 $img_end += $img_start;
318 $img_end += strlen('[/img]');
320 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
321 // This is an embedded image
323 if( ($textlen + $img_start) > $maxlen ) {
324 if($textlen < $maxlen) {
325 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
326 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
331 $new_body = $new_body . substr($orig_body, 0, $img_start);
332 $textlen += $img_start;
335 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
339 if( ($textlen + $img_end) > $maxlen ) {
340 if($textlen < $maxlen) {
341 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
342 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
347 $new_body = $new_body . substr($orig_body, 0, $img_end);
348 $textlen += $img_end;
351 $orig_body = substr($orig_body, $img_end);
353 if($orig_body === false) // in case the body ends on a closing image tag
356 $img_start = strpos($orig_body, '[img');
357 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
358 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
361 if( ($textlen + strlen($orig_body)) > $maxlen) {
362 if($textlen < $maxlen) {
363 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
364 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
369 logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
370 $new_body = $new_body . $orig_body;
371 $textlen += strlen($orig_body);
380 function title_is_body($title, $body) {
382 $title = strip_tags($title);
383 $title = trim($title);
384 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
385 $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
387 $body = strip_tags($body);
389 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
390 $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
392 if (strlen($title) < strlen($body))
393 $body = substr($body, 0, strlen($title));
395 if (($title != $body) and (substr($title, -3) == "...")) {
396 $pos = strrpos($title, "...");
398 $title = substr($title, 0, $pos);
399 $body = substr($body, 0, $pos);
403 return($title == $body);
408 function get_atom_elements($feed,$item) {
410 require_once('library/HTMLPurifier.auto.php');
411 require_once('include/html2bbcode.php');
413 $best_photo = array();
417 $author = $item->get_author();
419 $res['author-name'] = unxmlify($author->get_name());
420 $res['author-link'] = unxmlify($author->get_link());
423 $res['author-name'] = unxmlify($feed->get_title());
424 $res['author-link'] = unxmlify($feed->get_permalink());
426 $res['uri'] = unxmlify($item->get_id());
427 $res['title'] = unxmlify($item->get_title());
428 $res['body'] = unxmlify($item->get_content());
429 $res['plink'] = unxmlify($item->get_link(0));
431 // removing the content of the title if its identically to the body
432 // This helps with auto generated titles e.g. from tumblr
433 if (title_is_body($res["title"], $res["body"]))
437 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
441 // look for a photo. We should check media size and find the best one,
442 // but for now let's just find any author photo
444 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
446 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
447 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
448 foreach($base as $link) {
449 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
450 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
451 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
456 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
458 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
459 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
460 if($base && count($base)) {
461 foreach($base as $link) {
462 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
463 $res['author-link'] = unxmlify($link['attribs']['']['href']);
464 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
465 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
466 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
472 // No photo/profile-link on the item - look at the feed level
474 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
475 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
476 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
477 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
478 foreach($base as $link) {
479 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
480 $res['author-link'] = unxmlify($link['attribs']['']['href']);
481 if(! $res['author-avatar']) {
482 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
483 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
488 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
490 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
491 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
493 if($base && count($base)) {
494 foreach($base as $link) {
495 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
496 $res['author-link'] = unxmlify($link['attribs']['']['href']);
497 if(! (x($res,'author-avatar'))) {
498 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
499 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
506 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
507 if($apps && $apps[0]['attribs']['']['source']) {
508 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
509 if($res['app'] === 'web')
510 $res['app'] = 'OStatus';
513 // base64 encoded json structure representing Diaspora signature
515 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
517 $res['dsprsig'] = unxmlify($dsig[0]['data']);
520 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
522 $res['guid'] = unxmlify($dguid[0]['data']);
524 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
526 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
530 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
533 $have_real_body = false;
535 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
537 $have_real_body = true;
538 $res['body'] = $rawenv[0]['data'];
539 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
540 // make sure nobody is trying to sneak some html tags by us
541 $res['body'] = notags(base64url_decode($res['body']));
545 $res['body'] = limit_body_size($res['body']);
547 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
548 // the content type. Our own network only emits text normally, though it might have been converted to
549 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
550 // have to assume it is all html and needs to be purified.
552 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
553 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
554 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
557 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
559 $res['body'] = reltoabs($res['body'],$base_url);
561 $res['body'] = html2bb_video($res['body']);
563 $res['body'] = oembed_html2bbcode($res['body']);
565 $config = HTMLPurifier_Config::createDefault();
566 $config->set('Cache.DefinitionImpl', null);
568 // we shouldn't need a whitelist, because the bbcode converter
569 // will strip out any unsupported tags.
571 $purifier = new HTMLPurifier($config);
572 $res['body'] = $purifier->purify($res['body']);
574 $res['body'] = @html2bbcode($res['body']);
578 elseif(! $have_real_body) {
580 // it's not one of our messages and it has no tags
581 // so it's probably just text. We'll escape it just to be safe.
583 $res['body'] = escape_tags($res['body']);
587 // this tag is obsolete but we keep it for really old sites
589 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
590 if($allow && $allow[0]['data'] == 1)
591 $res['last-child'] = 1;
593 $res['last-child'] = 0;
595 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
596 if($private && intval($private[0]['data']) > 0)
597 $res['private'] = intval($private[0]['data']);
601 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
602 if($extid && $extid[0]['data'])
603 $res['extid'] = $extid[0]['data'];
605 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
607 $res['location'] = unxmlify($rawlocation[0]['data']);
610 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
612 $res['created'] = unxmlify($rawcreated[0]['data']);
615 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
617 $res['edited'] = unxmlify($rawedited[0]['data']);
619 if((x($res,'edited')) && (! (x($res,'created'))))
620 $res['created'] = $res['edited'];
622 if(! $res['created'])
623 $res['created'] = $item->get_date('c');
626 $res['edited'] = $item->get_date('c');
629 // Disallow time travelling posts
631 $d1 = strtotime($res['created']);
632 $d2 = strtotime($res['edited']);
633 $d3 = strtotime('now');
636 $res['created'] = datetime_convert();
638 $res['edited'] = datetime_convert();
640 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
641 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
642 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
643 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
644 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
645 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
646 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
647 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
648 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
650 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
651 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
653 foreach($base as $link) {
654 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
655 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
656 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
661 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
663 $res['coord'] = unxmlify($rawgeo[0]['data']);
666 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
668 // select between supported verbs
671 $res['verb'] = unxmlify($rawverb[0]['data']);
674 // translate OStatus unfollow to activity streams if it happened to get selected
676 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
677 $res['verb'] = ACTIVITY_UNFOLLOW;
679 $cats = $item->get_categories();
682 foreach($cats as $cat) {
683 $term = $cat->get_term();
685 $term = $cat->get_label();
686 $scheme = $cat->get_scheme();
687 if($scheme && $term && stristr($scheme,'X-DFRN:'))
688 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
690 $tag_arr[] = notags(trim($term));
692 $res['tag'] = implode(',', $tag_arr);
695 $attach = $item->get_enclosures();
698 foreach($attach as $att) {
699 $len = intval($att->get_length());
700 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
701 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
702 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
703 if(strpos($type,';'))
704 $type = substr($type,0,strpos($type,';'));
705 if((! $link) || (strpos($link,'http') !== 0))
711 $type = 'application/octet-stream';
713 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
715 $res['attach'] = implode(',', $att_arr);
718 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
721 $res['object'] = '<object>' . "\n";
722 $child = $rawobj[0]['child'];
723 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
724 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
725 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
727 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
728 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
729 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
730 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
731 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
732 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
733 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
734 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
736 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
737 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
738 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
739 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
741 $body = html2bb_video($body);
743 $config = HTMLPurifier_Config::createDefault();
744 $config->set('Cache.DefinitionImpl', null);
746 $purifier = new HTMLPurifier($config);
747 $body = $purifier->purify($body);
748 $body = html2bbcode($body);
751 $res['object'] .= '<content>' . $body . '</content>' . "\n";
754 $res['object'] .= '</object>' . "\n";
757 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
760 $res['target'] = '<target>' . "\n";
761 $child = $rawobj[0]['child'];
762 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
763 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
765 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
766 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
767 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
768 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
769 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
770 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
771 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
772 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
774 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
775 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
776 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
777 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
779 $body = html2bb_video($body);
781 $config = HTMLPurifier_Config::createDefault();
782 $config->set('Cache.DefinitionImpl', null);
784 $purifier = new HTMLPurifier($config);
785 $body = $purifier->purify($body);
786 $body = html2bbcode($body);
789 $res['target'] .= '<content>' . $body . '</content>' . "\n";
792 $res['target'] .= '</target>' . "\n";
795 // This is some experimental stuff. By now retweets are shown with "RT:"
796 // But: There is data so that the message could be shown similar to native retweets
797 // There is some better way to parse this array - but it didn't worked for me.
798 $child = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://activitystrea.ms/spec/1.0/"][object][0]["child"];
799 if (is_array($child)) {
800 logger('get_atom_elements: Looking for status.net repeated message');
802 $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
803 $orig_uri = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["id"][0]["data"];
804 $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
805 $uri = $author["uri"][0]["data"];
806 $name = $author["name"][0]["data"];
807 $avatar = @array_shift($author["link"][2]["attribs"]);
808 $avatar = $avatar["href"];
810 if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
811 logger('get_atom_elements: fixing sender of repeated message.');
813 if (intval(get_config('system','new_share'))) {
814 $prefix = "[share author='".str_replace("'", "'",$name).
816 "' avatar='".$avatar.
817 "' link='".$orig_uri."']";
819 $res["body"] = $prefix.html2bbcode($message)."[/share]";
821 $res["owner-name"] = $res["author-name"];
822 $res["owner-link"] = $res["author-link"];
823 $res["owner-avatar"] = $res["author-avatar"];
825 $res["author-name"] = $name;
826 $res["author-link"] = $uri;
827 $res["author-avatar"] = $avatar;
829 $res["body"] = html2bbcode($message);
834 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
836 call_hooks('parse_atom', $arr);
838 //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
839 //if (strpos($res["body"], "RT @") !== false) {
840 // $debugfile = tempnam("/home/ike/log", "item-res2-");
841 // file_put_contents($debugfile, serialize($arr));
847 function encode_rel_links($links) {
849 if(! ((is_array($links)) && (count($links))))
851 foreach($links as $link) {
853 if($link['attribs']['']['rel'])
854 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
855 if($link['attribs']['']['type'])
856 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
857 if($link['attribs']['']['href'])
858 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
859 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
860 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
861 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
862 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
870 function item_store($arr,$force_parent = false) {
872 // If a Diaspora signature structure was passed in, pull it out of the
873 // item array and set it aside for later storage.
876 if(x($arr,'dsprsig')) {
877 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
878 unset($arr['dsprsig']);
881 if(x($arr, 'gravity'))
882 $arr['gravity'] = intval($arr['gravity']);
883 elseif($arr['parent-uri'] === $arr['uri'])
885 elseif(activity_match($arr['verb'],ACTIVITY_POST))
888 $arr['gravity'] = 6; // extensible catchall
891 $arr['type'] = 'remote';
893 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
895 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
896 $arr['body'] = strip_tags($arr['body']);
899 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
900 require_once('library/langdet/Text/LanguageDetect.php');
901 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
902 $l = new Text_LanguageDetect;
903 //$lng = $l->detectConfidence($naked_body);
904 //$arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
905 $lng = $l->detect($naked_body, 3);
907 if (sizeof($lng) > 0) {
910 foreach ($lng as $language => $score) {
916 $postopts .= $language.";".$score;
918 $arr['postopts'] = $postopts;
922 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
923 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
924 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
925 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
926 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
927 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
928 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
929 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
930 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
931 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
932 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
933 $arr['commented'] = datetime_convert();
934 $arr['received'] = datetime_convert();
935 $arr['changed'] = datetime_convert();
936 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
937 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
938 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
939 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
940 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
942 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
943 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
944 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
945 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
946 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
947 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
948 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
949 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
950 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
951 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
952 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
953 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
954 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
955 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
956 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
957 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
958 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
959 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
960 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
963 $arr['thr-parent'] = $arr['parent-uri'];
964 if($arr['parent-uri'] === $arr['uri']) {
967 $allow_cid = $arr['allow_cid'];
968 $allow_gid = $arr['allow_gid'];
969 $deny_cid = $arr['deny_cid'];
970 $deny_gid = $arr['deny_gid'];
974 // find the parent and snarf the item id and ACL's
975 // and anything else we need to inherit
977 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
978 dbesc($arr['parent-uri']),
984 // is the new message multi-level threaded?
985 // even though we don't support it now, preserve the info
986 // and re-attach to the conversation parent.
988 if($r[0]['uri'] != $r[0]['parent-uri']) {
989 $arr['parent-uri'] = $r[0]['parent-uri'];
990 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
991 ORDER BY `id` ASC LIMIT 1",
992 dbesc($r[0]['parent-uri']),
993 dbesc($r[0]['parent-uri']),
1000 $parent_id = $r[0]['id'];
1001 $parent_deleted = $r[0]['deleted'];
1002 $allow_cid = $r[0]['allow_cid'];
1003 $allow_gid = $r[0]['allow_gid'];
1004 $deny_cid = $r[0]['deny_cid'];
1005 $deny_gid = $r[0]['deny_gid'];
1006 $arr['wall'] = $r[0]['wall'];
1008 // if the parent is private, force privacy for the entire conversation
1009 // This differs from the above settings as it subtly allows comments from
1010 // email correspondents to be private even if the overall thread is not.
1012 if($r[0]['private'])
1013 $arr['private'] = $r[0]['private'];
1015 // Edge case. We host a public forum that was originally posted to privately.
1016 // The original author commented, but as this is a comment, the permissions
1017 // weren't fixed up so it will still show the comment as private unless we fix it here.
1019 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
1020 $arr['private'] = 0;
1024 // Allow one to see reply tweets from status.net even when
1025 // we don't have or can't see the original post.
1028 logger('item_store: $force_parent=true, reply converted to top-level post.');
1030 $arr['parent-uri'] = $arr['uri'];
1031 $arr['gravity'] = 0;
1034 logger('item_store: item parent was not found - ignoring item');
1038 $parent_deleted = 0;
1042 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1046 if($r && count($r)) {
1047 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
1051 call_hooks('post_remote',$arr);
1053 if(x($arr,'cancel')) {
1054 logger('item_store: post cancelled by plugin.');
1060 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
1062 $r = dbq("INSERT INTO `item` (`"
1063 . implode("`, `", array_keys($arr))
1065 . implode("', '", array_values($arr))
1068 // find the item we just created
1070 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
1071 $arr['uri'], // already dbesc'd
1076 $current_post = $r[0]['id'];
1077 logger('item_store: created item ' . $current_post);
1078 create_tags_from_item($r[0]['id']);
1080 logger('item_store: could not locate created item');
1084 logger('item_store: duplicated post occurred. Removing duplicates.');
1085 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
1087 intval($arr['uid']),
1088 intval($current_post)
1092 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
1093 $parent_id = $current_post;
1095 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1098 $private = $arr['private'];
1100 // Set parent id - and also make sure to inherit the parent's ACL's.
1102 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1103 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1110 intval($parent_deleted),
1111 intval($current_post)
1113 create_tags_from_item($current_post);
1115 $arr['id'] = $current_post;
1116 $arr['parent'] = $parent_id;
1117 $arr['allow_cid'] = $allow_cid;
1118 $arr['allow_gid'] = $allow_gid;
1119 $arr['deny_cid'] = $deny_cid;
1120 $arr['deny_gid'] = $deny_gid;
1121 $arr['private'] = $private;
1122 $arr['deleted'] = $parent_deleted;
1123 call_hooks('post_remote_end',$arr);
1125 // update the commented timestamp on the parent
1127 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1128 dbesc(datetime_convert()),
1129 dbesc(datetime_convert()),
1134 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1135 intval($current_post),
1136 dbesc($dsprsig->signed_text),
1137 dbesc($dsprsig->signature),
1138 dbesc($dsprsig->signer)
1144 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1147 if($arr['last-child']) {
1148 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1150 intval($arr['uid']),
1151 intval($current_post)
1155 tag_deliver($arr['uid'],$current_post);
1157 // Store the fresh generated item into the cache
1158 $cachefile = get_cachefile($arr["guid"]."-".hash("md5", $arr['body']));
1160 if (($cachefile != '') AND !file_exists($cachefile)) {
1161 $s = prepare_text($arr['body']);
1162 file_put_contents($cachefile, $s);
1163 logger('item_store: put item '.$current_post.' into cachefile '.$cachefile);
1166 return $current_post;
1169 function get_item_contact($item,$contacts) {
1170 if(! count($contacts) || (! is_array($item)))
1172 foreach($contacts as $contact) {
1173 if($contact['id'] == $item['contact-id']) {
1175 break; // NOTREACHED
1182 function tag_deliver($uid,$item_id) {
1184 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1190 $u = q("select * from user where uid = %d limit 1",
1196 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1197 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1200 $i = q("select * from item where id = %d and uid = %d limit 1",
1209 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1211 // Diaspora uses their own hardwired link URL in @-tags
1212 // instead of the one we supply with webfinger
1214 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1216 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1218 foreach($matches as $mtch) {
1219 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1221 logger('tag_deliver: mention found: ' . $mtch[2]);
1229 // send a notification
1231 // use a local photo if we have one
1233 $r = q("select * from contact where uid = %d and nurl = '%s' limit 1",
1234 intval($u[0]['uid']),
1235 dbesc(normalise_link($item['author-link']))
1237 $photo = (($r && count($r)) ? $r[0]['thumb'] : $item['author-avatar']);
1240 require_once('include/enotify.php');
1242 'type' => NOTIFY_TAGSELF,
1243 'notify_flags' => $u[0]['notify-flags'],
1244 'language' => $u[0]['language'],
1245 'to_name' => $u[0]['username'],
1246 'to_email' => $u[0]['email'],
1247 'uid' => $u[0]['uid'],
1249 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1250 'source_name' => $item['author-name'],
1251 'source_link' => $item['author-link'],
1252 'source_photo' => $photo,
1253 'verb' => ACTIVITY_TAG,
1258 $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1260 call_hooks('tagged', $arr);
1262 if((! $community_page) && (! $prvgroup))
1266 // tgroup delivery - setup a second delivery chain
1267 // prevent delivery looping - only proceed
1268 // if the message originated elsewhere and is a top-level post
1270 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1273 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1276 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1277 intval($u[0]['uid'])
1282 // also reset all the privacy bits to the forum default permissions
1284 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1286 $forum_mode = (($prvgroup) ? 2 : 1);
1288 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1289 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1290 intval($forum_mode),
1291 dbesc($c[0]['name']),
1292 dbesc($c[0]['url']),
1293 dbesc($c[0]['thumb']),
1295 dbesc($u[0]['allow_cid']),
1296 dbesc($u[0]['allow_gid']),
1297 dbesc($u[0]['deny_cid']),
1298 dbesc($u[0]['deny_gid']),
1302 proc_run('php','include/notifier.php','tgroup',$item_id);
1308 function tgroup_check($uid,$item) {
1314 // check that the message originated elsewhere and is a top-level post
1316 if(($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri']))
1320 $u = q("select * from user where uid = %d limit 1",
1326 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1327 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1330 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1332 // Diaspora uses their own hardwired link URL in @-tags
1333 // instead of the one we supply with webfinger
1335 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1337 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1339 foreach($matches as $mtch) {
1340 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1342 logger('tgroup_check: mention found: ' . $mtch[2]);
1350 if((! $community_page) && (! $prvgroup))
1364 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1368 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1370 if($contact['duplex'] && $contact['dfrn-id'])
1371 $idtosend = '0:' . $orig_id;
1372 if($contact['duplex'] && $contact['issued-id'])
1373 $idtosend = '1:' . $orig_id;
1375 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1377 $rino_enable = get_config('system','rino_encrypt');
1382 $ssl_val = intval(get_config('system','ssl_policy'));
1386 case SSL_POLICY_FULL:
1387 $ssl_policy = 'full';
1389 case SSL_POLICY_SELFSIGN:
1390 $ssl_policy = 'self';
1392 case SSL_POLICY_NONE:
1394 $ssl_policy = 'none';
1398 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1400 logger('dfrn_deliver: ' . $url);
1402 $xml = fetch_url($url);
1404 $curl_stat = $a->get_curl_code();
1406 return(-1); // timed out
1408 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1413 if(strpos($xml,'<?xml') === false) {
1414 logger('dfrn_deliver: no valid XML returned');
1415 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1419 $res = parse_xml_string($xml);
1421 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1422 return (($res->status) ? $res->status : 3);
1424 $postvars = array();
1425 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1426 $challenge = hex2bin((string) $res->challenge);
1427 $perm = (($res->perm) ? $res->perm : null);
1428 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1429 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1430 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1432 if($owner['page-flags'] == PAGE_PRVGROUP)
1435 $final_dfrn_id = '';
1438 if((($perm == 'rw') && (! intval($contact['writable'])))
1439 || (($perm == 'r') && (intval($contact['writable'])))) {
1440 q("update contact set writable = %d where id = %d limit 1",
1441 intval(($perm == 'rw') ? 1 : 0),
1442 intval($contact['id'])
1444 $contact['writable'] = (string) 1 - intval($contact['writable']);
1448 if(($contact['duplex'] && strlen($contact['pubkey']))
1449 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1450 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1451 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1452 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1455 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1456 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1459 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1461 if(strpos($final_dfrn_id,':') == 1)
1462 $final_dfrn_id = substr($final_dfrn_id,2);
1464 if($final_dfrn_id != $orig_id) {
1465 logger('dfrn_deliver: wrong dfrn_id.');
1466 // did not decode properly - cannot trust this site
1470 $postvars['dfrn_id'] = $idtosend;
1471 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1473 $postvars['dissolve'] = '1';
1476 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1477 $postvars['data'] = $atom;
1478 $postvars['perm'] = 'rw';
1481 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1482 $postvars['perm'] = 'r';
1485 $postvars['ssl_policy'] = $ssl_policy;
1488 $postvars['page'] = $page;
1490 if($rino && $rino_allowed && (! $dissolve)) {
1491 $key = substr(random_string(),0,16);
1492 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1493 $postvars['data'] = $data;
1494 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1497 if($dfrn_version >= 2.1) {
1498 if(($contact['duplex'] && strlen($contact['pubkey']))
1499 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1500 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1502 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1505 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1509 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1510 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1513 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1517 logger('md5 rawkey ' . md5($postvars['key']));
1519 $postvars['key'] = bin2hex($postvars['key']);
1522 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1524 $xml = post_url($contact['notify'],$postvars);
1526 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1528 $curl_stat = $a->get_curl_code();
1529 if((! $curl_stat) || (! strlen($xml)))
1530 return(-1); // timed out
1532 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1535 if(strpos($xml,'<?xml') === false) {
1536 logger('dfrn_deliver: phase 2: no valid XML returned');
1537 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1541 if($contact['term-date'] != '0000-00-00 00:00:00') {
1542 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1543 require_once('include/Contact.php');
1544 unmark_for_death($contact);
1547 $res = parse_xml_string($xml);
1549 return $res->status;
1555 * consume_feed - process atom feed and update anything/everything we might need to update
1557 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1559 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1560 * It is this person's stuff that is going to be updated.
1561 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1562 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1563 * have a contact record.
1564 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1565 * might not) try and subscribe to it.
1566 * $datedir sorts in reverse order
1567 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1568 * imported prior to its children being seen in the stream unless we are certain
1569 * of how the feed is arranged/ordered.
1570 * With $pass = 1, we only pull parent items out of the stream.
1571 * With $pass = 2, we only pull children (comments/likes).
1573 * So running this twice, first with pass 1 and then with pass 2 will do the right
1574 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1575 * model where comments can have sub-threads. That would require some massive sorting
1576 * to get all the feed items into a mostly linear ordering, and might still require
1580 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1582 require_once('library/simplepie/simplepie.inc');
1584 if(! strlen($xml)) {
1585 logger('consume_feed: empty input');
1589 $feed = new SimplePie();
1590 $feed->set_raw_data($xml);
1592 $feed->enable_order_by_date(true);
1594 $feed->enable_order_by_date(false);
1598 logger('consume_feed: Error parsing XML: ' . $feed->error());
1600 $permalink = $feed->get_permalink();
1602 // Check at the feed level for updated contact name and/or photo
1606 $photo_timestamp = '';
1610 $hubs = $feed->get_links('hub');
1611 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1614 $hub = implode(',', $hubs);
1616 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1618 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1620 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1621 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1622 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1623 $new_name = $elems['name'][0]['data'];
1625 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1626 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1627 $photo_url = $elems['link'][0]['attribs']['']['href'];
1630 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1631 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1635 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1636 logger('consume_feed: Updating photo for ' . $contact['name']);
1637 require_once("include/Photo.php");
1638 $photo_failure = false;
1639 $have_photo = false;
1641 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1642 intval($contact['id']),
1643 intval($contact['uid'])
1646 $resource_id = $r[0]['resource-id'];
1650 $resource_id = photo_new_resource();
1653 $img_str = fetch_url($photo_url,true);
1654 // guess mimetype from headers or filename
1655 $type = guess_image_type($photo_url,true);
1658 $img = new Photo($img_str, $type);
1659 if($img->is_valid()) {
1661 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1662 dbesc($resource_id),
1663 intval($contact['id']),
1664 intval($contact['uid'])
1668 $img->scaleImageSquare(175);
1670 $hash = $resource_id;
1671 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1673 $img->scaleImage(80);
1674 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1676 $img->scaleImage(48);
1677 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1681 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1682 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1683 dbesc(datetime_convert()),
1684 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1685 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1686 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1687 intval($contact['uid']),
1688 intval($contact['id'])
1693 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1694 $r = q("select * from contact where uid = %d and id = %d limit 1",
1695 intval($contact['uid']),
1696 intval($contact['id'])
1699 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1700 dbesc(notags(trim($new_name))),
1701 dbesc(datetime_convert()),
1702 intval($contact['uid']),
1703 intval($contact['id'])
1706 // do our best to update the name on content items
1709 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1710 dbesc(notags(trim($new_name))),
1711 dbesc($r[0]['name']),
1712 dbesc($r[0]['url']),
1713 intval($contact['uid'])
1718 if(strlen($birthday)) {
1719 if(substr($birthday,0,4) != $contact['bdyear']) {
1720 logger('consume_feed: updating birthday: ' . $birthday);
1724 * Add new birthday event for this person
1726 * $bdtext is just a readable placeholder in case the event is shared
1727 * with others. We will replace it during presentation to our $importer
1728 * to contain a sparkle link and perhaps a photo.
1732 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1733 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1736 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1737 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1738 intval($contact['uid']),
1739 intval($contact['id']),
1740 dbesc(datetime_convert()),
1741 dbesc(datetime_convert()),
1742 dbesc(datetime_convert('UTC','UTC', $birthday)),
1743 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1752 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1753 dbesc(substr($birthday,0,4)),
1754 intval($contact['uid']),
1755 intval($contact['id'])
1758 // This function is called twice without reloading the contact
1759 // Make sure we only create one event. This is why &$contact
1760 // is a reference var in this function
1762 $contact['bdyear'] = substr($birthday,0,4);
1767 $community_page = 0;
1768 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1770 $community_page = intval($rawtags[0]['data']);
1772 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1773 q("update contact set forum = %d where id = %d limit 1",
1774 intval($community_page),
1775 intval($contact['id'])
1777 $contact['forum'] = (string) $community_page;
1781 // process any deleted entries
1783 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1784 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1785 foreach($del_entries as $dentry) {
1787 if(isset($dentry['attribs']['']['ref'])) {
1788 $uri = $dentry['attribs']['']['ref'];
1790 if(isset($dentry['attribs']['']['when'])) {
1791 $when = $dentry['attribs']['']['when'];
1792 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1795 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1797 if($deleted && is_array($contact)) {
1798 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1799 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1801 intval($importer['uid']),
1802 intval($contact['id'])
1807 if(! $item['deleted'])
1808 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1810 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1811 $xo = parse_xml_string($item['object'],false);
1812 $xt = parse_xml_string($item['target'],false);
1813 if($xt->type === ACTIVITY_OBJ_NOTE) {
1814 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1816 intval($importer['importer_uid'])
1820 // For tags, the owner cannot remove the tag on the author's copy of the post.
1822 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1823 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1824 $author_copy = (($item['origin']) ? true : false);
1826 if($owner_remove && $author_copy)
1828 if($author_remove || $owner_remove) {
1829 $tags = explode(',',$i[0]['tag']);
1832 foreach($tags as $tag)
1833 if(trim($tag) !== trim($xo->body))
1834 $newtags[] = trim($tag);
1836 q("update item set tag = '%s' where id = %d limit 1",
1837 dbesc(implode(',',$newtags)),
1840 create_tags_from_item($i[0]['id']);
1846 if($item['uri'] == $item['parent-uri']) {
1847 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1848 `body` = '', `title` = ''
1849 WHERE `parent-uri` = '%s' AND `uid` = %d",
1851 dbesc(datetime_convert()),
1852 dbesc($item['uri']),
1853 intval($importer['uid'])
1855 create_tags_from_itemuri($item['uri'], $importer['uid']);
1858 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1859 `body` = '', `title` = ''
1860 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1862 dbesc(datetime_convert()),
1864 intval($importer['uid'])
1866 create_tags_from_itemuri($uri, $importer['uid']);
1867 if($item['last-child']) {
1868 // ensure that last-child is set in case the comment that had it just got wiped.
1869 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1870 dbesc(datetime_convert()),
1871 dbesc($item['parent-uri']),
1872 intval($item['uid'])
1874 // who is the last child now?
1875 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1876 ORDER BY `created` DESC LIMIT 1",
1877 dbesc($item['parent-uri']),
1878 intval($importer['uid'])
1881 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1892 // Now process the feed
1894 if($feed->get_item_quantity()) {
1896 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1898 // in inverse date order
1900 $items = array_reverse($feed->get_items());
1902 $items = $feed->get_items();
1905 foreach($items as $item) {
1908 $item_id = $item->get_id();
1909 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1910 if(isset($rawthread[0]['attribs']['']['ref'])) {
1912 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1915 if(($is_reply) && is_array($contact)) {
1920 // not allowed to post
1922 if($contact['rel'] == CONTACT_IS_FOLLOWER)
1926 // Have we seen it? If not, import it.
1928 $item_id = $item->get_id();
1929 $datarray = get_atom_elements($feed,$item);
1931 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1932 $datarray['author-name'] = $contact['name'];
1933 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1934 $datarray['author-link'] = $contact['url'];
1935 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1936 $datarray['author-avatar'] = $contact['thumb'];
1938 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1939 logger('consume_feed: no author information! ' . print_r($datarray,true));
1943 $force_parent = false;
1944 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1945 if($contact['network'] === NETWORK_OSTATUS)
1946 $force_parent = true;
1947 if(strlen($datarray['title']))
1948 unset($datarray['title']);
1949 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1950 dbesc(datetime_convert()),
1952 intval($importer['uid'])
1954 $datarray['last-child'] = 1;
1958 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1960 intval($importer['uid'])
1963 // Update content if 'updated' changes
1966 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1968 // do not accept (ignore) an earlier edit than one we currently have.
1969 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1972 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1973 dbesc($datarray['title']),
1974 dbesc($datarray['body']),
1975 dbesc($datarray['tag']),
1976 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
1978 intval($importer['uid'])
1980 create_tags_from_itemuri($item_id, $importer['uid']);
1983 // update last-child if it changes
1985 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
1986 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
1987 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1988 dbesc(datetime_convert()),
1990 intval($importer['uid'])
1992 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1993 intval($allow[0]['data']),
1994 dbesc(datetime_convert()),
1996 intval($importer['uid'])
2003 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2004 // one way feed - no remote comment ability
2005 $datarray['last-child'] = 0;
2007 $datarray['parent-uri'] = $parent_uri;
2008 $datarray['uid'] = $importer['uid'];
2009 $datarray['contact-id'] = $contact['id'];
2010 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
2011 $datarray['type'] = 'activity';
2012 $datarray['gravity'] = GRAVITY_LIKE;
2013 // only one like or dislike per person
2014 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s' OR `thr-parent` = '%s') limit 1",
2015 intval($datarray['uid']),
2016 intval($datarray['contact-id']),
2017 dbesc($datarray['verb']),
2025 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2026 $xo = parse_xml_string($datarray['object'],false);
2027 $xt = parse_xml_string($datarray['target'],false);
2029 if($xt->type == ACTIVITY_OBJ_NOTE) {
2030 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2032 intval($importer['importer_uid'])
2037 // extract tag, if not duplicate, add to parent item
2038 if($xo->id && $xo->content) {
2039 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2040 if(! (stristr($r[0]['tag'],$newtag))) {
2041 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2042 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2045 create_tags_from_item($r[0]['id']);
2051 $r = item_store($datarray,$force_parent);
2057 // Head post of a conversation. Have we seen it? If not, import it.
2059 $item_id = $item->get_id();
2061 $datarray = get_atom_elements($feed,$item);
2063 if(is_array($contact)) {
2064 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
2065 $datarray['author-name'] = $contact['name'];
2066 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
2067 $datarray['author-link'] = $contact['url'];
2068 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
2069 $datarray['author-avatar'] = $contact['thumb'];
2072 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
2073 logger('consume_feed: no author information! ' . print_r($datarray,true));
2077 // special handling for events
2079 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2080 $ev = bbtoevent($datarray['body']);
2081 if(x($ev,'desc') && x($ev,'start')) {
2082 $ev['uid'] = $importer['uid'];
2083 $ev['uri'] = $item_id;
2084 $ev['edited'] = $datarray['edited'];
2085 $ev['private'] = $datarray['private'];
2087 if(is_array($contact))
2088 $ev['cid'] = $contact['id'];
2089 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2091 intval($importer['uid'])
2094 $ev['id'] = $r[0]['id'];
2095 $xyz = event_store($ev);
2100 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
2101 if(strlen($datarray['title']))
2102 unset($datarray['title']);
2103 $datarray['last-child'] = 1;
2107 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2109 intval($importer['uid'])
2112 // Update content if 'updated' changes
2115 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2117 // do not accept (ignore) an earlier edit than one we currently have.
2118 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2121 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2122 dbesc($datarray['title']),
2123 dbesc($datarray['body']),
2124 dbesc($datarray['tag']),
2125 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2127 intval($importer['uid'])
2129 create_tags_from_itemuri($item_id, $importer['uid']);
2132 // update last-child if it changes
2134 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2135 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2136 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2137 intval($allow[0]['data']),
2138 dbesc(datetime_convert()),
2140 intval($importer['uid'])
2146 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
2147 logger('consume-feed: New follower');
2148 new_follower($importer,$contact,$datarray,$item);
2151 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
2152 lose_follower($importer,$contact,$datarray,$item);
2156 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
2157 logger('consume-feed: New friend request');
2158 new_follower($importer,$contact,$datarray,$item,true);
2161 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
2162 lose_sharer($importer,$contact,$datarray,$item);
2167 if(! is_array($contact))
2171 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2172 // one way feed - no remote comment ability
2173 $datarray['last-child'] = 0;
2175 if($contact['network'] === NETWORK_FEED)
2176 $datarray['private'] = 2;
2178 // This is my contact on another system, but it's really me.
2179 // Turn this into a wall post.
2181 if($contact['remote_self']) {
2182 $datarray['wall'] = 1;
2183 if($contact['network'] === NETWORK_FEED) {
2184 $datarray['private'] = 0;
2188 $datarray['parent-uri'] = $item_id;
2189 $datarray['uid'] = $importer['uid'];
2190 $datarray['contact-id'] = $contact['id'];
2192 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2193 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2194 // but otherwise there's a possible data mixup on the sender's system.
2195 // the tgroup delivery code called from item_store will correct it if it's a forum,
2196 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2197 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2198 $datarray['owner-name'] = $contact['name'];
2199 $datarray['owner-link'] = $contact['url'];
2200 $datarray['owner-avatar'] = $contact['thumb'];
2203 // We've allowed "followers" to reach this point so we can decide if they are
2204 // posting an @-tag delivery, which followers are allowed to do for certain
2205 // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it.
2207 if(($contact['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['uid'],$datarray)))
2211 $r = item_store($datarray);
2219 function local_delivery($importer,$data) {
2222 logger(__function__, LOGGER_TRACE);
2224 if($importer['readonly']) {
2225 // We aren't receiving stuff from this person. But we will quietly ignore them
2226 // rather than a blatant "go away" message.
2227 logger('local_delivery: ignoring');
2232 // Consume notification feed. This may differ from consuming a public feed in several ways
2233 // - might contain email or friend suggestions
2234 // - might contain remote followup to our message
2235 // - in which case we need to accept it and then notify other conversants
2236 // - we may need to send various email notifications
2238 $feed = new SimplePie();
2239 $feed->set_raw_data($data);
2240 $feed->enable_order_by_date(false);
2245 logger('local_delivery: Error parsing XML: ' . $feed->error());
2248 // Check at the feed level for updated contact name and/or photo
2252 $photo_timestamp = '';
2256 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
2258 // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
2260 // $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
2263 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
2264 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
2265 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
2266 $new_name = $elems['name'][0]['data'];
2268 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
2269 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
2270 $photo_url = $elems['link'][0]['attribs']['']['href'];
2274 if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
2275 logger('local_delivery: Updating photo for ' . $importer['name']);
2276 require_once("include/Photo.php");
2277 $photo_failure = false;
2278 $have_photo = false;
2280 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
2281 intval($importer['id']),
2282 intval($importer['importer_uid'])
2285 $resource_id = $r[0]['resource-id'];
2289 $resource_id = photo_new_resource();
2292 $img_str = fetch_url($photo_url,true);
2293 // guess mimetype from headers or filename
2294 $type = guess_image_type($photo_url,true);
2297 $img = new Photo($img_str, $type);
2298 if($img->is_valid()) {
2300 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
2301 dbesc($resource_id),
2302 intval($importer['id']),
2303 intval($importer['importer_uid'])
2307 $img->scaleImageSquare(175);
2309 $hash = $resource_id;
2310 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 4);
2312 $img->scaleImage(80);
2313 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 5);
2315 $img->scaleImage(48);
2316 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 6);
2320 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
2321 WHERE `uid` = %d AND `id` = %d LIMIT 1",
2322 dbesc(datetime_convert()),
2323 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
2324 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
2325 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
2326 intval($importer['importer_uid']),
2327 intval($importer['id'])
2332 if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
2333 $r = q("select * from contact where uid = %d and id = %d limit 1",
2334 intval($importer['importer_uid']),
2335 intval($importer['id'])
2338 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2339 dbesc(notags(trim($new_name))),
2340 dbesc(datetime_convert()),
2341 intval($importer['importer_uid']),
2342 intval($importer['id'])
2345 // do our best to update the name on content items
2348 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
2349 dbesc(notags(trim($new_name))),
2350 dbesc($r[0]['name']),
2351 dbesc($r[0]['url']),
2352 intval($importer['importer_uid'])
2359 // Currently unsupported - needs a lot of work
2360 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2361 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2362 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2364 $newloc['uid'] = $importer['importer_uid'];
2365 $newloc['cid'] = $importer['id'];
2366 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2367 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2368 $newloc['thumb'] = notags(unxmlify($base['thumb'][0]['data']));
2369 $newloc['micro'] = notags(unxmlify($base['micro'][0]['data']));
2370 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2371 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2372 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2373 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2374 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2375 $newloc['sitepubkey'] = notags(unxmlify($base['sitepubkey'][0]['data']));
2376 /** relocated user must have original key pair */
2377 /*$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2378 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));*/
2380 logger("items:relocate contact ".print_r($newloc, true).print_r($importer, true), LOGGER_DEBUG);
2383 $r = q("SELECT photo, url FROM contact WHERE id=%d AND uid=%d;",
2384 intval($importer['id']),
2385 intval($importer['importer_uid']));
2390 $x = q("UPDATE contact SET
2400 `site-pubkey` = '%s'
2401 WHERE id=%d AND uid=%d;",
2402 dbesc($newloc['name']),
2403 dbesc($newloc['photo']),
2404 dbesc($newloc['thumb']),
2405 dbesc($newloc['micro']),
2406 dbesc($newloc['url']),
2407 dbesc($newloc['request']),
2408 dbesc($newloc['confirm']),
2409 dbesc($newloc['notify']),
2410 dbesc($newloc['poll']),
2411 dbesc($newloc['sitepubkey']),
2412 intval($importer['id']),
2413 intval($importer['importer_uid']));
2419 'owner-link' => array($old['url'], $newloc['url']),
2420 'author-link' => array($old['url'], $newloc['url']),
2421 'owner-avatar' => array($old['photo'], $newloc['photo']),
2422 'author-avatar' => array($old['photo'], $newloc['photo']),
2424 foreach ($fields as $n=>$f){
2425 $x = q("UPDATE item SET `%s`='%s' WHERE `%s`='%s' AND uid=%d",
2428 intval($importer['importer_uid']));
2434 // merge with current record, current contents have priority
2435 // update record, set url-updated
2436 // update profile photos
2442 // handle friend suggestion notification
2444 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2445 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2446 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2448 $fsugg['uid'] = $importer['importer_uid'];
2449 $fsugg['cid'] = $importer['id'];
2450 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2451 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2452 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2453 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2454 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2456 // Does our member already have a friend matching this description?
2458 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2459 dbesc($fsugg['name']),
2460 dbesc(normalise_link($fsugg['url'])),
2461 intval($fsugg['uid'])
2466 // Do we already have an fcontact record for this person?
2469 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2470 dbesc($fsugg['url']),
2471 dbesc($fsugg['name']),
2472 dbesc($fsugg['request'])
2477 // OK, we do. Do we already have an introduction for this person ?
2478 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2479 intval($fsugg['uid']),
2486 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2487 dbesc($fsugg['name']),
2488 dbesc($fsugg['url']),
2489 dbesc($fsugg['photo']),
2490 dbesc($fsugg['request'])
2492 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2493 dbesc($fsugg['url']),
2494 dbesc($fsugg['name']),
2495 dbesc($fsugg['request'])
2500 // database record did not get created. Quietly give up.
2505 $hash = random_string();
2507 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2508 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2509 intval($fsugg['uid']),
2511 intval($fsugg['cid']),
2512 dbesc($fsugg['body']),
2514 dbesc(datetime_convert()),
2519 'type' => NOTIFY_SUGGEST,
2520 'notify_flags' => $importer['notify-flags'],
2521 'language' => $importer['language'],
2522 'to_name' => $importer['username'],
2523 'to_email' => $importer['email'],
2524 'uid' => $importer['importer_uid'],
2526 'link' => $a->get_baseurl() . '/notifications/intros',
2527 'source_name' => $importer['name'],
2528 'source_link' => $importer['url'],
2529 'source_photo' => $importer['photo'],
2530 'verb' => ACTIVITY_REQ_FRIEND,
2539 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2540 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2542 logger('local_delivery: private message received');
2545 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2548 $msg['uid'] = $importer['importer_uid'];
2549 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2550 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2551 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2552 $msg['contact-id'] = $importer['id'];
2553 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2554 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2556 $msg['replied'] = 0;
2557 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2558 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2559 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2563 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2564 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2566 // send notifications.
2568 require_once('include/enotify.php');
2570 $notif_params = array(
2571 'type' => NOTIFY_MAIL,
2572 'notify_flags' => $importer['notify-flags'],
2573 'language' => $importer['language'],
2574 'to_name' => $importer['username'],
2575 'to_email' => $importer['email'],
2576 'uid' => $importer['importer_uid'],
2578 'source_name' => $msg['from-name'],
2579 'source_link' => $importer['url'],
2580 'source_photo' => $importer['thumb'],
2581 'verb' => ACTIVITY_POST,
2585 notification($notif_params);
2591 $community_page = 0;
2592 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2594 $community_page = intval($rawtags[0]['data']);
2596 if(intval($importer['forum']) != $community_page) {
2597 q("update contact set forum = %d where id = %d limit 1",
2598 intval($community_page),
2599 intval($importer['id'])
2601 $importer['forum'] = (string) $community_page;
2604 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2606 // process any deleted entries
2608 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2609 if(is_array($del_entries) && count($del_entries)) {
2610 foreach($del_entries as $dentry) {
2612 if(isset($dentry['attribs']['']['ref'])) {
2613 $uri = $dentry['attribs']['']['ref'];
2615 if(isset($dentry['attribs']['']['when'])) {
2616 $when = $dentry['attribs']['']['when'];
2617 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2620 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2624 // check for relayed deletes to our conversation
2627 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2629 intval($importer['importer_uid'])
2632 $parent_uri = $r[0]['parent-uri'];
2633 if($r[0]['id'] != $r[0]['parent'])
2640 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2643 logger('local_delivery: possible community delete');
2646 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2648 // was the top-level post for this reply written by somebody on this site?
2649 // Specifically, the recipient?
2651 $is_a_remote_delete = false;
2653 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2654 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2655 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2656 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2657 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2658 AND `item`.`uid` = %d
2664 intval($importer['importer_uid'])
2667 $is_a_remote_delete = true;
2669 // Does this have the characteristics of a community or private group comment?
2670 // If it's a reply to a wall post on a community/prvgroup page it's a
2671 // valid community comment. Also forum_mode makes it valid for sure.
2672 // If neither, it's not.
2674 if($is_a_remote_delete && $community) {
2675 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2676 $is_a_remote_delete = false;
2677 logger('local_delivery: not a community delete');
2681 if($is_a_remote_delete) {
2682 logger('local_delivery: received remote delete');
2686 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2687 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2689 intval($importer['importer_uid']),
2690 intval($importer['id'])
2696 if($item['deleted'])
2699 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2701 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2702 $xo = parse_xml_string($item['object'],false);
2703 $xt = parse_xml_string($item['target'],false);
2705 if($xt->type === ACTIVITY_OBJ_NOTE) {
2706 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2708 intval($importer['importer_uid'])
2712 // For tags, the owner cannot remove the tag on the author's copy of the post.
2714 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2715 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2716 $author_copy = (($item['origin']) ? true : false);
2718 if($owner_remove && $author_copy)
2720 if($author_remove || $owner_remove) {
2721 $tags = explode(',',$i[0]['tag']);
2724 foreach($tags as $tag)
2725 if(trim($tag) !== trim($xo->body))
2726 $newtags[] = trim($tag);
2728 q("update item set tag = '%s' where id = %d limit 1",
2729 dbesc(implode(',',$newtags)),
2732 create_tags_from_item($i[0]['id']);
2738 if($item['uri'] == $item['parent-uri']) {
2739 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2740 `body` = '', `title` = ''
2741 WHERE `parent-uri` = '%s' AND `uid` = %d",
2743 dbesc(datetime_convert()),
2744 dbesc($item['uri']),
2745 intval($importer['importer_uid'])
2747 create_tags_from_itemuri($item['uri'], $importer['importer_uid']);
2750 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2751 `body` = '', `title` = ''
2752 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2754 dbesc(datetime_convert()),
2756 intval($importer['importer_uid'])
2758 create_tags_from_itemuri($uri, $importer['importer_uid']);
2759 if($item['last-child']) {
2760 // ensure that last-child is set in case the comment that had it just got wiped.
2761 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2762 dbesc(datetime_convert()),
2763 dbesc($item['parent-uri']),
2764 intval($item['uid'])
2766 // who is the last child now?
2767 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2768 ORDER BY `created` DESC LIMIT 1",
2769 dbesc($item['parent-uri']),
2770 intval($importer['importer_uid'])
2773 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2778 // if this is a relayed delete, propagate it to other recipients
2780 if($is_a_remote_delete)
2781 proc_run('php',"include/notifier.php","drop",$item['id']);
2789 foreach($feed->get_items() as $item) {
2792 $item_id = $item->get_id();
2793 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2794 if(isset($rawthread[0]['attribs']['']['ref'])) {
2796 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2802 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2805 logger('local_delivery: possible community reply');
2808 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2810 // was the top-level post for this reply written by somebody on this site?
2811 // Specifically, the recipient?
2813 $is_a_remote_comment = false;
2814 $top_uri = $parent_uri;
2816 $r = q("select `item`.`parent-uri` from `item`
2817 WHERE `item`.`uri` = '%s'
2821 if($r && count($r)) {
2822 $top_uri = $r[0]['parent-uri'];
2824 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2825 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2826 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2827 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2828 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2829 AND `item`.`uid` = %d
2835 intval($importer['importer_uid'])
2838 $is_a_remote_comment = true;
2841 // Does this have the characteristics of a community or private group comment?
2842 // If it's a reply to a wall post on a community/prvgroup page it's a
2843 // valid community comment. Also forum_mode makes it valid for sure.
2844 // If neither, it's not.
2846 if($is_a_remote_comment && $community) {
2847 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2848 $is_a_remote_comment = false;
2849 logger('local_delivery: not a community reply');
2853 if($is_a_remote_comment) {
2854 logger('local_delivery: received remote comment');
2856 // remote reply to our post. Import and then notify everybody else.
2858 $datarray = get_atom_elements($feed,$item);
2860 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2862 intval($importer['importer_uid'])
2865 // Update content if 'updated' changes
2869 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2871 // do not accept (ignore) an earlier edit than one we currently have.
2872 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2875 logger('received updated comment' , LOGGER_DEBUG);
2876 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2877 dbesc($datarray['title']),
2878 dbesc($datarray['body']),
2879 dbesc($datarray['tag']),
2880 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2882 intval($importer['importer_uid'])
2884 create_tags_from_itemuri($item_id, $importer['importer_uid']);
2886 proc_run('php',"include/notifier.php","comment-import",$iid);
2895 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2896 intval($importer['importer_uid'])
2900 $datarray['type'] = 'remote-comment';
2901 $datarray['wall'] = 1;
2902 $datarray['parent-uri'] = $parent_uri;
2903 $datarray['uid'] = $importer['importer_uid'];
2904 $datarray['owner-name'] = $own[0]['name'];
2905 $datarray['owner-link'] = $own[0]['url'];
2906 $datarray['owner-avatar'] = $own[0]['thumb'];
2907 $datarray['contact-id'] = $importer['id'];
2909 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2911 $datarray['type'] = 'activity';
2912 $datarray['gravity'] = GRAVITY_LIKE;
2913 $datarray['last-child'] = 0;
2914 // only one like or dislike per person
2915 $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`thr-parent` = '%s' or `parent-uri` = '%s') and deleted = 0 limit 1",
2916 intval($datarray['uid']),
2917 intval($datarray['contact-id']),
2918 dbesc($datarray['verb']),
2919 dbesc($datarray['parent-uri']),
2920 dbesc($datarray['parent-uri'])
2927 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2929 $xo = parse_xml_string($datarray['object'],false);
2930 $xt = parse_xml_string($datarray['target'],false);
2932 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2934 // fetch the parent item
2936 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2938 intval($importer['importer_uid'])
2943 // extract tag, if not duplicate, and this user allows tags, add to parent item
2945 if($xo->id && $xo->content) {
2946 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2947 if(! (stristr($tagp[0]['tag'],$newtag))) {
2948 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2949 intval($importer['importer_uid'])
2951 if(count($i) && ! intval($i[0]['blocktags'])) {
2952 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2953 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2954 intval($tagp[0]['id']),
2955 dbesc(datetime_convert())
2957 create_tags_from_item($tagp[0]['id']);
2965 $posted_id = item_store($datarray);
2969 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2971 intval($importer['importer_uid'])
2974 $parent = $r[0]['parent'];
2975 $parent_uri = $r[0]['parent-uri'];
2979 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2980 dbesc(datetime_convert()),
2981 intval($importer['importer_uid']),
2982 intval($r[0]['parent'])
2985 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2986 dbesc(datetime_convert()),
2987 intval($importer['importer_uid']),
2992 if($posted_id && $parent) {
2994 proc_run('php',"include/notifier.php","comment-import","$posted_id");
2996 if((! $is_like) && (! $importer['self'])) {
2998 require_once('include/enotify.php');
3001 'type' => NOTIFY_COMMENT,
3002 'notify_flags' => $importer['notify-flags'],
3003 'language' => $importer['language'],
3004 'to_name' => $importer['username'],
3005 'to_email' => $importer['email'],
3006 'uid' => $importer['importer_uid'],
3007 'item' => $datarray,
3008 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3009 'source_name' => stripslashes($datarray['author-name']),
3010 'source_link' => $datarray['author-link'],
3011 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3012 ? $importer['thumb'] : $datarray['author-avatar']),
3013 'verb' => ACTIVITY_POST,
3015 'parent' => $parent,
3016 'parent_uri' => $parent_uri,
3028 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
3030 $item_id = $item->get_id();
3031 $datarray = get_atom_elements($feed,$item);
3033 if($importer['rel'] == CONTACT_IS_FOLLOWER)
3036 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3038 intval($importer['importer_uid'])
3041 // Update content if 'updated' changes
3044 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
3046 // do not accept (ignore) an earlier edit than one we currently have.
3047 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3050 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3051 dbesc($datarray['title']),
3052 dbesc($datarray['body']),
3053 dbesc($datarray['tag']),
3054 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3056 intval($importer['importer_uid'])
3058 create_tags_from_itemuri($item_id, $importer['importer_uid']);
3061 // update last-child if it changes
3063 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3064 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
3065 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
3066 dbesc(datetime_convert()),
3068 intval($importer['importer_uid'])
3070 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3071 intval($allow[0]['data']),
3072 dbesc(datetime_convert()),
3074 intval($importer['importer_uid'])
3080 $datarray['parent-uri'] = $parent_uri;
3081 $datarray['uid'] = $importer['importer_uid'];
3082 $datarray['contact-id'] = $importer['id'];
3083 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
3084 $datarray['type'] = 'activity';
3085 $datarray['gravity'] = GRAVITY_LIKE;
3086 // only one like or dislike per person
3087 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s' OR `thr-parent` = '%s') limit 1",
3088 intval($datarray['uid']),
3089 intval($datarray['contact-id']),
3090 dbesc($datarray['verb']),
3099 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
3101 $xo = parse_xml_string($datarray['object'],false);
3102 $xt = parse_xml_string($datarray['target'],false);
3104 if($xt->type == ACTIVITY_OBJ_NOTE) {
3105 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
3107 intval($importer['importer_uid'])
3112 // extract tag, if not duplicate, add to parent item
3114 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
3115 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
3116 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
3119 create_tags_from_item($r[0]['id']);
3125 $posted_id = item_store($datarray);
3127 // find out if our user is involved in this conversation and wants to be notified.
3129 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
3131 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
3133 intval($importer['importer_uid'])
3136 if(count($myconv)) {
3137 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
3139 // first make sure this isn't our own post coming back to us from a wall-to-wall event
3140 if(! link_compare($datarray['author-link'],$importer_url)) {
3143 foreach($myconv as $conv) {
3145 // now if we find a match, it means we're in this conversation
3147 if(! link_compare($conv['author-link'],$importer_url))
3150 require_once('include/enotify.php');
3152 $conv_parent = $conv['parent'];
3155 'type' => NOTIFY_COMMENT,
3156 'notify_flags' => $importer['notify-flags'],
3157 'language' => $importer['language'],
3158 'to_name' => $importer['username'],
3159 'to_email' => $importer['email'],
3160 'uid' => $importer['importer_uid'],
3161 'item' => $datarray,
3162 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3163 'source_name' => stripslashes($datarray['author-name']),
3164 'source_link' => $datarray['author-link'],
3165 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3166 ? $importer['thumb'] : $datarray['author-avatar']),
3167 'verb' => ACTIVITY_POST,
3169 'parent' => $conv_parent,
3170 'parent_uri' => $parent_uri
3174 // only send one notification
3186 // Head post of a conversation. Have we seen it? If not, import it.
3189 $item_id = $item->get_id();
3190 $datarray = get_atom_elements($feed,$item);
3192 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
3193 $ev = bbtoevent($datarray['body']);
3194 if(x($ev,'desc') && x($ev,'start')) {
3195 $ev['cid'] = $importer['id'];
3196 $ev['uid'] = $importer['uid'];
3197 $ev['uri'] = $item_id;
3198 $ev['edited'] = $datarray['edited'];
3199 $ev['private'] = $datarray['private'];
3201 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3203 intval($importer['uid'])
3206 $ev['id'] = $r[0]['id'];
3207 $xyz = event_store($ev);
3212 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3214 intval($importer['importer_uid'])
3217 // Update content if 'updated' changes
3220 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
3222 // do not accept (ignore) an earlier edit than one we currently have.
3223 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3226 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3227 dbesc($datarray['title']),
3228 dbesc($datarray['body']),
3229 dbesc($datarray['tag']),
3230 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3232 intval($importer['importer_uid'])
3234 create_tags_from_itemuri($item_id, $importer['importer_uid']);
3237 // update last-child if it changes
3239 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3240 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
3241 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3242 intval($allow[0]['data']),
3243 dbesc(datetime_convert()),
3245 intval($importer['importer_uid'])
3251 // This is my contact on another system, but it's really me.
3252 // Turn this into a wall post.
3254 if($importer['remote_self'])
3255 $datarray['wall'] = 1;
3257 $datarray['parent-uri'] = $item_id;
3258 $datarray['uid'] = $importer['importer_uid'];
3259 $datarray['contact-id'] = $importer['id'];
3262 if(! link_compare($datarray['owner-link'],$importer['url'])) {
3263 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
3264 // but otherwise there's a possible data mixup on the sender's system.
3265 // the tgroup delivery code called from item_store will correct it if it's a forum,
3266 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
3267 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
3268 $datarray['owner-name'] = $importer['senderName'];
3269 $datarray['owner-link'] = $importer['url'];
3270 $datarray['owner-avatar'] = $importer['thumb'];
3273 if(($importer['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['importer_uid'],$datarray)))
3276 $posted_id = item_store($datarray);
3278 if(stristr($datarray['verb'],ACTIVITY_POKE)) {
3279 $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
3282 $xo = parse_xml_string($datarray['object'],false);
3284 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
3286 // somebody was poked/prodded. Was it me?
3288 $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
3290 foreach($links->link as $l) {
3291 $atts = $l->attributes();
3292 switch($atts['rel']) {
3294 $Blink = $atts['href'];
3300 if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
3302 // send a notification
3303 require_once('include/enotify.php');
3306 'type' => NOTIFY_POKE,
3307 'notify_flags' => $importer['notify-flags'],
3308 'language' => $importer['language'],
3309 'to_name' => $importer['username'],
3310 'to_email' => $importer['email'],
3311 'uid' => $importer['importer_uid'],
3312 'item' => $datarray,
3313 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3314 'source_name' => stripslashes($datarray['author-name']),
3315 'source_link' => $datarray['author-link'],
3316 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3317 ? $importer['thumb'] : $datarray['author-avatar']),
3318 'verb' => $datarray['verb'],
3319 'otype' => 'person',
3320 'activity' => $verb,
3337 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
3338 $url = notags(trim($datarray['author-link']));
3339 $name = notags(trim($datarray['author-name']));
3340 $photo = notags(trim($datarray['author-avatar']));
3342 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
3343 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
3344 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
3346 if(is_array($contact)) {
3347 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
3348 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
3349 $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
3350 intval(CONTACT_IS_FRIEND),
3351 intval($contact['id']),
3352 intval($importer['uid'])
3355 // send email notification to owner?
3359 // create contact record
3361 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
3362 `blocked`, `readonly`, `pending`, `writable` )
3363 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
3364 intval($importer['uid']),
3365 dbesc(datetime_convert()),
3367 dbesc(normalise_link($url)),
3371 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
3372 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
3374 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
3375 intval($importer['uid']),
3379 $contact_record = $r[0];
3381 // create notification
3382 $hash = random_string();
3384 if(is_array($contact_record)) {
3385 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
3386 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
3387 intval($importer['uid']),
3388 intval($contact_record['id']),
3390 dbesc(datetime_convert())
3393 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3394 intval($importer['uid'])
3399 if(intval($r[0]['def_gid'])) {
3400 require_once('include/group.php');
3401 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
3404 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
3405 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
3406 $email = replace_macros($email_tpl, array(
3407 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
3409 '$myname' => $r[0]['username'],
3410 '$siteurl' => $a->get_baseurl(),
3411 '$sitename' => $a->config['sitename']
3413 $res = mail($r[0]['email'],
3414 email_header_encode((($sharing) ? t('A new person is sharing with you at ') : t("You have a new follower at ")) . $a->config['sitename'],'UTF-8'),
3416 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
3417 . 'Content-type: text/plain; charset=UTF-8' . "\n"
3418 . 'Content-transfer-encoding: 8bit' );
3425 function lose_follower($importer,$contact,$datarray,$item) {
3427 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
3428 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3429 intval(CONTACT_IS_SHARING),
3430 intval($contact['id'])
3434 contact_remove($contact['id']);
3438 function lose_sharer($importer,$contact,$datarray,$item) {
3440 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3441 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3442 intval(CONTACT_IS_FOLLOWER),
3443 intval($contact['id'])
3447 contact_remove($contact['id']);
3452 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3456 if(is_array($importer)) {
3457 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3458 intval($importer['uid'])
3462 // Diaspora has different message-ids in feeds than they do
3463 // through the direct Diaspora protocol. If we try and use
3464 // the feed, we'll get duplicates. So don't.
3466 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3469 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3471 // Use a single verify token, even if multiple hubs
3473 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3475 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3477 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
3479 if(! strlen($contact['hub-verify'])) {
3480 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3481 dbesc($verify_token),
3482 intval($contact['id'])
3486 post_url($url,$params);
3488 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3495 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3499 $name = xmlify($name);
3500 $uri = xmlify($uri);
3503 $photo = xmlify($photo);
3507 $o .= "<name>$name</name>\r\n";
3508 $o .= "<uri>$uri</uri>\r\n";
3509 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3510 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3512 call_hooks('atom_author', $o);
3514 $o .= "</$tag>\r\n";
3518 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3522 if(! $item['parent'])
3525 if($item['deleted'])
3526 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3529 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3530 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3532 $body = $item['body'];
3534 $o = "\r\n\r\n<entry>\r\n";
3536 if(is_array($author))
3537 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3539 $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']));
3540 if(strlen($item['owner-name']))
3541 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3543 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
3544 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3545 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3548 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3549 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3550 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3551 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3552 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3553 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3554 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3556 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3558 if($item['location']) {
3559 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3560 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3564 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3566 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3567 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3570 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3571 if($item['bookmark'])
3572 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3575 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3578 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3580 if($item['signed_text']) {
3581 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3582 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3585 $verb = construct_verb($item);
3586 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3587 $actobj = construct_activity_object($item);
3590 $actarg = construct_activity_target($item);
3594 $tags = item_getfeedtags($item);
3596 foreach($tags as $t) {
3597 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3601 $o .= item_getfeedattach($item);
3603 $mentioned = get_mentions($item);
3607 call_hooks('atom_entry', $o);
3609 $o .= '</entry>' . "\r\n";
3614 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3617 logger('fix_private_photos', LOGGER_DEBUG);
3618 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3623 $img_start = strpos($orig_body, '[img');
3624 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3625 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3626 while( ($img_st_close !== false) && ($img_len !== false) ) {
3628 $img_st_close++; // make it point to AFTER the closing bracket
3629 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3631 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3634 if(stristr($image , $site . '/photo/')) {
3635 // Only embed locally hosted photos
3637 $i = basename($image);
3638 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3639 $x = strpos($i,'-');
3642 $res = substr($i,$x+1);
3643 $i = substr($i,0,$x);
3644 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3651 // Check to see if we should replace this photo link with an embedded image
3652 // 1. No need to do so if the photo is public
3653 // 2. If there's a contact-id provided, see if they're in the access list
3654 // for the photo. If so, embed it.
3655 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3656 // permissions, regardless of order but first check to see if they're an exact
3657 // match to save some processing overhead.
3659 if(has_permissions($r[0])) {
3661 $recips = enumerate_permissions($r[0]);
3662 if(in_array($cid, $recips)) {
3667 if(compare_permissions($item,$r[0]))
3672 $data = $r[0]['data'];
3673 $type = $r[0]['type'];
3675 // If a custom width and height were specified, apply before embedding
3676 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3677 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3679 $width = intval($match[1]);
3680 $height = intval($match[2]);
3682 $ph = new Photo($data, $type);
3683 if($ph->is_valid()) {
3684 $ph->scaleImage(max($width, $height));
3685 $data = $ph->imageString();
3686 $type = $ph->getType();
3690 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3691 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3692 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3698 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3699 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3700 if($orig_body === false)
3703 $img_start = strpos($orig_body, '[img');
3704 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3705 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3708 $new_body = $new_body . $orig_body;
3714 function has_permissions($obj) {
3715 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3720 function compare_permissions($obj1,$obj2) {
3721 // first part is easy. Check that these are exactly the same.
3722 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3723 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3724 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3725 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3728 // This is harder. Parse all the permissions and compare the resulting set.
3730 $recipients1 = enumerate_permissions($obj1);
3731 $recipients2 = enumerate_permissions($obj2);
3734 if($recipients1 == $recipients2)
3739 // returns an array of contact-ids that are allowed to see this object
3741 function enumerate_permissions($obj) {
3742 require_once('include/group.php');
3743 $allow_people = expand_acl($obj['allow_cid']);
3744 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3745 $deny_people = expand_acl($obj['deny_cid']);
3746 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3747 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3748 $deny = array_unique(array_merge($deny_people,$deny_groups));
3749 $recipients = array_diff($recipients,$deny);
3753 function item_getfeedtags($item) {
3756 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3758 for($x = 0; $x < $cnt; $x ++) {
3760 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3764 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3766 for($x = 0; $x < $cnt; $x ++) {
3768 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3774 function item_getfeedattach($item) {
3776 $arr = explode('[/attach],',$item['attach']);
3778 foreach($arr as $r) {
3780 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
3782 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3783 if(intval($matches[2]))
3784 $ret .= 'length="' . intval($matches[2]) . '" ';
3785 if($matches[4] !== ' ')
3786 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3787 $ret .= ' />' . "\r\n";
3796 function item_expire($uid,$days) {
3798 if((! $uid) || ($days < 1))
3801 // $expire_network_only = save your own wall posts
3802 // and just expire conversations started by others
3804 $expire_network_only = get_pconfig($uid,'expire','network_only');
3805 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3807 $r = q("SELECT * FROM `item`
3809 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3820 $expire_items = get_pconfig($uid, 'expire','items');
3821 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3823 $expire_notes = get_pconfig($uid, 'expire','notes');
3824 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3826 $expire_starred = get_pconfig($uid, 'expire','starred');
3827 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3829 $expire_photos = get_pconfig($uid, 'expire','photos');
3830 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3832 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3834 foreach($r as $item) {
3836 // don't expire filed items
3838 if(strpos($item['file'],'[') !== false)
3841 // Only expire posts, not photos and photo comments
3843 if($expire_photos==0 && strlen($item['resource-id']))
3845 if($expire_starred==0 && intval($item['starred']))
3847 if($expire_notes==0 && $item['type']=='note')
3849 if($expire_items==0 && $item['type']!='note')
3852 drop_item($item['id'],false);
3855 proc_run('php',"include/notifier.php","expire","$uid");
3860 function drop_items($items) {
3863 if(! local_user() && ! remote_user())
3867 foreach($items as $item) {
3868 $owner = drop_item($item,false);
3869 if($owner && ! $uid)
3874 // multiple threads may have been deleted, send an expire notification
3877 proc_run('php',"include/notifier.php","expire","$uid");
3881 function drop_item($id,$interactive = true) {
3885 // locate item to be deleted
3887 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3894 notice( t('Item not found.') . EOL);
3895 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3900 $owner = $item['uid'];
3904 // check if logged in user is either the author or owner of this item
3906 if(is_array($_SESSION['remote'])) {
3907 foreach($_SESSION['remote'] as $visitor) {
3908 if($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
3909 $cid = $visitor['cid'];
3916 if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
3918 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
3921 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3922 dbesc(datetime_convert()),
3923 dbesc(datetime_convert()),
3926 create_tags_from_item($item['id']);
3928 // clean up categories and tags so they don't end up as orphans
3931 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3933 foreach($matches as $mtch) {
3934 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3940 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3942 foreach($matches as $mtch) {
3943 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3947 // If item is a link to a photo resource, nuke all the associated photos
3948 // (visitors will not have photo resources)
3949 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3950 // generate a resource-id and therefore aren't intimately linked to the item.
3952 if(strlen($item['resource-id'])) {
3953 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3954 dbesc($item['resource-id']),
3955 intval($item['uid'])
3957 // ignore the result
3960 // If item is a link to an event, nuke the event record.
3962 if(intval($item['event-id'])) {
3963 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3964 intval($item['event-id']),
3965 intval($item['uid'])
3967 // ignore the result
3970 // clean up item_id and sign meta-data tables
3972 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3973 intval($item['id']),
3974 intval($item['uid'])
3977 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
3978 intval($item['id']),
3979 intval($item['uid'])
3982 // If it's the parent of a comment thread, kill all the kids
3984 if($item['uri'] == $item['parent-uri']) {
3985 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
3986 WHERE `parent-uri` = '%s' AND `uid` = %d ",
3987 dbesc(datetime_convert()),
3988 dbesc(datetime_convert()),
3989 dbesc($item['parent-uri']),
3990 intval($item['uid'])
3992 create_tags_from_item($item['parent-uri'], $item['uid']);
3993 // ignore the result
3996 // ensure that last-child is set in case the comment that had it just got wiped.
3997 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3998 dbesc(datetime_convert()),
3999 dbesc($item['parent-uri']),
4000 intval($item['uid'])
4002 // who is the last child now?
4003 $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",
4004 dbesc($item['parent-uri']),
4005 intval($item['uid'])
4008 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
4013 // Add a relayable_retraction signature for Diaspora.
4014 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
4016 $drop_id = intval($item['id']);
4018 // send the notification upstream/downstream as the case may be
4020 proc_run('php',"include/notifier.php","drop","$drop_id");
4024 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
4030 notice( t('Permission denied.') . EOL);
4031 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
4038 function first_post_date($uid,$wall = false) {
4039 $r = q("select id, created from item
4040 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
4042 order by created asc limit 1",
4044 intval($wall ? 1 : 0)
4047 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
4048 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
4053 function posted_dates($uid,$wall) {
4054 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
4056 $dthen = first_post_date($uid,$wall);
4060 // If it's near the end of a long month, backup to the 28th so that in
4061 // consecutive loops we'll always get a whole month difference.
4063 if(intval(substr($dnow,8)) > 28)
4064 $dnow = substr($dnow,0,8) . '28';
4065 if(intval(substr($dthen,8)) > 28)
4066 $dnow = substr($dthen,0,8) . '28';
4069 // Starting with the current month, get the first and last days of every
4070 // month down to and including the month of the first post
4071 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
4072 $dstart = substr($dnow,0,8) . '01';
4073 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
4074 $start_month = datetime_convert('','',$dstart,'Y-m-d');
4075 $end_month = datetime_convert('','',$dend,'Y-m-d');
4076 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
4077 $ret[] = array($str,$end_month,$start_month);
4078 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
4084 function posted_date_widget($url,$uid,$wall) {
4087 if(! feature_enabled($uid,'archives'))
4090 // For former Facebook folks that left because of "timeline"
4092 /* if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
4095 $ret = posted_dates($uid,$wall);
4099 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
4100 '$title' => t('Archives'),
4101 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
4108 function store_diaspora_retract_sig($item, $user, $baseurl) {
4109 // Note that we can't add a target_author_signature
4110 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
4111 // the comment, that means we're the home of the post, and Diaspora will only
4112 // check the parent_author_signature of retractions that it doesn't have to relay further
4114 // I don't think this function gets called for an "unlike," but I'll check anyway
4116 $enabled = intval(get_config('system','diaspora_enabled'));
4118 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
4122 logger('drop_item: storing diaspora retraction signature');
4124 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
4126 if(local_user() == $item['uid']) {
4128 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
4129 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
4132 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
4133 $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
4136 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
4137 // only handles DFRN deletes
4138 $handle_baseurl_start = strpos($r['url'],'://') + 3;
4139 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
4140 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
4146 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
4147 intval($item['id']),
4148 dbesc($signed_text),