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/files.php');
10 require_once('include/text.php');
11 require_once('include/email.php');
12 require_once('include/threads.php');
13 require_once('include/socgraph.php');
14 require_once('include/plaintext.php');
15 require_once('include/ostatus.php');
16 require_once('include/feed.php');
17 require_once('mod/share.php');
19 require_once('library/defuse/php-encryption-1.2.1/Crypto.php');
22 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0, $forpubsub = false) {
25 $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
26 $public_feed = (($dfrn_id) ? false : true);
27 $starred = false; // not yet implemented, possible security issues
30 if($public_feed && $a->argc > 2) {
31 for($x = 2; $x < $a->argc; $x++) {
32 if($a->argv[$x] == 'converse')
34 if($a->argv[$x] == 'starred')
36 if($a->argv[$x] === 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1]))
37 $category = $a->argv[$x+1];
43 // default permissions - anonymous user
45 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
47 $r = q("SELECT `contact`.*, `user`.`uid` AS `user_uid`, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
48 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
49 WHERE `contact`.`self` = 1 AND `user`.`nickname` = '%s' LIMIT 1",
57 $owner_id = $owner['user_uid'];
58 $owner_nick = $owner['nickname'];
60 $birthday = feed_birthday($owner_id,$owner['timezone']);
70 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
74 $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
75 $my_id = '1:' . $dfrn_id;
78 $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
79 $my_id = '0:' . $dfrn_id;
86 $r = q("SELECT * FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `contact`.`uid` = %d $sql_extra LIMIT 1",
94 require_once('include/security.php');
95 $groups = init_groups_visitor($contact['id']);
98 for($x = 0; $x < count($groups); $x ++)
99 $groups[$x] = '<' . intval($groups[$x]) . '>' ;
100 $gs = implode('|', $groups);
103 $gs = '<<>>' ; // Impossible to match
105 $sql_extra = sprintf("
106 AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
107 AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
108 AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
109 AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
111 intval($contact['id']),
112 intval($contact['id']),
123 // Include answers to status.net posts in pubsub feeds
125 $sql_post_table = "INNER JOIN `thread` ON `thread`.`iid` = `item`.`parent`
126 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`";
127 $visibility = sprintf("AND (`item`.`parent` = `item`.`id`) OR (`item`.`network` = '%s' AND ((`thread`.`network`='%s') OR (`thritem`.`network` = '%s')))",
128 dbesc(NETWORK_DFRN), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS));
129 $date_field = "`received`";
130 $sql_order = "`item`.`received` DESC";
132 $date_field = "`changed`";
133 $sql_order = "`item`.`parent` ".$sort.", `item`.`created` ASC";
136 if(! strlen($last_update))
137 $last_update = 'now -30 days';
139 if(isset($category)) {
140 $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
141 dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
142 //$sql_extra .= file_tag_file_query('item',$category,'category');
147 $sql_extra .= " AND `contact`.`self` = 1 ";
150 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
152 // AND ( `item`.`edited` > '%s' OR `item`.`changed` > '%s' )
153 // dbesc($check_date),
155 $r = q("SELECT STRAIGHT_JOIN `item`.*, `item`.`id` AS `item_id`,
156 `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
157 `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
158 `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
159 `contact`.`id` AS `contact-id`, `contact`.`uid` AS `contact-uid`,
160 `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
161 FROM `item` $sql_post_table
162 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
163 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
164 LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
165 WHERE `item`.`uid` = %d AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`parent` != 0
166 AND ((`item`.`wall` = 1) $visibility) AND `item`.$date_field > '%s'
168 ORDER BY $sql_order LIMIT 0, 300",
174 // Will check further below if this actually returned results.
175 // We will provide an empty feed if that is the case.
179 $feed_template = get_markup_template(($dfrn_id) ? 'atom_feed_dfrn.tpl' : 'atom_feed.tpl');
183 $hubxml = feed_hublinks();
185 $salmon = feed_salmonlinks($owner_nick);
187 $alternatelink = $owner['url'];
190 $alternatelink .= "/category/".$category;
192 $atom .= replace_macros($feed_template, array(
193 '$version' => xmlify(FRIENDICA_VERSION),
194 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner_nick),
195 '$feed_title' => xmlify($owner['name']),
196 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', 'now' , ATOM_TIME)) ,
198 '$salmon' => $salmon,
199 '$alternatelink' => xmlify($alternatelink),
200 '$name' => xmlify($owner['name']),
201 '$profile_page' => xmlify($owner['url']),
202 '$photo' => xmlify($owner['photo']),
203 '$thumb' => xmlify($owner['thumb']),
204 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
205 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
206 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
207 '$birthday' => ((strlen($birthday)) ? '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>' : ''),
208 '$community' => (($owner['page-flags'] == PAGE_COMMUNITY) ? '<dfrn:community>1</dfrn:community>' : '')
211 call_hooks('atom_feed', $atom);
213 if(! count($items)) {
215 call_hooks('atom_feed_end', $atom);
217 $atom .= '</feed>' . "\r\n";
221 foreach($items as $item) {
223 // prevent private email from leaking.
224 if($item['network'] === NETWORK_MAIL)
227 // public feeds get html, our own nodes use bbcode
231 // catch any email that's in a public conversation and make sure it doesn't leak
239 $atom .= atom_entry($item,$type,null,$owner,true);
242 call_hooks('atom_feed_end', $atom);
244 $atom .= '</feed>' . "\r\n";
250 function construct_verb($item) {
252 return $item['verb'];
253 return ACTIVITY_POST;
256 function construct_activity_object($item) {
258 if($item['object']) {
259 $o = '<as:object>' . "\r\n";
260 $r = parse_xml_string($item['object'],false);
266 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
268 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
270 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
272 if(substr($r->link,0,1) === '<') {
273 // patch up some facebook "like" activity objects that got stored incorrectly
274 // for a couple of months prior to 9-Jun-2011 and generated bad XML.
275 // we can probably remove this hack here and in the following function in a few months time.
276 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
277 $r->link = str_replace('&','&', $r->link);
278 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
282 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
285 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
286 $o .= '</as:object>' . "\r\n";
293 function construct_activity_target($item) {
295 if($item['target']) {
296 $o = '<as:target>' . "\r\n";
297 $r = parse_xml_string($item['target'],false);
301 $o .= '<as:object-type>' . xmlify($r->type) . '</as:object-type>' . "\r\n";
303 $o .= '<id>' . xmlify($r->id) . '</id>' . "\r\n";
305 $o .= '<title>' . xmlify($r->title) . '</title>' . "\r\n";
307 if(substr($r->link,0,1) === '<') {
308 if(strstr($r->link,'&') && (! strstr($r->link,'&')))
309 $r->link = str_replace('&','&', $r->link);
310 $r->link = preg_replace('/\<link(.*?)\"\>/','<link$1"/>',$r->link);
314 $o .= '<link rel="alternate" type="text/html" href="' . xmlify($r->link) . '" />' . "\r\n";
317 $o .= '<content type="html" >' . xmlify(bbcode($r->content)) . '</content>' . "\r\n";
318 $o .= '</as:target>' . "\r\n";
327 * The purpose of this function is to apply system message length limits to
328 * imported messages without including any embedded photos in the length
330 if(! function_exists('limit_body_size')) {
331 function limit_body_size($body) {
333 // logger('limit_body_size: start', LOGGER_DEBUG);
335 $maxlen = get_max_import_size();
337 // If the length of the body, including the embedded images, is smaller
338 // than the maximum, then don't waste time looking for the images
339 if($maxlen && (strlen($body) > $maxlen)) {
341 logger('limit_body_size: the total body length exceeds the limit', LOGGER_DEBUG);
348 $img_start = strpos($orig_body, '[img');
349 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
350 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
351 while(($img_st_close !== false) && ($img_end !== false)) {
353 $img_st_close++; // make it point to AFTER the closing bracket
354 $img_end += $img_start;
355 $img_end += strlen('[/img]');
357 if(! strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
358 // This is an embedded image
360 if( ($textlen + $img_start) > $maxlen ) {
361 if($textlen < $maxlen) {
362 logger('limit_body_size: the limit happens before an embedded image', LOGGER_DEBUG);
363 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
368 $new_body = $new_body . substr($orig_body, 0, $img_start);
369 $textlen += $img_start;
372 $new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
376 if( ($textlen + $img_end) > $maxlen ) {
377 if($textlen < $maxlen) {
378 logger('limit_body_size: the limit happens before the end of a non-embedded image', LOGGER_DEBUG);
379 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
384 $new_body = $new_body . substr($orig_body, 0, $img_end);
385 $textlen += $img_end;
388 $orig_body = substr($orig_body, $img_end);
390 if($orig_body === false) // in case the body ends on a closing image tag
393 $img_start = strpos($orig_body, '[img');
394 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
395 $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
398 if( ($textlen + strlen($orig_body)) > $maxlen) {
399 if($textlen < $maxlen) {
400 logger('limit_body_size: the limit happens after the end of the last image', LOGGER_DEBUG);
401 $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
406 logger('limit_body_size: the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG);
407 $new_body = $new_body . $orig_body;
408 $textlen += strlen($orig_body);
417 function title_is_body($title, $body) {
419 $title = strip_tags($title);
420 $title = trim($title);
421 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
422 $title = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $title);
424 $body = strip_tags($body);
426 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
427 $body = str_replace(array("\n", "\r", "\t", " "), array("","","",""), $body);
429 if (strlen($title) < strlen($body))
430 $body = substr($body, 0, strlen($title));
432 if (($title != $body) and (substr($title, -3) == "...")) {
433 $pos = strrpos($title, "...");
435 $title = substr($title, 0, $pos);
436 $body = substr($body, 0, $pos);
440 return($title == $body);
445 function get_atom_elements($feed, $item, $contact = array()) {
447 require_once('library/HTMLPurifier.auto.php');
448 require_once('include/html2bbcode.php');
450 $best_photo = array();
454 $author = $item->get_author();
456 $res['author-name'] = unxmlify($author->get_name());
457 $res['author-link'] = unxmlify($author->get_link());
460 $res['author-name'] = unxmlify($feed->get_title());
461 $res['author-link'] = unxmlify($feed->get_permalink());
463 $res['uri'] = unxmlify($item->get_id());
464 $res['title'] = unxmlify($item->get_title());
465 $res['body'] = unxmlify($item->get_content());
466 $res['plink'] = unxmlify($item->get_link(0));
468 if (isset($contact["network"]) AND ($contact["network"] == NETWORK_FEED) AND strstr($res['plink'], ".app.net/")) {
469 logger("get_atom_elements: detected app.net posting: ".print_r($res, true), LOGGER_DEBUG);
471 $res['body'] = nl2br($res['body']);
474 // removing the content of the title if its identically to the body
475 // This helps with auto generated titles e.g. from tumblr
476 if (title_is_body($res["title"], $res["body"]))
480 $base_url = implode('/', array_slice(explode('/',$res['plink']),0,3));
484 // look for a photo. We should check media size and find the best one,
485 // but for now let's just find any author photo
486 // Additionally we look for an alternate author link. On OStatus this one is the one we want.
488 $authorlinks = $item->feed->data["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["feed"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"]["http://www.w3.org/2005/Atom"]["link"];
489 if (is_array($authorlinks)) {
490 foreach ($authorlinks as $link) {
491 $linkdata = array_shift($link["attribs"]);
493 if ($linkdata["rel"] == "alternate")
494 $res["author-link"] = $linkdata["href"];
498 $rawauthor = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
500 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
501 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
502 foreach($base as $link) {
503 if($link['attribs']['']['rel'] === 'alternate')
504 $res['author-link'] = unxmlify($link['attribs']['']['href']);
506 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
507 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
508 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
513 $rawactor = $item->get_item_tags(NAMESPACE_ACTIVITY, 'actor');
515 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
516 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
517 if($base && count($base)) {
518 foreach($base as $link) {
519 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
520 $res['author-link'] = unxmlify($link['attribs']['']['href']);
521 if(!x($res, 'author-avatar') || !$res['author-avatar']) {
522 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
523 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
529 // No photo/profile-link on the item - look at the feed level
531 if((! (x($res,'author-link'))) || (! (x($res,'author-avatar')))) {
532 $rawauthor = $feed->get_feed_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'author');
533 if($rawauthor && $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
534 $base = $rawauthor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
535 foreach($base as $link) {
536 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
537 $res['author-link'] = unxmlify($link['attribs']['']['href']);
538 if(! $res['author-avatar']) {
539 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
540 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
545 $rawactor = $feed->get_feed_tags(NAMESPACE_ACTIVITY, 'subject');
547 if($rawactor && activity_match($rawactor[0]['child'][NAMESPACE_ACTIVITY]['object-type'][0]['data'],ACTIVITY_OBJ_PERSON)) {
548 $base = $rawactor[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
550 if($base && count($base)) {
551 foreach($base as $link) {
552 if($link['attribs']['']['rel'] === 'alternate' && (! $res['author-link']))
553 $res['author-link'] = unxmlify($link['attribs']['']['href']);
554 if(! (x($res,'author-avatar'))) {
555 if($link['attribs']['']['rel'] === 'avatar' || $link['attribs']['']['rel'] === 'photo')
556 $res['author-avatar'] = unxmlify($link['attribs']['']['href']);
563 $apps = $item->get_item_tags(NAMESPACE_STATUSNET,'notice_info');
564 if($apps && $apps[0]['attribs']['']['source']) {
565 $res['app'] = strip_tags(unxmlify($apps[0]['attribs']['']['source']));
566 if($res['app'] === 'web')
567 $res['app'] = 'OStatus';
570 // base64 encoded json structure representing Diaspora signature
572 $dsig = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_signature');
574 $res['dsprsig'] = unxmlify($dsig[0]['data']);
577 $dguid = $item->get_item_tags(NAMESPACE_DFRN,'diaspora_guid');
579 $res['guid'] = unxmlify($dguid[0]['data']);
581 $bm = $item->get_item_tags(NAMESPACE_DFRN,'bookmark');
583 $res['bookmark'] = ((unxmlify($bm[0]['data']) === 'true') ? 1 : 0);
587 * If there's a copy of the body content which is guaranteed to have survived mangling in transit, use it.
590 $have_real_body = false;
592 $rawenv = $item->get_item_tags(NAMESPACE_DFRN, 'env');
594 $have_real_body = true;
595 $res['body'] = $rawenv[0]['data'];
596 $res['body'] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$res['body']);
597 // make sure nobody is trying to sneak some html tags by us
598 $res['body'] = notags(base64url_decode($res['body']));
602 $res['body'] = limit_body_size($res['body']);
604 // It isn't certain at this point whether our content is plaintext or html and we'd be foolish to trust
605 // the content type. Our own network only emits text normally, though it might have been converted to
606 // html if we used a pubsubhubbub transport. But if we see even one html tag in our text, we will
607 // have to assume it is all html and needs to be purified.
609 // It doesn't matter all that much security wise - because before this content is used anywhere, we are
610 // going to escape any tags we find regardless, but this lets us import a limited subset of html from
611 // the wild, by sanitising it and converting supported tags to bbcode before we rip out any remaining
614 if((strpos($res['body'],'<') !== false) && (strpos($res['body'],'>') !== false)) {
616 $res['body'] = reltoabs($res['body'],$base_url);
618 $res['body'] = html2bb_video($res['body']);
620 $res['body'] = oembed_html2bbcode($res['body']);
622 $config = HTMLPurifier_Config::createDefault();
623 $config->set('Cache.DefinitionImpl', null);
625 // we shouldn't need a whitelist, because the bbcode converter
626 // will strip out any unsupported tags.
628 $purifier = new HTMLPurifier($config);
629 $res['body'] = $purifier->purify($res['body']);
631 $res['body'] = @html2bbcode($res['body']);
635 elseif(! $have_real_body) {
637 // it's not one of our messages and it has no tags
638 // so it's probably just text. We'll escape it just to be safe.
640 $res['body'] = escape_tags($res['body']);
644 // this tag is obsolete but we keep it for really old sites
646 $allow = $item->get_item_tags(NAMESPACE_DFRN,'comment-allow');
647 if($allow && $allow[0]['data'] == 1)
648 $res['last-child'] = 1;
650 $res['last-child'] = 0;
652 $private = $item->get_item_tags(NAMESPACE_DFRN,'private');
653 if($private && intval($private[0]['data']) > 0)
654 $res['private'] = intval($private[0]['data']);
658 $extid = $item->get_item_tags(NAMESPACE_DFRN,'extid');
659 if($extid && $extid[0]['data'])
660 $res['extid'] = $extid[0]['data'];
662 $rawlocation = $item->get_item_tags(NAMESPACE_DFRN, 'location');
664 $res['location'] = unxmlify($rawlocation[0]['data']);
667 $rawcreated = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'published');
669 $res['created'] = unxmlify($rawcreated[0]['data']);
672 $rawedited = $item->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10,'updated');
674 $res['edited'] = unxmlify($rawedited[0]['data']);
676 if((x($res,'edited')) && (! (x($res,'created'))))
677 $res['created'] = $res['edited'];
679 if(! $res['created'])
680 $res['created'] = $item->get_date('c');
683 $res['edited'] = $item->get_date('c');
686 // Disallow time travelling posts
688 $d1 = strtotime($res['created']);
689 $d2 = strtotime($res['edited']);
690 $d3 = strtotime('now');
693 $res['created'] = datetime_convert();
695 $res['edited'] = datetime_convert();
697 $rawowner = $item->get_item_tags(NAMESPACE_DFRN, 'owner');
698 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])
699 $res['owner-name'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data']);
700 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data'])
701 $res['owner-name'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['name'][0]['data']);
702 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])
703 $res['owner-link'] = unxmlify($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data']);
704 elseif($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data'])
705 $res['owner-link'] = unxmlify($rawowner[0]['child'][NAMESPACE_DFRN]['uri'][0]['data']);
707 if($rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link']) {
708 $base = $rawowner[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['link'];
710 foreach($base as $link) {
711 if(!x($res, 'owner-avatar') || !$res['owner-avatar']) {
712 if($link['attribs']['']['rel'] === 'photo' || $link['attribs']['']['rel'] === 'avatar')
713 $res['owner-avatar'] = unxmlify($link['attribs']['']['href']);
718 $rawgeo = $item->get_item_tags(NAMESPACE_GEORSS,'point');
720 $res['coord'] = unxmlify($rawgeo[0]['data']);
722 if ($contact["network"] == NETWORK_FEED) {
723 $res['verb'] = ACTIVITY_POST;
724 $res['object-type'] = ACTIVITY_OBJ_NOTE;
727 $rawverb = $item->get_item_tags(NAMESPACE_ACTIVITY, 'verb');
729 // select between supported verbs
732 $res['verb'] = unxmlify($rawverb[0]['data']);
735 // translate OStatus unfollow to activity streams if it happened to get selected
737 if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
738 $res['verb'] = ACTIVITY_UNFOLLOW;
740 $cats = $item->get_categories();
743 foreach($cats as $cat) {
744 $term = $cat->get_term();
746 $term = $cat->get_label();
747 $scheme = $cat->get_scheme();
748 if($scheme && $term && stristr($scheme,'X-DFRN:'))
749 $tag_arr[] = substr($scheme,7,1) . '[url=' . unxmlify(substr($scheme,9)) . ']' . unxmlify($term) . '[/url]';
751 $tag_arr[] = notags(trim($term));
753 $res['tag'] = implode(',', $tag_arr);
756 $attach = $item->get_enclosures();
759 foreach($attach as $att) {
760 $len = intval($att->get_length());
761 $link = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_link()))));
762 $title = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_title()))));
763 $type = str_replace(array(',','"'),array('%2D','%22'),notags(trim(unxmlify($att->get_type()))));
764 if(strpos($type,';'))
765 $type = substr($type,0,strpos($type,';'));
766 if((! $link) || (strpos($link,'http') !== 0))
772 $type = 'application/octet-stream';
774 $att_arr[] = '[attach]href="' . $link . '" length="' . $len . '" type="' . $type . '" title="' . $title . '"[/attach]';
776 $res['attach'] = implode(',', $att_arr);
779 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'object');
782 $res['object'] = '<object>' . "\n";
783 $child = $rawobj[0]['child'];
784 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
785 $res['object-type'] = $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'];
786 $res['object'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
788 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
789 $res['object'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
790 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
791 $res['object'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
792 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'title') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
793 $res['object'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
794 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'content') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
795 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
797 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
798 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
799 $res['object'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
800 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
802 $body = html2bb_video($body);
804 $config = HTMLPurifier_Config::createDefault();
805 $config->set('Cache.DefinitionImpl', null);
807 $purifier = new HTMLPurifier($config);
808 $body = $purifier->purify($body);
809 $body = html2bbcode($body);
812 $res['object'] .= '<content>' . $body . '</content>' . "\n";
815 $res['object'] .= '</object>' . "\n";
818 $rawobj = $item->get_item_tags(NAMESPACE_ACTIVITY, 'target');
821 $res['target'] = '<target>' . "\n";
822 $child = $rawobj[0]['child'];
823 if($child[NAMESPACE_ACTIVITY]['object-type'][0]['data']) {
824 $res['target'] .= '<type>' . $child[NAMESPACE_ACTIVITY]['object-type'][0]['data'] . '</type>' . "\n";
826 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'id') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'])
827 $res['target'] .= '<id>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['id'][0]['data'] . '</id>' . "\n";
828 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'link') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['link'])
829 $res['target'] .= '<link>' . encode_rel_links($child[SIMPLEPIE_NAMESPACE_ATOM_10]['link']) . '</link>' . "\n";
830 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'])
831 $res['target'] .= '<title>' . $child[SIMPLEPIE_NAMESPACE_ATOM_10]['title'][0]['data'] . '</title>' . "\n";
832 if(x($child[SIMPLEPIE_NAMESPACE_ATOM_10], 'data') && $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data']) {
833 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['content'][0]['data'];
835 $body = $child[SIMPLEPIE_NAMESPACE_ATOM_10]['summary'][0]['data'];
836 // preserve a copy of the original body content in case we later need to parse out any microformat information, e.g. events
837 $res['target'] .= '<orig>' . xmlify($body) . '</orig>' . "\n";
838 if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
840 $body = html2bb_video($body);
842 $config = HTMLPurifier_Config::createDefault();
843 $config->set('Cache.DefinitionImpl', null);
845 $purifier = new HTMLPurifier($config);
846 $body = $purifier->purify($body);
847 $body = html2bbcode($body);
850 $res['target'] .= '<content>' . $body . '</content>' . "\n";
853 $res['target'] .= '</target>' . "\n";
856 // This is some experimental stuff. By now retweets are shown with "RT:"
857 // But: There is data so that the message could be shown similar to native retweets
858 // There is some better way to parse this array - but it didn't worked for me.
859 $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"];
860 if (is_array($child)) {
861 logger('get_atom_elements: Looking for status.net repeated message');
863 $message = $child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["content"][0]["data"];
864 $orig_id = ostatus_convert_href($child["http://activitystrea.ms/spec/1.0/"]["object"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10]["id"][0]["data"]);
865 $author = $child[SIMPLEPIE_NAMESPACE_ATOM_10]["author"][0]["child"][SIMPLEPIE_NAMESPACE_ATOM_10];
866 $uri = $author["uri"][0]["data"];
867 $name = $author["name"][0]["data"];
868 $avatar = @array_shift($author["link"][2]["attribs"]);
869 $avatar = $avatar["href"];
871 if (($name != "") and ($uri != "") and ($avatar != "") and ($message != "")) {
872 logger('get_atom_elements: fixing sender of repeated message. '.$orig_id, LOGGER_DEBUG);
874 if (!intval(get_config('system','wall-to-wall_share'))) {
875 $prefix = share_header($name, $uri, $avatar, "", "", $orig_link);
877 $res["body"] = $prefix.html2bbcode($message)."[/share]";
879 $res["owner-name"] = $res["author-name"];
880 $res["owner-link"] = $res["author-link"];
881 $res["owner-avatar"] = $res["author-avatar"];
883 $res["author-name"] = $name;
884 $res["author-link"] = $uri;
885 $res["author-avatar"] = $avatar;
887 $res["body"] = html2bbcode($message);
892 if (isset($contact["network"]) AND ($contact["network"] == NETWORK_FEED) AND $contact['fetch_further_information']) {
895 // Handle enclosures and treat them as preview picture
897 foreach ($attach AS $attachment)
898 if ($attachment->type == "image/jpeg")
899 $preview = $attachment->link;
901 $res["body"] = $res["title"].add_page_info($res['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_blacklist']);
902 $res["tag"] = add_page_keywords($res['plink'], false, $preview, ($contact['fetch_further_information'] == 2), $contact['ffi_keyword_blacklist']);
904 $res["object-type"] = ACTIVITY_OBJ_BOOKMARK;
905 unset($res["attach"]);
906 } elseif (isset($contact["network"]) AND ($contact["network"] == NETWORK_OSTATUS))
907 $res["body"] = add_page_info_to_body($res["body"]);
908 elseif (isset($contact["network"]) AND ($contact["network"] == NETWORK_FEED) AND strstr($res['plink'], ".app.net/")) {
909 $res["body"] = add_page_info_to_body($res["body"]);
912 $arr = array('feed' => $feed, 'item' => $item, 'result' => $res);
914 call_hooks('parse_atom', $arr);
919 function add_page_info_data($data) {
920 call_hooks('page_info_data', $data);
922 // It maybe is a rich content, but if it does have everything that a link has,
923 // then treat it that way
924 if (($data["type"] == "rich") AND is_string($data["title"]) AND
925 is_string($data["text"]) AND (sizeof($data["images"]) > 0))
926 $data["type"] = "link";
928 if ((($data["type"] != "link") AND ($data["type"] != "video") AND ($data["type"] != "photo")) OR ($data["title"] == $url))
931 if ($no_photos AND ($data["type"] == "photo"))
934 // If the link contains BBCode stuff, make a short link out of this to avoid parsing problems
935 if (strpos($data["url"], '[') OR strpos($data["url"], ']')) {
936 require_once("include/network.php");
937 $data["url"] = short_link($data["url"]);
940 if (($data["type"] != "photo") AND is_string($data["title"]))
941 $text .= "[bookmark=".$data["url"]."]".trim($data["title"])."[/bookmark]";
943 if (($data["type"] != "video") AND ($photo != ""))
944 $text .= '[img]'.$photo.'[/img]';
945 elseif (($data["type"] != "video") AND (sizeof($data["images"]) > 0)) {
946 $imagedata = $data["images"][0];
947 $text .= '[img]'.$imagedata["src"].'[/img]';
950 if (($data["type"] != "photo") AND is_string($data["text"]))
951 $text .= "[quote]".$data["text"]."[/quote]";
954 if (isset($data["keywords"]) AND count($data["keywords"])) {
957 foreach ($data["keywords"] AS $keyword) {
958 $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
959 array("","", "", "", "", ""), $keyword);
960 $hashtags .= "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag)."]".$hashtag."[/url] ";
964 return("\n[class=type-".$data["type"]."]".$text."[/class]".$hashtags);
967 function query_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
968 require_once("mod/parse_url.php");
970 $data = Cache::get("parse_url:".$url);
972 $data = parseurl_getsiteinfo($url, true);
973 Cache::set("parse_url:".$url,serialize($data), CACHE_DAY);
975 $data = unserialize($data);
978 $data["images"][0]["src"] = $photo;
980 logger('fetch page info for '.$url.' '.print_r($data, true), LOGGER_DEBUG);
982 if (!$keywords AND isset($data["keywords"]))
983 unset($data["keywords"]);
985 if (($keyword_blacklist != "") AND isset($data["keywords"])) {
986 $list = explode(",", $keyword_blacklist);
987 foreach ($list AS $keyword) {
988 $keyword = trim($keyword);
989 $index = array_search($keyword, $data["keywords"]);
990 if ($index !== false)
991 unset($data["keywords"][$index]);
998 function add_page_keywords($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
999 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
1002 if (isset($data["keywords"]) AND count($data["keywords"])) {
1004 foreach ($data["keywords"] AS $keyword) {
1005 $hashtag = str_replace(array(" ", "+", "/", ".", "#", "'"),
1006 array("","", "", "", "", ""), $keyword);
1011 $tags .= "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag)."]".$hashtag."[/url]";
1018 function add_page_info($url, $no_photos = false, $photo = "", $keywords = false, $keyword_blacklist = "") {
1019 $data = query_page_info($url, $no_photos, $photo, $keywords, $keyword_blacklist);
1021 $text = add_page_info_data($data);
1026 function add_page_info_to_body($body, $texturl = false, $no_photos = false) {
1028 logger('add_page_info_to_body: fetch page info for body '.$body, LOGGER_DEBUG);
1030 $URLSearchString = "^\[\]";
1032 // Adding these spaces is a quick hack due to my problems with regular expressions :)
1033 preg_match("/[^!#@]\[url\]([$URLSearchString]*)\[\/url\]/ism", " ".$body, $matches);
1036 preg_match("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", " ".$body, $matches);
1038 // Convert urls without bbcode elements
1039 if (!$matches AND $texturl) {
1040 preg_match("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", " ".$body, $matches);
1042 // Yeah, a hack. I really hate regular expressions :)
1044 $matches[1] = $matches[2];
1048 $footer = add_page_info($matches[1], $no_photos);
1050 // Remove the link from the body if the link is attached at the end of the post
1051 if (isset($footer) AND (trim($footer) != "") AND (strpos($footer, $matches[1]))) {
1052 $removedlink = trim(str_replace($matches[1], "", $body));
1053 if (($removedlink == "") OR strstr($body, $removedlink))
1054 $body = $removedlink;
1056 $url = str_replace(array('/', '.'), array('\/', '\.'), $matches[1]);
1057 $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $body);
1058 if (($removedlink == "") OR strstr($body, $removedlink))
1059 $body = $removedlink;
1062 // Add the page information to the bottom
1063 if (isset($footer) AND (trim($footer) != ""))
1069 function encode_rel_links($links) {
1071 if(! ((is_array($links)) && (count($links))))
1073 foreach($links as $link) {
1075 if($link['attribs']['']['rel'])
1076 $o .= 'rel="' . $link['attribs']['']['rel'] . '" ';
1077 if($link['attribs']['']['type'])
1078 $o .= 'type="' . $link['attribs']['']['type'] . '" ';
1079 if($link['attribs']['']['href'])
1080 $o .= 'href="' . $link['attribs']['']['href'] . '" ';
1081 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['width'])
1082 $o .= 'media:width="' . $link['attribs'][NAMESPACE_MEDIA]['width'] . '" ';
1083 if( (x($link['attribs'],NAMESPACE_MEDIA)) && $link['attribs'][NAMESPACE_MEDIA]['height'])
1084 $o .= 'media:height="' . $link['attribs'][NAMESPACE_MEDIA]['height'] . '" ';
1085 $o .= ' />' . "\n" ;
1090 function add_guid($item) {
1091 $r = q("SELECT `guid` FROM `guid` WHERE `guid` = '%s' LIMIT 1", dbesc($item["guid"]));
1095 q("INSERT INTO `guid` (`guid`,`plink`,`uri`,`network`) VALUES ('%s','%s','%s','%s')",
1096 dbesc($item["guid"]), dbesc($item["plink"]),
1097 dbesc($item["uri"]), dbesc($item["network"]));
1100 // Adds a "lang" specification in a "postopts" element of given $arr,
1101 // if possible and not already present.
1102 // Expects "body" element to exist in $arr.
1103 // TODO: add a parameter to request forcing override
1104 function item_add_language_opt(&$arr) {
1106 if (version_compare(PHP_VERSION, '5.3.0', '<')) return; // LanguageDetect.php not available ?
1108 if ( x($arr, 'postopts') )
1110 if ( strstr($arr['postopts'], 'lang=') )
1113 // TODO: add parameter to request overriding
1116 $postopts = $arr['postopts'];
1123 require_once('library/langdet/Text/LanguageDetect.php');
1124 $naked_body = preg_replace('/\[(.+?)\]/','',$arr['body']);
1125 $l = new Text_LanguageDetect;
1126 //$lng = $l->detectConfidence($naked_body);
1127 //$arr['postopts'] = (($lng['language']) ? 'lang=' . $lng['language'] . ';' . $lng['confidence'] : '');
1128 $lng = $l->detect($naked_body, 3);
1130 if (sizeof($lng) > 0) {
1131 if ($postopts != "") $postopts .= '&'; // arbitrary separator, to be reviewed
1132 $postopts .= 'lang=';
1134 foreach ($lng as $language => $score) {
1135 $postopts .= $sep . $language.";".$score;
1138 $arr['postopts'] = $postopts;
1142 function item_store($arr,$force_parent = false, $notify = false, $dontcache = false) {
1144 // If it is a posting where users should get notifications, then define it as wall posting
1147 $arr['type'] = 'wall';
1149 $arr['last-child'] = 1;
1150 $arr['network'] = NETWORK_DFRN;
1153 // If a Diaspora signature structure was passed in, pull it out of the
1154 // item array and set it aside for later storage.
1157 if(x($arr,'dsprsig')) {
1158 $dsprsig = json_decode(base64_decode($arr['dsprsig']));
1159 unset($arr['dsprsig']);
1162 // Converting the plink
1163 if ($arr['network'] == NETWORK_OSTATUS) {
1164 if (isset($arr['plink']))
1165 $arr['plink'] = ostatus_convert_href($arr['plink']);
1166 elseif (isset($arr['uri']))
1167 $arr['plink'] = ostatus_convert_href($arr['uri']);
1170 if(x($arr, 'gravity'))
1171 $arr['gravity'] = intval($arr['gravity']);
1172 elseif($arr['parent-uri'] === $arr['uri'])
1173 $arr['gravity'] = 0;
1174 elseif(activity_match($arr['verb'],ACTIVITY_POST))
1175 $arr['gravity'] = 6;
1177 $arr['gravity'] = 6; // extensible catchall
1179 if(! x($arr,'type'))
1180 $arr['type'] = 'remote';
1184 /* check for create date and expire time */
1185 $uid = intval($arr['uid']);
1186 $r = q("SELECT expire FROM user WHERE uid = %d", intval($uid));
1188 $expire_interval = $r[0]['expire'];
1189 if ($expire_interval>0) {
1190 $expire_date = new DateTime( '- '.$expire_interval.' days', new DateTimeZone('UTC'));
1191 $created_date = new DateTime($arr['created'], new DateTimeZone('UTC'));
1192 if ($created_date < $expire_date) {
1193 logger('item-store: item created ('.$arr['created'].') before expiration time ('.$expire_date->format(DateTime::W3C).'). ignored. ' . print_r($arr,true), LOGGER_DEBUG);
1199 // If there is no guid then take the same guid that was taken before for the same uri
1200 if ((trim($arr['guid']) == "") AND (trim($arr['uri']) != "") AND (trim($arr['network']) != "")) {
1201 logger('item_store: checking for an existing guid for uri '.$arr['uri'], LOGGER_DEBUG);
1202 $r = q("SELECT `guid` FROM `guid` WHERE `uri` = '%s' AND `network` = '%s' LIMIT 1",
1203 dbesc(trim($arr['uri'])), dbesc(trim($arr['network'])));
1206 $arr['guid'] = $r[0]["guid"];
1207 logger('item_store: found guid '.$arr['guid'].' for uri '.$arr['uri'], LOGGER_DEBUG);
1211 // If there is no guid then take the same guid that was taken before for the same plink
1212 if ((trim($arr['guid']) == "") AND (trim($arr['plink']) != "") AND (trim($arr['network']) != "")) {
1213 logger('item_store: checking for an existing guid for plink '.$arr['plink'], LOGGER_DEBUG);
1214 $r = q("SELECT `guid`, `uri` FROM `guid` WHERE `plink` = '%s' AND `network` = '%s' LIMIT 1",
1215 dbesc(trim($arr['plink'])), dbesc(trim($arr['network'])));
1218 $arr['guid'] = $r[0]["guid"];
1219 logger('item_store: found guid '.$arr['guid'].' for plink '.$arr['plink'], LOGGER_DEBUG);
1221 if ($r[0]["uri"] != $arr['uri'])
1222 logger('Different uri for same guid: '.$arr['uri'].' and '.$r[0]["uri"].' - this shouldnt happen!', LOGGER_DEBUG);
1226 // Shouldn't happen but we want to make absolutely sure it doesn't leak from a plugin.
1227 // Deactivated, since the bbcode parser can handle with it - and it destroys posts with some smileys that contain "<"
1228 //if((strpos($arr['body'],'<') !== false) || (strpos($arr['body'],'>') !== false))
1229 // $arr['body'] = strip_tags($arr['body']);
1231 item_add_language_opt($arr);
1236 $guid_prefix = $arr['network'];
1238 $arr['wall'] = ((x($arr,'wall')) ? intval($arr['wall']) : 0);
1239 $arr['guid'] = ((x($arr,'guid')) ? notags(trim($arr['guid'])) : get_guid(32, $guid_prefix));
1240 $arr['uri'] = ((x($arr,'uri')) ? notags(trim($arr['uri'])) : $arr['guid']);
1241 $arr['extid'] = ((x($arr,'extid')) ? notags(trim($arr['extid'])) : '');
1242 $arr['author-name'] = ((x($arr,'author-name')) ? trim($arr['author-name']) : '');
1243 $arr['author-link'] = ((x($arr,'author-link')) ? notags(trim($arr['author-link'])) : '');
1244 $arr['author-avatar'] = ((x($arr,'author-avatar')) ? notags(trim($arr['author-avatar'])) : '');
1245 $arr['owner-name'] = ((x($arr,'owner-name')) ? trim($arr['owner-name']) : '');
1246 $arr['owner-link'] = ((x($arr,'owner-link')) ? notags(trim($arr['owner-link'])) : '');
1247 $arr['owner-avatar'] = ((x($arr,'owner-avatar')) ? notags(trim($arr['owner-avatar'])) : '');
1248 $arr['created'] = ((x($arr,'created') !== false) ? datetime_convert('UTC','UTC',$arr['created']) : datetime_convert());
1249 $arr['edited'] = ((x($arr,'edited') !== false) ? datetime_convert('UTC','UTC',$arr['edited']) : datetime_convert());
1250 $arr['commented'] = ((x($arr,'commented') !== false) ? datetime_convert('UTC','UTC',$arr['commented']) : datetime_convert());
1251 $arr['received'] = ((x($arr,'received') !== false) ? datetime_convert('UTC','UTC',$arr['received']) : datetime_convert());
1252 $arr['changed'] = ((x($arr,'changed') !== false) ? datetime_convert('UTC','UTC',$arr['changed']) : datetime_convert());
1253 $arr['title'] = ((x($arr,'title')) ? trim($arr['title']) : '');
1254 $arr['location'] = ((x($arr,'location')) ? trim($arr['location']) : '');
1255 $arr['coord'] = ((x($arr,'coord')) ? notags(trim($arr['coord'])) : '');
1256 $arr['last-child'] = ((x($arr,'last-child')) ? intval($arr['last-child']) : 0 );
1257 $arr['visible'] = ((x($arr,'visible') !== false) ? intval($arr['visible']) : 1 );
1258 $arr['deleted'] = 0;
1259 $arr['parent-uri'] = ((x($arr,'parent-uri')) ? notags(trim($arr['parent-uri'])) : '');
1260 $arr['verb'] = ((x($arr,'verb')) ? notags(trim($arr['verb'])) : '');
1261 $arr['object-type'] = ((x($arr,'object-type')) ? notags(trim($arr['object-type'])) : '');
1262 $arr['object'] = ((x($arr,'object')) ? trim($arr['object']) : '');
1263 $arr['target-type'] = ((x($arr,'target-type')) ? notags(trim($arr['target-type'])) : '');
1264 $arr['target'] = ((x($arr,'target')) ? trim($arr['target']) : '');
1265 $arr['plink'] = ((x($arr,'plink')) ? notags(trim($arr['plink'])) : '');
1266 $arr['allow_cid'] = ((x($arr,'allow_cid')) ? trim($arr['allow_cid']) : '');
1267 $arr['allow_gid'] = ((x($arr,'allow_gid')) ? trim($arr['allow_gid']) : '');
1268 $arr['deny_cid'] = ((x($arr,'deny_cid')) ? trim($arr['deny_cid']) : '');
1269 $arr['deny_gid'] = ((x($arr,'deny_gid')) ? trim($arr['deny_gid']) : '');
1270 $arr['private'] = ((x($arr,'private')) ? intval($arr['private']) : 0 );
1271 $arr['bookmark'] = ((x($arr,'bookmark')) ? intval($arr['bookmark']) : 0 );
1272 $arr['body'] = ((x($arr,'body')) ? trim($arr['body']) : '');
1273 $arr['tag'] = ((x($arr,'tag')) ? notags(trim($arr['tag'])) : '');
1274 $arr['attach'] = ((x($arr,'attach')) ? notags(trim($arr['attach'])) : '');
1275 $arr['app'] = ((x($arr,'app')) ? notags(trim($arr['app'])) : '');
1276 $arr['origin'] = ((x($arr,'origin')) ? intval($arr['origin']) : 0 );
1277 $arr['network'] = ((x($arr,'network')) ? trim($arr['network']) : '');
1278 $arr['postopts'] = ((x($arr,'postopts')) ? trim($arr['postopts']) : '');
1279 $arr['resource-id'] = ((x($arr,'resource-id')) ? trim($arr['resource-id']) : '');
1280 $arr['event-id'] = ((x($arr,'event-id')) ? intval($arr['event-id']) : 0 );
1281 $arr['inform'] = ((x($arr,'inform')) ? trim($arr['inform']) : '');
1282 $arr['file'] = ((x($arr,'file')) ? trim($arr['file']) : '');
1284 if ($arr['plink'] == "") {
1286 $arr['plink'] = $a->get_baseurl().'/display/'.urlencode($arr['guid']);
1289 if ($arr['network'] == "") {
1290 $r = q("SELECT `network` FROM `contact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1291 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
1292 dbesc(normalise_link($arr['author-link'])),
1297 $r = q("SELECT `network` FROM `gcontact` WHERE `network` IN ('%s', '%s', '%s') AND `nurl` = '%s' LIMIT 1",
1298 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS),
1299 dbesc(normalise_link($arr['author-link']))
1303 $r = q("SELECT `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1304 intval($arr['contact-id']),
1309 $arr['network'] = $r[0]["network"];
1311 // Fallback to friendica (why is it empty in some cases?)
1312 if ($arr['network'] == "")
1313 $arr['network'] = NETWORK_DFRN;
1315 logger("item_store: Set network to ".$arr["network"]." for ".$arr["uri"], LOGGER_DEBUG);
1318 if ($arr['guid'] != "") {
1319 // Checking if there is already an item with the same guid
1320 logger('checking for an item for user '.$arr['uid'].' on network '.$arr['network'].' with the guid '.$arr['guid'], LOGGER_DEBUG);
1321 $r = q("SELECT `guid` FROM `item` WHERE `guid` = '%s' AND `network` = '%s' AND `uid` = '%d' LIMIT 1",
1322 dbesc($arr['guid']), dbesc($arr['network']), intval($arr['uid']));
1325 logger('found item with guid '.$arr['guid'].' for user '.$arr['uid'].' on network '.$arr['network'], LOGGER_DEBUG);
1330 // Check for hashtags in the body and repair or add hashtag links
1331 item_body_set_hashtags($arr);
1333 $arr['thr-parent'] = $arr['parent-uri'];
1334 if($arr['parent-uri'] === $arr['uri']) {
1336 $parent_deleted = 0;
1337 $allow_cid = $arr['allow_cid'];
1338 $allow_gid = $arr['allow_gid'];
1339 $deny_cid = $arr['deny_cid'];
1340 $deny_gid = $arr['deny_gid'];
1341 $notify_type = 'wall-new';
1345 // find the parent and snarf the item id and ACLs
1346 // and anything else we need to inherit
1348 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d ORDER BY `id` ASC LIMIT 1",
1349 dbesc($arr['parent-uri']),
1355 // is the new message multi-level threaded?
1356 // even though we don't support it now, preserve the info
1357 // and re-attach to the conversation parent.
1359 if($r[0]['uri'] != $r[0]['parent-uri']) {
1360 $arr['parent-uri'] = $r[0]['parent-uri'];
1361 $z = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `parent-uri` = '%s' AND `uid` = %d
1362 ORDER BY `id` ASC LIMIT 1",
1363 dbesc($r[0]['parent-uri']),
1364 dbesc($r[0]['parent-uri']),
1371 $parent_id = $r[0]['id'];
1372 $parent_deleted = $r[0]['deleted'];
1373 $allow_cid = $r[0]['allow_cid'];
1374 $allow_gid = $r[0]['allow_gid'];
1375 $deny_cid = $r[0]['deny_cid'];
1376 $deny_gid = $r[0]['deny_gid'];
1377 $arr['wall'] = $r[0]['wall'];
1378 $notify_type = 'comment-new';
1380 // if the parent is private, force privacy for the entire conversation
1381 // This differs from the above settings as it subtly allows comments from
1382 // email correspondents to be private even if the overall thread is not.
1384 if($r[0]['private'])
1385 $arr['private'] = $r[0]['private'];
1387 // Edge case. We host a public forum that was originally posted to privately.
1388 // The original author commented, but as this is a comment, the permissions
1389 // weren't fixed up so it will still show the comment as private unless we fix it here.
1391 if((intval($r[0]['forum_mode']) == 1) && (! $r[0]['private']))
1392 $arr['private'] = 0;
1395 // If its a post from myself then tag the thread as "mention"
1396 logger("item_store: Checking if parent ".$parent_id." has to be tagged as mention for user ".$arr['uid'], LOGGER_DEBUG);
1397 $u = q("select * from user where uid = %d limit 1", intval($arr['uid']));
1400 $self = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1401 logger("item_store: 'myself' is ".$self." for parent ".$parent_id." checking against ".$arr['author-link']." and ".$arr['owner-link'], LOGGER_DEBUG);
1402 if ((normalise_link($arr['author-link']) == $self) OR (normalise_link($arr['owner-link']) == $self)) {
1403 q("UPDATE `thread` SET `mention` = 1 WHERE `iid` = %d", intval($parent_id));
1404 logger("item_store: tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1410 // Allow one to see reply tweets from status.net even when
1411 // we don't have or can't see the original post.
1414 logger('item_store: $force_parent=true, reply converted to top-level post.');
1416 $arr['parent-uri'] = $arr['uri'];
1417 $arr['gravity'] = 0;
1420 logger('item_store: item parent '.$arr['parent-uri'].' for '.$arr['uid'].' was not found - ignoring item');
1424 $parent_deleted = 0;
1428 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1430 dbesc($arr['network']),
1433 if($r && count($r)) {
1434 logger('duplicated item with the same uri found. ' . print_r($arr,true));
1438 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1439 $r = q("SELECT `id` FROM `item` WHERE `body` = '%s' AND `network` = '%s' AND `created` = '%s' AND `contact-id` = %d AND `uid` = %d LIMIT 1",
1440 dbesc($arr['body']),
1441 dbesc($arr['network']),
1442 dbesc($arr['created']),
1443 intval($arr['contact-id']),
1446 if($r && count($r)) {
1447 logger('duplicated item with the same body found. ' . print_r($arr,true));
1451 // Is this item available in the global items (with uid=0)?
1452 if ($arr["uid"] == 0) {
1453 $arr["global"] = true;
1455 q("UPDATE `item` SET `global` = 1 WHERE `guid` = '%s'", dbesc($arr["guid"]));
1457 $isglobal = q("SELECT `global` FROM `item` WHERE `uid` = 0 AND `guid` = '%s'", dbesc($arr["guid"]));
1459 $arr["global"] = (count($isglobal) > 0);
1462 // Fill the cache field
1463 put_item_in_cache($arr);
1466 call_hooks('post_local',$arr);
1468 call_hooks('post_remote',$arr);
1470 if(x($arr,'cancel')) {
1471 logger('item_store: post cancelled by plugin.');
1475 // Store the unescaped version
1480 logger('item_store: ' . print_r($arr,true), LOGGER_DATA);
1482 $r = dbq("INSERT INTO `item` (`"
1483 . implode("`, `", array_keys($arr))
1485 . implode("', '", array_values($arr))
1491 // find the item we just created
1492 $r = q("SELECT `id` FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `network` = '%s' ORDER BY `id` ASC ",
1494 intval($arr['uid']),
1495 dbesc($arr['network'])
1500 // Store the guid and other relevant data
1503 $current_post = $r[0]['id'];
1504 logger('item_store: created item ' . $current_post);
1506 // Set "success_update" and "last-item" to the date of the last time we heard from this contact
1507 // This can be used to filter for inactive contacts.
1508 // Only do this for public postings to avoid privacy problems, since poco data is public.
1509 // Don't set this value if it isn't from the owner (could be an author that we don't know)
1511 $update = (!$arr['private'] AND (($arr["author-link"] === $arr["owner-link"]) OR ($arr["parent-uri"] === $arr["uri"])));
1513 // Is it a forum? Then we don't care about the rules from above
1514 if (!$update AND ($arr["network"] == NETWORK_DFRN) AND ($arr["parent-uri"] === $arr["uri"])) {
1515 $isforum = q("SELECT `forum` FROM `contact` WHERE `id` = %d AND `forum`",
1516 intval($arr['contact-id']));
1522 q("UPDATE `contact` SET `success_update` = '%s', `last-item` = '%s' WHERE `id` = %d",
1523 dbesc($arr['received']),
1524 dbesc($arr['received']),
1525 intval($arr['contact-id'])
1528 logger('item_store: could not locate created item');
1532 logger('item_store: duplicated post occurred. Removing duplicates. uri = '.$arr['uri'].' uid = '.$arr['uid']);
1533 q("DELETE FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `id` != %d ",
1535 intval($arr['uid']),
1536 intval($current_post)
1540 if((! $parent_id) || ($arr['parent-uri'] === $arr['uri']))
1541 $parent_id = $current_post;
1543 if(strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid))
1546 $private = $arr['private'];
1548 // Set parent id - and also make sure to inherit the parent's ACLs.
1550 $r = q("UPDATE `item` SET `parent` = %d, `allow_cid` = '%s', `allow_gid` = '%s',
1551 `deny_cid` = '%s', `deny_gid` = '%s', `private` = %d, `deleted` = %d WHERE `id` = %d",
1558 intval($parent_deleted),
1559 intval($current_post)
1562 $arr['id'] = $current_post;
1563 $arr['parent'] = $parent_id;
1564 $arr['allow_cid'] = $allow_cid;
1565 $arr['allow_gid'] = $allow_gid;
1566 $arr['deny_cid'] = $deny_cid;
1567 $arr['deny_gid'] = $deny_gid;
1568 $arr['private'] = $private;
1569 $arr['deleted'] = $parent_deleted;
1571 // update the commented timestamp on the parent
1572 // Only update "commented" if it is really a comment
1573 if (($arr['verb'] == ACTIVITY_POST) OR !get_config("system", "like_no_comment"))
1574 q("UPDATE `item` SET `commented` = '%s', `changed` = '%s' WHERE `id` = %d",
1575 dbesc(datetime_convert()),
1576 dbesc(datetime_convert()),
1580 q("UPDATE `item` SET `changed` = '%s' WHERE `id` = %d",
1581 dbesc(datetime_convert()),
1586 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1587 intval($current_post),
1588 dbesc($dsprsig->signed_text),
1589 dbesc($dsprsig->signature),
1590 dbesc($dsprsig->signer)
1596 * If this is now the last-child, force all _other_ children of this parent to *not* be last-child
1599 if($arr['last-child']) {
1600 $r = q("UPDATE `item` SET `last-child` = 0 WHERE `parent-uri` = '%s' AND `uid` = %d AND `id` != %d",
1602 intval($arr['uid']),
1603 intval($current_post)
1607 $deleted = tag_deliver($arr['uid'],$current_post);
1609 // current post can be deleted if is for a community page and no mention are
1611 if (!$deleted AND !$dontcache) {
1613 $r = q('SELECT * FROM `item` WHERE id = %d', intval($current_post));
1614 if (count($r) == 1) {
1616 call_hooks('post_local_end', $r[0]);
1618 call_hooks('post_remote_end', $r[0]);
1620 logger('item_store: new item not found in DB, id ' . $current_post);
1623 // Add every contact of the post to the global contact table
1626 create_tags_from_item($current_post);
1627 create_files_from_item($current_post);
1629 // Only check for notifications on start posts
1630 if ($arr['parent-uri'] === $arr['uri']) {
1631 add_thread($current_post);
1632 logger('item_store: Check notification for contact '.$arr['contact-id'].' and post '.$current_post, LOGGER_DEBUG);
1634 // Send a notification for every new post?
1635 $r = q("SELECT `notify_new_posts` FROM `contact` WHERE `id` = %d AND `uid` = %d AND `notify_new_posts` LIMIT 1",
1636 intval($arr['contact-id']),
1639 $send_notification = count($r);
1641 if (!$send_notification) {
1642 $tags = q("SELECT `url` FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` = %d AND `uid` = %d",
1643 intval(TERM_OBJ_POST), intval($current_post), intval(TERM_MENTION), intval($arr['uid']));
1646 foreach ($tags AS $tag) {
1647 $r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d AND `notify_new_posts`",
1648 normalise_link($tag["url"]), intval($arr['uid']));
1650 $send_notification = true;
1655 if ($send_notification) {
1656 logger('item_store: Send notification for contact '.$arr['contact-id'].' and post '.$current_post, LOGGER_DEBUG);
1657 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1658 intval($arr['uid']));
1660 $item = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d",
1661 intval($current_post),
1667 require_once('include/enotify.php');
1669 'type' => NOTIFY_SHARE,
1670 'notify_flags' => $u[0]['notify-flags'],
1671 'language' => $u[0]['language'],
1672 'to_name' => $u[0]['username'],
1673 'to_email' => $u[0]['email'],
1674 'uid' => $u[0]['uid'],
1676 'link' => $a->get_baseurl().'/display/'.urlencode($arr['guid']),
1677 'source_name' => $item[0]['author-name'],
1678 'source_link' => $item[0]['author-link'],
1679 'source_photo' => $item[0]['author-avatar'],
1680 'verb' => ACTIVITY_TAG,
1682 'parent' => $arr['parent']
1684 logger('item_store: Notification sent for contact '.$arr['contact-id'].' and post '.$current_post, LOGGER_DEBUG);
1687 update_thread($parent_id);
1688 add_shadow_entry($arr);
1692 proc_run('php', "include/notifier.php", $notify_type, $current_post);
1694 return $current_post;
1697 function item_body_set_hashtags(&$item) {
1699 $tags = get_tags($item["body"]);
1705 // This sorting is important when there are hashtags that are part of other hashtags
1706 // Otherwise there could be problems with hashtags like #test and #test2
1711 $URLSearchString = "^\[\]";
1713 // All hashtags should point to the home server
1714 //$item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1715 // "#[url=".$a->get_baseurl()."/search?tag=$2]$2[/url]", $item["body"]);
1717 //$item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1718 // "#[url=".$a->get_baseurl()."/search?tag=$2]$2[/url]", $item["tag"]);
1720 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1721 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1723 return("[url=".str_replace("#", "#", $match[1])."]".str_replace("#", "#", $match[2])."[/url]");
1726 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1728 return("[bookmark=".str_replace("#", "#", $match[1])."]".str_replace("#", "#", $match[2])."[/bookmark]");
1731 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
1733 return("[attachment ".str_replace("#", "#", $match[1])."]".$match[2]."[/attachment]");
1736 // Repair recursive urls
1737 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1738 "#$2", $item["body"]);
1741 foreach($tags as $tag) {
1742 if(strpos($tag,'#') !== 0)
1745 if(strpos($tag,'[url='))
1748 $basetag = str_replace('_',' ',substr($tag,1));
1750 $newtag = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($basetag).']'.$basetag.'[/url]';
1752 $item["body"] = str_replace($tag, $newtag, $item["body"]);
1754 if(!stristr($item["tag"],"/search?tag=".$basetag."]".$basetag."[/url]")) {
1755 if(strlen($item["tag"]))
1756 $item["tag"] = ','.$item["tag"];
1757 $item["tag"] = $newtag.$item["tag"];
1761 // Convert back the masked hashtags
1762 $item["body"] = str_replace("#", "#", $item["body"]);
1765 function get_item_guid($id) {
1766 $r = q("SELECT `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($id));
1768 return($r[0]["guid"]);
1773 function get_item_id($guid, $uid = 0) {
1779 $uid == local_user();
1781 // Does the given user have this item?
1783 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1784 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1785 AND `item`.`guid` = '%s' AND `item`.`uid` = %d", dbesc($guid), intval($uid));
1788 $nick = $r[0]["nickname"];
1792 // Or is it anywhere on the server?
1794 $r = q("SELECT `item`.`id`, `user`.`nickname` FROM `item` INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1795 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1796 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1797 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1798 AND `item`.`private` = 0 AND `item`.`wall` = 1
1799 AND `item`.`guid` = '%s'", dbesc($guid));
1802 $nick = $r[0]["nickname"];
1805 return(array("nick" => $nick, "id" => $id));
1809 function get_item_contact($item,$contacts) {
1810 if(! count($contacts) || (! is_array($item)))
1812 foreach($contacts as $contact) {
1813 if($contact['id'] == $item['contact-id']) {
1815 break; // NOTREACHED
1822 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
1824 * @param int $item_id
1825 * @return bool true if item was deleted, else false
1827 function tag_deliver($uid,$item_id) {
1835 $u = q("select * from user where uid = %d limit 1",
1841 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1842 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1845 $i = q("select * from item where id = %d and uid = %d limit 1",
1854 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1856 // Diaspora uses their own hardwired link URL in @-tags
1857 // instead of the one we supply with webfinger
1859 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1861 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1863 foreach($matches as $mtch) {
1864 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
1866 logger('tag_deliver: mention found: ' . $mtch[2]);
1872 if ( ($community_page || $prvgroup) &&
1873 (!$item['wall']) && (!$item['origin']) && ($item['id'] == $item['parent'])){
1874 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
1876 logger("tag_deliver: no-mention top-level post to communuty or private group. delete.");
1877 q("DELETE FROM item WHERE id = %d and uid = %d",
1887 // send a notification
1889 // use a local photo if we have one
1891 $r = q("select * from contact where uid = %d and nurl = '%s' limit 1",
1892 intval($u[0]['uid']),
1893 dbesc(normalise_link($item['author-link']))
1895 $photo = (($r && count($r)) ? $r[0]['thumb'] : $item['author-avatar']);
1898 require_once('include/enotify.php');
1900 'type' => NOTIFY_TAGSELF,
1901 'notify_flags' => $u[0]['notify-flags'],
1902 'language' => $u[0]['language'],
1903 'to_name' => $u[0]['username'],
1904 'to_email' => $u[0]['email'],
1905 'uid' => $u[0]['uid'],
1907 'link' => $a->get_baseurl() . '/display/'.urlencode(get_item_guid($item['id'])),
1908 'source_name' => $item['author-name'],
1909 'source_link' => $item['author-link'],
1910 'source_photo' => $photo,
1911 'verb' => ACTIVITY_TAG,
1913 'parent' => $item['parent']
1917 $arr = array('item' => $item, 'user' => $u[0], 'contact' => $r[0]);
1919 call_hooks('tagged', $arr);
1921 if((! $community_page) && (! $prvgroup))
1925 // tgroup delivery - setup a second delivery chain
1926 // prevent delivery looping - only proceed
1927 // if the message originated elsewhere and is a top-level post
1929 if(($item['wall']) || ($item['origin']) || ($item['id'] != $item['parent']))
1932 // now change this copy of the post to a forum head message and deliver to all the tgroup members
1935 $c = q("select name, url, thumb from contact where self = 1 and uid = %d limit 1",
1936 intval($u[0]['uid'])
1941 // also reset all the privacy bits to the forum default permissions
1943 $private = ($u[0]['allow_cid'] || $u[0]['allow_gid'] || $u[0]['deny_cid'] || $u[0]['deny_gid']) ? 1 : 0;
1945 $forum_mode = (($prvgroup) ? 2 : 1);
1947 q("update item set wall = 1, origin = 1, forum_mode = %d, `owner-name` = '%s', `owner-link` = '%s', `owner-avatar` = '%s',
1948 `private` = %d, `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' where id = %d",
1949 intval($forum_mode),
1950 dbesc($c[0]['name']),
1951 dbesc($c[0]['url']),
1952 dbesc($c[0]['thumb']),
1954 dbesc($u[0]['allow_cid']),
1955 dbesc($u[0]['allow_gid']),
1956 dbesc($u[0]['deny_cid']),
1957 dbesc($u[0]['deny_gid']),
1960 update_thread($item_id);
1962 proc_run('php','include/notifier.php','tgroup',$item_id);
1968 function tgroup_check($uid,$item) {
1974 // check that the message originated elsewhere and is a top-level post
1976 if(($item['wall']) || ($item['origin']) || ($item['uri'] != $item['parent-uri']))
1980 $u = q("select * from user where uid = %d limit 1",
1986 $community_page = (($u[0]['page-flags'] == PAGE_COMMUNITY) ? true : false);
1987 $prvgroup = (($u[0]['page-flags'] == PAGE_PRVGROUP) ? true : false);
1990 $link = normalise_link($a->get_baseurl() . '/profile/' . $u[0]['nickname']);
1992 // Diaspora uses their own hardwired link URL in @-tags
1993 // instead of the one we supply with webfinger
1995 $dlink = normalise_link($a->get_baseurl() . '/u/' . $u[0]['nickname']);
1997 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism',$item['body'],$matches,PREG_SET_ORDER);
1999 foreach($matches as $mtch) {
2000 if(link_compare($link,$mtch[1]) || link_compare($dlink,$mtch[1])) {
2002 logger('tgroup_check: mention found: ' . $mtch[2]);
2010 if((! $community_page) && (! $prvgroup))
2024 function dfrn_deliver($owner,$contact,$atom, $dissolve = false) {
2028 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
2030 if($contact['duplex'] && $contact['dfrn-id'])
2031 $idtosend = '0:' . $orig_id;
2032 if($contact['duplex'] && $contact['issued-id'])
2033 $idtosend = '1:' . $orig_id;
2036 $rino = get_config('system','rino_encrypt');
2037 $rino = intval($rino);
2038 // use RINO1 if mcrypt isn't installed and RINO2 was selected
2039 if ($rino==2 and !function_exists('mcrypt_create_iv')) $rino=1;
2041 logger("Local rino version: ". $rino, LOGGER_DEBUG);
2043 $ssl_val = intval(get_config('system','ssl_policy'));
2047 case SSL_POLICY_FULL:
2048 $ssl_policy = 'full';
2050 case SSL_POLICY_SELFSIGN:
2051 $ssl_policy = 'self';
2053 case SSL_POLICY_NONE:
2055 $ssl_policy = 'none';
2059 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
2061 logger('dfrn_deliver: ' . $url);
2063 $xml = fetch_url($url);
2065 $curl_stat = $a->get_curl_code();
2067 return(-1); // timed out
2069 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
2074 if(strpos($xml,'<?xml') === false) {
2075 logger('dfrn_deliver: no valid XML returned');
2076 logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
2080 $res = parse_xml_string($xml);
2082 if((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id)))
2083 return (($res->status) ? $res->status : 3);
2085 $postvars = array();
2086 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
2087 $challenge = hex2bin((string) $res->challenge);
2088 $perm = (($res->perm) ? $res->perm : null);
2089 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
2090 $rino_remote_version = intval($res->rino);
2091 $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
2093 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
2095 if($owner['page-flags'] == PAGE_PRVGROUP)
2098 $final_dfrn_id = '';
2101 if((($perm == 'rw') && (! intval($contact['writable'])))
2102 || (($perm == 'r') && (intval($contact['writable'])))) {
2103 q("update contact set writable = %d where id = %d",
2104 intval(($perm == 'rw') ? 1 : 0),
2105 intval($contact['id'])
2107 $contact['writable'] = (string) 1 - intval($contact['writable']);
2111 if(($contact['duplex'] && strlen($contact['pubkey']))
2112 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
2113 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
2114 openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
2115 openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
2118 openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
2119 openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
2122 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
2124 if(strpos($final_dfrn_id,':') == 1)
2125 $final_dfrn_id = substr($final_dfrn_id,2);
2127 if($final_dfrn_id != $orig_id) {
2128 logger('dfrn_deliver: wrong dfrn_id.');
2129 // did not decode properly - cannot trust this site
2133 $postvars['dfrn_id'] = $idtosend;
2134 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
2136 $postvars['dissolve'] = '1';
2139 if((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
2140 $postvars['data'] = $atom;
2141 $postvars['perm'] = 'rw';
2144 $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
2145 $postvars['perm'] = 'r';
2148 $postvars['ssl_policy'] = $ssl_policy;
2151 $postvars['page'] = $page;
2154 if($rino>0 && $rino_remote_version>0 && (! $dissolve)) {
2155 logger('rino version: '. $rino_remote_version);
2157 switch($rino_remote_version) {
2159 // Deprecated rino version!
2160 $key = substr(random_string(),0,16);
2161 $data = aes_encrypt($postvars['data'],$key);
2164 // RINO 2 based on php-encryption
2166 $key = Crypto::createNewRandomKey();
2167 } catch (CryptoTestFailed $ex) {
2168 logger('Cannot safely create a key');
2170 } catch (CannotPerformOperation $ex) {
2171 logger('Cannot safely create a key');
2175 $data = Crypto::encrypt($postvars['data'], $key);
2176 } catch (CryptoTestFailed $ex) {
2177 logger('Cannot safely perform encryption');
2179 } catch (CannotPerformOperation $ex) {
2180 logger('Cannot safely perform encryption');
2185 logger("rino: invalid requested verision '$rino_remote_version'");
2189 $postvars['rino'] = $rino_remote_version;
2190 $postvars['data'] = bin2hex($data);
2192 #logger('rino: sent key = ' . $key, LOGGER_DEBUG);
2195 if($dfrn_version >= 2.1) {
2196 if(($contact['duplex'] && strlen($contact['pubkey']))
2197 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
2198 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
2200 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
2203 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
2207 if(($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
2208 openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
2211 openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
2215 logger('md5 rawkey ' . md5($postvars['key']));
2217 $postvars['key'] = bin2hex($postvars['key']);
2221 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
2223 $xml = post_url($contact['notify'],$postvars);
2225 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
2227 $curl_stat = $a->get_curl_code();
2228 if((! $curl_stat) || (! strlen($xml)))
2229 return(-1); // timed out
2231 if(($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))
2234 if(strpos($xml,'<?xml') === false) {
2235 logger('dfrn_deliver: phase 2: no valid XML returned');
2236 logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
2240 if($contact['term-date'] != '0000-00-00 00:00:00') {
2241 logger("dfrn_deliver: $url back from the dead - removing mark for death");
2242 require_once('include/Contact.php');
2243 unmark_for_death($contact);
2246 $res = parse_xml_string($xml);
2248 return $res->status;
2253 This function returns true if $update has an edited timestamp newer
2254 than $existing, i.e. $update contains new data which should override
2255 what's already there. If there is no timestamp yet, the update is
2256 assumed to be newer. If the update has no timestamp, the existing
2257 item is assumed to be up-to-date. If the timestamps are equal it
2258 assumes the update has been seen before and should be ignored.
2260 function edited_timestamp_is_newer($existing, $update) {
2261 if (!x($existing,'edited') || !$existing['edited']) {
2264 if (!x($update,'edited') || !$update['edited']) {
2267 $existing_edited = datetime_convert('UTC', 'UTC', $existing['edited']);
2268 $update_edited = datetime_convert('UTC', 'UTC', $update['edited']);
2269 return (strcmp($existing_edited, $update_edited) < 0);
2274 * consume_feed - process atom feed and update anything/everything we might need to update
2276 * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
2278 * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
2279 * It is this person's stuff that is going to be updated.
2280 * $contact = the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
2281 * from an external network and MAY create an appropriate contact record. Otherwise, we MUST
2282 * have a contact record.
2283 * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
2284 * might not) try and subscribe to it.
2285 * $datedir sorts in reverse order
2286 * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
2287 * imported prior to its children being seen in the stream unless we are certain
2288 * of how the feed is arranged/ordered.
2289 * With $pass = 1, we only pull parent items out of the stream.
2290 * With $pass = 2, we only pull children (comments/likes).
2292 * So running this twice, first with pass 1 and then with pass 2 will do the right
2293 * thing regardless of feed ordering. This won't be adequate in a fully-threaded
2294 * model where comments can have sub-threads. That would require some massive sorting
2295 * to get all the feed items into a mostly linear ordering, and might still require
2299 function consume_feed($xml,$importer,&$contact, &$hub, $datedir = 0, $pass = 0) {
2300 if ($contact['network'] === NETWORK_OSTATUS) {
2302 logger("Consume OStatus messages ", LOGGER_DEBUG);
2303 ostatus_import($xml,$importer,$contact, $hub);
2308 if ($contact['network'] === NETWORK_FEED) {
2310 logger("Consume feeds", LOGGER_DEBUG);
2311 feed_import($xml,$importer,$contact, $hub);
2316 require_once('library/simplepie/simplepie.inc');
2317 require_once('include/contact_selectors.php');
2319 if(! strlen($xml)) {
2320 logger('consume_feed: empty input');
2324 $feed = new SimplePie();
2325 $feed->set_raw_data($xml);
2327 $feed->enable_order_by_date(true);
2329 $feed->enable_order_by_date(false);
2333 logger('consume_feed: Error parsing XML: ' . $feed->error());
2335 $permalink = $feed->get_permalink();
2337 // Check at the feed level for updated contact name and/or photo
2341 $photo_timestamp = '';
2344 $contact_updated = '';
2346 $hubs = $feed->get_links('hub');
2347 logger('consume_feed: hubs: ' . print_r($hubs,true), LOGGER_DATA);
2350 $hub = implode(',', $hubs);
2352 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
2354 $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
2356 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
2357 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
2358 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
2359 $new_name = $elems['name'][0]['data'];
2361 // Manually checking for changed contact names
2362 if (($new_name != $contact['name']) AND ($new_name != "") AND ($name_updated <= $contact['name-date'])) {
2363 $name_updated = date("c");
2364 $photo_timestamp = date("c");
2367 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
2368 if ($photo_timestamp == "")
2369 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
2370 $photo_url = $elems['link'][0]['attribs']['']['href'];
2373 if((x($rawtags[0]['child'], NAMESPACE_DFRN)) && (x($rawtags[0]['child'][NAMESPACE_DFRN],'birthday'))) {
2374 $birthday = datetime_convert('UTC','UTC', $rawtags[0]['child'][NAMESPACE_DFRN]['birthday'][0]['data']);
2378 if((is_array($contact)) && ($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $contact['avatar-date'])) {
2379 logger('consume_feed: Updating photo for '.$contact['name'].' from '.$photo_url.' uid: '.$contact['uid']);
2381 $contact_updated = $photo_timestamp;
2383 require_once("include/Photo.php");
2384 $photos = import_profile_photo($photo_url,$contact['uid'],$contact['id']);
2386 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
2387 WHERE `uid` = %d AND `id` = %d AND NOT `self`",
2388 dbesc(datetime_convert()),
2392 intval($contact['uid']),
2393 intval($contact['id'])
2397 if((is_array($contact)) && ($name_updated) && (strlen($new_name)) && ($name_updated > $contact['name-date'])) {
2398 if ($name_updated > $contact_updated)
2399 $contact_updated = $name_updated;
2401 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
2402 intval($contact['uid']),
2403 intval($contact['id'])
2406 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d AND `name` != '%s' AND NOT `self`",
2407 dbesc(notags(trim($new_name))),
2408 dbesc(datetime_convert()),
2409 intval($contact['uid']),
2410 intval($contact['id']),
2411 dbesc(notags(trim($new_name)))
2414 // do our best to update the name on content items
2416 if(count($r) AND (notags(trim($new_name)) != $r[0]['name'])) {
2417 q("UPDATE `item` SET `author-name` = '%s' WHERE `author-name` = '%s' AND `author-link` = '%s' AND `uid` = %d AND `author-name` != '%s'",
2418 dbesc(notags(trim($new_name))),
2419 dbesc($r[0]['name']),
2420 dbesc($r[0]['url']),
2421 intval($contact['uid']),
2422 dbesc(notags(trim($new_name)))
2427 if ($contact_updated AND $new_name AND $photo_url)
2428 poco_check($contact['url'], $new_name, NETWORK_DFRN, $photo_url, "", "", "", "", "", $contact_updated, 2, $contact['id'], $contact['uid']);
2430 if(strlen($birthday)) {
2431 if(substr($birthday,0,4) != $contact['bdyear']) {
2432 logger('consume_feed: updating birthday: ' . $birthday);
2436 * Add new birthday event for this person
2438 * $bdtext is just a readable placeholder in case the event is shared
2439 * with others. We will replace it during presentation to our $importer
2440 * to contain a sparkle link and perhaps a photo.
2444 $bdtext = sprintf( t('%s\'s birthday'), $contact['name']);
2445 $bdtext2 = sprintf( t('Happy Birthday %s'), ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]' ) ;
2448 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
2449 VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ",
2450 intval($contact['uid']),
2451 intval($contact['id']),
2452 dbesc(datetime_convert()),
2453 dbesc(datetime_convert()),
2454 dbesc(datetime_convert('UTC','UTC', $birthday)),
2455 dbesc(datetime_convert('UTC','UTC', $birthday . ' + 1 day ')),
2464 q("UPDATE `contact` SET `bdyear` = '%s' WHERE `uid` = %d AND `id` = %d",
2465 dbesc(substr($birthday,0,4)),
2466 intval($contact['uid']),
2467 intval($contact['id'])
2470 // This function is called twice without reloading the contact
2471 // Make sure we only create one event. This is why &$contact
2472 // is a reference var in this function
2474 $contact['bdyear'] = substr($birthday,0,4);
2478 $community_page = 0;
2479 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
2481 $community_page = intval($rawtags[0]['data']);
2483 if(is_array($contact) && intval($contact['forum']) != $community_page) {
2484 q("update contact set forum = %d where id = %d",
2485 intval($community_page),
2486 intval($contact['id'])
2488 $contact['forum'] = (string) $community_page;
2492 // process any deleted entries
2494 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
2495 if(is_array($del_entries) && count($del_entries) && $pass != 2) {
2496 foreach($del_entries as $dentry) {
2498 if(isset($dentry['attribs']['']['ref'])) {
2499 $uri = $dentry['attribs']['']['ref'];
2501 if(isset($dentry['attribs']['']['when'])) {
2502 $when = $dentry['attribs']['']['when'];
2503 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
2506 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
2508 if($deleted && is_array($contact)) {
2509 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2510 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2512 intval($importer['uid']),
2513 intval($contact['id'])
2518 if(! $item['deleted'])
2519 logger('consume_feed: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
2521 if($item['object-type'] === ACTIVITY_OBJ_EVENT) {
2522 logger("Deleting event ".$item['event-id'], LOGGER_DEBUG);
2523 event_delete($item['event-id']);
2526 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2527 $xo = parse_xml_string($item['object'],false);
2528 $xt = parse_xml_string($item['target'],false);
2529 if($xt->type === ACTIVITY_OBJ_NOTE) {
2530 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
2532 intval($importer['importer_uid'])
2536 // For tags, the owner cannot remove the tag on the author's copy of the post.
2538 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
2539 $author_remove = (($item['origin'] && $item['self']) ? true : false);
2540 $author_copy = (($item['origin']) ? true : false);
2542 if($owner_remove && $author_copy)
2544 if($author_remove || $owner_remove) {
2545 $tags = explode(',',$i[0]['tag']);
2548 foreach($tags as $tag)
2549 if(trim($tag) !== trim($xo->body))
2550 $newtags[] = trim($tag);
2552 q("update item set tag = '%s' where id = %d",
2553 dbesc(implode(',',$newtags)),
2556 create_tags_from_item($i[0]['id']);
2562 if($item['uri'] == $item['parent-uri']) {
2563 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2564 `body` = '', `title` = ''
2565 WHERE `parent-uri` = '%s' AND `uid` = %d",
2567 dbesc(datetime_convert()),
2568 dbesc($item['uri']),
2569 intval($importer['uid'])
2571 create_tags_from_itemuri($item['uri'], $importer['uid']);
2572 create_files_from_itemuri($item['uri'], $importer['uid']);
2573 update_thread_uri($item['uri'], $importer['uid']);
2576 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2577 `body` = '', `title` = ''
2578 WHERE `uri` = '%s' AND `uid` = %d",
2580 dbesc(datetime_convert()),
2582 intval($importer['uid'])
2584 create_tags_from_itemuri($uri, $importer['uid']);
2585 create_files_from_itemuri($uri, $importer['uid']);
2586 if($item['last-child']) {
2587 // ensure that last-child is set in case the comment that had it just got wiped.
2588 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
2589 dbesc(datetime_convert()),
2590 dbesc($item['parent-uri']),
2591 intval($item['uid'])
2593 // who is the last child now?
2594 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2595 ORDER BY `created` DESC LIMIT 1",
2596 dbesc($item['parent-uri']),
2597 intval($importer['uid'])
2600 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2611 // Now process the feed
2613 if($feed->get_item_quantity()) {
2615 logger('consume_feed: feed item count = ' . $feed->get_item_quantity());
2617 // in inverse date order
2619 $items = array_reverse($feed->get_items());
2621 $items = $feed->get_items();
2624 foreach($items as $item) {
2627 $item_id = $item->get_id();
2628 $rawthread = $item->get_item_tags( NAMESPACE_THREAD,'in-reply-to');
2629 if(isset($rawthread[0]['attribs']['']['ref'])) {
2631 $parent_uri = $rawthread[0]['attribs']['']['ref'];
2634 if(($is_reply) && is_array($contact)) {
2639 // not allowed to post
2641 if($contact['rel'] == CONTACT_IS_FOLLOWER)
2645 // Have we seen it? If not, import it.
2647 $item_id = $item->get_id();
2648 $datarray = get_atom_elements($feed, $item, $contact);
2650 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
2651 $datarray['author-name'] = $contact['name'];
2652 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
2653 $datarray['author-link'] = $contact['url'];
2654 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
2655 $datarray['author-avatar'] = $contact['thumb'];
2657 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
2658 logger('consume_feed: no author information! ' . print_r($datarray,true));
2662 $force_parent = false;
2663 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
2664 if($contact['network'] === NETWORK_OSTATUS)
2665 $force_parent = true;
2666 if(strlen($datarray['title']))
2667 unset($datarray['title']);
2668 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2669 dbesc(datetime_convert()),
2671 intval($importer['uid'])
2673 $datarray['last-child'] = 1;
2674 update_thread_uri($parent_uri, $importer['uid']);
2678 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2680 intval($importer['uid'])
2683 // Update content if 'updated' changes
2686 if (edited_timestamp_is_newer($r[0], $datarray)) {
2688 // do not accept (ignore) an earlier edit than one we currently have.
2689 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2692 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
2693 dbesc($datarray['title']),
2694 dbesc($datarray['body']),
2695 dbesc($datarray['tag']),
2696 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2697 dbesc(datetime_convert()),
2699 intval($importer['uid'])
2701 create_tags_from_itemuri($item_id, $importer['uid']);
2702 update_thread_uri($item_id, $importer['uid']);
2705 // update last-child if it changes
2707 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2708 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
2709 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
2710 dbesc(datetime_convert()),
2712 intval($importer['uid'])
2714 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
2715 intval($allow[0]['data']),
2716 dbesc(datetime_convert()),
2718 intval($importer['uid'])
2720 update_thread_uri($item_id, $importer['uid']);
2726 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2727 // one way feed - no remote comment ability
2728 $datarray['last-child'] = 0;
2730 $datarray['parent-uri'] = $parent_uri;
2731 $datarray['uid'] = $importer['uid'];
2732 $datarray['contact-id'] = $contact['id'];
2733 if(($datarray['verb'] === ACTIVITY_LIKE)
2734 || ($datarray['verb'] === ACTIVITY_DISLIKE)
2735 || ($datarray['verb'] === ACTIVITY_ATTEND)
2736 || ($datarray['verb'] === ACTIVITY_ATTENDNO)
2737 || ($datarray['verb'] === ACTIVITY_ATTENDMAYBE)) {
2738 $datarray['type'] = 'activity';
2739 $datarray['gravity'] = GRAVITY_LIKE;
2740 // only one like or dislike per person
2741 // splitted into two queries for performance issues
2742 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s') limit 1",
2743 intval($datarray['uid']),
2744 intval($datarray['contact-id']),
2745 dbesc($datarray['verb']),
2751 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`thr-parent` = '%s') limit 1",
2752 intval($datarray['uid']),
2753 intval($datarray['contact-id']),
2754 dbesc($datarray['verb']),
2761 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
2762 $xo = parse_xml_string($datarray['object'],false);
2763 $xt = parse_xml_string($datarray['target'],false);
2765 if($xt->type == ACTIVITY_OBJ_NOTE) {
2766 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
2768 intval($importer['importer_uid'])
2773 // extract tag, if not duplicate, add to parent item
2774 if($xo->id && $xo->content) {
2775 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2776 if(! (stristr($r[0]['tag'],$newtag))) {
2777 q("UPDATE item SET tag = '%s' WHERE id = %d",
2778 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . $newtag),
2781 create_tags_from_item($r[0]['id']);
2787 $r = item_store($datarray,$force_parent);
2793 // Head post of a conversation. Have we seen it? If not, import it.
2795 $item_id = $item->get_id();
2797 $datarray = get_atom_elements($feed, $item, $contact);
2799 if(is_array($contact)) {
2800 if((! x($datarray,'author-name')) && ($contact['network'] != NETWORK_DFRN))
2801 $datarray['author-name'] = $contact['name'];
2802 if((! x($datarray,'author-link')) && ($contact['network'] != NETWORK_DFRN))
2803 $datarray['author-link'] = $contact['url'];
2804 if((! x($datarray,'author-avatar')) && ($contact['network'] != NETWORK_DFRN))
2805 $datarray['author-avatar'] = $contact['thumb'];
2808 if((! x($datarray,'author-name')) || (! x($datarray,'author-link'))) {
2809 logger('consume_feed: no author information! ' . print_r($datarray,true));
2813 // special handling for events
2815 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
2816 $ev = bbtoevent($datarray['body']);
2817 if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
2818 $ev['uid'] = $importer['uid'];
2819 $ev['uri'] = $item_id;
2820 $ev['edited'] = $datarray['edited'];
2821 $ev['private'] = $datarray['private'];
2822 $ev['guid'] = $datarray['guid'];
2824 if(is_array($contact))
2825 $ev['cid'] = $contact['id'];
2826 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2828 intval($importer['uid'])
2831 $ev['id'] = $r[0]['id'];
2832 $xyz = event_store($ev);
2837 if($contact['network'] === NETWORK_OSTATUS || stristr($contact['url'],'twitter.com')) {
2838 if(strlen($datarray['title']))
2839 unset($datarray['title']);
2840 $datarray['last-child'] = 1;
2844 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2846 intval($importer['uid'])
2849 // Update content if 'updated' changes
2852 if (edited_timestamp_is_newer($r[0], $datarray)) {
2854 // do not accept (ignore) an earlier edit than one we currently have.
2855 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
2858 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
2859 dbesc($datarray['title']),
2860 dbesc($datarray['body']),
2861 dbesc($datarray['tag']),
2862 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
2863 dbesc(datetime_convert()),
2865 intval($importer['uid'])
2867 create_tags_from_itemuri($item_id, $importer['uid']);
2868 update_thread_uri($item_id, $importer['uid']);
2871 // update last-child if it changes
2873 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
2874 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
2875 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
2876 intval($allow[0]['data']),
2877 dbesc(datetime_convert()),
2879 intval($importer['uid'])
2881 update_thread_uri($item_id, $importer['uid']);
2886 if(activity_match($datarray['verb'],ACTIVITY_FOLLOW)) {
2887 logger('consume-feed: New follower');
2888 new_follower($importer,$contact,$datarray,$item);
2891 if(activity_match($datarray['verb'],ACTIVITY_UNFOLLOW)) {
2892 lose_follower($importer,$contact,$datarray,$item);
2896 if(activity_match($datarray['verb'],ACTIVITY_REQ_FRIEND)) {
2897 logger('consume-feed: New friend request');
2898 new_follower($importer,$contact,$datarray,$item,true);
2901 if(activity_match($datarray['verb'],ACTIVITY_UNFRIEND)) {
2902 lose_sharer($importer,$contact,$datarray,$item);
2907 if(! is_array($contact))
2911 if(($contact['network'] === NETWORK_FEED) || (! strlen($contact['notify']))) {
2912 // one way feed - no remote comment ability
2913 $datarray['last-child'] = 0;
2915 if($contact['network'] === NETWORK_FEED)
2916 $datarray['private'] = 2;
2918 $datarray['parent-uri'] = $item_id;
2919 $datarray['uid'] = $importer['uid'];
2920 $datarray['contact-id'] = $contact['id'];
2922 if(! link_compare($datarray['owner-link'],$contact['url'])) {
2923 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2924 // but otherwise there's a possible data mixup on the sender's system.
2925 // the tgroup delivery code called from item_store will correct it if it's a forum,
2926 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2927 logger('consume_feed: Correcting item owner.', LOGGER_DEBUG);
2928 $datarray['owner-name'] = $contact['name'];
2929 $datarray['owner-link'] = $contact['url'];
2930 $datarray['owner-avatar'] = $contact['thumb'];
2933 // We've allowed "followers" to reach this point so we can decide if they are
2934 // posting an @-tag delivery, which followers are allowed to do for certain
2935 // page types. Now that we've parsed the post, let's check if it is legit. Otherwise ignore it.
2937 if(($contact['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['uid'],$datarray)))
2940 // This is my contact on another system, but it's really me.
2941 // Turn this into a wall post.
2942 $notify = item_is_remote_self($contact, $datarray);
2944 $r = item_store($datarray, false, $notify);
2945 logger('Stored - Contact '.$contact['url'].' Notify '.$notify.' return '.$r.' Item '.print_r($datarray, true), LOGGER_DEBUG);
2953 function item_is_remote_self($contact, &$datarray) {
2956 if (!$contact['remote_self'])
2959 // Prevent the forwarding of posts that are forwarded
2960 if ($datarray["extid"] == NETWORK_DFRN)
2963 // Prevent to forward already forwarded posts
2964 if ($datarray["app"] == $a->get_hostname())
2967 // Only forward posts
2968 if ($datarray["verb"] != ACTIVITY_POST)
2971 if (($contact['network'] != NETWORK_FEED) AND $datarray['private'])
2974 $datarray2 = $datarray;
2975 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2976 if ($contact['remote_self'] == 2) {
2977 $r = q("SELECT `id`,`url`,`name`,`thumb` FROM `contact` WHERE `uid` = %d AND `self`",
2978 intval($contact['uid']));
2980 $datarray['contact-id'] = $r[0]["id"];
2982 $datarray['owner-name'] = $r[0]["name"];
2983 $datarray['owner-link'] = $r[0]["url"];
2984 $datarray['owner-avatar'] = $r[0]["thumb"];
2986 $datarray['author-name'] = $datarray['owner-name'];
2987 $datarray['author-link'] = $datarray['owner-link'];
2988 $datarray['author-avatar'] = $datarray['owner-avatar'];
2991 if ($contact['network'] != NETWORK_FEED) {
2992 $datarray["guid"] = get_guid(32);
2993 unset($datarray["plink"]);
2994 $datarray["uri"] = item_new_uri($a->get_hostname(),$contact['uid'], $datarray["guid"]);
2995 $datarray["parent-uri"] = $datarray["uri"];
2996 $datarray["extid"] = $contact['network'];
2997 $urlpart = parse_url($datarray2['author-link']);
2998 $datarray["app"] = $urlpart["host"];
3000 $datarray['private'] = 0;
3003 if ($contact['network'] != NETWORK_FEED) {
3004 // Store the original post
3005 $r = item_store($datarray2, false, false);
3006 logger('remote-self post original item - Contact '.$contact['url'].' return '.$r.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
3008 $datarray["app"] = "Feed";
3013 function local_delivery($importer,$data) {
3016 logger(__function__, LOGGER_TRACE);
3018 if($importer['readonly']) {
3019 // We aren't receiving stuff from this person. But we will quietly ignore them
3020 // rather than a blatant "go away" message.
3021 logger('local_delivery: ignoring');
3026 // Consume notification feed. This may differ from consuming a public feed in several ways
3027 // - might contain email or friend suggestions
3028 // - might contain remote followup to our message
3029 // - in which case we need to accept it and then notify other conversants
3030 // - we may need to send various email notifications
3032 $feed = new SimplePie();
3033 $feed->set_raw_data($data);
3034 $feed->enable_order_by_date(false);
3039 logger('local_delivery: Error parsing XML: ' . $feed->error());
3042 // Check at the feed level for updated contact name and/or photo
3046 $photo_timestamp = '';
3048 $contact_updated = '';
3051 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'owner');
3053 // Fallback should not be needed here. If it isn't DFRN it won't have DFRN updated tags
3055 // $rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
3058 $elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
3059 if($elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated']) {
3060 $name_updated = $elems['name'][0]['attribs'][NAMESPACE_DFRN]['updated'];
3061 $new_name = $elems['name'][0]['data'];
3063 // Manually checking for changed contact names
3064 if (($new_name != $importer['name']) AND ($new_name != "") AND ($name_updated <= $importer['name-date'])) {
3065 $name_updated = date("c");
3066 $photo_timestamp = date("c");
3069 if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo') && ($elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated'])) {
3070 if ($photo_timestamp == "")
3071 $photo_timestamp = datetime_convert('UTC','UTC',$elems['link'][0]['attribs'][NAMESPACE_DFRN]['updated']);
3072 $photo_url = $elems['link'][0]['attribs']['']['href'];
3076 if(($photo_timestamp) && (strlen($photo_url)) && ($photo_timestamp > $importer['avatar-date'])) {
3078 $contact_updated = $photo_timestamp;
3080 logger('local_delivery: Updating photo for ' . $importer['name']);
3081 require_once("include/Photo.php");
3083 $photos = import_profile_photo($photo_url,$importer['importer_uid'],$importer['id']);
3085 q("UPDATE `contact` SET `avatar-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s'
3086 WHERE `uid` = %d AND `id` = %d AND NOT `self`",
3087 dbesc(datetime_convert()),
3091 intval($importer['importer_uid']),
3092 intval($importer['id'])
3096 if(($name_updated) && (strlen($new_name)) && ($name_updated > $importer['name-date'])) {
3097 if ($name_updated > $contact_updated)
3098 $contact_updated = $name_updated;
3100 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `id` = %d LIMIT 1",
3101 intval($importer['importer_uid']),
3102 intval($importer['id'])
3105 $x = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s' WHERE `uid` = %d AND `id` = %d AND `name` != '%s' AND NOT `self`",
3106 dbesc(notags(trim($new_name))),
3107 dbesc(datetime_convert()),
3108 intval($importer['importer_uid']),
3109 intval($importer['id']),
3110 dbesc(notags(trim($new_name)))
3113 // do our best to update the name on content items
3115 if(count($r) AND (notags(trim($new_name)) != $r[0]['name'])) {
3116 q("UPDATE `item` SET `author-name` = '%s' WHERE `author-name` = '%s' AND `author-link` = '%s' AND `uid` = %d AND `author-name` != '%s'",
3117 dbesc(notags(trim($new_name))),
3118 dbesc($r[0]['name']),
3119 dbesc($r[0]['url']),
3120 intval($importer['importer_uid']),
3121 dbesc(notags(trim($new_name)))
3126 if ($contact_updated AND $new_name AND $photo_url)
3127 poco_check($importer['url'], $new_name, NETWORK_DFRN, $photo_url, "", "", "", "", "", $contact_updated, 2, $importer['id'], $importer['importer_uid']);
3129 // Currently unsupported - needs a lot of work
3130 $reloc = $feed->get_feed_tags( NAMESPACE_DFRN, 'relocate' );
3131 if(isset($reloc[0]['child'][NAMESPACE_DFRN])) {
3132 $base = $reloc[0]['child'][NAMESPACE_DFRN];
3134 $newloc['uid'] = $importer['importer_uid'];
3135 $newloc['cid'] = $importer['id'];
3136 $newloc['name'] = notags(unxmlify($base['name'][0]['data']));
3137 $newloc['photo'] = notags(unxmlify($base['photo'][0]['data']));
3138 $newloc['thumb'] = notags(unxmlify($base['thumb'][0]['data']));
3139 $newloc['micro'] = notags(unxmlify($base['micro'][0]['data']));
3140 $newloc['url'] = notags(unxmlify($base['url'][0]['data']));
3141 $newloc['request'] = notags(unxmlify($base['request'][0]['data']));
3142 $newloc['confirm'] = notags(unxmlify($base['confirm'][0]['data']));
3143 $newloc['notify'] = notags(unxmlify($base['notify'][0]['data']));
3144 $newloc['poll'] = notags(unxmlify($base['poll'][0]['data']));
3145 $newloc['sitepubkey'] = notags(unxmlify($base['sitepubkey'][0]['data']));
3146 /** relocated user must have original key pair */
3147 /*$newloc['pubkey'] = notags(unxmlify($base['pubkey'][0]['data']));
3148 $newloc['prvkey'] = notags(unxmlify($base['prvkey'][0]['data']));*/
3150 logger("items:relocate contact ".print_r($newloc, true).print_r($importer, true), LOGGER_DEBUG);
3153 $r = q("SELECT photo, url FROM contact WHERE id=%d AND uid=%d;",
3154 intval($importer['id']),
3155 intval($importer['importer_uid']));
3160 $x = q("UPDATE contact SET
3171 `site-pubkey` = '%s'
3172 WHERE id=%d AND uid=%d;",
3173 dbesc($newloc['name']),
3174 dbesc($newloc['photo']),
3175 dbesc($newloc['thumb']),
3176 dbesc($newloc['micro']),
3177 dbesc($newloc['url']),
3178 dbesc(normalise_link($newloc['url'])),
3179 dbesc($newloc['request']),
3180 dbesc($newloc['confirm']),
3181 dbesc($newloc['notify']),
3182 dbesc($newloc['poll']),
3183 dbesc($newloc['sitepubkey']),
3184 intval($importer['id']),
3185 intval($importer['importer_uid']));
3191 'owner-link' => array($old['url'], $newloc['url']),
3192 'author-link' => array($old['url'], $newloc['url']),
3193 'owner-avatar' => array($old['photo'], $newloc['photo']),
3194 'author-avatar' => array($old['photo'], $newloc['photo']),
3196 foreach ($fields as $n=>$f){
3197 $x = q("UPDATE `item` SET `%s`='%s' WHERE `%s`='%s' AND uid=%d",
3200 intval($importer['importer_uid']));
3206 // merge with current record, current contents have priority
3207 // update record, set url-updated
3208 // update profile photos
3214 // handle friend suggestion notification
3216 $sugg = $feed->get_feed_tags( NAMESPACE_DFRN, 'suggest' );
3217 if(isset($sugg[0]['child'][NAMESPACE_DFRN])) {
3218 $base = $sugg[0]['child'][NAMESPACE_DFRN];
3220 $fsugg['uid'] = $importer['importer_uid'];
3221 $fsugg['cid'] = $importer['id'];
3222 $fsugg['name'] = notags(unxmlify($base['name'][0]['data']));
3223 $fsugg['photo'] = notags(unxmlify($base['photo'][0]['data']));
3224 $fsugg['url'] = notags(unxmlify($base['url'][0]['data']));
3225 $fsugg['request'] = notags(unxmlify($base['request'][0]['data']));
3226 $fsugg['body'] = escape_tags(unxmlify($base['note'][0]['data']));
3228 // Does our member already have a friend matching this description?
3230 $r = q("SELECT * FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
3231 dbesc($fsugg['name']),
3232 dbesc(normalise_link($fsugg['url'])),
3233 intval($fsugg['uid'])
3238 // Do we already have an fcontact record for this person?
3241 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
3242 dbesc($fsugg['url']),
3243 dbesc($fsugg['name']),
3244 dbesc($fsugg['request'])
3249 // OK, we do. Do we already have an introduction for this person ?
3250 $r = q("select id from intro where uid = %d and fid = %d limit 1",
3251 intval($fsugg['uid']),
3258 $r = q("INSERT INTO `fcontact` ( `name`,`url`,`photo`,`request` ) VALUES ( '%s', '%s', '%s', '%s' ) ",
3259 dbesc($fsugg['name']),
3260 dbesc($fsugg['url']),
3261 dbesc($fsugg['photo']),
3262 dbesc($fsugg['request'])
3264 $r = q("SELECT * FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
3265 dbesc($fsugg['url']),
3266 dbesc($fsugg['name']),
3267 dbesc($fsugg['request'])
3272 // database record did not get created. Quietly give up.
3277 $hash = random_string();
3279 $r = q("INSERT INTO `intro` ( `uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked` )
3280 VALUES( %d, %d, %d, '%s', '%s', '%s', %d )",
3281 intval($fsugg['uid']),
3283 intval($fsugg['cid']),
3284 dbesc($fsugg['body']),
3286 dbesc(datetime_convert()),
3291 'type' => NOTIFY_SUGGEST,
3292 'notify_flags' => $importer['notify-flags'],
3293 'language' => $importer['language'],
3294 'to_name' => $importer['username'],
3295 'to_email' => $importer['email'],
3296 'uid' => $importer['importer_uid'],
3298 'link' => $a->get_baseurl() . '/notifications/intros',
3299 'source_name' => $importer['name'],
3300 'source_link' => $importer['url'],
3301 'source_photo' => $importer['photo'],
3302 'verb' => ACTIVITY_REQ_FRIEND,
3311 $rawmail = $feed->get_feed_tags( NAMESPACE_DFRN, 'mail' );
3312 if(isset($rawmail[0]['child'][NAMESPACE_DFRN])) {
3314 logger('local_delivery: private message received');
3317 $base = $rawmail[0]['child'][NAMESPACE_DFRN];
3320 $msg['uid'] = $importer['importer_uid'];
3321 $msg['from-name'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['name'][0]['data']));
3322 $msg['from-photo'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['avatar'][0]['data']));
3323 $msg['from-url'] = notags(unxmlify($base['sender'][0]['child'][NAMESPACE_DFRN]['uri'][0]['data']));
3324 $msg['contact-id'] = $importer['id'];
3325 $msg['title'] = notags(unxmlify($base['subject'][0]['data']));
3326 $msg['body'] = escape_tags(unxmlify($base['content'][0]['data']));
3328 $msg['replied'] = 0;
3329 $msg['uri'] = notags(unxmlify($base['id'][0]['data']));
3330 $msg['parent-uri'] = notags(unxmlify($base['in-reply-to'][0]['data']));
3331 $msg['created'] = datetime_convert(notags(unxmlify('UTC','UTC',$base['sentdate'][0]['data'])));
3335 $r = dbq("INSERT INTO `mail` (`" . implode("`, `", array_keys($msg))
3336 . "`) VALUES ('" . implode("', '", array_values($msg)) . "')" );
3338 // send notifications.
3340 require_once('include/enotify.php');
3342 $notif_params = array(
3343 'type' => NOTIFY_MAIL,
3344 'notify_flags' => $importer['notify-flags'],
3345 'language' => $importer['language'],
3346 'to_name' => $importer['username'],
3347 'to_email' => $importer['email'],
3348 'uid' => $importer['importer_uid'],
3350 'source_name' => $msg['from-name'],
3351 'source_link' => $importer['url'],
3352 'source_photo' => $importer['thumb'],
3353 'verb' => ACTIVITY_POST,
3357 notification($notif_params);
3363 $community_page = 0;
3364 $rawtags = $feed->get_feed_tags( NAMESPACE_DFRN, 'community');
3366 $community_page = intval($rawtags[0]['data']);
3368 if(intval($importer['forum']) != $community_page) {
3369 q("update contact set forum = %d where id = %d",
3370 intval($community_page),
3371 intval($importer['id'])
3373 $importer['forum'] = (string) $community_page;
3376 logger('local_delivery: feed item count = ' . $feed->get_item_quantity());
3378 // process any deleted entries
3380 $del_entries = $feed->get_feed_tags(NAMESPACE_TOMB, 'deleted-entry');
3381 if(is_array($del_entries) && count($del_entries)) {
3382 foreach($del_entries as $dentry) {
3384 if(isset($dentry['attribs']['']['ref'])) {
3385 $uri = $dentry['attribs']['']['ref'];
3387 if(isset($dentry['attribs']['']['when'])) {
3388 $when = $dentry['attribs']['']['when'];
3389 $when = datetime_convert('UTC','UTC', $when, 'Y-m-d H:i:s');
3392 $when = datetime_convert('UTC','UTC','now','Y-m-d H:i:s');
3396 // check for relayed deletes to our conversation
3399 $r = q("select * from item where uri = '%s' and uid = %d limit 1",
3401 intval($importer['importer_uid'])
3404 $parent_uri = $r[0]['parent-uri'];
3405 if($r[0]['id'] != $r[0]['parent'])
3412 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
3415 logger('local_delivery: possible community delete');
3418 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
3420 // was the top-level post for this reply written by somebody on this site?
3421 // Specifically, the recipient?
3423 $is_a_remote_delete = false;
3425 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
3426 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
3427 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
3428 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
3429 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
3430 AND `item`.`uid` = %d
3436 intval($importer['importer_uid'])
3439 $is_a_remote_delete = true;
3441 // Does this have the characteristics of a community or private group comment?
3442 // If it's a reply to a wall post on a community/prvgroup page it's a
3443 // valid community comment. Also forum_mode makes it valid for sure.
3444 // If neither, it's not.
3446 if($is_a_remote_delete && $community) {
3447 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
3448 $is_a_remote_delete = false;
3449 logger('local_delivery: not a community delete');
3453 if($is_a_remote_delete) {
3454 logger('local_delivery: received remote delete');
3458 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN contact on `item`.`contact-id` = `contact`.`id`
3459 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
3461 intval($importer['importer_uid']),
3462 intval($importer['id'])
3468 if($item['deleted'])
3471 logger('local_delivery: deleting item ' . $item['id'] . ' uri=' . $item['uri'], LOGGER_DEBUG);
3473 if($item['object-type'] === ACTIVITY_OBJ_EVENT) {
3474 logger("Deleting event ".$item['event-id'], LOGGER_DEBUG);
3475 event_delete($item['event-id']);
3478 if(($item['verb'] === ACTIVITY_TAG) && ($item['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
3479 $xo = parse_xml_string($item['object'],false);
3480 $xt = parse_xml_string($item['target'],false);
3482 if($xt->type === ACTIVITY_OBJ_NOTE) {
3483 $i = q("select * from `item` where uri = '%s' and uid = %d limit 1",
3485 intval($importer['importer_uid'])
3489 // For tags, the owner cannot remove the tag on the author's copy of the post.
3491 $owner_remove = (($item['contact-id'] == $i[0]['contact-id']) ? true: false);
3492 $author_remove = (($item['origin'] && $item['self']) ? true : false);
3493 $author_copy = (($item['origin']) ? true : false);
3495 if($owner_remove && $author_copy)
3497 if($author_remove || $owner_remove) {
3498 $tags = explode(',',$i[0]['tag']);
3501 foreach($tags as $tag)
3502 if(trim($tag) !== trim($xo->body))
3503 $newtags[] = trim($tag);
3505 q("update item set tag = '%s' where id = %d",
3506 dbesc(implode(',',$newtags)),
3509 create_tags_from_item($i[0]['id']);
3515 if($item['uri'] == $item['parent-uri']) {
3516 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
3517 `body` = '', `title` = ''
3518 WHERE `parent-uri` = '%s' AND `uid` = %d",
3520 dbesc(datetime_convert()),
3521 dbesc($item['uri']),
3522 intval($importer['importer_uid'])
3524 create_tags_from_itemuri($item['uri'], $importer['importer_uid']);
3525 create_files_from_itemuri($item['uri'], $importer['importer_uid']);
3526 update_thread_uri($item['uri'], $importer['importer_uid']);
3529 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
3530 `body` = '', `title` = ''
3531 WHERE `uri` = '%s' AND `uid` = %d",
3533 dbesc(datetime_convert()),
3535 intval($importer['importer_uid'])
3537 create_tags_from_itemuri($uri, $importer['importer_uid']);
3538 create_files_from_itemuri($uri, $importer['importer_uid']);
3539 update_thread_uri($uri, $importer['importer_uid']);
3540 if($item['last-child']) {
3541 // ensure that last-child is set in case the comment that had it just got wiped.
3542 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
3543 dbesc(datetime_convert()),
3544 dbesc($item['parent-uri']),
3545 intval($item['uid'])
3547 // who is the last child now?
3548 $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `uid` = %d
3549 ORDER BY `created` DESC LIMIT 1",
3550 dbesc($item['parent-uri']),
3551 intval($importer['importer_uid'])
3554 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
3559 // if this is a relayed delete, propagate it to other recipients
3561 if($is_a_remote_delete)
3562 proc_run('php',"include/notifier.php","drop",$item['id']);
3570 foreach($feed->get_items() as $item) {
3573 $item_id = $item->get_id();
3574 $rawthread = $item->get_item_tags( NAMESPACE_THREAD, 'in-reply-to');
3575 if(isset($rawthread[0]['attribs']['']['ref'])) {
3577 $parent_uri = $rawthread[0]['attribs']['']['ref'];
3583 if($importer['page-flags'] == PAGE_COMMUNITY || $importer['page-flags'] == PAGE_PRVGROUP ) {
3586 logger('local_delivery: possible community reply');
3589 $sql_extra = " and contact.self = 1 and item.wall = 1 ";
3591 // was the top-level post for this reply written by somebody on this site?
3592 // Specifically, the recipient?
3594 $is_a_remote_comment = false;
3595 $top_uri = $parent_uri;
3597 $r = q("select `item`.`parent-uri` from `item`
3598 WHERE `item`.`uri` = '%s'
3602 if($r && count($r)) {
3603 $top_uri = $r[0]['parent-uri'];
3605 // POSSIBLE CLEANUP --> Why select so many fields when only forum_mode and wall are used?
3606 $r = q("select `item`.`id`, `item`.`uri`, `item`.`tag`, `item`.`forum_mode`,`item`.`origin`,`item`.`wall`,
3607 `contact`.`name`, `contact`.`url`, `contact`.`thumb` from `item`
3608 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
3609 WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' or `item`.`thr-parent` = '%s')
3610 AND `item`.`uid` = %d
3616 intval($importer['importer_uid'])
3619 $is_a_remote_comment = true;
3622 // Does this have the characteristics of a community or private group comment?
3623 // If it's a reply to a wall post on a community/prvgroup page it's a
3624 // valid community comment. Also forum_mode makes it valid for sure.
3625 // If neither, it's not.
3627 if($is_a_remote_comment && $community) {
3628 if((! $r[0]['forum_mode']) && (! $r[0]['wall'])) {
3629 $is_a_remote_comment = false;
3630 logger('local_delivery: not a community reply');
3634 if($is_a_remote_comment) {
3635 logger('local_delivery: received remote comment');
3637 // remote reply to our post. Import and then notify everybody else.
3639 $datarray = get_atom_elements($feed, $item);
3641 $r = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3643 intval($importer['importer_uid'])
3646 // Update content if 'updated' changes
3650 if (edited_timestamp_is_newer($r[0], $datarray)) {
3652 // do not accept (ignore) an earlier edit than one we currently have.
3653 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3656 logger('received updated comment' , LOGGER_DEBUG);
3657 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
3658 dbesc($datarray['title']),
3659 dbesc($datarray['body']),
3660 dbesc($datarray['tag']),
3661 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3662 dbesc(datetime_convert()),
3664 intval($importer['importer_uid'])
3666 create_tags_from_itemuri($item_id, $importer['importer_uid']);
3668 proc_run('php',"include/notifier.php","comment-import",$iid);
3677 $own = q("select name,url,thumb from contact where uid = %d and self = 1 limit 1",
3678 intval($importer['importer_uid'])
3682 $datarray['type'] = 'remote-comment';
3683 $datarray['wall'] = 1;
3684 $datarray['parent-uri'] = $parent_uri;
3685 $datarray['uid'] = $importer['importer_uid'];
3686 $datarray['owner-name'] = $own[0]['name'];
3687 $datarray['owner-link'] = $own[0]['url'];
3688 $datarray['owner-avatar'] = $own[0]['thumb'];
3689 $datarray['contact-id'] = $importer['id'];
3691 if(($datarray['verb'] === ACTIVITY_LIKE)
3692 || ($datarray['verb'] === ACTIVITY_DISLIKE)
3693 || ($datarray['verb'] === ACTIVITY_ATTEND)
3694 || ($datarray['verb'] === ACTIVITY_ATTENDNO)
3695 || ($datarray['verb'] === ACTIVITY_ATTENDMAYBE)) {
3697 $datarray['type'] = 'activity';
3698 $datarray['gravity'] = GRAVITY_LIKE;
3699 $datarray['last-child'] = 0;
3700 // only one like or dislike per person
3701 // splitted into two queries for performance issues
3702 $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`parent-uri` = '%s') and deleted = 0 limit 1",
3703 intval($datarray['uid']),
3704 intval($datarray['contact-id']),
3705 dbesc($datarray['verb']),
3706 dbesc($datarray['parent-uri'])
3712 $r = q("select id from item where uid = %d and `contact-id` = %d and verb = '%s' and (`thr-parent` = '%s') and deleted = 0 limit 1",
3713 intval($datarray['uid']),
3714 intval($datarray['contact-id']),
3715 dbesc($datarray['verb']),
3716 dbesc($datarray['parent-uri'])
3723 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
3725 $xo = parse_xml_string($datarray['object'],false);
3726 $xt = parse_xml_string($datarray['target'],false);
3728 if(($xt->type == ACTIVITY_OBJ_NOTE) && ($xt->id)) {
3730 // fetch the parent item
3732 $tagp = q("select * from item where uri = '%s' and uid = %d limit 1",
3734 intval($importer['importer_uid'])
3739 // extract tag, if not duplicate, and this user allows tags, add to parent item
3741 if($xo->id && $xo->content) {
3742 $newtag = '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
3743 if(! (stristr($tagp[0]['tag'],$newtag))) {
3744 $i = q("SELECT `blocktags` FROM `user` where `uid` = %d LIMIT 1",
3745 intval($importer['importer_uid'])
3747 if(count($i) && ! intval($i[0]['blocktags'])) {
3748 q("UPDATE item SET tag = '%s', `edited` = '%s', `changed` = '%s' WHERE id = %d",
3749 dbesc($tagp[0]['tag'] . (strlen($tagp[0]['tag']) ? ',' : '') . $newtag),
3750 intval($tagp[0]['id']),
3751 dbesc(datetime_convert()),
3752 dbesc(datetime_convert())
3754 create_tags_from_item($tagp[0]['id']);
3762 $posted_id = item_store($datarray);
3767 $datarray["id"] = $posted_id;
3769 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3771 intval($importer['importer_uid'])
3774 $parent = $r[0]['parent'];
3775 $parent_uri = $r[0]['parent-uri'];
3779 $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
3780 dbesc(datetime_convert()),
3781 intval($importer['importer_uid']),
3782 intval($r[0]['parent'])
3785 $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
3786 dbesc(datetime_convert()),
3787 intval($importer['importer_uid']),
3792 if($posted_id && $parent) {
3794 proc_run('php',"include/notifier.php","comment-import","$posted_id");
3796 if((! $is_like) && (! $importer['self'])) {
3798 require_once('include/enotify.php');
3801 'type' => NOTIFY_COMMENT,
3802 'notify_flags' => $importer['notify-flags'],
3803 'language' => $importer['language'],
3804 'to_name' => $importer['username'],
3805 'to_email' => $importer['email'],
3806 'uid' => $importer['importer_uid'],
3807 'item' => $datarray,
3808 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($posted_id)),
3809 'source_name' => stripslashes($datarray['author-name']),
3810 'source_link' => $datarray['author-link'],
3811 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3812 ? $importer['thumb'] : $datarray['author-avatar']),
3813 'verb' => ACTIVITY_POST,
3815 'parent' => $parent,
3816 'parent_uri' => $parent_uri,
3828 // regular comment that is part of this total conversation. Have we seen it? If not, import it.
3830 $item_id = $item->get_id();
3831 $datarray = get_atom_elements($feed,$item);
3833 if($importer['rel'] == CONTACT_IS_FOLLOWER)
3836 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
3838 intval($importer['importer_uid'])
3841 // Update content if 'updated' changes
3844 if (edited_timestamp_is_newer($r[0], $datarray)) {
3846 // do not accept (ignore) an earlier edit than one we currently have.
3847 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
3850 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
3851 dbesc($datarray['title']),
3852 dbesc($datarray['body']),
3853 dbesc($datarray['tag']),
3854 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
3855 dbesc(datetime_convert()),
3857 intval($importer['importer_uid'])
3859 create_tags_from_itemuri($item_id, $importer['importer_uid']);
3862 // update last-child if it changes
3864 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
3865 if(($allow) && ($allow[0]['data'] != $r[0]['last-child'])) {
3866 $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d",
3867 dbesc(datetime_convert()),
3869 intval($importer['importer_uid'])
3871 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
3872 intval($allow[0]['data']),
3873 dbesc(datetime_convert()),
3875 intval($importer['importer_uid'])
3881 $datarray['parent-uri'] = $parent_uri;
3882 $datarray['uid'] = $importer['importer_uid'];
3883 $datarray['contact-id'] = $importer['id'];
3884 if(($datarray['verb'] === ACTIVITY_LIKE)
3885 || ($datarray['verb'] === ACTIVITY_DISLIKE)
3886 || ($datarray['verb'] === ACTIVITY_ATTEND)
3887 || ($datarray['verb'] === ACTIVITY_ATTENDNO)
3888 || ($datarray['verb'] === ACTIVITY_ATTENDMAYBE)) {
3889 $datarray['type'] = 'activity';
3890 $datarray['gravity'] = GRAVITY_LIKE;
3891 // only one like or dislike per person
3892 // splitted into two queries for performance issues
3893 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`parent-uri` = '%s') limit 1",
3894 intval($datarray['uid']),
3895 intval($datarray['contact-id']),
3896 dbesc($datarray['verb']),
3902 $r = q("select id from item where uid = %d and `contact-id` = %d and verb ='%s' and deleted = 0 and (`thr-parent` = '%s') limit 1",
3903 intval($datarray['uid']),
3904 intval($datarray['contact-id']),
3905 dbesc($datarray['verb']),
3913 if(($datarray['verb'] === ACTIVITY_TAG) && ($datarray['object-type'] === ACTIVITY_OBJ_TAGTERM)) {
3915 $xo = parse_xml_string($datarray['object'],false);
3916 $xt = parse_xml_string($datarray['target'],false);
3918 if($xt->type == ACTIVITY_OBJ_NOTE) {
3919 $r = q("select * from item where `uri` = '%s' AND `uid` = %d limit 1",
3921 intval($importer['importer_uid'])
3926 // extract tag, if not duplicate, add to parent item
3928 if(! (stristr($r[0]['tag'],trim($xo->content)))) {
3929 q("UPDATE item SET tag = '%s' WHERE id = %d",
3930 dbesc($r[0]['tag'] . (strlen($r[0]['tag']) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
3933 create_tags_from_item($r[0]['id']);
3939 $posted_id = item_store($datarray);
3941 // find out if our user is involved in this conversation and wants to be notified.
3943 if(!x($datarray['type']) || $datarray['type'] != 'activity') {
3945 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
3947 intval($importer['importer_uid'])
3950 if(count($myconv)) {
3951 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
3953 // first make sure this isn't our own post coming back to us from a wall-to-wall event
3954 if(! link_compare($datarray['author-link'],$importer_url)) {
3957 foreach($myconv as $conv) {
3959 // now if we find a match, it means we're in this conversation
3961 if(! link_compare($conv['author-link'],$importer_url))
3964 require_once('include/enotify.php');
3966 $conv_parent = $conv['parent'];
3969 'type' => NOTIFY_COMMENT,
3970 'notify_flags' => $importer['notify-flags'],
3971 'language' => $importer['language'],
3972 'to_name' => $importer['username'],
3973 'to_email' => $importer['email'],
3974 'uid' => $importer['importer_uid'],
3975 'item' => $datarray,
3976 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($posted_id)),
3977 'source_name' => stripslashes($datarray['author-name']),
3978 'source_link' => $datarray['author-link'],
3979 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
3980 ? $importer['thumb'] : $datarray['author-avatar']),
3981 'verb' => ACTIVITY_POST,
3983 'parent' => $conv_parent,
3984 'parent_uri' => $parent_uri
3988 // only send one notification
4000 // Head post of a conversation. Have we seen it? If not, import it.
4003 $item_id = $item->get_id();
4004 $datarray = get_atom_elements($feed,$item);
4006 if((x($datarray,'object-type')) && ($datarray['object-type'] === ACTIVITY_OBJ_EVENT)) {
4007 $ev = bbtoevent($datarray['body']);
4008 if((x($ev,'desc') || x($ev,'summary')) && x($ev,'start')) {
4009 $ev['cid'] = $importer['id'];
4010 $ev['uid'] = $importer['uid'];
4011 $ev['uri'] = $item_id;
4012 $ev['edited'] = $datarray['edited'];
4013 $ev['private'] = $datarray['private'];
4014 $ev['guid'] = $datarray['guid'];
4016 $r = q("SELECT * FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
4018 intval($importer['uid'])
4021 $ev['id'] = $r[0]['id'];
4022 $xyz = event_store($ev);
4027 $r = q("SELECT `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
4029 intval($importer['importer_uid'])
4032 // Update content if 'updated' changes
4035 if (edited_timestamp_is_newer($r[0], $datarray)) {
4037 // do not accept (ignore) an earlier edit than one we currently have.
4038 if(datetime_convert('UTC','UTC',$datarray['edited']) < $r[0]['edited'])
4041 $r = q("UPDATE `item` SET `title` = '%s', `body` = '%s', `tag` = '%s', `edited` = '%s', `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
4042 dbesc($datarray['title']),
4043 dbesc($datarray['body']),
4044 dbesc($datarray['tag']),
4045 dbesc(datetime_convert('UTC','UTC',$datarray['edited'])),
4046 dbesc(datetime_convert()),
4048 intval($importer['importer_uid'])
4050 create_tags_from_itemuri($item_id, $importer['importer_uid']);
4051 update_thread_uri($item_id, $importer['importer_uid']);
4054 // update last-child if it changes
4056 $allow = $item->get_item_tags( NAMESPACE_DFRN, 'comment-allow');
4057 if($allow && $allow[0]['data'] != $r[0]['last-child']) {
4058 $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` = %d",
4059 intval($allow[0]['data']),
4060 dbesc(datetime_convert()),
4062 intval($importer['importer_uid'])
4068 $datarray['parent-uri'] = $item_id;
4069 $datarray['uid'] = $importer['importer_uid'];
4070 $datarray['contact-id'] = $importer['id'];
4073 if(! link_compare($datarray['owner-link'],$importer['url'])) {
4074 // The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
4075 // but otherwise there's a possible data mixup on the sender's system.
4076 // the tgroup delivery code called from item_store will correct it if it's a forum,
4077 // but we're going to unconditionally correct it here so that the post will always be owned by our contact.
4078 logger('local_delivery: Correcting item owner.', LOGGER_DEBUG);
4079 $datarray['owner-name'] = $importer['senderName'];
4080 $datarray['owner-link'] = $importer['url'];
4081 $datarray['owner-avatar'] = $importer['thumb'];
4084 if(($importer['rel'] == CONTACT_IS_FOLLOWER) && (! tgroup_check($importer['importer_uid'],$datarray)))
4087 // This is my contact on another system, but it's really me.
4088 // Turn this into a wall post.
4089 $notify = item_is_remote_self($importer, $datarray);
4091 $posted_id = item_store($datarray, false, $notify);
4093 if(stristr($datarray['verb'],ACTIVITY_POKE)) {
4094 $verb = urldecode(substr($datarray['verb'],strpos($datarray['verb'],'#')+1));
4097 $xo = parse_xml_string($datarray['object'],false);
4099 if(($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
4101 // somebody was poked/prodded. Was it me?
4103 $links = parse_xml_string("<links>".unxmlify($xo->link)."</links>",false);
4105 foreach($links->link as $l) {
4106 $atts = $l->attributes();
4107 switch($atts['rel']) {
4109 $Blink = $atts['href'];
4115 if($Blink && link_compare($Blink,$a->get_baseurl() . '/profile/' . $importer['nickname'])) {
4117 // send a notification
4118 require_once('include/enotify.php');
4121 'type' => NOTIFY_POKE,
4122 'notify_flags' => $importer['notify-flags'],
4123 'language' => $importer['language'],
4124 'to_name' => $importer['username'],
4125 'to_email' => $importer['email'],
4126 'uid' => $importer['importer_uid'],
4127 'item' => $datarray,
4128 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($posted_id)),
4129 'source_name' => stripslashes($datarray['author-name']),
4130 'source_link' => $datarray['author-link'],
4131 'source_photo' => ((link_compare($datarray['author-link'],$importer['url']))
4132 ? $importer['thumb'] : $datarray['author-avatar']),
4133 'verb' => $datarray['verb'],
4134 'otype' => 'person',
4135 'activity' => $verb,
4136 'parent' => $datarray['parent']
4152 function new_follower($importer,$contact,$datarray,$item,$sharing = false) {
4153 $url = notags(trim($datarray['author-link']));
4154 $name = notags(trim($datarray['author-name']));
4155 $photo = notags(trim($datarray['author-avatar']));
4157 if (is_object($item)) {
4158 $rawtag = $item->get_item_tags(NAMESPACE_ACTIVITY,'actor');
4159 if($rawtag && $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'])
4160 $nick = $rawtag[0]['child'][NAMESPACE_POCO]['preferredUsername'][0]['data'];
4164 if(is_array($contact)) {
4165 if(($contact['network'] == NETWORK_OSTATUS && $contact['rel'] == CONTACT_IS_SHARING)
4166 || ($sharing && $contact['rel'] == CONTACT_IS_FOLLOWER)) {
4167 $r = q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
4168 intval(CONTACT_IS_FRIEND),
4169 intval($contact['id']),
4170 intval($importer['uid'])
4173 // send email notification to owner?
4177 // create contact record
4179 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
4180 `blocked`, `readonly`, `pending`, `writable` )
4181 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1 ) ",
4182 intval($importer['uid']),
4183 dbesc(datetime_convert()),
4185 dbesc(normalise_link($url)),
4189 dbesc(($sharing) ? NETWORK_ZOT : NETWORK_OSTATUS),
4190 intval(($sharing) ? CONTACT_IS_SHARING : CONTACT_IS_FOLLOWER)
4192 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `pending` = 1 LIMIT 1",
4193 intval($importer['uid']),
4197 $contact_record = $r[0];
4199 // create notification
4200 $hash = random_string();
4202 if(is_array($contact_record)) {
4203 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `hash`, `datetime`)
4204 VALUES ( %d, %d, 0, 0, '%s', '%s' )",
4205 intval($importer['uid']),
4206 intval($contact_record['id']),
4208 dbesc(datetime_convert())
4212 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
4213 intval($importer['uid'])
4218 if(intval($r[0]['def_gid'])) {
4219 require_once('include/group.php');
4220 group_add_member($r[0]['uid'],'',$contact_record['id'],$r[0]['def_gid']);
4223 if(($r[0]['notify-flags'] & NOTIFY_INTRO) &&
4224 in_array($r[0]['page-flags'], array(PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE))) {
4227 'type' => NOTIFY_INTRO,
4228 'notify_flags' => $r[0]['notify-flags'],
4229 'language' => $r[0]['language'],
4230 'to_name' => $r[0]['username'],
4231 'to_email' => $r[0]['email'],
4232 'uid' => $r[0]['uid'],
4233 'link' => $a->get_baseurl() . '/notifications/intro',
4234 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : t('[Name Withheld]')),
4235 'source_link' => $contact_record['url'],
4236 'source_photo' => $contact_record['photo'],
4237 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
4246 function lose_follower($importer,$contact,$datarray,$item) {
4248 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_SHARING)) {
4249 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
4250 intval(CONTACT_IS_SHARING),
4251 intval($contact['id'])
4255 contact_remove($contact['id']);
4259 function lose_sharer($importer,$contact,$datarray,$item) {
4261 if(($contact['rel'] == CONTACT_IS_FRIEND) || ($contact['rel'] == CONTACT_IS_FOLLOWER)) {
4262 q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d",
4263 intval(CONTACT_IS_FOLLOWER),
4264 intval($contact['id'])
4268 contact_remove($contact['id']);
4273 function subscribe_to_hub($url,$importer,$contact,$hubmode = 'subscribe') {
4277 if(is_array($importer)) {
4278 $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",
4279 intval($importer['uid'])
4283 // Diaspora has different message-ids in feeds than they do
4284 // through the direct Diaspora protocol. If we try and use
4285 // the feed, we'll get duplicates. So don't.
4287 if((! count($r)) || $contact['network'] === NETWORK_DIASPORA)
4290 $push_url = get_config('system','url') . '/pubsub/' . $r[0]['nickname'] . '/' . $contact['id'];
4292 // Use a single verify token, even if multiple hubs
4294 $verify_token = ((strlen($contact['hub-verify'])) ? $contact['hub-verify'] : random_string());
4296 $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
4298 logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
4300 if(!strlen($contact['hub-verify']) OR ($contact['hub-verify'] != $verify_token)) {
4301 $r = q("UPDATE `contact` SET `hub-verify` = '%s' WHERE `id` = %d",
4302 dbesc($verify_token),
4303 intval($contact['id'])
4307 post_url($url,$params);
4309 logger('subscribe_to_hub: returns: ' . $a->get_curl_code(), LOGGER_DEBUG);
4316 function atom_author($tag,$name,$uri,$h,$w,$photo,$geo) {
4320 $name = xmlify($name);
4321 $uri = xmlify($uri);
4324 $photo = xmlify($photo);
4328 $o .= "\t<name>$name</name>\r\n";
4329 $o .= "\t<uri>$uri</uri>\r\n";
4330 $o .= "\t".'<link rel="photo" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
4331 $o .= "\t".'<link rel="avatar" type="image/jpeg" media:width="' . $w . '" media:height="' . $h . '" href="' . $photo . '" />' . "\r\n";
4333 if ($tag == "author") {
4336 $o .= '<georss:point>'.xmlify($geo).'</georss:point>'."\r\n";
4338 $r = q("SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
4339 `profile`.`name`, `profile`.`pub_keywords`, `profile`.`about`,
4340 `profile`.`homepage`,`contact`.`nick` FROM `profile`
4341 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
4342 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
4343 WHERE `profile`.`is-default` AND `contact`.`self` AND
4344 NOT `user`.`hidewall` AND `contact`.`nurl`='%s'",
4345 dbesc(normalise_link($uri)));
4348 if($r[0]['locality'])
4349 $location .= $r[0]['locality'];
4350 if($r[0]['region']) {
4353 $location .= $r[0]['region'];
4355 if($r[0]['country-name']) {
4358 $location .= $r[0]['country-name'];
4361 $o .= "\t<poco:preferredUsername>".xmlify($r[0]["nick"])."</poco:preferredUsername>\r\n";
4362 $o .= "\t<poco:displayName>".xmlify($r[0]["name"])."</poco:displayName>\r\n";
4363 $o .= "\t<poco:note>".xmlify($r[0]["about"])."</poco:note>\r\n";
4364 $o .= "\t<poco:address>\r\n";
4365 $o .= "\t\t<poco:formatted>".xmlify($location)."</poco:formatted>\r\n";
4366 $o .= "\t</poco:address>\r\n";
4367 $o .= "\t<poco:urls>\r\n";
4368 $o .= "\t<poco:type>homepage</poco:type>\r\n";
4369 $o .= "\t\t<poco:value>".xmlify($r[0]["homepage"])."</poco:value>\r\n";
4370 $o .= "\t\t<poco:primary>true</poco:primary>\r\n";
4371 $o .= "\t</poco:urls>\r\n";
4375 call_hooks('atom_author', $o);
4377 $o .= "</$tag>\r\n";
4381 function atom_entry($item,$type,$author,$owner,$comment = false,$cid = 0) {
4385 if(! $item['parent'])
4388 if($item['deleted'])
4389 return '<at:deleted-entry ref="' . xmlify($item['uri']) . '" when="' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '" />' . "\r\n";
4392 if($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid'])
4393 $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
4395 $body = $item['body'];
4398 $o = "\r\n\r\n<entry>\r\n";
4400 if(is_array($author))
4401 $o .= atom_author('author',$author['name'],$author['url'],80,80,$author['thumb'], $item['coord']);
4403 $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']), $item['coord']);
4404 if(strlen($item['owner-name']))
4405 $o .= atom_author('dfrn:owner',$item['owner-name'],$item['owner-link'],80,80,$item['owner-avatar'], $item['coord']);
4407 if(($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
4408 $parent = q("SELECT `guid` FROM `item` WHERE `id` = %d", intval($item["parent"]));
4409 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
4410 $o .= '<thr:in-reply-to ref="'.xmlify($parent_item).'" type="text/html" href="'.xmlify($a->get_baseurl().'/display/'.$parent[0]['guid']).'" />'."\r\n";
4415 if ($item['title'] != "")
4416 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
4418 $htmlbody = bbcode($htmlbody, false, false, 7);
4420 $o .= '<id>' . xmlify($item['uri']) . '</id>' . "\r\n";
4421 $o .= '<title>' . xmlify($item['title']) . '</title>' . "\r\n";
4422 $o .= '<published>' . xmlify(datetime_convert('UTC','UTC',$item['created'] . '+00:00',ATOM_TIME)) . '</published>' . "\r\n";
4423 $o .= '<updated>' . xmlify(datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME)) . '</updated>' . "\r\n";
4424 $o .= '<dfrn:env>' . base64url_encode($body, true) . '</dfrn:env>' . "\r\n";
4425 $o .= '<content type="' . $type . '" >' . xmlify((($type === 'html') ? $htmlbody : $body)) . '</content>' . "\r\n";
4426 $o .= '<link rel="alternate" type="text/html" href="'.xmlify($a->get_baseurl().'/display/'.$item['guid']).'" />'."\r\n";
4428 $o .= '<status_net notice_id="'.$item['id'].'"></status_net>'."\r\n";
4431 $o .= '<dfrn:comment-allow>' . intval($item['last-child']) . '</dfrn:comment-allow>' . "\r\n";
4433 if($item['location']) {
4434 $o .= '<dfrn:location>' . xmlify($item['location']) . '</dfrn:location>' . "\r\n";
4435 $o .= '<poco:address><poco:formatted>' . xmlify($item['location']) . '</poco:formatted></poco:address>' . "\r\n";
4439 $o .= '<georss:point>' . xmlify($item['coord']) . '</georss:point>' . "\r\n";
4441 if(($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid']))
4442 $o .= '<dfrn:private>' . (($item['private']) ? $item['private'] : 1) . '</dfrn:private>' . "\r\n";
4445 $o .= '<dfrn:extid>' . xmlify($item['extid']) . '</dfrn:extid>' . "\r\n";
4446 if($item['bookmark'])
4447 $o .= '<dfrn:bookmark>true</dfrn:bookmark>' . "\r\n";
4450 $o .= '<statusnet:notice_info local_id="' . $item['id'] . '" source="' . xmlify($item['app']) . '" ></statusnet:notice_info>' . "\r\n";
4453 $o .= '<dfrn:diaspora_guid>' . $item['guid'] . '</dfrn:diaspora_guid>' . "\r\n";
4455 if($item['signed_text']) {
4456 $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
4457 $o .= '<dfrn:diaspora_signature>' . xmlify($sign) . '</dfrn:diaspora_signature>' . "\r\n";
4460 $verb = construct_verb($item);
4461 $o .= '<as:verb>' . xmlify($verb) . '</as:verb>' . "\r\n";
4462 $actobj = construct_activity_object($item);
4465 $actarg = construct_activity_target($item);
4469 $tags = item_getfeedtags($item);
4471 foreach($tags as $t)
4472 if (($type != 'html') OR ($t[0] != "@"))
4473 $o .= '<category scheme="X-DFRN:' . xmlify($t[0]) . ':' . xmlify($t[1]) . '" term="' . xmlify($t[2]) . '" />' . "\r\n";
4477 // To support these elements, the API needs to be enhanced
4478 //$o .= '<link rel="ostatus:conversation" href="'.xmlify($a->get_baseurl().'/display/'.$owner['nickname'].'/'.$item['parent']).'"/>'."\r\n";
4479 //$o .= "\t".'<link rel="self" type="application/atom+xml" href="'.xmlify($a->get_baseurl().'/api/statuses/show/'.$item['id'].'.atom').'"/>'."\r\n";
4480 //$o .= "\t".'<link rel="edit" type="application/atom+xml" href="'.xmlify($a->get_baseurl().'/api/statuses/show/'.$item['id'].'.atom').'"/>'."\r\n";
4482 // Deactivated since it was meant only for OStatus
4483 //$o .= item_get_attachment($item);
4485 $o .= item_getfeedattach($item);
4487 $mentioned = get_mentions($item);
4491 call_hooks('atom_entry', $o);
4493 $o .= '</entry>' . "\r\n";
4498 function fix_private_photos($s, $uid, $item = null, $cid = 0) {
4500 if(get_config('system','disable_embedded'))
4505 logger('fix_private_photos: check for photos', LOGGER_DEBUG);
4506 $site = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://'));
4511 $img_start = strpos($orig_body, '[img');
4512 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
4513 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
4514 while( ($img_st_close !== false) && ($img_len !== false) ) {
4516 $img_st_close++; // make it point to AFTER the closing bracket
4517 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
4519 logger('fix_private_photos: found photo ' . $image, LOGGER_DEBUG);
4522 if(stristr($image , $site . '/photo/')) {
4523 // Only embed locally hosted photos
4525 $i = basename($image);
4526 $i = str_replace(array('.jpg','.png','.gif'),array('','',''),$i);
4527 $x = strpos($i,'-');
4530 $res = substr($i,$x+1);
4531 $i = substr($i,0,$x);
4532 $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `scale` = %d AND `uid` = %d",
4539 // Check to see if we should replace this photo link with an embedded image
4540 // 1. No need to do so if the photo is public
4541 // 2. If there's a contact-id provided, see if they're in the access list
4542 // for the photo. If so, embed it.
4543 // 3. Otherwise, if we have an item, see if the item permissions match the photo
4544 // permissions, regardless of order but first check to see if they're an exact
4545 // match to save some processing overhead.
4547 if(has_permissions($r[0])) {
4549 $recips = enumerate_permissions($r[0]);
4550 if(in_array($cid, $recips)) {
4555 if(compare_permissions($item,$r[0]))
4560 $data = $r[0]['data'];
4561 $type = $r[0]['type'];
4563 // If a custom width and height were specified, apply before embedding
4564 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
4565 logger('fix_private_photos: scaling photo', LOGGER_DEBUG);
4567 $width = intval($match[1]);
4568 $height = intval($match[2]);
4570 $ph = new Photo($data, $type);
4571 if($ph->is_valid()) {
4572 $ph->scaleImage(max($width, $height));
4573 $data = $ph->imageString();
4574 $type = $ph->getType();
4578 logger('fix_private_photos: replacing photo', LOGGER_DEBUG);
4579 $image = 'data:' . $type . ';base64,' . base64_encode($data);
4580 logger('fix_private_photos: replaced: ' . $image, LOGGER_DATA);
4586 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
4587 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
4588 if($orig_body === false)
4591 $img_start = strpos($orig_body, '[img');
4592 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
4593 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
4596 $new_body = $new_body . $orig_body;
4602 function has_permissions($obj) {
4603 if(($obj['allow_cid'] != '') || ($obj['allow_gid'] != '') || ($obj['deny_cid'] != '') || ($obj['deny_gid'] != ''))
4608 function compare_permissions($obj1,$obj2) {
4609 // first part is easy. Check that these are exactly the same.
4610 if(($obj1['allow_cid'] == $obj2['allow_cid'])
4611 && ($obj1['allow_gid'] == $obj2['allow_gid'])
4612 && ($obj1['deny_cid'] == $obj2['deny_cid'])
4613 && ($obj1['deny_gid'] == $obj2['deny_gid']))
4616 // This is harder. Parse all the permissions and compare the resulting set.
4618 $recipients1 = enumerate_permissions($obj1);
4619 $recipients2 = enumerate_permissions($obj2);
4622 if($recipients1 == $recipients2)
4627 // returns an array of contact-ids that are allowed to see this object
4629 function enumerate_permissions($obj) {
4630 require_once('include/group.php');
4631 $allow_people = expand_acl($obj['allow_cid']);
4632 $allow_groups = expand_groups(expand_acl($obj['allow_gid']));
4633 $deny_people = expand_acl($obj['deny_cid']);
4634 $deny_groups = expand_groups(expand_acl($obj['deny_gid']));
4635 $recipients = array_unique(array_merge($allow_people,$allow_groups));
4636 $deny = array_unique(array_merge($deny_people,$deny_groups));
4637 $recipients = array_diff($recipients,$deny);
4641 function item_getfeedtags($item) {
4644 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
4646 for($x = 0; $x < $cnt; $x ++) {
4648 $ret[] = array('#',$matches[1][$x], $matches[2][$x]);
4652 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|',$item['tag'],$matches);
4654 for($x = 0; $x < $cnt; $x ++) {
4656 $ret[] = array('@',$matches[1][$x], $matches[2][$x]);
4662 function item_get_attachment($item) {
4664 $siteinfo = get_attached_data($item["body"]);
4666 switch($siteinfo["type"]) {
4668 $o = '<link rel="enclosure" href="'.xmlify($siteinfo["url"]).'" type="text/html; charset=UTF-8" length="" title="'.xmlify($siteinfo["title"]).'"/>'."\r\n";
4671 $imgdata = get_photo_info($siteinfo["image"]);
4672 $o = '<link rel="enclosure" href="'.xmlify($siteinfo["image"]).'" type="'.$imgdata["mime"].'" length="'.$imgdata["size"].'"/>'."\r\n";
4675 $o = '<link rel="enclosure" href="'.xmlify($siteinfo["url"]).'" type="text/html; charset=UTF-8" length="" title="'.xmlify($siteinfo["title"]).'"/>'."\r\n";
4684 function item_getfeedattach($item) {
4686 $arr = explode('[/attach],',$item['attach']);
4688 foreach($arr as $r) {
4690 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
4692 $ret .= '<link rel="enclosure" href="' . xmlify($matches[1]) . '" type="' . xmlify($matches[3]) . '" ';
4693 if(intval($matches[2]))
4694 $ret .= 'length="' . intval($matches[2]) . '" ';
4695 if($matches[4] !== ' ')
4696 $ret .= 'title="' . xmlify(trim($matches[4])) . '" ';
4697 $ret .= ' />' . "\r\n";
4706 function item_expire($uid, $days, $network = "", $force = false) {
4708 if((! $uid) || ($days < 1))
4711 // $expire_network_only = save your own wall posts
4712 // and just expire conversations started by others
4714 $expire_network_only = get_pconfig($uid,'expire','network_only');
4715 $sql_extra = ((intval($expire_network_only)) ? " AND wall = 0 " : "");
4717 if ($network != "") {
4718 $sql_extra .= sprintf(" AND network = '%s' ", dbesc($network));
4719 // There is an index "uid_network_received" but not "uid_network_created"
4720 // This avoids the creation of another index just for one purpose.
4721 // And it doesn't really matter wether to look at "received" or "created"
4722 $range = "AND `received` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
4724 $range = "AND `created` < UTC_TIMESTAMP() - INTERVAL %d DAY ";
4726 $r = q("SELECT * FROM `item`
4727 WHERE `uid` = %d $range
4738 $expire_items = get_pconfig($uid, 'expire','items');
4739 $expire_items = (($expire_items===false)?1:intval($expire_items)); // default if not set: 1
4741 // Forcing expiring of items - but not notes and marked items
4743 $expire_items = true;
4745 $expire_notes = get_pconfig($uid, 'expire','notes');
4746 $expire_notes = (($expire_notes===false)?1:intval($expire_notes)); // default if not set: 1
4748 $expire_starred = get_pconfig($uid, 'expire','starred');
4749 $expire_starred = (($expire_starred===false)?1:intval($expire_starred)); // default if not set: 1
4751 $expire_photos = get_pconfig($uid, 'expire','photos');
4752 $expire_photos = (($expire_photos===false)?0:intval($expire_photos)); // default if not set: 0
4754 logger('expire: # items=' . count($r). "; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
4756 foreach($r as $item) {
4758 // don't expire filed items
4760 if(strpos($item['file'],'[') !== false)
4763 // Only expire posts, not photos and photo comments
4765 if($expire_photos==0 && strlen($item['resource-id']))
4767 if($expire_starred==0 && intval($item['starred']))
4769 if($expire_notes==0 && $item['type']=='note')
4771 if($expire_items==0 && $item['type']!='note')
4774 drop_item($item['id'],false);
4777 proc_run('php',"include/notifier.php","expire","$uid");
4782 function drop_items($items) {
4785 if(! local_user() && ! remote_user())
4789 foreach($items as $item) {
4790 $owner = drop_item($item,false);
4791 if($owner && ! $uid)
4796 // multiple threads may have been deleted, send an expire notification
4799 proc_run('php',"include/notifier.php","expire","$uid");
4803 function drop_item($id,$interactive = true) {
4807 // locate item to be deleted
4809 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
4816 notice( t('Item not found.') . EOL);
4817 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
4822 $owner = $item['uid'];
4826 // check if logged in user is either the author or owner of this item
4828 if(is_array($_SESSION['remote'])) {
4829 foreach($_SESSION['remote'] as $visitor) {
4830 if($visitor['uid'] == $item['uid'] && $visitor['cid'] == $item['contact-id']) {
4831 $cid = $visitor['cid'];
4838 if((local_user() == $item['uid']) || ($cid) || (! $interactive)) {
4840 // Check if we should do HTML-based delete confirmation
4841 if($_REQUEST['confirm']) {
4842 // <form> can't take arguments in its "action" parameter
4843 // so add any arguments as hidden inputs
4844 $query = explode_querystring($a->query_string);
4846 foreach($query['args'] as $arg) {
4847 if(strpos($arg, 'confirm=') === false) {
4848 $arg_parts = explode('=', $arg);
4849 $inputs[] = array('name' => $arg_parts[0], 'value' => $arg_parts[1]);
4853 return replace_macros(get_markup_template('confirm.tpl'), array(
4855 '$message' => t('Do you really want to delete this item?'),
4856 '$extra_inputs' => $inputs,
4857 '$confirm' => t('Yes'),
4858 '$confirm_url' => $query['base'],
4859 '$confirm_name' => 'confirmed',
4860 '$cancel' => t('Cancel'),
4863 // Now check how the user responded to the confirmation query
4864 if($_REQUEST['canceled']) {
4865 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
4868 logger('delete item: ' . $item['id'], LOGGER_DEBUG);
4871 $r = q("UPDATE `item` SET `deleted` = 1, `title` = '', `body` = '', `edited` = '%s', `changed` = '%s' WHERE `id` = %d",
4872 dbesc(datetime_convert()),
4873 dbesc(datetime_convert()),
4876 create_tags_from_item($item['id']);
4877 create_files_from_item($item['id']);
4878 delete_thread($item['id'], $item['parent-uri']);
4880 // clean up categories and tags so they don't end up as orphans
4883 $cnt = preg_match_all('/<(.*?)>/',$item['file'],$matches,PREG_SET_ORDER);
4885 foreach($matches as $mtch) {
4886 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],true);
4892 $cnt = preg_match_all('/\[(.*?)\]/',$item['file'],$matches,PREG_SET_ORDER);
4894 foreach($matches as $mtch) {
4895 file_tag_unsave_file($item['uid'],$item['id'],$mtch[1],false);
4899 // If item is a link to a photo resource, nuke all the associated photos
4900 // (visitors will not have photo resources)
4901 // This only applies to photos uploaded from the photos page. Photos inserted into a post do not
4902 // generate a resource-id and therefore aren't intimately linked to the item.
4904 if(strlen($item['resource-id'])) {
4905 q("DELETE FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d ",
4906 dbesc($item['resource-id']),
4907 intval($item['uid'])
4909 // ignore the result
4912 // If item is a link to an event, nuke the event record.
4914 if(intval($item['event-id'])) {
4915 q("DELETE FROM `event` WHERE `id` = %d AND `uid` = %d",
4916 intval($item['event-id']),
4917 intval($item['uid'])
4919 // ignore the result
4922 // If item has attachments, drop them
4924 foreach(explode(",",$item['attach']) as $attach){
4925 preg_match("|attach/(\d+)|", $attach, $matches);
4926 q("DELETE FROM `attach` WHERE `id` = %d AND `uid` = %d",
4927 intval($matches[1]),
4930 // ignore the result
4934 // clean up item_id and sign meta-data tables
4937 // Old code - caused very long queries and warning entries in the mysql logfiles:
4939 $r = q("DELETE FROM item_id where iid in (select id from item where parent = %d and uid = %d)",
4940 intval($item['id']),
4941 intval($item['uid'])
4944 $r = q("DELETE FROM sign where iid in (select id from item where parent = %d and uid = %d)",
4945 intval($item['id']),
4946 intval($item['uid'])
4950 // The new code splits the queries since the mysql optimizer really has bad problems with subqueries
4952 // Creating list of parents
4953 $r = q("select id from item where parent = %d and uid = %d",
4954 intval($item['id']),
4955 intval($item['uid'])
4960 foreach ($r AS $row) {
4961 if ($parentid != "")
4964 $parentid .= $row["id"];
4968 if ($parentid != "") {
4969 $r = q("DELETE FROM item_id where iid in (%s)", dbesc($parentid));
4971 $r = q("DELETE FROM sign where iid in (%s)", dbesc($parentid));
4974 // If it's the parent of a comment thread, kill all the kids
4976 if($item['uri'] == $item['parent-uri']) {
4977 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = ''
4978 WHERE `parent-uri` = '%s' AND `uid` = %d ",
4979 dbesc(datetime_convert()),
4980 dbesc(datetime_convert()),
4981 dbesc($item['parent-uri']),
4982 intval($item['uid'])
4984 create_tags_from_itemuri($item['parent-uri'], $item['uid']);
4985 create_files_from_itemuri($item['parent-uri'], $item['uid']);
4986 delete_thread_uri($item['parent-uri'], $item['uid']);
4987 // ignore the result
4990 // ensure that last-child is set in case the comment that had it just got wiped.
4991 q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` = %d ",
4992 dbesc(datetime_convert()),
4993 dbesc($item['parent-uri']),
4994 intval($item['uid'])
4996 // who is the last child now?
4997 $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",
4998 dbesc($item['parent-uri']),
4999 intval($item['uid'])
5002 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
5007 // Add a relayable_retraction signature for Diaspora.
5008 store_diaspora_retract_sig($item, $a->user, $a->get_baseurl());
5011 $drop_id = intval($item['id']);
5013 // send the notification upstream/downstream as the case may be
5015 proc_run('php',"include/notifier.php","drop","$drop_id");
5019 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
5025 notice( t('Permission denied.') . EOL);
5026 goaway($a->get_baseurl() . '/' . $_SESSION['return_url']);
5033 function first_post_date($uid,$wall = false) {
5034 $r = q("select id, created from item
5035 where uid = %d and wall = %d and deleted = 0 and visible = 1 AND moderated = 0
5037 order by created asc limit 1",
5039 intval($wall ? 1 : 0)
5042 // logger('first_post_date: ' . $r[0]['id'] . ' ' . $r[0]['created'], LOGGER_DATA);
5043 return substr(datetime_convert('',date_default_timezone_get(),$r[0]['created']),0,10);
5048 /* modified posted_dates() {below} to arrange the list in years */
5049 function list_post_dates($uid, $wall) {
5050 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
5052 $dthen = first_post_date($uid, $wall);
5056 // Set the start and end date to the beginning of the month
5057 $dnow = substr($dnow,0,8).'01';
5058 $dthen = substr($dthen,0,8).'01';
5062 // Starting with the current month, get the first and last days of every
5063 // month down to and including the month of the first post
5064 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
5065 $dyear = intval(substr($dnow,0,4));
5066 $dstart = substr($dnow,0,8) . '01';
5067 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
5068 $start_month = datetime_convert('','',$dstart,'Y-m-d');
5069 $end_month = datetime_convert('','',$dend,'Y-m-d');
5070 $str = day_translate(datetime_convert('','',$dnow,'F'));
5072 $ret[$dyear] = array();
5073 $ret[$dyear][] = array($str,$end_month,$start_month);
5074 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
5079 function posted_dates($uid,$wall) {
5080 $dnow = datetime_convert('',date_default_timezone_get(),'now','Y-m-d');
5082 $dthen = first_post_date($uid,$wall);
5086 // Set the start and end date to the beginning of the month
5087 $dnow = substr($dnow,0,8).'01';
5088 $dthen = substr($dthen,0,8).'01';
5091 // Starting with the current month, get the first and last days of every
5092 // month down to and including the month of the first post
5093 while(substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
5094 $dstart = substr($dnow,0,8) . '01';
5095 $dend = substr($dnow,0,8) . get_dim(intval($dnow),intval(substr($dnow,5)));
5096 $start_month = datetime_convert('','',$dstart,'Y-m-d');
5097 $end_month = datetime_convert('','',$dend,'Y-m-d');
5098 $str = day_translate(datetime_convert('','',$dnow,'F Y'));
5099 $ret[] = array($str,$end_month,$start_month);
5100 $dnow = datetime_convert('','',$dnow . ' -1 month', 'Y-m-d');
5106 function posted_date_widget($url,$uid,$wall) {
5109 if(! feature_enabled($uid,'archives'))
5112 // For former Facebook folks that left because of "timeline"
5114 /* if($wall && intval(get_pconfig($uid,'system','no_wall_archive_widget')))
5117 $visible_years = get_pconfig($uid,'system','archive_visible_years');
5118 if(! $visible_years)
5121 $ret = list_post_dates($uid,$wall);
5126 $cutoff_year = intval(datetime_convert('',date_default_timezone_get(),'now','Y')) - $visible_years;
5127 $cutoff = ((array_key_exists($cutoff_year,$ret))? true : false);
5129 $o = replace_macros(get_markup_template('posted_date_widget.tpl'),array(
5130 '$title' => t('Archives'),
5131 '$size' => $visible_years,
5132 '$cutoff_year' => $cutoff_year,
5133 '$cutoff' => $cutoff,
5136 '$showmore' => t('show more')
5142 function store_diaspora_retract_sig($item, $user, $baseurl) {
5143 // Note that we can't add a target_author_signature
5144 // if the comment was deleted by a remote user. That should be ok, because if a remote user is deleting
5145 // the comment, that means we're the home of the post, and Diaspora will only
5146 // check the parent_author_signature of retractions that it doesn't have to relay further
5148 // I don't think this function gets called for an "unlike," but I'll check anyway
5150 $enabled = intval(get_config('system','diaspora_enabled'));
5152 logger('drop_item: diaspora support disabled, not storing retraction signature', LOGGER_DEBUG);
5156 logger('drop_item: storing diaspora retraction signature');
5158 $signed_text = $item['guid'] . ';' . ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
5160 if(local_user() == $item['uid']) {
5162 $handle = $user['nickname'] . '@' . substr($baseurl, strpos($baseurl,'://') + 3);
5163 $authorsig = base64_encode(rsa_sign($signed_text,$user['prvkey'],'sha256'));
5166 $r = q("SELECT `nick`, `url` FROM `contact` WHERE `id` = '%d' LIMIT 1",
5167 $item['contact-id'] // If this function gets called, drop_item() has already checked remote_user() == $item['contact-id']
5170 // The below handle only works for NETWORK_DFRN. I think that's ok, because this function
5171 // only handles DFRN deletes
5172 $handle_baseurl_start = strpos($r['url'],'://') + 3;
5173 $handle_baseurl_length = strpos($r['url'],'/profile') - $handle_baseurl_start;
5174 $handle = $r['nick'] . '@' . substr($r['url'], $handle_baseurl_start, $handle_baseurl_length);
5180 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
5181 intval($item['id']),
5182 dbesc($signed_text),