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\Addon;
19 use Friendica\Core\Config;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBM;
23 use Friendica\Model\Contact;
24 use Friendica\Model\GContact;
25 use Friendica\Model\Item;
26 use Friendica\Network\Probe;
27 use Friendica\Protocol\Diaspora;
28 use Friendica\Protocol\Email;
29 use Friendica\Util\Emailer;
31 require_once 'include/enotify.php';
32 require_once 'include/tags.php';
33 require_once 'include/threads.php';
34 require_once 'include/text.php';
35 require_once 'include/items.php';
37 function item_post(App $a) {
38 if (!local_user() && !remote_user()) {
42 require_once 'include/security.php';
46 if (x($_REQUEST, 'dropitems')) {
47 $arr_drop = explode(',', $_REQUEST['dropitems']);
48 drop_items($arr_drop);
49 $json = ['success' => 1];
50 echo json_encode($json);
54 Addon::callHooks('post_local_start', $_REQUEST);
55 // logger('postinput ' . file_get_contents('php://input'));
56 logger('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
58 $api_source = x($_REQUEST, 'api_source') && $_REQUEST['api_source'];
60 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
62 $return_path = (x($_REQUEST, 'return') ? $_REQUEST['return'] : '');
63 $preview = (x($_REQUEST, 'preview') ? intval($_REQUEST['preview']) : 0);
66 * Check for doubly-submitted posts, and reject duplicates
67 * Note that we have to ignore previews, otherwise nothing will post
68 * after it's been previewed
70 if (!$preview && x($_REQUEST, 'post_id_random')) {
71 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
72 logger("item post: duplicate post", LOGGER_DEBUG);
73 item_post_return(System::baseUrl(), $api_source, $return_path);
75 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
79 // Is this a reply to something?
80 $parent = (x($_REQUEST, 'parent') ? intval($_REQUEST['parent']) : 0);
81 $parent_uri = (x($_REQUEST, 'parent_uri') ? trim($_REQUEST['parent_uri']) : '');
84 $parent_contact = null;
90 if ($parent || $parent_uri) {
92 $objecttype = ACTIVITY_OBJ_COMMENT;
94 if (!x($_REQUEST, 'type')) {
95 $_REQUEST['type'] = 'net-comment';
99 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
102 } elseif ($parent_uri && local_user()) {
103 // This is coming from an API source, and we are logged in
104 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
109 // if this isn't the real parent of the conversation, find it
110 if (DBM::is_result($r)) {
111 $parid = $r[0]['parent'];
112 if ($r[0]['id'] != $r[0]['parent']) {
113 $r = q("SELECT * FROM `item` WHERE `id` = `parent` AND `parent` = %d LIMIT 1",
120 if (!DBM::is_result($r)) {
121 notice(t('Unable to locate original post.') . EOL);
122 if (x($_REQUEST, 'return')) {
123 goaway($return_path);
127 $parent_item = $r[0];
128 $parent = $parent_item['id'];
129 $parent_uri = $parent_item['uri'];
130 $parent_user = $parent_item['uid'];
132 if ($parent_item['contact-id']) {
133 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
134 intval($parent_item['contact-id'])
136 if (DBM::is_result($r)) {
137 $parent_contact = $r[0];
140 // If the contact id doesn't fit with the contact, then set the contact to null
141 $thrparent = q("SELECT `author-link`, `network` FROM `item` WHERE `uri` = '%s' LIMIT 1", dbesc($parent_uri));
142 if (DBM::is_result($thrparent) && ($thrparent[0]["network"] === NETWORK_OSTATUS)
143 && (normalise_link($parent_contact["url"]) != normalise_link($thrparent[0]["author-link"]))) {
144 $parent_contact = Contact::getDetailsByURL($thrparent[0]["author-link"]);
146 if (!isset($parent_contact["nick"])) {
147 $probed_contact = Probe::uri($thrparent[0]["author-link"]);
148 if ($probed_contact["network"] != NETWORK_FEED) {
149 $parent_contact = $probed_contact;
150 $parent_contact["nurl"] = normalise_link($probed_contact["url"]);
151 $parent_contact["thumb"] = $probed_contact["photo"];
152 $parent_contact["micro"] = $probed_contact["photo"];
153 $parent_contact["addr"] = $probed_contact["addr"];
156 logger('no contact found: ' . print_r($thrparent, true), LOGGER_DEBUG);
158 logger('parent contact: ' . print_r($parent_contact, true), LOGGER_DEBUG);
161 if ($parent_contact["nick"] == "") {
162 $parent_contact["nick"] = $parent_contact["name"];
168 logger('mod_item: item_post parent=' . $parent);
171 $profile_uid = (x($_REQUEST, 'profile_uid') ? intval($_REQUEST['profile_uid']) : 0);
172 $post_id = (x($_REQUEST, 'post_id') ? intval($_REQUEST['post_id']) : 0);
173 $app = (x($_REQUEST, 'source') ? strip_tags($_REQUEST['source']) : '');
174 $extid = (x($_REQUEST, 'extid') ? strip_tags($_REQUEST['extid']) : '');
175 $object = (x($_REQUEST, 'object') ? $_REQUEST['object'] : '');
177 // Ensure that the user id in a thread always stay the same
178 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
179 $profile_uid = $parent_user;
182 // Check for multiple posts with the same message id (when the post was created via API)
183 if (($message_id != '') && ($profile_uid != 0)) {
184 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
189 if (DBM::is_result($r)) {
190 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
195 // Allow commenting if it is an answer to a public post
196 $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
198 // Now check that valid personal details have been provided
199 if (!can_write_wall($profile_uid) && !$allow_comment) {
200 notice(t('Permission denied.') . EOL) ;
201 if (x($_REQUEST, 'return')) {
202 goaway($return_path);
208 // is this an edited post?
213 $i = q("SELECT * FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
214 intval($profile_uid),
217 if (!DBM::is_result($i)) {
225 $r = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
228 if (DBM::is_result($r)) {
233 $str_group_allow = $orig_post['allow_gid'];
234 $str_contact_allow = $orig_post['allow_cid'];
235 $str_group_deny = $orig_post['deny_gid'];
236 $str_contact_deny = $orig_post['deny_cid'];
237 $location = $orig_post['location'];
238 $coord = $orig_post['coord'];
239 $verb = $orig_post['verb'];
240 $objecttype = $orig_post['object-type'];
241 $emailcc = $orig_post['emailcc'];
242 $app = $orig_post['app'];
243 $categories = $orig_post['file'];
244 $title = notags(trim($_REQUEST['title']));
245 $body = escape_tags(trim($_REQUEST['body']));
246 $private = $orig_post['private'];
247 $pubmail_enable = $orig_post['pubmail'];
248 $network = $orig_post['network'];
249 $guid = $orig_post['guid'];
250 $extid = $orig_post['extid'];
255 * if coming from the API and no privacy settings are set,
256 * use the user default permissions - as they won't have
257 * been supplied via a form.
259 /// @TODO use x($_REQUEST, 'foo') here
261 && !array_key_exists('contact_allow', $_REQUEST)
262 && !array_key_exists('group_allow', $_REQUEST)
263 && !array_key_exists('contact_deny', $_REQUEST)
264 && !array_key_exists('group_deny', $_REQUEST)) {
265 $str_group_allow = $user['allow_gid'];
266 $str_contact_allow = $user['allow_cid'];
267 $str_group_deny = $user['deny_gid'];
268 $str_contact_deny = $user['deny_cid'];
271 // use the posted permissions
273 $str_group_allow = perms2str($_REQUEST['group_allow']);
274 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
275 $str_group_deny = perms2str($_REQUEST['group_deny']);
276 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
279 $title = notags(trim($_REQUEST['title']));
280 $location = notags(trim($_REQUEST['location']));
281 $coord = notags(trim($_REQUEST['coord']));
282 $verb = notags(trim($_REQUEST['verb']));
283 $emailcc = notags(trim($_REQUEST['emailcc']));
284 $body = escape_tags(trim($_REQUEST['body']));
285 $network = notags(trim($_REQUEST['network']));
286 $guid = get_guid(32);
288 item_add_language_opt($_REQUEST);
289 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
291 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
293 if ($user['hidewall']) {
297 // If this is a comment, set the permissions from the parent.
301 // for non native networks use the network of the original post as network of the item
302 if (($parent_item['network'] != NETWORK_DIASPORA)
303 && ($parent_item['network'] != NETWORK_OSTATUS)
304 && ($network == "")) {
305 $network = $parent_item['network'];
308 $str_contact_allow = $parent_item['allow_cid'];
309 $str_group_allow = $parent_item['allow_gid'];
310 $str_contact_deny = $parent_item['deny_cid'];
311 $str_group_deny = $parent_item['deny_gid'];
312 $private = $parent_item['private'];
315 $pubmail_enable = ((x($_REQUEST, 'pubmail_enable') && intval($_REQUEST['pubmail_enable']) && !$private) ? 1 : 0);
317 // if using the API, we won't see pubmail_enable - figure out if it should be set
319 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
320 $mail_disabled = ((function_exists('imap_open') && !Config::get('system', 'imap_disabled')) ? 0 : 1);
321 if (!$mail_disabled) {
322 /// @TODO Check if only pubmail is loaded, * loads all columns
323 $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
326 if (DBM::is_result($r) && intval($r[0]['pubmail'])) {
327 $pubmail_enabled = true;
332 if (!strlen($body)) {
336 info(t('Empty post discarded.') . EOL);
337 if (x($_REQUEST, 'return')) {
338 goaway($return_path);
344 if (strlen($categories)) {
345 // get the "fileas" tags for this post
346 $filedas = file_tag_file_to_list($categories, 'file');
348 // save old and new categories, so we can determine what needs to be deleted from pconfig
349 $categories_old = $categories;
350 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
351 $categories_new = $categories;
352 if (strlen($filedas)) {
353 // append the fileas stuff to the new categories list
354 $categories .= file_tag_list_to_file($filedas, 'file');
357 // get contact info for poster
363 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
365 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
366 intval($_SESSION['uid']));
367 } elseif (remote_user()) {
368 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
369 foreach ($_SESSION['remote'] as $v) {
370 if ($v['uid'] == $profile_uid) {
371 $contact_id = $v['cid'];
377 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
383 if (DBM::is_result($r)) {
385 $contact_id = $author['id'];
388 // get contact info for owner
390 if ($profile_uid == local_user() || $allow_comment) {
391 $contact_record = $author;
393 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
396 if (DBM::is_result($r)) {
397 $contact_record = $r[0];
401 $post_type = notags(trim($_REQUEST['type']));
403 if ($post_type === 'net-comment' && $parent_item !== null) {
404 if ($parent_item['wall'] == 1) {
405 $post_type = 'wall-comment';
407 $post_type = 'remote-comment';
411 // Look for any tags and linkify them
415 $tags = get_tags($body);
418 * add a statusnet style reply tag if the original post was from there
419 * and we are replying, and there isn't one already
421 if ($parent && ($parent_contact['network'] == NETWORK_OSTATUS)) {
422 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
424 if (!in_array($contact, $tags)) {
425 $body = $contact . ' ' . $body;
429 $toplevel_contact = "";
430 $toplevel_parent = q("SELECT `contact`.* FROM `contact`
431 INNER JOIN `item` ON `item`.`contact-id` = `contact`.`id` AND `contact`.`url` = `item`.`author-link`
432 WHERE `item`.`id` = `item`.`parent` AND `item`.`parent` = %d", intval($parent));
433 if (DBM::is_result($toplevel_parent)) {
434 if (!empty($toplevel_parent[0]['addr'])) {
435 $toplevel_contact = '@' . $toplevel_parent[0]['addr'];
437 $toplevel_contact = '@' . $toplevel_parent[0]['nick'] . '+' . $toplevel_parent[0]['id'];
440 $toplevel_parent = q("SELECT `author-link`, `author-name` FROM `item` WHERE `id` = `parent` AND `parent` = %d", intval($parent));
441 $toplevel_contact = '@[url=' . $toplevel_parent[0]['author-link'] . ']' . $toplevel_parent[0]['author-name'] . '[/url]';
444 if (!in_array($toplevel_contact, $tags)) {
445 $tags[] = $toplevel_contact;
451 $private_forum = false;
452 $only_to_forum = false;
456 foreach ($tags as $tag) {
458 $tag_type = substr($tag, 0, 1);
460 if ($tag_type == '#') {
465 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
466 * Robert Johnson should be first in the $tags array
468 $fullnametagged = false;
469 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
470 foreach ($tagged as $nextTag) {
471 if (stristr($nextTag, $tag . ' ')) {
472 $fullnametagged = true;
476 if ($fullnametagged) {
480 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
481 if ($success['replaced']) {
484 // When the forum is private or the forum is addressed with a "!" make the post private
485 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
486 $private_forum = $success['contact']['prv'];
487 $only_to_forum = ($tag_type == '!');
488 $private_id = $success['contact']['id'];
489 $forum_contact = $success['contact'];
490 } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
491 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
492 $private_forum = false;
493 $only_to_forum = true;
494 $private_id = $success['contact']['id'];
495 $forum_contact = $success['contact'];
500 $original_contact_id = $contact_id;
502 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
503 // we tagged a forum in a top level post. Now we change the post
504 $private = $private_forum;
506 $str_group_allow = '';
507 $str_contact_deny = '';
508 $str_group_deny = '';
509 if ($private_forum) {
510 $str_contact_allow = '<' . $private_id . '>';
512 $str_contact_allow = '';
514 $contact_id = $private_id;
515 $contact_record = $forum_contact;
516 $_REQUEST['origin'] = false;
520 * When a photo was uploaded into the message using the (profile wall) ajax
521 * uploader, The permissions are initially set to disallow anybody but the
522 * owner from seeing it. This is because the permissions may not yet have been
523 * set for the post. If it's private, the photo permissions should be set
524 * appropriately. But we didn't know the final permissions on the post until
525 * now. So now we'll look for links of uploaded messages that are in the
526 * post and set them to the same permissions as the post itself.
531 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
533 if (count($images)) {
535 $objecttype = ACTIVITY_OBJ_IMAGE;
537 foreach ($images as $image) {
538 if (!stristr($image, System::baseUrl() . '/photo/')) {
541 $image_uri = substr($image,strrpos($image,'/') + 1);
542 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
543 if (!strlen($image_uri)) {
546 $srch = '<' . intval($original_contact_id) . '>';
548 $r = q("SELECT `id` FROM `photo` WHERE `allow_cid` = '%s' AND `allow_gid` = '' AND `deny_cid` = '' AND `deny_gid` = ''
549 AND `resource-id` = '%s' AND `uid` = %d LIMIT 1",
555 if (!DBM::is_result($r)) {
559 $r = q("UPDATE `photo` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
560 WHERE `resource-id` = '%s' AND `uid` = %d AND `album` = '%s' ",
561 dbesc($str_contact_allow),
562 dbesc($str_group_allow),
563 dbesc($str_contact_deny),
564 dbesc($str_group_deny),
566 intval($profile_uid),
567 dbesc(t('Wall Photos'))
575 * Next link in any attachment references we find in the post.
579 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
580 $attaches = $match[1];
581 if (count($attaches)) {
582 foreach ($attaches as $attach) {
583 $r = q("SELECT * FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
584 intval($profile_uid),
587 if (DBM::is_result($r)) {
588 $r = q("UPDATE `attach` SET `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s'
589 WHERE `uid` = %d AND `id` = %d",
590 dbesc($str_contact_allow),
591 dbesc($str_group_allow),
592 dbesc($str_contact_deny),
593 dbesc($str_group_deny),
594 intval($profile_uid),
602 // embedded bookmark or attachment in post? set bookmark flag
605 $data = get_attachment_data($body);
606 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
607 $objecttype = ACTIVITY_OBJ_BOOKMARK;
611 $body = bb_translate_video($body);
614 // Fold multi-line [code] sequences
615 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
617 $body = scale_external_images($body, false);
619 // Setting the object type if not defined before
621 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
622 require_once 'include/plaintext.php';
623 $objectdata = get_attached_data($body);
625 if ($objectdata["type"] == "link") {
626 $objecttype = ACTIVITY_OBJ_BOOKMARK;
627 } elseif ($objectdata["type"] == "video") {
628 $objecttype = ACTIVITY_OBJ_VIDEO;
629 } elseif ($objectdata["type"] == "photo") {
630 $objecttype = ACTIVITY_OBJ_IMAGE;
638 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
639 foreach ($match[2] as $mtch) {
640 $r = q("SELECT `id`,`filename`,`filesize`,`filetype` FROM `attach` WHERE `uid` = %d AND `id` = %d LIMIT 1",
641 intval($profile_uid),
644 if (DBM::is_result($r)) {
645 if (strlen($attachments)) {
648 $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]';
650 $body = str_replace($match[1],'',$body);
656 if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
660 if (!strlen($verb)) {
661 $verb = ACTIVITY_POST;
664 if ($network == "") {
665 $network = NETWORK_DFRN;
668 $gravity = ($parent ? 6 : 0);
670 // even if the post arrived via API we are considering that it
671 // originated on this site by default for determining relayability.
673 $origin = (x($_REQUEST, 'origin') ? intval($_REQUEST['origin']) : 1);
675 $notify_type = ($parent ? 'comment-new' : 'wall-new');
677 $uri = ($message_id ? $message_id : item_new_uri($a->get_hostname(), $profile_uid, $guid));
679 // Fallback so that we alway have a parent uri
680 if (!$parent_uri || !$parent) {
685 $datarray['uid'] = $profile_uid;
686 $datarray['type'] = $post_type;
687 $datarray['wall'] = $wall;
688 $datarray['gravity'] = $gravity;
689 $datarray['network'] = $network;
690 $datarray['contact-id'] = $contact_id;
691 $datarray['owner-name'] = $contact_record['name'];
692 $datarray['owner-link'] = $contact_record['url'];
693 $datarray['owner-avatar'] = $contact_record['thumb'];
694 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link'], 0);
695 $datarray['author-name'] = $author['name'];
696 $datarray['author-link'] = $author['url'];
697 $datarray['author-avatar'] = $author['thumb'];
698 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link'], 0);
699 $datarray['created'] = datetime_convert();
700 $datarray['edited'] = datetime_convert();
701 $datarray['commented'] = datetime_convert();
702 $datarray['received'] = datetime_convert();
703 $datarray['changed'] = datetime_convert();
704 $datarray['extid'] = $extid;
705 $datarray['guid'] = $guid;
706 $datarray['uri'] = $uri;
707 $datarray['title'] = $title;
708 $datarray['body'] = $body;
709 $datarray['app'] = $app;
710 $datarray['location'] = $location;
711 $datarray['coord'] = $coord;
712 $datarray['tag'] = $str_tags;
713 $datarray['file'] = $categories;
714 $datarray['inform'] = $inform;
715 $datarray['verb'] = $verb;
716 $datarray['object-type'] = $objecttype;
717 $datarray['allow_cid'] = $str_contact_allow;
718 $datarray['allow_gid'] = $str_group_allow;
719 $datarray['deny_cid'] = $str_contact_deny;
720 $datarray['deny_gid'] = $str_group_deny;
721 $datarray['private'] = $private;
722 $datarray['pubmail'] = $pubmail_enable;
723 $datarray['attach'] = $attachments;
724 $datarray['bookmark'] = intval($bookmark);
725 $datarray['parent-uri'] = $parent_uri;
726 $datarray['postopts'] = $postopts;
727 $datarray['origin'] = $origin;
728 $datarray['moderated'] = false;
729 $datarray['gcontact-id'] = GContact::getId(["url" => $datarray['author-link'], "network" => $datarray['network'],
730 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']]);
731 $datarray['object'] = $object;
734 * These fields are for the convenience of addons...
735 * 'self' if true indicates the owner is posting on their own wall
736 * If parent is 0 it is a top-level post.
738 $datarray['parent'] = $parent;
739 $datarray['self'] = $self;
741 // This triggers posts via API and the mirror functions
742 $datarray['api_source'] = $api_source;
744 // This field is for storing the raw conversation data
745 $datarray['protocol'] = PROTOCOL_DFRN;
747 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
748 if (DBM::is_result($r)) {
749 if ($r['conversation-uri'] != '') {
750 $datarray['conversation-uri'] = $r['conversation-uri'];
752 if ($r['conversation-href'] != '') {
753 $datarray['conversation-href'] = $r['conversation-href'];
758 $datarray['edit'] = true;
761 // Search for hashtags
762 item_body_set_hashtags($datarray);
764 // preview mode - prepare the body for display and send it via json
766 require_once 'include/conversation.php';
767 // We set the datarray ID to -1 because in preview mode the dataray
768 // doesn't have an ID.
769 $datarray["id"] = -1;
770 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
771 logger('preview: ' . $o);
772 echo json_encode(['preview' => $o]);
776 Addon::callHooks('post_local',$datarray);
778 if (x($datarray, 'cancel')) {
779 logger('mod_item: post cancelled by addon.');
781 goaway($return_path);
784 $json = ['cancel' => 1];
785 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
786 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
789 echo json_encode($json);
795 // Fill the cache field
796 // This could be done in Item::update as well - but we have to check for the existance of some fields.
797 put_item_in_cache($datarray);
800 'title' => $datarray['title'],
801 'body' => $datarray['body'],
802 'tag' => $datarray['tag'],
803 'attach' => $datarray['attach'],
804 'file' => $datarray['file'],
805 'rendered-html' => $datarray['rendered-html'],
806 'rendered-hash' => $datarray['rendered-hash'],
807 'edited' => datetime_convert(),
808 'changed' => datetime_convert()];
810 Item::update($fields, ['id' => $post_id]);
812 // update filetags in pconfig
813 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
815 if (x($_REQUEST, 'return') && strlen($return_path)) {
816 logger('return: ' . $return_path);
817 goaway($return_path);
824 unset($datarray['edit']);
825 unset($datarray['self']);
826 unset($datarray['api_source']);
828 $post_id = item_store($datarray);
831 logger("Item wasn't stored.");
832 goaway($return_path);
835 $datarray = dba::selectFirst('item', [], ['id' => $post_id]);
837 if (!DBM::is_result($datarray)) {
838 logger("Item with id ".$post_id." couldn't be fetched.");
839 goaway($return_path);
842 // update filetags in pconfig
843 file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
845 // These notifications are sent if someone else is commenting other your wall
847 if ($contact_record != $author) {
849 'type' => NOTIFY_COMMENT,
850 'notify_flags' => $user['notify-flags'],
851 'language' => $user['language'],
852 'to_name' => $user['username'],
853 'to_email' => $user['email'],
854 'uid' => $user['uid'],
856 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
857 'source_name' => $datarray['author-name'],
858 'source_link' => $datarray['author-link'],
859 'source_photo' => $datarray['author-avatar'],
860 'verb' => ACTIVITY_POST,
863 'parent_uri' => $parent_item['uri']
867 // Store the comment signature information in case we need to relay to Diaspora
868 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
870 if (($contact_record != $author) && !count($forum_contact)) {
872 'type' => NOTIFY_WALL,
873 'notify_flags' => $user['notify-flags'],
874 'language' => $user['language'],
875 'to_name' => $user['username'],
876 'to_email' => $user['email'],
877 'uid' => $user['uid'],
879 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
880 'source_name' => $datarray['author-name'],
881 'source_link' => $datarray['author-link'],
882 'source_photo' => $datarray['author-avatar'],
883 'verb' => ACTIVITY_POST,
889 Addon::callHooks('post_local_end', $datarray);
891 if (strlen($emailcc) && $profile_uid == local_user()) {
892 $erecips = explode(',', $emailcc);
893 if (count($erecips)) {
894 foreach ($erecips as $recip) {
895 $addr = trim($recip);
896 if (!strlen($addr)) {
899 $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
901 $disclaimer .= sprintf(t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
902 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
903 if (!$datarray['title']=='') {
904 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
906 $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8');
908 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
909 $html = prepare_body($datarray);
910 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
911 include_once 'include/html2plain.php';
913 'fromName' => $a->user['username'],
914 'fromEmail' => $a->user['email'],
916 'replyTo' => $a->user['email'],
917 'messageSubject' => $subject,
918 'htmlVersion' => $message,
919 'textVersion' => html2plain($html.$disclaimer)
921 Emailer::send($params);
926 // Insert an item entry for UID=0 for global entries.
927 // We now do it in the background to save some time.
928 // This is important in interactive environments like the frontend or the API.
929 // We don't fork a new process since this is done anyway with the following command
930 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
932 // Call the background process that is delivering the item to the receivers
933 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
935 logger('post_complete');
937 item_post_return(System::baseUrl(), $api_source, $return_path);
941 function item_post_return($baseurl, $api_source, $return_path) {
942 // figure out how to return, depending on from whence we came
949 goaway($return_path);
952 $json = ['success' => 1];
953 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
954 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
957 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
959 echo json_encode($json);
965 function item_content(App $a) {
967 if (!local_user() && !remote_user()) {
971 require_once 'include/security.php';
974 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
976 $o = Item::delete($a->argv[2]);
978 $o = drop_item($a->argv[2]);
981 // ajax return: [<item id>, 0 (no perm) | <owner id>]
982 echo json_encode([intval($a->argv[2]), intval($o)]);
990 * This function removes the tag $tag from the text $body and replaces it with
991 * the appropiate link.
993 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
994 * @param unknown_type $body the text to replace the tag in
995 * @param string $inform a comma-seperated string containing everybody to inform
996 * @param string $str_tags string to add the tag to
997 * @param integer $profile_uid
998 * @param string $tag the tag to replace
999 * @param string $network The network of the post
1001 * @return boolean true if replaced, false if not replaced
1003 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
1009 //is it a person tag?
1010 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
1011 $tag_type = substr($tag, 0, 1);
1012 //is it already replaced?
1013 if (strpos($tag, '[url=')) {
1014 //append tag to str_tags
1015 if (!stristr($str_tags, $tag)) {
1016 if (strlen($str_tags)) {
1022 // Checking for the alias that is used for OStatus
1023 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
1024 if (preg_match($pattern, $tag, $matches)) {
1026 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
1027 normalise_link($matches[1]));
1028 if (!DBM::is_result($r)) {
1029 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
1030 normalise_link($matches[1]));
1032 if (DBM::is_result($r)) {
1035 $data = Probe::uri($matches[1]);
1038 if ($data["alias"] != "") {
1039 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
1040 if (!stristr($str_tags, $newtag)) {
1041 if (strlen($str_tags)) {
1044 $str_tags .= $newtag;
1052 //get the person's name
1053 $name = substr($tag, 1);
1055 // Sometimes the tag detection doesn't seem to work right
1056 // This is some workaround
1057 $nameparts = explode(" ", $name);
1058 $name = $nameparts[0];
1060 // Try to detect the contact in various ways
1061 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
1062 // Is it in format @user@domain.tld or @http://domain.tld/...?
1064 // First check the contact table for the address
1065 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1066 WHERE `addr` = '%s' AND `uid` = %d AND
1067 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1070 intval($profile_uid),
1071 dbesc(NETWORK_OSTATUS)
1074 // Then check in the contact table for the url
1075 if (!DBM::is_result($r)) {
1076 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
1077 WHERE `nurl` = '%s' AND `uid` = %d AND
1078 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1080 dbesc(normalise_link($name)),
1081 intval($profile_uid),
1082 dbesc(NETWORK_OSTATUS)
1086 // Then check in the global contacts for the address
1087 if (!DBM::is_result($r)) {
1088 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1089 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1092 dbesc(NETWORK_OSTATUS)
1096 // Then check in the global contacts for the url
1097 if (!DBM::is_result($r)) {
1098 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
1099 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
1101 dbesc(normalise_link($name)),
1102 dbesc(NETWORK_OSTATUS)
1106 if (!DBM::is_result($r)) {
1107 $probed = Probe::uri($name);
1108 if ($result['network'] != NETWORK_PHANTOM) {
1109 GContact::update($probed);
1110 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1111 dbesc(normalise_link($probed["url"])));
1116 if (strrpos($name, '+')) {
1117 // Is it in format @nick+number?
1118 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1120 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1122 intval($profile_uid)
1126 // select someone by attag or nick and the name passed in the current network
1127 if (!DBM::is_result($r) && ($network != ""))
1128 $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",
1132 intval($profile_uid)
1135 //select someone from this user's contacts by name in the current network
1136 if (!DBM::is_result($r) && ($network != "")) {
1137 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1140 intval($profile_uid)
1144 // select someone by attag or nick and the name passed in
1145 if (!DBM::is_result($r)) {
1146 $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",
1149 intval($profile_uid)
1153 // select someone from this user's contacts by name
1154 if (!DBM::is_result($r)) {
1155 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1157 intval($profile_uid)
1162 if (DBM::is_result($r)) {
1163 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1167 if (isset($r[0]["id"])) {
1168 $inform .= 'cid:' . $r[0]["id"];
1169 } elseif (isset($r[0]["notify"])) {
1170 $inform .= $r[0]["notify"];
1173 $profile = $r[0]["url"];
1174 $alias = $r[0]["alias"];
1175 $newname = $r[0]["nick"];
1176 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1177 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1178 $newname = $r[0]["name"];
1182 //if there is an url for this persons profile
1183 if (isset($profile) && ($newname != "")) {
1185 // create profile link
1186 $profile = str_replace(',', '%2c', $profile);
1187 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1188 $body = str_replace($tag_type . $name, $newtag, $body);
1189 // append tag to str_tags
1190 if (!stristr($str_tags, $newtag)) {
1191 if (strlen($str_tags)) {
1194 $str_tags .= $newtag;
1198 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1199 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1201 if (strlen($alias)) {
1202 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1203 if (!stristr($str_tags, $newtag)) {
1204 if (strlen($str_tags)) {
1207 $str_tags .= $newtag;
1213 return ['replaced' => $replaced, 'contact' => $r[0]];