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 // Search for ostatus conversation url
835 $links = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["entry"][0]["child"]["http://www.w3.org/2005/Atom"]["link"];
837 foreach ($links as $link) {
838 $conversation = array_shift($link["attribs"]);
840 if ($conversation["rel"] == "ostatus:conversation") {
841 $res["ostatus_conversation"] = $conversation["href"];
842 logger('get_atom_elements: found conversation url '.$res["ostatus_conversation"]);
846 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
848 call_hooks('parse_atom', $arr);
850 //if (($res["title"] != "") or (strpos($res["body"], "RT @") > 0)) {
851 //if (strpos($res["body"], "RT @") !== false) {
852 /*if (strpos($res["body"], "@") !== false) {
853 $debugfile = tempnam("/var/www/virtual/pirati.ca/phptmp/", "item-res2-");
854 file_put_contents($debugfile, serialize($arr));
860 function encode_rel_links($links) {
862 if(! ((is_array($links)) && (count($links))))
864 foreach($links as $link) {
866 if($link['attribs']['']['rel'])
867 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
868 if($link['attribs']['']['type'])
869 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
870 if($link['attribs']['']['href'])
871 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
872 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
873 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
874 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
875 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
883 function item_store($arr,$force_parent = false) {
885 // If a Diaspora signature structure was passed in, pull it out of the
886 // item array and set it aside for later storage.
889 if(x($arr,'dsprsig')) {
890 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
891 unset($arr['dsprsig']);
894 // if an OStatus conversation url was passed in, it is stored and then
895 // removed from the array.
896 $ostatus_conversation = null;
898 if (isset($arr["ostatus_conversation"])) {
899 $ostatus_conversation = $arr["ostatus_conversation"];
900 unset($arr["ostatus_conversation"]);
903 if(x($arr, 'gravity'))
904 $arr['gravity'] = intval($arr['gravity']);
905 elseif($arr['parent-uri'] === $arr['uri'])
907 elseif(activity_match($arr['verb'],ACTIVITY_POST))
910 $arr['gravity'] = 6; // extensible catchall
913 $arr['type'] = 'remote';
915 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
917 if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
918 $arr['body'] = strip_tags($arr['body']);
921 if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
922 require_once('library/langdet/Text/LanguageDetect.php');
923 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
924 $l = new Text_LanguageDetect;
925 //$lng = $l->detectConfidence($naked_body);
926 //$arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
927 $lng = $l->detect($naked_body, 3);
929 if (sizeof($lng) > 0) {
932 foreach ($lng as $language => $score) {
938 $postopts .= $language.";".$score;
940 $arr['postopts'] = $postopts;
944 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
945 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : random_string());
946 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
947 $arr['author-name'] = ((x($arr,'author-name')) ? notags(trim($arr['author-name'])) : '');
948 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
949 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
950 $arr['owner-name'] = ((x($arr,'owner-name')) ? notags(trim($arr['owner-name'])) : '');
951 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
952 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
953 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
954 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
955 $arr['commented'] = datetime_convert();
956 $arr['received'] = datetime_convert();
957 $arr['changed'] = datetime_convert();
958 $arr['title'] = ((x($arr,'title')) ? notags(trim($arr['title'])) : '');
959 $arr['location'] = ((x($arr,'location')) ? notags(trim($arr['location'])) : '');
960 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
961 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
962 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
964 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
965 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
966 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
967 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
968 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
969 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
970 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
971 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
972 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
973 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
974 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
975 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
976 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
977 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
978 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
979 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
980 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
981 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
982 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid());
985 $arr['thr-parent'] = $arr['parent-uri'];
986 if($arr['parent-uri'] === $arr['uri']) {
989 $allow_cid = $arr['allow_cid'];
990 $allow_gid = $arr['allow_gid'];
991 $deny_cid = $arr['deny_cid'];
992 $deny_gid = $arr['deny_gid'];
996 // find the parent and snarf the item id and ACLs
997 // and anything else we need to inherit
999 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
1000 dbesc($arr['parent-uri']),
1006 // is the new message multi-level threaded?
1007 // even though we don't support it now, preserve the info
1008 // and re-attach to the conversation parent.
1010 if($r[0]['uri'] != $r[0]['parent-uri']) {
1011 $arr['parent-uri'] = $r[0]['parent-uri'];
1012 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
1013 ORDER BY `id` ASC LIMIT 1",
1014 dbesc($r[0]['parent-uri']),
1015 dbesc($r[0]['parent-uri']),
1022 $parent_id = $r[0]['id'];
1023 $parent_deleted = $r[0]['deleted'];
1024 $allow_cid = $r[0]['allow_cid'];
1025 $allow_gid = $r[0]['allow_gid'];
1026 $deny_cid = $r[0]['deny_cid'];
1027 $deny_gid = $r[0]['deny_gid'];
1028 $arr['wall'] = $r[0]['wall'];
1030 // if the parent is private, force privacy for the entire conversation
1031 // This differs from the above settings as it subtly allows comments from
1032 // email correspondents to be private even if the overall thread is not.
1034 if($r[0]['private'])
1035 $arr['private'] = $r[0]['private'];
1037 // Edge case. We host a public forum that was originally posted to privately.
1038 // The original author commented, but as this is a comment, the permissions
1039 // weren't fixed up so it will still show the comment as private unless we fix it here.
1041 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
1042 $arr['private'] = 0;
1046 // Allow one to see reply tweets from status.net even when
1047 // we don't have or can't see the original post.
1050 logger('item_store: $force_parent=true, reply converted to top-level post.');
1052 $arr['parent-uri'] = $arr['uri'];
1053 $arr['gravity'] = 0;
1056 logger('item_store: item parent was not found - ignoring item');
1060 $parent_deleted = 0;
1064 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1068 if($r && count($r)) {
1069 logger('item-store: duplicate item ignored. ' . print_r($arr,true));
1073 call_hooks('post_remote',$arr);
1075 if(x($arr,'cancel')) {
1076 logger('item_store: post cancelled by plugin.');
1082 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
1084 $r = dbq("INSERT INTO `item` (`"
1085 . implode("`, `", array_keys($arr))
1087 . implode("', '", array_values($arr))
1090 // find the item we just created
1092 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC ",
1093 $arr['uri'], // already dbesc'd
1098 $current_post = $r[0]['id'];
1099 logger('item_store: created item ' . $current_post);
1100 create_tags_from_item($r[0]['id']);
1101 // ostatus_conversation
1103 logger('item_store: could not locate created item');
1107 logger('item_store: duplicated post occurred. Removing duplicates.');
1108 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
1110 intval($arr['uid']),
1111 intval($current_post)
1115 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
1116 $parent_id = $current_post;
1118 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1121 $private = $arr['private'];
1123 // Set parent id - and also make sure to inherit the parent's ACL's.
1125 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1126 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d LIMIT 1",
1133 intval($parent_deleted),
1134 intval($current_post)
1136 create_tags_from_item($current_post);
1138 $arr['id'] = $current_post;
1139 $arr['parent'] = $parent_id;
1140 $arr['allow_cid'] = $allow_cid;
1141 $arr['allow_gid'] = $allow_gid;
1142 $arr['deny_cid'] = $deny_cid;
1143 $arr['deny_gid'] = $deny_gid;
1144 $arr['private'] = $private;
1145 $arr['deleted'] = $parent_deleted;
1146 call_hooks('post_remote_end',$arr);
1148 // update the commented timestamp on the parent
1150 q("UPDATE `item` set `commented` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
1151 dbesc(datetime_convert()),
1152 dbesc(datetime_convert()),
1157 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1158 intval($current_post),
1159 dbesc($dsprsig->signed_text),
1160 dbesc($dsprsig->signature),
1161 dbesc($dsprsig->signer)
1167 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1170 if($arr['last-child']) {
1171 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1173 intval($arr['uid']),
1174 intval($current_post)
1178 tag_deliver($arr['uid'],$current_post);
1180 // Store the fresh generated item into the cache
1181 $cachefile = get_cachefile($arr["guid"]."-".hash("md5", $arr['body']));
1183 if (($cachefile != '') AND !file_exists($cachefile)) {
1184 $s = prepare_text($arr['body']);
1186 $stamp1 = microtime(true);
1187 file_put_contents($cachefile, $s);
1188 $a->save_timestamp($stamp1, "file");
1189 logger('item_store: put item '.$current_post.' into cachefile '.$cachefile);
1192 return $current_post;
1195 function get_item_contact($item,$contacts) {
1196 if(! count($contacts) || (! is_array($item)))
1198 foreach($contacts as $contact) {
1199 if($contact['id'] == $item['contact-id']) {
1201 break; // NOTREACHED
1208 function tag_deliver($uid,$item_id) {
1210 // look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1216 $u = q("select * from user where uid = %d limit 1",
1222 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1223 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1226 $i = q("select * from item where id = %d and uid = %d limit 1",
1235 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1237 // Diaspora uses their own hardwired link URL in @-tags
1238 // instead of the one we supply with webfinger
1240 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1242 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1244 foreach($matches as $mtch) {
1245 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1247 logger('tag_deliver: mention found: ' . $mtch[2]);
1255 // send a notification
1257 // use a local photo if we have one
1259 $r = q("select * from contact where uid = %d and nurl = '%s' limit 1",
1260 intval($u[0]['uid']),
1261 dbesc(normalise_link($item['author-link']))
1263 $photo = (($r && count($r)) ? $r[0]['thumb'] : $item['author-avatar']);
1266 require_once('include/enotify.php');
1268 'type' => NOTIFY_TAGSELF,
1269 'notify_flags' => $u[0]['notify-flags'],
1270 'language' => $u[0]['language'],
1271 'to_name' => $u[0]['username'],
1272 'to_email' => $u[0]['email'],
1273 'uid' => $u[0]['uid'],
1275 'link' => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item['id'],
1276 'source_name' => $item['author-name'],
1277 'source_link' => $item['author-link'],
1278 'source_photo' => $photo,
1279 'verb' => ACTIVITY_TAG,
1284 $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1286 call_hooks('tagged', $arr);
1288 if((! $community_page) && (! $prvgroup))
1292 // tgroup delivery - setup a second delivery chain
1293 // prevent delivery looping - only proceed
1294 // if the message originated elsewhere and is a top-level post
1296 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1299 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1302 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1303 intval($u[0]['uid'])
1308 // also reset all the privacy bits to the forum default permissions
1310 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1312 $forum_mode = (($prvgroup) ? 2 : 1);
1314 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1315 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d limit 1",
1316 intval($forum_mode),
1317 dbesc($c[0]['name']),
1318 dbesc($c[0]['url']),
1319 dbesc($c[0]['thumb']),
1321 dbesc($u[0]['allow_cid']),
1322 dbesc($u[0]['allow_gid']),
1323 dbesc($u[0]['deny_cid']),
1324 dbesc($u[0]['deny_gid']),
1328 proc_run('php','include/notifier.php','tgroup',$item_id);
1334 function tgroup_check($uid,$item) {
1340 // check that the message originated elsewhere and is a top-level post
1342 if(($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri']))
1346 $u = q("select * from user where uid = %d limit 1",
1352 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1353 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1356 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1358 // Diaspora uses their own hardwired link URL in @-tags
1359 // instead of the one we supply with webfinger
1361 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1363 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1365 foreach($matches as $mtch) {
1366 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1368 logger('tgroup_check: mention found: ' . $mtch[2]);
1376 if((! $community_page) && (! $prvgroup))
1390 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
1394 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1396 if($contact['duplex'] && $contact['dfrn-id'])
1397 $idtosend = '0:' . $orig_id;
1398 if($contact['duplex'] && $contact['issued-id'])
1399 $idtosend = '1:' . $orig_id;
1401 $rino = ((function_exists('mcrypt_encrypt')) ? 1 : 0);
1403 $rino_enable = get_config('system','rino_encrypt');
1408 $ssl_val = intval(get_config('system','ssl_policy'));
1412 case SSL_POLICY_FULL:
1413 $ssl_policy = 'full';
1415 case SSL_POLICY_SELFSIGN:
1416 $ssl_policy = 'self';
1418 case SSL_POLICY_NONE:
1420 $ssl_policy = 'none';
1424 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino=1' : '');
1426 logger('dfrn_deliver: ' . $url);
1428 $xml = fetch_url($url);
1430 $curl_stat = $a->get_curl_code();
1432 return(-1); // timed out
1434 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1439 if(strpos($xml,'<?xml') === false) {
1440 logger('dfrn_deliver: no valid XML returned');
1441 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1445 $res = parse_xml_string($xml);
1447 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
1448 return (($res->status) ? $res->status : 3);
1450 $postvars = array();
1451 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1452 $challenge = hex2bin((string) $res->challenge);
1453 $perm = (($res->perm) ? $res->perm : null);
1454 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1455 $rino_allowed = ((intval($res->rino) === 1) ? 1 : 0);
1456 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1458 if($owner['page-flags'] == PAGE_PRVGROUP)
1461 $final_dfrn_id = '';
1464 if((($perm == 'rw') && (! intval($contact['writable'])))
1465 || (($perm == 'r') && (intval($contact['writable'])))) {
1466 q("update contact set writable = %d where id = %d limit 1",
1467 intval(($perm == 'rw') ? 1 : 0),
1468 intval($contact['id'])
1470 $contact['writable'] = (string) 1 - intval($contact['writable']);
1474 if(($contact['duplex'] && strlen($contact['pubkey']))
1475 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1476 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1477 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1478 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1481 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1482 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1485 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1487 if(strpos($final_dfrn_id,':') == 1)
1488 $final_dfrn_id = substr($final_dfrn_id,2);
1490 if($final_dfrn_id != $orig_id) {
1491 logger('dfrn_deliver: wrong dfrn_id.');
1492 // did not decode properly - cannot trust this site
1496 $postvars['dfrn_id'] = $idtosend;
1497 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1499 $postvars['dissolve'] = '1';
1502 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1503 $postvars['data'] = $atom;
1504 $postvars['perm'] = 'rw';
1507 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1508 $postvars['perm'] = 'r';
1511 $postvars['ssl_policy'] = $ssl_policy;
1514 $postvars['page'] = $page;
1516 if($rino && $rino_allowed && (! $dissolve)) {
1517 $key = substr(random_string(),0,16);
1518 $data = bin2hex(aes_encrypt($postvars['data'],$key));
1519 $postvars['data'] = $data;
1520 logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1523 if($dfrn_version >= 2.1) {
1524 if(($contact['duplex'] && strlen($contact['pubkey']))
1525 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1526 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1528 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1531 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1535 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1536 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1539 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1543 logger('md5 rawkey ' . md5($postvars['key']));
1545 $postvars['key'] = bin2hex($postvars['key']);
1548 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1550 $xml = post_url($contact['notify'],$postvars);
1552 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1554 $curl_stat = $a->get_curl_code();
1555 if((! $curl_stat) || (! strlen($xml)))
1556 return(-1); // timed out
1558 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
1561 if(strpos($xml,'<?xml') === false) {
1562 logger('dfrn_deliver: phase 2: no valid XML returned');
1563 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1567 if($contact['term-date'] != '0000-00-00 00:00:00') {
1568 logger("dfrn_deliver: $url back from the dead - removing mark for death");
1569 require_once('include/Contact.php');
1570 unmark_for_death($contact);
1573 $res = parse_xml_string($xml);
1575 return $res->status;
1581 * consume_feed - process atom feed and update anything/everything we might need to update
1583 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
1585 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
1586 * It is this person's stuff that is going to be updated.
1587 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
1588 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
1589 * have a contact record.
1590 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
1591 * might not) try and subscribe to it.
1592 * $datedir sorts in reverse order
1593 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
1594 * imported prior to its children being seen in the stream unless we are certain
1595 * of how the feed is arranged/ordered.
1596 * With $pass = 1, we only pull parent items out of the stream.
1597 * With $pass = 2, we only pull children (comments/likes).
1599 * So running this twice, first with pass 1 and then with pass 2 will do the right
1600 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
1601 * model where comments can have sub-threads. That would require some massive sorting
1602 * to get all the feed items into a mostly linear ordering, and might still require
1606 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
1608 require_once('library/simplepie/simplepie.inc');
1610 if(! strlen($xml)) {
1611 logger('consume_feed: empty input');
1615 $feed = new SimplePie();
1616 $feed->set_raw_data($xml);
1618 $feed->enable_order_by_date(true);
1620 $feed->enable_order_by_date(false);
1624 logger('consume_feed: Error parsing XML: ' . $feed->error());
1626 $permalink = $feed->get_permalink();
1628 // Check at the feed level for updated contact name and/or photo
1632 $photo_timestamp = '';
1636 $hubs = $feed->get_links('hub');
1637 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
1640 $hub = implode(',', $hubs);
1642 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
1644 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
1646 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
1647 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
1648 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
1649 $new_name = $elems['name'][0]['data'];
1651 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
1652 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
1653 $photo_url = $elems['link'][0]['attribs']['']['href'];
1656 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
1657 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
1661 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
1662 logger('consume_feed: Updating photo for ' . $contact['name']);
1663 require_once("include/Photo.php");
1664 $photo_failure = false;
1665 $have_photo = false;
1667 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
1668 intval($contact['id']),
1669 intval($contact['uid'])
1672 $resource_id = $r[0]['resource-id'];
1676 $resource_id = photo_new_resource();
1679 $img_str = fetch_url($photo_url,true);
1680 // guess mimetype from headers or filename
1681 $type = guess_image_type($photo_url,true);
1684 $img = new Photo($img_str, $type);
1685 if($img->is_valid()) {
1687 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
1688 dbesc($resource_id),
1689 intval($contact['id']),
1690 intval($contact['uid'])
1694 $img->scaleImageSquare(175);
1696 $hash = $resource_id;
1697 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 4);
1699 $img->scaleImage(80);
1700 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 5);
1702 $img->scaleImage(48);
1703 $r = $img->store($contact['uid'], $contact['id'], $hash, basename($photo_url), 'Contact Photos', 6);
1707 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
1708 WHERE `uid` = %d AND `id` = %d LIMIT 1",
1709 dbesc(datetime_convert()),
1710 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
1711 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
1712 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
1713 intval($contact['uid']),
1714 intval($contact['id'])
1719 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
1720 $r = q("select * from contact where uid = %d and id = %d limit 1",
1721 intval($contact['uid']),
1722 intval($contact['id'])
1725 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1726 dbesc(notags(trim($new_name))),
1727 dbesc(datetime_convert()),
1728 intval($contact['uid']),
1729 intval($contact['id'])
1732 // do our best to update the name on content items
1735 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
1736 dbesc(notags(trim($new_name))),
1737 dbesc($r[0]['name']),
1738 dbesc($r[0]['url']),
1739 intval($contact['uid'])
1744 if(strlen($birthday)) {
1745 if(substr($birthday,0,4) != $contact['bdyear']) {
1746 logger('consume_feed: updating birthday: ' . $birthday);
1750 * Add new birthday event for this person
1752 * $bdtext is just a readable placeholder in case the event is shared
1753 * with others. We will replace it during presentation to our $importer
1754 * to contain a sparkle link and perhaps a photo.
1758 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
1759 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
1762 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1763 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
1764 intval($contact['uid']),
1765 intval($contact['id']),
1766 dbesc(datetime_convert()),
1767 dbesc(datetime_convert()),
1768 dbesc(datetime_convert('UTC','UTC', $birthday)),
1769 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
1778 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
1779 dbesc(substr($birthday,0,4)),
1780 intval($contact['uid']),
1781 intval($contact['id'])
1784 // This function is called twice without reloading the contact
1785 // Make sure we only create one event. This is why &$contact
1786 // is a reference var in this function
1788 $contact['bdyear'] = substr($birthday,0,4);
1793 $community_page = 0;
1794 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
1796 $community_page = intval($rawtags[0]['data']);
1798 if(is_array($contact) && intval($contact['forum']) != $community_page) {
1799 q("update contact set forum = %d where id = %d limit 1",
1800 intval($community_page),
1801 intval($contact['id'])
1803 $contact['forum'] = (string) $community_page;
1807 // process any deleted entries
1809 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
1810 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
1811 foreach($del_entries as $dentry) {
1813 if(isset($dentry['attribs']['']['ref'])) {
1814 $uri = $dentry['attribs']['']['ref'];
1816 if(isset($dentry['attribs']['']['when'])) {
1817 $when = $dentry['attribs']['']['when'];
1818 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
1821 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
1823 if($deleted && is_array($contact)) {
1824 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join `contact` on `item`.`contact-id` = `contact`.`id`
1825 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
1827 intval($importer['uid']),
1828 intval($contact['id'])
1833 if(! $item['deleted'])
1834 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
1836 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
1837 $xo = parse_xml_string($item['object'],false);
1838 $xt = parse_xml_string($item['target'],false);
1839 if($xt->type === ACTIVITY_OBJ_NOTE) {
1840 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
1842 intval($importer['importer_uid'])
1846 // For tags, the owner cannot remove the tag on the author's copy of the post.
1848 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
1849 $author_remove = (($item['origin'] && $item['self']) ? true : false);
1850 $author_copy = (($item['origin']) ? true : false);
1852 if($owner_remove && $author_copy)
1854 if($author_remove || $owner_remove) {
1855 $tags = explode(',',$i[0]['tag']);
1858 foreach($tags as $tag)
1859 if(trim($tag) !== trim($xo->body))
1860 $newtags[] = trim($tag);
1862 q("update item set tag = '%s' where id = %d limit 1",
1863 dbesc(implode(',',$newtags)),
1866 create_tags_from_item($i[0]['id']);
1872 if($item['uri'] == $item['parent-uri']) {
1873 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1874 `body` = '', `title` = ''
1875 WHERE `parent-uri` = '%s' AND `uid` = %d",
1877 dbesc(datetime_convert()),
1878 dbesc($item['uri']),
1879 intval($importer['uid'])
1881 create_tags_from_itemuri($item['uri'], $importer['uid']);
1884 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
1885 `body` = '', `title` = ''
1886 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1888 dbesc(datetime_convert()),
1890 intval($importer['uid'])
1892 create_tags_from_itemuri($uri, $importer['uid']);
1893 if($item['last-child']) {
1894 // ensure that last-child is set in case the comment that had it just got wiped.
1895 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
1896 dbesc(datetime_convert()),
1897 dbesc($item['parent-uri']),
1898 intval($item['uid'])
1900 // who is the last child now?
1901 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
1902 ORDER BY `created` DESC LIMIT 1",
1903 dbesc($item['parent-uri']),
1904 intval($importer['uid'])
1907 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
1918 // Now process the feed
1920 if($feed->get_item_quantity()) {
1922 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
1924 // in inverse date order
1926 $items = array_reverse($feed->get_items());
1928 $items = $feed->get_items();
1931 foreach($items as $item) {
1934 $item_id = $item->get_id();
1935 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
1936 if(isset($rawthread[0]['attribs']['']['ref'])) {
1938 $parent_uri = $rawthread[0]['attribs']['']['ref'];
1941 if(($is_reply) && is_array($contact)) {
1946 // not allowed to post
1948 if($contact['rel'] == CONTACT_IS_FOLLOWER)
1952 // Have we seen it? If not, import it.
1954 $item_id = $item->get_id();
1955 $datarray = get_atom_elements($feed,$item);
1957 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
1958 $datarray['author-name'] = $contact['name'];
1959 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
1960 $datarray['author-link'] = $contact['url'];
1961 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
1962 $datarray['author-avatar'] = $contact['thumb'];
1964 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
1965 logger('consume_feed: no author information! ' . print_r($datarray,true));
1969 $force_parent = false;
1970 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
1971 if($contact['network'] === NETWORK_OSTATUS)
1972 $force_parent = true;
1973 if(strlen($datarray['title']))
1974 unset($datarray['title']);
1975 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
1976 dbesc(datetime_convert()),
1978 intval($importer['uid'])
1980 $datarray['last-child'] = 1;
1984 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1986 intval($importer['uid'])
1989 // Update content if 'updated' changes
1992 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
1994 // do not accept (ignore) an earlier edit than one we currently have.
1995 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
1998 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1999 dbesc($datarray['title']),
2000 dbesc($datarray['body']),
2001 dbesc($datarray['tag']),
2002 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2004 intval($importer['uid'])
2006 create_tags_from_itemuri($item_id, $importer['uid']);
2009 // update last-child if it changes
2011 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2012 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2013 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2014 dbesc(datetime_convert()),
2016 intval($importer['uid'])
2018 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2019 intval($allow[0]['data']),
2020 dbesc(datetime_convert()),
2022 intval($importer['uid'])
2029 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2030 // one way feed - no remote comment ability
2031 $datarray['last-child'] = 0;
2033 $datarray['parent-uri'] = $parent_uri;
2034 $datarray['uid'] = $importer['uid'];
2035 $datarray['contact-id'] = $contact['id'];
2036 if((activity_match($datarray['verb'],ACTIVITY_LIKE)) || (activity_match($datarray['verb'],ACTIVITY_DISLIKE))) {
2037 $datarray['type'] = 'activity';
2038 $datarray['gravity'] = GRAVITY_LIKE;
2039 // only one like or dislike per person
2040 $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",
2041 intval($datarray['uid']),
2042 intval($datarray['contact-id']),
2043 dbesc($datarray['verb']),
2051 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2052 $xo = parse_xml_string($datarray['object'],false);
2053 $xt = parse_xml_string($datarray['target'],false);
2055 if($xt->type == ACTIVITY_OBJ_NOTE) {
2056 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2058 intval($importer['importer_uid'])
2063 // extract tag, if not duplicate, add to parent item
2064 if($xo->id && $xo->content) {
2065 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2066 if(! (stristr($r[0]['tag'],$newtag))) {
2067 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
2068 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2071 create_tags_from_item($r[0]['id']);
2077 $r = item_store($datarray,$force_parent);
2083 // Head post of a conversation. Have we seen it? If not, import it.
2085 $item_id = $item->get_id();
2087 $datarray = get_atom_elements($feed,$item);
2089 if(is_array($contact)) {
2090 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
2091 $datarray['author-name'] = $contact['name'];
2092 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
2093 $datarray['author-link'] = $contact['url'];
2094 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
2095 $datarray['author-avatar'] = $contact['thumb'];
2098 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
2099 logger('consume_feed: no author information! ' . print_r($datarray,true));
2103 // special handling for events
2105 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2106 $ev = bbtoevent($datarray['body']);
2107 if(x($ev,'desc') && x($ev,'start')) {
2108 $ev['uid'] = $importer['uid'];
2109 $ev['uri'] = $item_id;
2110 $ev['edited'] = $datarray['edited'];
2111 $ev['private'] = $datarray['private'];
2113 if(is_array($contact))
2114 $ev['cid'] = $contact['id'];
2115 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2117 intval($importer['uid'])
2120 $ev['id'] = $r[0]['id'];
2121 $xyz = event_store($ev);
2126 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
2127 if(strlen($datarray['title']))
2128 unset($datarray['title']);
2129 $datarray['last-child'] = 1;
2133 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2135 intval($importer['uid'])
2138 // Update content if 'updated' changes
2141 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2143 // do not accept (ignore) an earlier edit than one we currently have.
2144 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2147 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2148 dbesc($datarray['title']),
2149 dbesc($datarray['body']),
2150 dbesc($datarray['tag']),
2151 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2153 intval($importer['uid'])
2155 create_tags_from_itemuri($item_id, $importer['uid']);
2158 // update last-child if it changes
2160 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2161 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2162 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2163 intval($allow[0]['data']),
2164 dbesc(datetime_convert()),
2166 intval($importer['uid'])
2172 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
2173 logger('consume-feed: New follower');
2174 new_follower($importer,$contact,$datarray,$item);
2177 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
2178 lose_follower($importer,$contact,$datarray,$item);
2182 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
2183 logger('consume-feed: New friend request');
2184 new_follower($importer,$contact,$datarray,$item,true);
2187 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
2188 lose_sharer($importer,$contact,$datarray,$item);
2193 if(! is_array($contact))
2197 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2198 // one way feed - no remote comment ability
2199 $datarray['last-child'] = 0;
2201 if($contact['network'] === NETWORK_FEED)
2202 $datarray['private'] = 2;
2204 // This is my contact on another system, but it's really me.
2205 // Turn this into a wall post.
2207 if($contact['remote_self']) {
2208 $datarray['wall'] = 1;
2209 if($contact['network'] === NETWORK_FEED) {
2210 $datarray['private'] = 0;
2214 $datarray['parent-uri'] = $item_id;
2215 $datarray['uid'] = $importer['uid'];
2216 $datarray['contact-id'] = $contact['id'];
2218 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2219 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2220 // but otherwise there's a possible data mixup on the sender's system.
2221 // the tgroup delivery code called from item_store will correct it if it's a forum,
2222 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2223 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2224 $datarray['owner-name'] = $contact['name'];
2225 $datarray['owner-link'] = $contact['url'];
2226 $datarray['owner-avatar'] = $contact['thumb'];
2229 // We've allowed "followers" to reach this point so we can decide if they are
2230 // posting an @-tag delivery, which followers are allowed to do for certain
2231 // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it.
2233 if(($contact['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['uid'],$datarray)))
2237 $r = item_store($datarray);
2245 function local_delivery($importer,$data) {
2248 logger(__function__, LOGGER_TRACE);
2250 if($importer['readonly']) {
2251 // We aren't receiving stuff from this person. But we will quietly ignore them
2252 // rather than a blatant "go away" message.
2253 logger('local_delivery: ignoring');
2258 // Consume notification feed. This may differ from consuming a public feed in several ways
2259 // - might contain email or friend suggestions
2260 // - might contain remote followup to our message
2261 // - in which case we need to accept it and then notify other conversants
2262 // - we may need to send various email notifications
2264 $feed = new SimplePie();
2265 $feed->set_raw_data($data);
2266 $feed->enable_order_by_date(false);
2271 logger('local_delivery: Error parsing XML: ' . $feed->error());
2274 // Check at the feed level for updated contact name and/or photo
2278 $photo_timestamp = '';
2282 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
2284 // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
2286 // $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
2289 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
2290 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
2291 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
2292 $new_name = $elems['name'][0]['data'];
2294 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
2295 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
2296 $photo_url = $elems['link'][0]['attribs']['']['href'];
2300 if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
2301 logger('local_delivery: Updating photo for ' . $importer['name']);
2302 require_once("include/Photo.php");
2303 $photo_failure = false;
2304 $have_photo = false;
2306 $r = q("SELECT `resource-id` FROM `photo` WHERE `contact-id` = %d AND `uid` = %d LIMIT 1",
2307 intval($importer['id']),
2308 intval($importer['importer_uid'])
2311 $resource_id = $r[0]['resource-id'];
2315 $resource_id = photo_new_resource();
2318 $img_str = fetch_url($photo_url,true);
2319 // guess mimetype from headers or filename
2320 $type = guess_image_type($photo_url,true);
2323 $img = new Photo($img_str, $type);
2324 if($img->is_valid()) {
2326 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `contact-id` = %d AND `uid` = %d",
2327 dbesc($resource_id),
2328 intval($importer['id']),
2329 intval($importer['importer_uid'])
2333 $img->scaleImageSquare(175);
2335 $hash = $resource_id;
2336 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 4);
2338 $img->scaleImage(80);
2339 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 5);
2341 $img->scaleImage(48);
2342 $r = $img->store($importer['importer_uid'], $importer['id'], $hash, basename($photo_url), 'Contact Photos', 6);
2346 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
2347 WHERE `uid` = %d AND `id` = %d LIMIT 1",
2348 dbesc(datetime_convert()),
2349 dbesc($a->get_baseurl() . '/photo/' . $hash . '-4.'.$img->getExt()),
2350 dbesc($a->get_baseurl() . '/photo/' . $hash . '-5.'.$img->getExt()),
2351 dbesc($a->get_baseurl() . '/photo/' . $hash . '-6.'.$img->getExt()),
2352 intval($importer['importer_uid']),
2353 intval($importer['id'])
2358 if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
2359 $r = q("select * from contact where uid = %d and id = %d limit 1",
2360 intval($importer['importer_uid']),
2361 intval($importer['id'])
2364 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
2365 dbesc(notags(trim($new_name))),
2366 dbesc(datetime_convert()),
2367 intval($importer['importer_uid']),
2368 intval($importer['id'])
2371 // do our best to update the name on content items
2374 q("update item set `author-name` = '%s' where `author-name` = '%s' and `author-link` = '%s' and uid = %d",
2375 dbesc(notags(trim($new_name))),
2376 dbesc($r[0]['name']),
2377 dbesc($r[0]['url']),
2378 intval($importer['importer_uid'])
2385 // Currently unsupported - needs a lot of work
2386 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
2387 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
2388 $base = $reloc[0]['child'][NAMESPACE_DFRN];
2390 $newloc['uid'] = $importer['importer_uid'];
2391 $newloc['cid'] = $importer['id'];
2392 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
2393 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
2394 $newloc['thumb'] = notags(unxmlify($base['thumb'][0]['data']));
2395 $newloc['micro'] = notags(unxmlify($base['micro'][0]['data']));
2396 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
2397 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
2398 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
2399 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
2400 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
2401 $newloc['sitepubkey'] = notags(unxmlify($base['sitepubkey'][0]['data']));
2402 /** relocated user must have original key pair */
2403 /*$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
2404 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));*/
2406 logger("items:relocate contact ".print_r($newloc, true).print_r($importer, true), LOGGER_DEBUG);
2409 $r = q("SELECT photo, url FROM contact WHERE id=%d AND uid=%d;",
2410 intval($importer['id']),
2411 intval($importer['importer_uid']));
2416 $x = q("UPDATE contact SET
2426 `site-pubkey` = '%s'
2427 WHERE id=%d AND uid=%d;",
2428 dbesc($newloc['name']),
2429 dbesc($newloc['photo']),
2430 dbesc($newloc['thumb']),
2431 dbesc($newloc['micro']),
2432 dbesc($newloc['url']),
2433 dbesc($newloc['request']),
2434 dbesc($newloc['confirm']),
2435 dbesc($newloc['notify']),
2436 dbesc($newloc['poll']),
2437 dbesc($newloc['sitepubkey']),
2438 intval($importer['id']),
2439 intval($importer['importer_uid']));
2445 'owner-link' => array($old['url'], $newloc['url']),
2446 'author-link' => array($old['url'], $newloc['url']),
2447 'owner-avatar' => array($old['photo'], $newloc['photo']),
2448 'author-avatar' => array($old['photo'], $newloc['photo']),
2450 foreach ($fields as $n=>$f){
2451 $x = q("UPDATE item SET `%s`='%s' WHERE `%s`='%s' AND uid=%d",
2454 intval($importer['importer_uid']));
2460 // merge with current record, current contents have priority
2461 // update record, set url-updated
2462 // update profile photos
2468 // handle friend suggestion notification
2470 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
2471 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
2472 $base = $sugg[0]['child'][NAMESPACE_DFRN];
2474 $fsugg['uid'] = $importer['importer_uid'];
2475 $fsugg['cid'] = $importer['id'];
2476 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
2477 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
2478 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
2479 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
2480 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
2482 // Does our member already have a friend matching this description?
2484 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
2485 dbesc($fsugg['name']),
2486 dbesc(normalise_link($fsugg['url'])),
2487 intval($fsugg['uid'])
2492 // Do we already have an fcontact record for this person?
2495 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2496 dbesc($fsugg['url']),
2497 dbesc($fsugg['name']),
2498 dbesc($fsugg['request'])
2503 // OK, we do. Do we already have an introduction for this person ?
2504 $r = q("select id from intro where uid = %d and fid = %d limit 1",
2505 intval($fsugg['uid']),
2512 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
2513 dbesc($fsugg['name']),
2514 dbesc($fsugg['url']),
2515 dbesc($fsugg['photo']),
2516 dbesc($fsugg['request'])
2518 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
2519 dbesc($fsugg['url']),
2520 dbesc($fsugg['name']),
2521 dbesc($fsugg['request'])
2526 // database record did not get created. Quietly give up.
2531 $hash = random_string();
2533 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
2534 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
2535 intval($fsugg['uid']),
2537 intval($fsugg['cid']),
2538 dbesc($fsugg['body']),
2540 dbesc(datetime_convert()),
2545 'type' => NOTIFY_SUGGEST,
2546 'notify_flags' => $importer['notify-flags'],
2547 'language' => $importer['language'],
2548 'to_name' => $importer['username'],
2549 'to_email' => $importer['email'],
2550 'uid' => $importer['importer_uid'],
2552 'link' => $a->get_baseurl() . '/notifications/intros',
2553 'source_name' => $importer['name'],
2554 'source_link' => $importer['url'],
2555 'source_photo' => $importer['photo'],
2556 'verb' => ACTIVITY_REQ_FRIEND,
2565 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
2566 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
2568 logger('local_delivery: private message received');
2571 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
2574 $msg['uid'] = $importer['importer_uid'];
2575 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
2576 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
2577 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
2578 $msg['contact-id'] = $importer['id'];
2579 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
2580 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
2582 $msg['replied'] = 0;
2583 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
2584 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
2585 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
2589 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
2590 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
2592 // send notifications.
2594 require_once('include/enotify.php');
2596 $notif_params = array(
2597 'type' => NOTIFY_MAIL,
2598 'notify_flags' => $importer['notify-flags'],
2599 'language' => $importer['language'],
2600 'to_name' => $importer['username'],
2601 'to_email' => $importer['email'],
2602 'uid' => $importer['importer_uid'],
2604 'source_name' => $msg['from-name'],
2605 'source_link' => $importer['url'],
2606 'source_photo' => $importer['thumb'],
2607 'verb' => ACTIVITY_POST,
2611 notification($notif_params);
2617 $community_page = 0;
2618 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2620 $community_page = intval($rawtags[0]['data']);
2622 if(intval($importer['forum']) != $community_page) {
2623 q("update contact set forum = %d where id = %d limit 1",
2624 intval($community_page),
2625 intval($importer['id'])
2627 $importer['forum'] = (string) $community_page;
2630 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
2632 // process any deleted entries
2634 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2635 if(is_array($del_entries) && count($del_entries)) {
2636 foreach($del_entries as $dentry) {
2638 if(isset($dentry['attribs']['']['ref'])) {
2639 $uri = $dentry['attribs']['']['ref'];
2641 if(isset($dentry['attribs']['']['when'])) {
2642 $when = $dentry['attribs']['']['when'];
2643 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2646 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2650 // check for relayed deletes to our conversation
2653 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
2655 intval($importer['importer_uid'])
2658 $parent_uri = $r[0]['parent-uri'];
2659 if($r[0]['id'] != $r[0]['parent'])
2666 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2669 logger('local_delivery: possible community delete');
2672 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2674 // was the top-level post for this reply written by somebody on this site?
2675 // Specifically, the recipient?
2677 $is_a_remote_delete = false;
2679 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2680 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2681 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2682 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2683 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2684 AND `item`.`uid` = %d
2690 intval($importer['importer_uid'])
2693 $is_a_remote_delete = true;
2695 // Does this have the characteristics of a community or private group comment?
2696 // If it's a reply to a wall post on a community/prvgroup page it's a
2697 // valid community comment. Also forum_mode makes it valid for sure.
2698 // If neither, it's not.
2700 if($is_a_remote_delete && $community) {
2701 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2702 $is_a_remote_delete = false;
2703 logger('local_delivery: not a community delete');
2707 if($is_a_remote_delete) {
2708 logger('local_delivery: received remote delete');
2712 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` left join contact on `item`.`contact-id` = `contact`.`id`
2713 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2715 intval($importer['importer_uid']),
2716 intval($importer['id'])
2722 if($item['deleted'])
2725 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2727 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2728 $xo = parse_xml_string($item['object'],false);
2729 $xt = parse_xml_string($item['target'],false);
2731 if($xt->type === ACTIVITY_OBJ_NOTE) {
2732 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2734 intval($importer['importer_uid'])
2738 // For tags, the owner cannot remove the tag on the author's copy of the post.
2740 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2741 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2742 $author_copy = (($item['origin']) ? true : false);
2744 if($owner_remove && $author_copy)
2746 if($author_remove || $owner_remove) {
2747 $tags = explode(',',$i[0]['tag']);
2750 foreach($tags as $tag)
2751 if(trim($tag) !== trim($xo->body))
2752 $newtags[] = trim($tag);
2754 q("update item set tag = '%s' where id = %d limit 1",
2755 dbesc(implode(',',$newtags)),
2758 create_tags_from_item($i[0]['id']);
2764 if($item['uri'] == $item['parent-uri']) {
2765 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2766 `body` = '', `title` = ''
2767 WHERE `parent-uri` = '%s' AND `uid` = %d",
2769 dbesc(datetime_convert()),
2770 dbesc($item['uri']),
2771 intval($importer['importer_uid'])
2773 create_tags_from_itemuri($item['uri'], $importer['importer_uid']);
2776 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2777 `body` = '', `title` = ''
2778 WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2780 dbesc(datetime_convert()),
2782 intval($importer['importer_uid'])
2784 create_tags_from_itemuri($uri, $importer['importer_uid']);
2785 if($item['last-child']) {
2786 // ensure that last-child is set in case the comment that had it just got wiped.
2787 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2788 dbesc(datetime_convert()),
2789 dbesc($item['parent-uri']),
2790 intval($item['uid'])
2792 // who is the last child now?
2793 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
2794 ORDER BY `created` DESC LIMIT 1",
2795 dbesc($item['parent-uri']),
2796 intval($importer['importer_uid'])
2799 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
2804 // if this is a relayed delete, propagate it to other recipients
2806 if($is_a_remote_delete)
2807 proc_run('php',"include/notifier.php","drop",$item['id']);
2815 foreach($feed->get_items() as $item) {
2818 $item_id = $item->get_id();
2819 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
2820 if(isset($rawthread[0]['attribs']['']['ref'])) {
2822 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2828 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
2831 logger('local_delivery: possible community reply');
2834 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
2836 // was the top-level post for this reply written by somebody on this site?
2837 // Specifically, the recipient?
2839 $is_a_remote_comment = false;
2840 $top_uri = $parent_uri;
2842 $r = q("select `item`.`parent-uri` from `item`
2843 WHERE `item`.`uri` = '%s'
2847 if($r && count($r)) {
2848 $top_uri = $r[0]['parent-uri'];
2850 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
2851 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
2852 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
2853 LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2854 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
2855 AND `item`.`uid` = %d
2861 intval($importer['importer_uid'])
2864 $is_a_remote_comment = true;
2867 // Does this have the characteristics of a community or private group comment?
2868 // If it's a reply to a wall post on a community/prvgroup page it's a
2869 // valid community comment. Also forum_mode makes it valid for sure.
2870 // If neither, it's not.
2872 if($is_a_remote_comment && $community) {
2873 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
2874 $is_a_remote_comment = false;
2875 logger('local_delivery: not a community reply');
2879 if($is_a_remote_comment) {
2880 logger('local_delivery: received remote comment');
2882 // remote reply to our post. Import and then notify everybody else.
2884 $datarray = get_atom_elements($feed,$item);
2886 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2888 intval($importer['importer_uid'])
2891 // Update content if 'updated' changes
2895 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
2897 // do not accept (ignore) an earlier edit than one we currently have.
2898 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2901 logger('received updated comment' , LOGGER_DEBUG);
2902 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2903 dbesc($datarray['title']),
2904 dbesc($datarray['body']),
2905 dbesc($datarray['tag']),
2906 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2908 intval($importer['importer_uid'])
2910 create_tags_from_itemuri($item_id, $importer['importer_uid']);
2912 proc_run('php',"include/notifier.php","comment-import",$iid);
2921 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
2922 intval($importer['importer_uid'])
2926 $datarray['type'] = 'remote-comment';
2927 $datarray['wall'] = 1;
2928 $datarray['parent-uri'] = $parent_uri;
2929 $datarray['uid'] = $importer['importer_uid'];
2930 $datarray['owner-name'] = $own[0]['name'];
2931 $datarray['owner-link'] = $own[0]['url'];
2932 $datarray['owner-avatar'] = $own[0]['thumb'];
2933 $datarray['contact-id'] = $importer['id'];
2935 if(($datarray['verb'] === ACTIVITY_LIKE) || ($datarray['verb'] === ACTIVITY_DISLIKE)) {
2937 $datarray['type'] = 'activity';
2938 $datarray['gravity'] = GRAVITY_LIKE;
2939 $datarray['last-child'] = 0;
2940 // only one like or dislike per person
2941 $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",
2942 intval($datarray['uid']),
2943 intval($datarray['contact-id']),
2944 dbesc($datarray['verb']),
2945 dbesc($datarray['parent-uri']),
2946 dbesc($datarray['parent-uri'])
2953 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2955 $xo = parse_xml_string($datarray['object'],false);
2956 $xt = parse_xml_string($datarray['target'],false);
2958 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
2960 // fetch the parent item
2962 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
2964 intval($importer['importer_uid'])
2969 // extract tag, if not duplicate, and this user allows tags, add to parent item
2971 if($xo->id && $xo->content) {
2972 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2973 if(! (stristr($tagp[0]['tag'],$newtag))) {
2974 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
2975 intval($importer['importer_uid'])
2977 if(count($i) && ! intval($i[0]['blocktags'])) {
2978 q("UPDATE item SET tag = '%s', `edited` = '%s' WHERE id = %d LIMIT 1",
2979 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
2980 intval($tagp[0]['id']),
2981 dbesc(datetime_convert())
2983 create_tags_from_item($tagp[0]['id']);
2991 $posted_id = item_store($datarray);
2995 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2997 intval($importer['importer_uid'])
3000 $parent = $r[0]['parent'];
3001 $parent_uri = $r[0]['parent-uri'];
3005 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
3006 dbesc(datetime_convert()),
3007 intval($importer['importer_uid']),
3008 intval($r[0]['parent'])
3011 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d LIMIT 1",
3012 dbesc(datetime_convert()),
3013 intval($importer['importer_uid']),
3018 if($posted_id && $parent) {
3020 proc_run('php',"include/notifier.php","comment-import","$posted_id");
3022 if((! $is_like) && (! $importer['self'])) {
3024 require_once('include/enotify.php');
3027 'type' => NOTIFY_COMMENT,
3028 'notify_flags' => $importer['notify-flags'],
3029 'language' => $importer['language'],
3030 'to_name' => $importer['username'],
3031 'to_email' => $importer['email'],
3032 'uid' => $importer['importer_uid'],
3033 'item' => $datarray,
3034 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3035 'source_name' => stripslashes($datarray['author-name']),
3036 'source_link' => $datarray['author-link'],
3037 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3038 ? $importer['thumb'] : $datarray['author-avatar']),
3039 'verb' => ACTIVITY_POST,
3041 'parent' => $parent,
3042 'parent_uri' => $parent_uri,
3054 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
3056 $item_id = $item->get_id();
3057 $datarray = get_atom_elements($feed,$item);
3059 if($importer['rel'] == CONTACT_IS_FOLLOWER)
3062 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3064 intval($importer['importer_uid'])
3067 // Update content if 'updated' changes
3070 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
3072 // do not accept (ignore) an earlier edit than one we currently have.
3073 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3076 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3077 dbesc($datarray['title']),
3078 dbesc($datarray['body']),
3079 dbesc($datarray['tag']),
3080 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3082 intval($importer['importer_uid'])
3084 create_tags_from_itemuri($item_id, $importer['importer_uid']);
3087 // update last-child if it changes
3089 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3090 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
3091 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
3092 dbesc(datetime_convert()),
3094 intval($importer['importer_uid'])
3096 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3097 intval($allow[0]['data']),
3098 dbesc(datetime_convert()),
3100 intval($importer['importer_uid'])
3106 $datarray['parent-uri'] = $parent_uri;
3107 $datarray['uid'] = $importer['importer_uid'];
3108 $datarray['contact-id'] = $importer['id'];
3109 if(($datarray['verb'] == ACTIVITY_LIKE) || ($datarray['verb'] == ACTIVITY_DISLIKE)) {
3110 $datarray['type'] = 'activity';
3111 $datarray['gravity'] = GRAVITY_LIKE;
3112 // only one like or dislike per person
3113 $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",
3114 intval($datarray['uid']),
3115 intval($datarray['contact-id']),
3116 dbesc($datarray['verb']),
3125 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
3127 $xo = parse_xml_string($datarray['object'],false);
3128 $xt = parse_xml_string($datarray['target'],false);
3130 if($xt->type == ACTIVITY_OBJ_NOTE) {
3131 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
3133 intval($importer['importer_uid'])
3138 // extract tag, if not duplicate, add to parent item
3140 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
3141 q("UPDATE item SET tag = '%s' WHERE id = %d LIMIT 1",
3142 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
3145 create_tags_from_item($r[0]['id']);
3151 $posted_id = item_store($datarray);
3153 // find out if our user is involved in this conversation and wants to be notified.
3155 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
3157 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
3159 intval($importer['importer_uid'])
3162 if(count($myconv)) {
3163 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
3165 // first make sure this isn't our own post coming back to us from a wall-to-wall event
3166 if(! link_compare($datarray['author-link'],$importer_url)) {
3169 foreach($myconv as $conv) {
3171 // now if we find a match, it means we're in this conversation
3173 if(! link_compare($conv['author-link'],$importer_url))
3176 require_once('include/enotify.php');
3178 $conv_parent = $conv['parent'];
3181 'type' => NOTIFY_COMMENT,
3182 'notify_flags' => $importer['notify-flags'],
3183 'language' => $importer['language'],
3184 'to_name' => $importer['username'],
3185 'to_email' => $importer['email'],
3186 'uid' => $importer['importer_uid'],
3187 'item' => $datarray,
3188 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3189 'source_name' => stripslashes($datarray['author-name']),
3190 'source_link' => $datarray['author-link'],
3191 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3192 ? $importer['thumb'] : $datarray['author-avatar']),
3193 'verb' => ACTIVITY_POST,
3195 'parent' => $conv_parent,
3196 'parent_uri' => $parent_uri
3200 // only send one notification
3212 // Head post of a conversation. Have we seen it? If not, import it.
3215 $item_id = $item->get_id();
3216 $datarray = get_atom_elements($feed,$item);
3218 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
3219 $ev = bbtoevent($datarray['body']);
3220 if(x($ev,'desc') && x($ev,'start')) {
3221 $ev['cid'] = $importer['id'];
3222 $ev['uid'] = $importer['uid'];
3223 $ev['uri'] = $item_id;
3224 $ev['edited'] = $datarray['edited'];
3225 $ev['private'] = $datarray['private'];
3227 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3229 intval($importer['uid'])
3232 $ev['id'] = $r[0]['id'];
3233 $xyz = event_store($ev);
3238 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3240 intval($importer['importer_uid'])
3243 // Update content if 'updated' changes
3246 if((x($datarray,'edited') !== false) && (datetime_convert('UTC','UTC',$datarray['edited']) !== $r[0]['edited'])) {
3248 // do not accept (ignore) an earlier edit than one we currently have.
3249 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3252 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3253 dbesc($datarray['title']),
3254 dbesc($datarray['body']),
3255 dbesc($datarray['tag']),
3256 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3258 intval($importer['importer_uid'])
3260 create_tags_from_itemuri($item_id, $importer['importer_uid']);
3263 // update last-child if it changes
3265 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3266 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
3267 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3268 intval($allow[0]['data']),
3269 dbesc(datetime_convert()),
3271 intval($importer['importer_uid'])
3277 // This is my contact on another system, but it's really me.
3278 // Turn this into a wall post.
3280 if($importer['remote_self'])
3281 $datarray['wall'] = 1;
3283 $datarray['parent-uri'] = $item_id;
3284 $datarray['uid'] = $importer['importer_uid'];
3285 $datarray['contact-id'] = $importer['id'];
3288 if(! link_compare($datarray['owner-link'],$importer['url'])) {
3289 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
3290 // but otherwise there's a possible data mixup on the sender's system.
3291 // the tgroup delivery code called from item_store will correct it if it's a forum,
3292 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
3293 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
3294 $datarray['owner-name'] = $importer['senderName'];
3295 $datarray['owner-link'] = $importer['url'];
3296 $datarray['owner-avatar'] = $importer['thumb'];
3299 if(($importer['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['importer_uid'],$datarray)))
3302 $posted_id = item_store($datarray);
3304 if(stristr($datarray['verb'],ACTIVITY_POKE)) {
3305 $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
3308 $xo = parse_xml_string($datarray['object'],false);
3310 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
3312 // somebody was poked/prodded. Was it me?
3314 $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
3316 foreach($links->link as $l) {
3317 $atts = $l->attributes();
3318 switch($atts['rel']) {
3320 $Blink = $atts['href'];
3326 if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
3328 // send a notification
3329 require_once('include/enotify.php');
3332 'type' => NOTIFY_POKE,
3333 'notify_flags' => $importer['notify-flags'],
3334 'language' => $importer['language'],
3335 'to_name' => $importer['username'],
3336 'to_email' => $importer['email'],
3337 'uid' => $importer['importer_uid'],
3338 'item' => $datarray,
3339 'link' => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $posted_id,
3340 'source_name' => stripslashes($datarray['author-name']),
3341 'source_link' => $datarray['author-link'],
3342 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3343 ? $importer['thumb'] : $datarray['author-avatar']),
3344 'verb' => $datarray['verb'],
3345 'otype' => 'person',
3346 'activity' => $verb,
3363 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
3364 $url = notags(trim($datarray['author-link']));
3365 $name = notags(trim($datarray['author-name']));
3366 $photo = notags(trim($datarray['author-avatar']));
3368 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
3369 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
3370 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
3372 if(is_array($contact)) {
3373 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
3374 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
3375 $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
3376 intval(CONTACT_IS_FRIEND),
3377 intval($contact['id']),
3378 intval($importer['uid'])
3381 // send email notification to owner?
3385 // create contact record
3387 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
3388 `blocked`, `readonly`, `pending`, `writable` )
3389 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
3390 intval($importer['uid']),
3391 dbesc(datetime_convert()),
3393 dbesc(normalise_link($url)),
3397 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
3398 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
3400 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
3401 intval($importer['uid']),
3405 $contact_record = $r[0];
3407 // create notification
3408 $hash = random_string();
3410 if(is_array($contact_record)) {
3411 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
3412 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
3413 intval($importer['uid']),
3414 intval($contact_record['id']),
3416 dbesc(datetime_convert())
3419 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3420 intval($importer['uid'])
3425 if(intval($r[0]['def_gid'])) {
3426 require_once('include/group.php');
3427 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
3430 if(($r[0]['notify-flags'] & NOTIFY_INTRO) && ($r[0]['page-flags'] == PAGE_NORMAL)) {
3431 $email_tpl = get_intltext_template('follow_notify_eml.tpl');
3432 $email = replace_macros($email_tpl, array(
3433 '$requestor' => ((strlen($name)) ? $name : t('[Name Withheld]')),
3435 '$myname' => $r[0]['username'],
3436 '$siteurl' => $a->get_baseurl(),
3437 '$sitename' => $a->config['sitename']
3439 $res = mail($r[0]['email'],
3440 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'),
3442 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
3443 . 'Content-type: text/plain; charset=UTF-8' . "\n"
3444 . 'Content-transfer-encoding: 8bit' );
3451 function lose_follower($importer,$contact,$datarray,$item) {
3453 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
3454 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3455 intval(CONTACT_IS_SHARING),
3456 intval($contact['id'])
3460 contact_remove($contact['id']);
3464 function lose_sharer($importer,$contact,$datarray,$item) {
3466 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
3467 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d LIMIT 1",
3468 intval(CONTACT_IS_FOLLOWER),
3469 intval($contact['id'])
3473 contact_remove($contact['id']);
3478 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
3482 if(is_array($importer)) {
3483 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
3484 intval($importer['uid'])
3488 // Diaspora has different message-ids in feeds than they do
3489 // through the direct Diaspora protocol. If we try and use
3490 // the feed, we'll get duplicates. So don't.
3492 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
3495 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
3497 // Use a single verify token, even if multiple hubs
3499 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
3501 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
3503 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
3505 if(! strlen($contact['hub-verify'])) {
3506 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d LIMIT 1",
3507 dbesc($verify_token),
3508 intval($contact['id'])
3512 post_url($url,$params);
3514 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
3521 function atom_author($tag,$name,$uri,$h,$w,$photo) {
3525 $name = xmlify($name);
3526 $uri = xmlify($uri);
3529 $photo = xmlify($photo);
3533 $o .= "<name>$name</name>\r\n";
3534 $o .= "<uri>$uri</uri>\r\n";
3535 $o .= '<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3536 $o .= '<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
3538 call_hooks('atom_author', $o);
3540 $o .= "</$tag>\r\n";
3544 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
3548 if(! $item['parent'])
3551 if($item['deleted'])
3552 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
3555 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
3556 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
3558 $body = $item['body'];
3560 $o = "\r\n\r\n<entry>\r\n";
3562 if(is_array($author))
3563 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb']);
3565 $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']));
3566 if(strlen($item['owner-name']))
3567 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar']);
3569 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
3570 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
3571 $o .= '<thr:in-reply-to ref="' . xmlify($parent_item) . '" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['parent']) . '" />' . "\r\n";
3574 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
3575 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
3576 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
3577 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
3578 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
3579 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? bbcode($body) : $body)) . '</content>' . "\r\n";
3580 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($a->get_baseurl() . '/display/' . $owner['nickname'] . '/' . $item['id']) . '" />' . "\r\n";
3582 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
3584 if($item['location']) {
3585 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
3586 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
3590 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
3592 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
3593 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
3596 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
3597 if($item['bookmark'])
3598 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
3601 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
3604 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
3606 if($item['signed_text']) {
3607 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
3608 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
3611 $verb = construct_verb($item);
3612 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
3613 $actobj = construct_activity_object($item);
3616 $actarg = construct_activity_target($item);
3620 $tags = item_getfeedtags($item);
3622 foreach($tags as $t) {
3623 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
3627 $o .= item_getfeedattach($item);
3629 $mentioned = get_mentions($item);
3633 call_hooks('atom_entry', $o);
3635 $o .= '</entry>' . "\r\n";
3640 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
3643 logger('fix_private_photos', LOGGER_DEBUG);
3644 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
3649 $img_start = strpos($orig_body, '[img');
3650 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3651 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3652 while( ($img_st_close !== false) && ($img_len !== false) ) {
3654 $img_st_close++; // make it point to AFTER the closing bracket
3655 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
3657 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
3660 if(stristr($image , $site . '/photo/')) {
3661 // Only embed locally hosted photos
3663 $i = basename($image);
3664 $i = str_replace(array('.jpg','.png'),array('',''),$i);
3665 $x = strpos($i,'-');
3668 $res = substr($i,$x+1);
3669 $i = substr($i,0,$x);
3670 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
3677 // Check to see if we should replace this photo link with an embedded image
3678 // 1. No need to do so if the photo is public
3679 // 2. If there's a contact-id provided, see if they're in the access list
3680 // for the photo. If so, embed it.
3681 // 3. Otherwise, if we have an item, see if the item permissions match the photo
3682 // permissions, regardless of order but first check to see if they're an exact
3683 // match to save some processing overhead.
3685 if(has_permissions($r[0])) {
3687 $recips = enumerate_permissions($r[0]);
3688 if(in_array($cid, $recips)) {
3693 if(compare_permissions($item,$r[0]))
3698 $data = $r[0]['data'];
3699 $type = $r[0]['type'];
3701 // If a custom width and height were specified, apply before embedding
3702 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
3703 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
3705 $width = intval($match[1]);
3706 $height = intval($match[2]);
3708 $ph = new Photo($data, $type);
3709 if($ph->is_valid()) {
3710 $ph->scaleImage(max($width, $height));
3711 $data = $ph->imageString();
3712 $type = $ph->getType();
3716 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
3717 $image = 'data:' . $type . ';base64,' . base64_encode($data);
3718 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
3724 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
3725 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
3726 if($orig_body === false)
3729 $img_start = strpos($orig_body, '[img');
3730 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
3731 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
3734 $new_body = $new_body . $orig_body;
3740 function has_permissions($obj) {
3741 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
3746 function compare_permissions($obj1,$obj2) {
3747 // first part is easy. Check that these are exactly the same.
3748 if(($obj1['allow_cid'] == $obj2['allow_cid'])
3749 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3750 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3751 && ($obj1['deny_gid'] == $obj2['deny_gid']))
3754 // This is harder. Parse all the permissions and compare the resulting set.
3756 $recipients1 = enumerate_permissions($obj1);
3757 $recipients2 = enumerate_permissions($obj2);
3760 if($recipients1 == $recipients2)
3765 // returns an array of contact-ids that are allowed to see this object
3767 function enumerate_permissions($obj) {
3768 require_once('include/group.php');
3769 $allow_people = expand_acl($obj['allow_cid']);
3770 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
3771 $deny_people = expand_acl($obj['deny_cid']);
3772 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
3773 $recipients = array_unique(array_merge($allow_people,$allow_groups));
3774 $deny = array_unique(array_merge($deny_people,$deny_groups));
3775 $recipients = array_diff($recipients,$deny);
3779 function item_getfeedtags($item) {
3782 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3784 for($x = 0; $x < $cnt; $x ++) {
3786 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
3790 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
3792 for($x = 0; $x < $cnt; $x ++) {
3794 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
3800 function item_getfeedattach($item) {
3802 $arr = explode('[/attach],',$item['attach']);
3804 foreach($arr as $r) {
3806 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
3808 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
3809 if(intval($matches[2]))
3810 $ret .= 'length="' . intval($matches[2]) . '" ';
3811 if($matches[4] !== ' ')
3812 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
3813 $ret .= ' />' . "\r\n";
3822 function item_expire($uid,$days) {
3824 if((! $uid) || ($days < 1))
3827 // $expire_network_only = save your own wall posts
3828 // and just expire conversations started by others
3830 $expire_network_only = get_pconfig($uid,'expire','network_only');
3831 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
3833 $r = q("SELECT * FROM `item`
3835 AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY
3846 $expire_items = get_pconfig($uid, 'expire','items');
3847 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
3849 $expire_notes = get_pconfig($uid, 'expire','notes');
3850 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
3852 $expire_starred = get_pconfig($uid, 'expire','starred');
3853 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
3855 $expire_photos = get_pconfig($uid, 'expire','photos');
3856 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
3858 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3860 foreach($r as $item) {
3862 // don't expire filed items
3864 if(strpos($item['file'],'[') !== false)
3867 // Only expire posts, not photos and photo comments
3869 if($expire_photos==0 && strlen($item['resource-id']))
3871 if($expire_starred==0 && intval($item['starred']))
3873 if($expire_notes==0 && $item['type']=='note')
3875 if($expire_items==0 && $item['type']!='note')
3878 drop_item($item['id'],false);
3881 proc_run('php',"include/notifier.php","expire","$uid");
3886 function drop_items($items) {
3889 if(! local_user() && ! remote_user())
3893 foreach($items as $item) {
3894 $owner = drop_item($item,false);
3895 if($owner && ! $uid)
3900 // multiple threads may have been deleted, send an expire notification
3903 proc_run('php',"include/notifier.php","expire","$uid");
3907 function drop_item($id,$interactive = true) {
3911 // locate item to be deleted
3913 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
3920 notice( t('Item not found.') . EOL);
3921 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
3926 $owner = $item['uid'];
3930 // check if logged in user is either the author or owner of this item
3932 if(is_array($_SESSION['remote'])) {
3933 foreach($_SESSION['remote'] as $visitor) {
3934 if($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
3935 $cid = $visitor['cid'];
3942 if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
3944 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
3947 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d LIMIT 1",
3948 dbesc(datetime_convert()),
3949 dbesc(datetime_convert()),
3952 create_tags_from_item($item['id']);
3954 // clean up categories and tags so they don't end up as orphans
3957 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
3959 foreach($matches as $mtch) {
3960 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
3966 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
3968 foreach($matches as $mtch) {
3969 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
3973 // If item is a link to a photo resource, nuke all the associated photos
3974 // (visitors will not have photo resources)
3975 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
3976 // generate a resource-id and therefore aren't intimately linked to the item.
3978 if(strlen($item['resource-id'])) {
3979 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
3980 dbesc($item['resource-id']),
3981 intval($item['uid'])
3983 // ignore the result
3986 // If item is a link to an event, nuke the event record.
3988 if(intval($item['event-id'])) {
3989 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3990 intval($item['event-id']),
3991 intval($item['uid'])
3993 // ignore the result
3996 // clean up item_id and sign meta-data tables
3998 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
3999 intval($item['id']),
4000 intval($item['uid'])
4003 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
4004 intval($item['id']),
4005 intval($item['uid'])
4008 // If it's the parent of a comment thread, kill all the kids
4010 if($item['uri'] == $item['parent-uri']) {
4011 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
4012 WHERE `parent-uri` = '%s' AND `uid` = %d ",
4013 dbesc(datetime_convert()),
4014 dbesc(datetime_convert()),
4015 dbesc($item['parent-uri']),
4016 intval($item['uid'])
4018 create_tags_from_item($item['parent-uri'], $item['uid']);
4019 // ignore the result
4022 // ensure that last-child is set in case the comment that had it just got wiped.
4023 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
4024 dbesc(datetime_convert()),
4025 dbesc($item['parent-uri']),
4026 intval($item['uid'])
4028 // who is the last child now?
4029 $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",
4030 dbesc($item['parent-uri']),
4031 intval($item['uid'])
4034 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d LIMIT 1",
4039 // Add a relayable_retraction signature for Diaspora.
4040 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
4042 $drop_id = intval($item['id']);
4044 // send the notification upstream/downstream as the case may be
4046 proc_run('php',"include/notifier.php","drop","$drop_id");
4050 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
4056 notice( t('Permission denied.') . EOL);
4057 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
4064 function first_post_date($uid,$wall = false) {
4065 $r = q("select id, created from item
4066 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
4068 order by created asc limit 1",
4070 intval($wall ? 1 : 0)
4073 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
4074 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
4079 function posted_dates($uid,$wall) {
4080 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
4082 $dthen = first_post_date($uid,$wall);
4086 // If it's near the end of a long month, backup to the 28th so that in
4087 // consecutive loops we'll always get a whole month difference.
4089 if(intval(substr($dnow,8)) > 28)
4090 $dnow = substr($dnow,0,8) . '28';
4091 if(intval(substr($dthen,8)) > 28)
4092 $dnow = substr($dthen,0,8) . '28';
4095 // Starting with the current month, get the first and last days of every
4096 // month down to and including the month of the first post
4097 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
4098 $dstart = substr($dnow,0,8) . '01';
4099 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
4100 $start_month = datetime_convert('','',$dstart,'Y-m-d');
4101 $end_month = datetime_convert('','',$dend,'Y-m-d');
4102 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
4103 $ret[] = array($str,$end_month,$start_month);
4104 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
4110 function posted_date_widget($url,$uid,$wall) {
4113 if(! feature_enabled($uid,'archives'))
4116 // For former Facebook folks that left because of "timeline"
4118 /* if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
4121 $ret = posted_dates($uid,$wall);
4125 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
4126 '$title' => t('Archives'),
4127 '$size' => ((count($ret) > 6) ? 6 : count($ret)),
4134 function store_diaspora_retract_sig($item, $user, $baseurl) {
4135 // Note that we can't add a target_author_signature
4136 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
4137 // the comment, that means we're the home of the post, and Diaspora will only
4138 // check the parent_author_signature of retractions that it doesn't have to relay further
4140 // I don't think this function gets called for an "unlike," but I'll check anyway
4142 $enabled = intval(get_config('system','diaspora_enabled'));
4144 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
4148 logger('drop_item: storing diaspora retraction signature');
4150 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
4152 if(local_user() == $item['uid']) {
4154 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
4155 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
4158 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
4159 $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
4162 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
4163 // only handles DFRN deletes
4164 $handle_baseurl_start = strpos($r['url'],'://') + 3;
4165 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
4166 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
4172 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
4173 intval($item['id']),
4174 dbesc($signed_text),