7 * This is the POST destination for most all locally posted
8 * text stuff. This function handles status, wall-to-wall status,
9 * local comments, and remote coments that are posted on this site
10 * (as opposed to being delivered in a feed).
11 * Also processed here are posts and comments coming through the
12 * statusnet/twitter API.
14 * All of these become an "item" which is our basic unit of
18 use Friendica\Core\Config;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Item;
25 use Friendica\Network\Probe;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Protocol\Email;
28 use Friendica\Util\Emailer;
30 require_once 'include/enotify.php';
31 require_once 'include/tags.php';
32 require_once 'include/threads.php';
33 require_once 'include/text.php';
34 require_once 'include/items.php';
36 function item_post(App $a) {
37 if (!local_user() && !remote_user()) {
41 require_once 'include/security.php';
45 if (x($_REQUEST, 'dropitems')) {
46 $arr_drop = explode(',', $_REQUEST['dropitems']);
47 drop_items($arr_drop);
48 $json = ['success' => 1];
49 echo json_encode($json);
53 call_hooks('post_local_start', $_REQUEST);
54 // logger('postinput ' . file_get_contents('php://input'));
55 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
57 $api_source = x($_REQUEST, 'api_source') && $_REQUEST['api_source'];
59 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
61 $return_path = (x($_REQUEST, 'return') ? $_REQUEST['return'] : '');
62 $preview = (x($_REQUEST, 'preview') ? intval($_REQUEST['preview']) : 0);
65 * Check for doubly-submitted posts, and reject duplicates
66 * Note that we have to ignore previews, otherwise nothing will post
67 * after it's been previewed
69 if (!$preview && x($_REQUEST, 'post_id_random')) {
70 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
71 logger("item post: duplicate post", LOGGER_DEBUG);
72 item_post_return(System::baseUrl(), $api_source, $return_path);
74 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
78 // Is this a reply to something?
79 $parent = (x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0);
80 $parent_uri = (x($_REQUEST, 'parent_uri') ? trim($_REQUEST['parent_uri']) : '');
83 $parent_contact = null;
89 if ($parent || $parent_uri) {
91 $objecttype = ACTIVITY_OBJ_COMMENT;
93 if (!x($_REQUEST, 'type')) {
94 $_REQUEST['type'] = 'net-comment';
98 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
101 } elseif ($parent_uri && local_user()) {
102 // This is coming from an API source, and we are logged in
103 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
108 // if this isn't the real parent of the conversation, find it
109 if (DBM::is_result($r)) {
110 $parid = $r[0]['parent'];
111 if ($r[0]['id'] != $r[0]['parent']) {
112 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
119 if (!DBM::is_result($r)) {
120 notice(t('Unable to locate original post.') . EOL);
121 if (x($_REQUEST, 'return')) {
122 goaway($return_path);
126 $parent_item = $r[0];
127 $parent = $parent_item['id'];
128 $parent_uri = $parent_item['uri'];
129 $parent_user = $parent_item['uid'];
131 if ($parent_item['contact-id']) {
132 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
133 intval($parent_item['contact-id'])
135 if (DBM::is_result($r)) {
136 $parent_contact = $r[0];
139 // If the contact id doesn't fit with the contact, then set the contact to null
140 $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($parent_uri));
141 if (DBM::is_result($thrparent) && ($thrparent[0]["network"] === NETWORK_OSTATUS)
142 && (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
143 $parent_contact = Contact::getDetailsByURL($thrparent[0]["author-link"]);
145 if (!isset($parent_contact["nick"])) {
146 $probed_contact = Probe::uri($thrparent[0]["author-link"]);
147 if ($probed_contact["network"] != NETWORK_FEED) {
148 $parent_contact = $probed_contact;
149 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
150 $parent_contact["thumb"] = $probed_contact["photo"];
151 $parent_contact["micro"] = $probed_contact["photo"];
152 $parent_contact["addr"] = $probed_contact["addr"];
155 logger('no contact found: ' . print_r($thrparent, true), LOGGER_DEBUG);
157 logger('parent contact: ' . print_r($parent_contact, true), LOGGER_DEBUG);
160 if ($parent_contact["nick"] == "") {
161 $parent_contact["nick"] = $parent_contact["name"];
167 logger('mod_item: item_post parent=' . $parent);
170 $profile_uid = (x($_REQUEST, 'profile_uid') ? intval($_REQUEST['profile_uid']) : 0);
171 $post_id = (x($_REQUEST, 'post_id') ? intval($_REQUEST['post_id']) : 0);
172 $app = (x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : '');
173 $extid = (x($_REQUEST, 'extid') ? strip_tags($_REQUEST['extid']) : '');
174 $object = (x($_REQUEST, 'object') ? $_REQUEST['object'] : '');
176 // Ensure that the user id in a thread always stay the same
177 if (!is_null($parent_user)) {
178 $profile_uid = $parent_user;
181 // Check for multiple posts with the same message id (when the post was created via API)
182 if (($message_id != '') && ($profile_uid != 0)) {
183 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
188 if (DBM::is_result($r)) {
189 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
194 // Allow commenting if it is an answer to a public post
195 $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
197 // Now check that valid personal details have been provided
198 if (!can_write_wall($profile_uid) && !$allow_comment) {
199 notice(t('Permission denied.') . EOL) ;
200 if (x($_REQUEST, 'return')) {
201 goaway($return_path);
207 // is this an edited post?
212 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
213 intval($profile_uid),
216 if (!DBM::is_result($i)) {
224 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
227 if (DBM::is_result($r)) {
232 $str_group_allow = $orig_post['allow_gid'];
233 $str_contact_allow = $orig_post['allow_cid'];
234 $str_group_deny = $orig_post['deny_gid'];
235 $str_contact_deny = $orig_post['deny_cid'];
236 $location = $orig_post['location'];
237 $coord = $orig_post['coord'];
238 $verb = $orig_post['verb'];
239 $objecttype = $orig_post['object-type'];
240 $emailcc = $orig_post['emailcc'];
241 $app = $orig_post['app'];
242 $categories = $orig_post['file'];
243 $title = notags(trim($_REQUEST['title']));
244 $body = escape_tags(trim($_REQUEST['body']));
245 $private = $orig_post['private'];
246 $pubmail_enable = $orig_post['pubmail'];
247 $network = $orig_post['network'];
248 $guid = $orig_post['guid'];
249 $extid = $orig_post['extid'];
254 * if coming from the API and no privacy settings are set,
255 * use the user default permissions - as they won't have
256 * been supplied via a form.
258 /// @TODO use x($_REQUEST, 'foo') here
260 && !array_key_exists('contact_allow', $_REQUEST)
261 && !array_key_exists('group_allow', $_REQUEST)
262 && !array_key_exists('contact_deny', $_REQUEST)
263 && !array_key_exists('group_deny', $_REQUEST)) {
264 $str_group_allow = $user['allow_gid'];
265 $str_contact_allow = $user['allow_cid'];
266 $str_group_deny = $user['deny_gid'];
267 $str_contact_deny = $user['deny_cid'];
270 // use the posted permissions
272 $str_group_allow = perms2str($_REQUEST['group_allow']);
273 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
274 $str_group_deny = perms2str($_REQUEST['group_deny']);
275 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
278 $title = notags(trim($_REQUEST['title']));
279 $location = notags(trim($_REQUEST['location']));
280 $coord = notags(trim($_REQUEST['coord']));
281 $verb = notags(trim($_REQUEST['verb']));
282 $emailcc = notags(trim($_REQUEST['emailcc']));
283 $body = escape_tags(trim($_REQUEST['body']));
284 $network = notags(trim($_REQUEST['network']));
285 $guid = get_guid(32);
287 item_add_language_opt($_REQUEST);
288 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
290 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
292 if ($user['hidewall']) {
296 // If this is a comment, set the permissions from the parent.
300 // for non native networks use the network of the original post as network of the item
301 if (($parent_item['network'] != NETWORK_DIASPORA)
302 && ($parent_item['network'] != NETWORK_OSTATUS)
303 && ($network == "")) {
304 $network = $parent_item['network'];
307 $str_contact_allow = $parent_item['allow_cid'];
308 $str_group_allow = $parent_item['allow_gid'];
309 $str_contact_deny = $parent_item['deny_cid'];
310 $str_group_deny = $parent_item['deny_gid'];
311 $private = $parent_item['private'];
314 $pubmail_enable = ((x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && !$private) ? 1 : 0);
316 // if using the API, we won't see pubmail_enable - figure out if it should be set
318 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
319 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
320 if (!$mail_disabled) {
321 /// @TODO Check if only pubmail is loaded, * loads all columns
322 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
325 if (DBM::is_result($r) && intval($r[0]['pubmail'])) {
326 $pubmail_enabled = true;
331 if (!strlen($body)) {
335 info(t('Empty post discarded.') . EOL);
336 if (x($_REQUEST, 'return')) {
337 goaway($return_path);
343 if (strlen($categories)) {
344 // get the "fileas" tags for this post
345 $filedas = file_tag_file_to_list($categories, 'file');
347 // save old and new categories, so we can determine what needs to be deleted from pconfig
348 $categories_old = $categories;
349 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
350 $categories_new = $categories;
351 if (strlen($filedas)) {
352 // append the fileas stuff to the new categories list
353 $categories .= file_tag_list_to_file($filedas, 'file');
356 // get contact info for poster
362 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
364 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
365 intval($_SESSION['uid']));
366 } elseif (remote_user()) {
367 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
368 foreach ($_SESSION['remote'] as $v) {
369 if ($v['uid'] == $profile_uid) {
370 $contact_id = $v['cid'];
376 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
382 if (DBM::is_result($r)) {
384 $contact_id = $author['id'];
387 // get contact info for owner
389 if ($profile_uid == local_user() || $allow_comment) {
390 $contact_record = $author;
392 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
395 if (DBM::is_result($r)) {
396 $contact_record = $r[0];
400 $post_type = notags(trim($_REQUEST['type']));
402 if ($post_type === 'net-comment' && $parent_item !== null) {
403 if ($parent_item['wall'] == 1) {
404 $post_type = 'wall-comment';
406 $post_type = 'remote-comment';
410 // Look for any tags and linkify them
414 $tags = get_tags($body);
417 * add a statusnet style reply tag if the original post was from there
418 * and we are replying, and there isn't one already
420 if ($parent && ($parent_contact['network'] == NETWORK_OSTATUS)) {
421 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
423 if (!in_array($contact, $tags)) {
424 $body = $contact . ' ' . $body;
428 $toplevel_contact = "";
429 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
430 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
431 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
432 if (DBM::is_result($toplevel_parent)) {
433 if (!empty($toplevel_parent[0]['addr'])) {
434 $toplevel_contact = '@' . $toplevel_parent[0]['addr'];
436 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
439 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
440 $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
443 if (!in_array($toplevel_contact, $tags)) {
444 $tags[] = $toplevel_contact;
450 $private_forum = false;
451 $only_to_forum = false;
455 foreach ($tags as $tag) {
457 $tag_type = substr($tag, 0, 1);
459 if ($tag_type == '#') {
464 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
465 * Robert Johnson should be first in the $tags array
467 $fullnametagged = false;
468 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
469 foreach ($tagged as $nextTag) {
470 if (stristr($nextTag, $tag . ' ')) {
471 $fullnametagged = true;
475 if ($fullnametagged) {
479 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
480 if ($success['replaced']) {
483 // When the forum is private or the forum is addressed with a "!" make the post private
484 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
485 $private_forum = $success['contact']['prv'];
486 $only_to_forum = ($tag_type == '!');
487 $private_id = $success['contact']['id'];
488 $forum_contact = $success['contact'];
489 } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
490 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
491 $private_forum = false;
492 $only_to_forum = true;
493 $private_id = $success['contact']['id'];
494 $forum_contact = $success['contact'];
499 $original_contact_id = $contact_id;
501 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
502 // we tagged a forum in a top level post. Now we change the post
503 $private = $private_forum;
505 $str_group_allow = '';
506 $str_contact_deny = '';
507 $str_group_deny = '';
508 if ($private_forum) {
509 $str_contact_allow = '<' . $private_id . '>';
511 $str_contact_allow = '';
513 $contact_id = $private_id;
514 $contact_record = $forum_contact;
515 $_REQUEST['origin'] = false;
519 * When a photo was uploaded into the message using the (profile wall) ajax
520 * uploader, The permissions are initially set to disallow anybody but the
521 * owner from seeing it. This is because the permissions may not yet have been
522 * set for the post. If it's private, the photo permissions should be set
523 * appropriately. But we didn't know the final permissions on the post until
524 * now. So now we'll look for links of uploaded messages that are in the
525 * post and set them to the same permissions as the post itself.
530 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
532 if (count($images)) {
534 $objecttype = ACTIVITY_OBJ_IMAGE;
536 foreach ($images as $image) {
537 if (!stristr($image, System::baseUrl() . '/photo/')) {
540 $image_uri = substr($image,strrpos($image,'/') + 1);
541 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
542 if (!strlen($image_uri)) {
545 $srch = '<' . intval($original_contact_id) . '>';
547 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
548 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
554 if (!DBM::is_result($r)) {
558 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
559 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
560 dbesc($str_contact_allow),
561 dbesc($str_group_allow),
562 dbesc($str_contact_deny),
563 dbesc($str_group_deny),
565 intval($profile_uid),
566 dbesc(t('Wall Photos'))
574 * Next link in any attachment references we find in the post.
578 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
579 $attaches = $match[1];
580 if (count($attaches)) {
581 foreach ($attaches as $attach) {
582 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
583 intval($profile_uid),
586 if (DBM::is_result($r)) {
587 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
588 WHERE `uid` = %d AND `id` = %d",
589 dbesc($str_contact_allow),
590 dbesc($str_group_allow),
591 dbesc($str_contact_deny),
592 dbesc($str_group_deny),
593 intval($profile_uid),
601 // embedded bookmark or attachment in post? set bookmark flag
604 $data = get_attachment_data($body);
605 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
606 $objecttype = ACTIVITY_OBJ_BOOKMARK;
610 $body = bb_translate_video($body);
613 // Fold multi-line [code] sequences
614 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
616 $body = scale_external_images($body, false);
618 // Setting the object type if not defined before
620 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
621 require_once 'include/plaintext.php';
622 $objectdata = get_attached_data($body);
624 if ($objectdata["type"] == "link") {
625 $objecttype = ACTIVITY_OBJ_BOOKMARK;
626 } elseif ($objectdata["type"] == "video") {
627 $objecttype = ACTIVITY_OBJ_VIDEO;
628 } elseif ($objectdata["type"] == "photo") {
629 $objecttype = ACTIVITY_OBJ_IMAGE;
637 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
638 foreach ($match[2] as $mtch) {
639 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
640 intval($profile_uid),
643 if (DBM::is_result($r)) {
644 if (strlen($attachments)) {
647 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $r[0]['id'] . '" length="' . $r[0]['filesize'] . '" type="' . $r[0]['filetype'] . '" title="' . (($r[0]['filename']) ? $r[0]['filename'] : '') . '"[/attach]';
649 $body = str_replace($match[1],'',$body);
655 if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
659 if (!strlen($verb)) {
660 $verb = ACTIVITY_POST;
663 if ($network == "") {
664 $network = NETWORK_DFRN;
667 $gravity = ($parent ? 6 : 0);
669 // even if the post arrived via API we are considering that it
670 // originated on this site by default for determining relayability.
672 $origin = (x($_REQUEST, 'origin') ? intval($_REQUEST['origin']) : 1);
674 $notify_type = ($parent ? 'comment-new' : 'wall-new');
676 $uri = ($message_id ? $message_id : item_new_uri($a->get_hostname(), $profile_uid, $guid));
678 // Fallback so that we alway have a parent uri
679 if (!$parent_uri || !$parent) {
684 $datarray['uid'] = $profile_uid;
685 $datarray['type'] = $post_type;
686 $datarray['wall'] = $wall;
687 $datarray['gravity'] = $gravity;
688 $datarray['network'] = $network;
689 $datarray['contact-id'] = $contact_id;
690 $datarray['owner-name'] = $contact_record['name'];
691 $datarray['owner-link'] = $contact_record['url'];
692 $datarray['owner-avatar'] = $contact_record['thumb'];
693 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link'], 0);
694 $datarray['author-name'] = $author['name'];
695 $datarray['author-link'] = $author['url'];
696 $datarray['author-avatar'] = $author['thumb'];
697 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link'], 0);
698 $datarray['created'] = datetime_convert();
699 $datarray['edited'] = datetime_convert();
700 $datarray['commented'] = datetime_convert();
701 $datarray['received'] = datetime_convert();
702 $datarray['changed'] = datetime_convert();
703 $datarray['extid'] = $extid;
704 $datarray['guid'] = $guid;
705 $datarray['uri'] = $uri;
706 $datarray['title'] = $title;
707 $datarray['body'] = $body;
708 $datarray['app'] = $app;
709 $datarray['location'] = $location;
710 $datarray['coord'] = $coord;
711 $datarray['tag'] = $str_tags;
712 $datarray['file'] = $categories;
713 $datarray['inform'] = $inform;
714 $datarray['verb'] = $verb;
715 $datarray['object-type'] = $objecttype;
716 $datarray['allow_cid'] = $str_contact_allow;
717 $datarray['allow_gid'] = $str_group_allow;
718 $datarray['deny_cid'] = $str_contact_deny;
719 $datarray['deny_gid'] = $str_group_deny;
720 $datarray['private'] = $private;
721 $datarray['pubmail'] = $pubmail_enable;
722 $datarray['attach'] = $attachments;
723 $datarray['bookmark'] = intval($bookmark);
724 $datarray['parent-uri'] = $parent_uri;
725 $datarray['postopts'] = $postopts;
726 $datarray['origin'] = $origin;
727 $datarray['moderated'] = false;
728 $datarray['gcontact-id'] = GContact::getId(["url" => $datarray['author-link'], "network" => $datarray['network'],
729 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']]);
730 $datarray['object'] = $object;
733 * These fields are for the convenience of plugins...
734 * 'self' if true indicates the owner is posting on their own wall
735 * If parent is 0 it is a top-level post.
737 $datarray['parent'] = $parent;
738 $datarray['self'] = $self;
740 // This triggers posts via API and the mirror functions
741 $datarray['api_source'] = $api_source;
743 // This field is for storing the raw conversation data
744 $datarray['protocol'] = PROTOCOL_DFRN;
746 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
747 if (DBM::is_result($r)) {
748 if ($r['conversation-uri'] != '') {
749 $datarray['conversation-uri'] = $r['conversation-uri'];
751 if ($r['conversation-href'] != '') {
752 $datarray['conversation-href'] = $r['conversation-href'];
757 $datarray['edit'] = true;
760 // Search for hashtags
761 item_body_set_hashtags($datarray);
763 // preview mode - prepare the body for display and send it via json
765 require_once 'include/conversation.php';
766 // We set the datarray ID to -1 because in preview mode the dataray
767 // doesn't have an ID.
768 $datarray["id"] = -1;
769 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
770 logger('preview: ' . $o);
771 echo json_encode(['preview' => $o]);
775 call_hooks('post_local',$datarray);
777 if (x($datarray, 'cancel')) {
778 logger('mod_item: post cancelled by plugin.');
780 goaway($return_path);
783 $json = ['cancel' => 1];
784 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
785 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
788 echo json_encode($json);
794 // Fill the cache field
795 // This could be done in Item::update as well - but we have to check for the existance of some fields.
796 put_item_in_cache($datarray);
799 'title' => $datarray['title'],
800 'body' => $datarray['body'],
801 'tag' => $datarray['tag'],
802 'attach' => $datarray['attach'],
803 'file' => $datarray['file'],
804 'rendered-html' => $datarray['rendered-html'],
805 'rendered-hash' => $datarray['rendered-hash'],
806 'edited' => datetime_convert(),
807 'changed' => datetime_convert()];
809 Item::update($fields, ['id' => $post_id]);
811 // update filetags in pconfig
812 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
814 if (x($_REQUEST, 'return') && strlen($return_path)) {
815 logger('return: ' . $return_path);
816 goaway($return_path);
823 unset($datarray['edit']);
824 unset($datarray['self']);
825 unset($datarray['api_source']);
827 $post_id = item_store($datarray);
830 logger("Item wasn't stored.");
831 goaway($return_path);
834 $datarray = dba::selectFirst('item', [], ['id' => $post_id]);
836 if (!DBM::is_result($datarray)) {
837 logger("Item with id ".$post_id." couldn't be fetched.");
838 goaway($return_path);
841 // update filetags in pconfig
842 file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
844 // These notifications are sent if someone else is commenting other your wall
846 if ($contact_record != $author) {
848 'type' => NOTIFY_COMMENT,
849 'notify_flags' => $user['notify-flags'],
850 'language' => $user['language'],
851 'to_name' => $user['username'],
852 'to_email' => $user['email'],
853 'uid' => $user['uid'],
855 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
856 'source_name' => $datarray['author-name'],
857 'source_link' => $datarray['author-link'],
858 'source_photo' => $datarray['author-avatar'],
859 'verb' => ACTIVITY_POST,
862 'parent_uri' => $parent_item['uri']
866 // Store the comment signature information in case we need to relay to Diaspora
867 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
869 if (($contact_record != $author) && !count($forum_contact)) {
871 'type' => NOTIFY_WALL,
872 'notify_flags' => $user['notify-flags'],
873 'language' => $user['language'],
874 'to_name' => $user['username'],
875 'to_email' => $user['email'],
876 'uid' => $user['uid'],
878 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
879 'source_name' => $datarray['author-name'],
880 'source_link' => $datarray['author-link'],
881 'source_photo' => $datarray['author-avatar'],
882 'verb' => ACTIVITY_POST,
888 call_hooks('post_local_end', $datarray);
890 if (strlen($emailcc) && $profile_uid == local_user()) {
891 $erecips = explode(',', $emailcc);
892 if (count($erecips)) {
893 foreach ($erecips as $recip) {
894 $addr = trim($recip);
895 if (!strlen($addr)) {
898 $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
900 $disclaimer .= sprintf(t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
901 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
902 if (!$datarray['title']=='') {
903 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
905 $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8');
907 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
908 $html = prepare_body($datarray);
909 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
910 include_once 'include/html2plain.php';
912 'fromName' => $a->user['username'],
913 'fromEmail' => $a->user['email'],
915 'replyTo' => $a->user['email'],
916 'messageSubject' => $subject,
917 'htmlVersion' => $message,
918 'textVersion' => html2plain($html.$disclaimer)
920 Emailer::send($params);
925 // Insert an item entry for UID=0 for global entries.
926 // We now do it in the background to save some time.
927 // This is important in interactive environments like the frontend or the API.
928 // We don't fork a new process since this is done anyway with the following command
929 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
931 // Call the background process that is delivering the item to the receivers
932 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
934 logger('post_complete');
936 item_post_return(System::baseUrl(), $api_source, $return_path);
940 function item_post_return($baseurl, $api_source, $return_path) {
941 // figure out how to return, depending on from whence we came
948 goaway($return_path);
951 $json = ['success' => 1];
952 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
953 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
956 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
958 echo json_encode($json);
964 function item_content(App $a) {
966 if (!local_user() && !remote_user()) {
970 require_once 'include/security.php';
973 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
975 $o = Item::delete($a->argv[2]);
977 $o = drop_item($a->argv[2]);
980 // ajax return: [<item id>, 0 (no perm) | <owner id>]
981 echo json_encode([intval($a->argv[2]), intval($o)]);
989 * This function removes the tag $tag from the text $body and replaces it with
990 * the appropiate link.
992 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
993 * @param unknown_type $body the text to replace the tag in
994 * @param string $inform a comma-seperated string containing everybody to inform
995 * @param string $str_tags string to add the tag to
996 * @param integer $profile_uid
997 * @param string $tag the tag to replace
998 * @param string $network The network of the post
1000 * @return boolean true if replaced, false if not replaced
1002 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
1008 //is it a person tag?
1009 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
1010 $tag_type = substr($tag, 0, 1);
1011 //is it already replaced?
1012 if (strpos($tag, '[url=')) {
1013 //append tag to str_tags
1014 if (!stristr($str_tags, $tag)) {
1015 if (strlen($str_tags)) {
1021 // Checking for the alias that is used for OStatus
1022 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
1023 if (preg_match($pattern, $tag, $matches)) {
1025 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1026 normalise_link($matches[1]));
1027 if (!DBM::is_result($r)) {
1028 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1029 normalise_link($matches[1]));
1031 if (DBM::is_result($r)) {
1034 $data = Probe::uri($matches[1]);
1037 if ($data["alias"] != "") {
1038 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1039 if (!stristr($str_tags, $newtag)) {
1040 if (strlen($str_tags)) {
1043 $str_tags .= $newtag;
1051 //get the person's name
1052 $name = substr($tag, 1);
1054 // Sometimes the tag detection doesn't seem to work right
1055 // This is some workaround
1056 $nameparts = explode(" ", $name);
1057 $name = $nameparts[0];
1059 // Try to detect the contact in various ways
1060 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1061 // Is it in format @user@domain.tld or @http://domain.tld/...?
1063 // First check the contact table for the address
1064 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1065 WHERE `addr` = '%s' AND `uid` = %d AND
1066 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1069 intval($profile_uid),
1070 dbesc(NETWORK_OSTATUS)
1073 // Then check in the contact table for the url
1074 if (!DBM::is_result($r)) {
1075 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1076 WHERE `nurl` = '%s' AND `uid` = %d AND
1077 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1079 dbesc(normalise_link($name)),
1080 intval($profile_uid),
1081 dbesc(NETWORK_OSTATUS)
1085 // Then check in the global contacts for the address
1086 if (!DBM::is_result($r)) {
1087 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1088 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1091 dbesc(NETWORK_OSTATUS)
1095 // Then check in the global contacts for the url
1096 if (!DBM::is_result($r)) {
1097 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1098 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1100 dbesc(normalise_link($name)),
1101 dbesc(NETWORK_OSTATUS)
1105 if (!DBM::is_result($r)) {
1106 $probed = Probe::uri($name);
1107 if ($result['network'] != NETWORK_PHANTOM) {
1108 GContact::update($probed);
1109 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1110 dbesc(normalise_link($probed["url"])));
1115 if (strrpos($name, '+')) {
1116 // Is it in format @nick+number?
1117 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1119 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1121 intval($profile_uid)
1125 // select someone by attag or nick and the name passed in the current network
1126 if (!DBM::is_result($r) && ($network != ""))
1127 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `network` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1131 intval($profile_uid)
1134 //select someone from this user's contacts by name in the current network
1135 if (!DBM::is_result($r) && ($network != "")) {
1136 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1139 intval($profile_uid)
1143 // select someone by attag or nick and the name passed in
1144 if (!DBM::is_result($r)) {
1145 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `attag` = '%s' OR `nick` = '%s' AND `uid` = %d ORDER BY `attag` DESC LIMIT 1",
1148 intval($profile_uid)
1152 // select someone from this user's contacts by name
1153 if (!DBM::is_result($r)) {
1154 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1156 intval($profile_uid)
1161 if (DBM::is_result($r)) {
1162 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1166 if (isset($r[0]["id"])) {
1167 $inform .= 'cid:' . $r[0]["id"];
1168 } elseif (isset($r[0]["notify"])) {
1169 $inform .= $r[0]["notify"];
1172 $profile = $r[0]["url"];
1173 $alias = $r[0]["alias"];
1174 $newname = $r[0]["nick"];
1175 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1176 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1177 $newname = $r[0]["name"];
1181 //if there is an url for this persons profile
1182 if (isset($profile) && ($newname != "")) {
1184 // create profile link
1185 $profile = str_replace(',', '%2c', $profile);
1186 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1187 $body = str_replace($tag_type . $name, $newtag, $body);
1188 // append tag to str_tags
1189 if (!stristr($str_tags, $newtag)) {
1190 if (strlen($str_tags)) {
1193 $str_tags .= $newtag;
1197 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1198 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1200 if (strlen($alias)) {
1201 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1202 if (!stristr($str_tags, $newtag)) {
1203 if (strlen($str_tags)) {
1206 $str_tags .= $newtag;
1212 return ['replaced' => $replaced, 'contact' => $r[0]];