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('postvars ' . print_r($_REQUEST,true), LOGGER_DATA);
56 $api_source = defaults($_REQUEST, 'api_source', false);
58 $message_id = ((x($_REQUEST, 'message_id') && $api_source) ? strip_tags($_REQUEST['message_id']) : '');
60 $return_path = defaults($_REQUEST, 'return', '');
61 $preview = intval(defaults($_REQUEST, 'preview', 0));
64 * Check for doubly-submitted posts, and reject duplicates
65 * Note that we have to ignore previews, otherwise nothing will post
66 * after it's been previewed
68 if (!$preview && x($_REQUEST, 'post_id_random')) {
69 if (x($_SESSION, 'post-random') && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
70 logger("item post: duplicate post", LOGGER_DEBUG);
71 item_post_return(System::baseUrl(), $api_source, $return_path);
73 $_SESSION['post-random'] = $_REQUEST['post_id_random'];
77 // Is this a reply to something?
78 $thr_parent = intval(defaults($_REQUEST, 'parent', 0));
79 $thr_parent_uri = trim(defaults($_REQUEST, 'parent_uri', ''));
81 $thr_parent_contact = null;
87 $parent_contact = null;
90 $profile_uid = defaults($_REQUEST, 'profile_uid', local_user());
92 if ($thr_parent || $thr_parent_uri) {
94 $parent_item = dba::selectFirst('item', [], ['id' => $thr_parent]);
95 } elseif ($thr_parent_uri) {
96 $parent_item = dba::selectFirst('item', [], ['uri' => $thr_parent_uri, 'uid' => $profile_uid]);
99 // if this isn't the real parent of the conversation, find it
100 if (DBM::is_result($parent_item)) {
102 // The URI and the contact is taken from the direct parent which needn't to be the top parent
103 $thr_parent_uri = $parent_item['uri'];
104 $thr_parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
106 if ($parent_item['id'] != $parent_item['parent']) {
107 $parent_item = dba::selectFirst('item', [], ['id' => $parent_item['parent']]);
111 if (!DBM::is_result($parent_item)) {
112 notice(t('Unable to locate original post.') . EOL);
113 if (x($_REQUEST, 'return')) {
114 goaway($return_path);
119 $parent = $parent_item['id'];
120 $parent_user = $parent_item['uid'];
122 $parent_contact = Contact::getDetailsByURL($parent_item["author-link"]);
124 $objecttype = ACTIVITY_OBJ_COMMENT;
126 if (!x($_REQUEST, 'type')) {
127 $_REQUEST['type'] = 'net-comment';
132 logger('mod_item: item_post parent=' . $parent);
135 $post_id = intval(defaults($_REQUEST, 'post_id', 0));
136 $app = strip_tags(defaults($_REQUEST, 'source', ''));
137 $extid = strip_tags(defaults($_REQUEST, 'extid', ''));
138 $object = defaults($_REQUEST, 'object', '');
140 // Ensure that the user id in a thread always stay the same
141 if (!is_null($parent_user) && in_array($parent_user, [local_user(), 0])) {
142 $profile_uid = $parent_user;
145 // Check for multiple posts with the same message id (when the post was created via API)
146 if (($message_id != '') && ($profile_uid != 0)) {
147 if (dba::exists('item', ['uri' => $message_id, 'uid' => $profile_uid])) {
148 logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG);
153 // Allow commenting if it is an answer to a public post
154 $allow_comment = local_user() && ($profile_uid == 0) && $parent && in_array($parent_item['network'], [NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_DFRN]);
156 // Now check that valid personal details have been provided
157 if (!can_write_wall($profile_uid) && !$allow_comment) {
158 notice(t('Permission denied.') . EOL) ;
159 if (x($_REQUEST, 'return')) {
160 goaway($return_path);
166 // is this an edited post?
171 $orig_post = dba::selectFirst('item', [], ['id' => $post_id]);
174 $user = dba::selectFirst('user', [], ['uid' => $profile_uid]);
175 if (!DBM::is_result($user) && !$orig_post) {
180 $str_group_allow = $orig_post['allow_gid'];
181 $str_contact_allow = $orig_post['allow_cid'];
182 $str_group_deny = $orig_post['deny_gid'];
183 $str_contact_deny = $orig_post['deny_cid'];
184 $location = $orig_post['location'];
185 $coord = $orig_post['coord'];
186 $verb = $orig_post['verb'];
187 $objecttype = $orig_post['object-type'];
188 $emailcc = $orig_post['emailcc'];
189 $app = $orig_post['app'];
190 $categories = $orig_post['file'];
191 $title = notags(trim($_REQUEST['title']));
192 $body = escape_tags(trim($_REQUEST['body']));
193 $private = $orig_post['private'];
194 $pubmail_enabled = $orig_post['pubmail'];
195 $network = $orig_post['network'];
196 $guid = $orig_post['guid'];
197 $extid = $orig_post['extid'];
202 * if coming from the API and no privacy settings are set,
203 * use the user default permissions - as they won't have
204 * been supplied via a form.
206 /// @TODO use x($_REQUEST, 'foo') here
208 && !array_key_exists('contact_allow', $_REQUEST)
209 && !array_key_exists('group_allow', $_REQUEST)
210 && !array_key_exists('contact_deny', $_REQUEST)
211 && !array_key_exists('group_deny', $_REQUEST)) {
212 $str_group_allow = $user['allow_gid'];
213 $str_contact_allow = $user['allow_cid'];
214 $str_group_deny = $user['deny_gid'];
215 $str_contact_deny = $user['deny_cid'];
217 // use the posted permissions
218 $str_group_allow = perms2str($_REQUEST['group_allow']);
219 $str_contact_allow = perms2str($_REQUEST['contact_allow']);
220 $str_group_deny = perms2str($_REQUEST['group_deny']);
221 $str_contact_deny = perms2str($_REQUEST['contact_deny']);
224 $title = notags(trim($_REQUEST['title']));
225 $location = notags(trim($_REQUEST['location']));
226 $coord = notags(trim($_REQUEST['coord']));
227 $verb = notags(trim($_REQUEST['verb']));
228 $emailcc = notags(trim($_REQUEST['emailcc']));
229 $body = escape_tags(trim($_REQUEST['body']));
230 $network = notags(trim($_REQUEST['network']));
231 $guid = get_guid(32);
233 item_add_language_opt($_REQUEST);
234 $postopts = $_REQUEST['postopts'] ? $_REQUEST['postopts'] : "";
236 $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0);
238 if ($user['hidewall']) {
242 // If this is a comment, set the permissions from the parent.
246 // for non native networks use the network of the original post as network of the item
247 if (($parent_item['network'] != NETWORK_DIASPORA)
248 && ($parent_item['network'] != NETWORK_OSTATUS)
249 && ($network == "")) {
250 $network = $parent_item['network'];
253 $str_contact_allow = $parent_item['allow_cid'];
254 $str_group_allow = $parent_item['allow_gid'];
255 $str_contact_deny = $parent_item['deny_cid'];
256 $str_group_deny = $parent_item['deny_gid'];
257 $private = $parent_item['private'];
260 $pubmail_enabled = defaults($_REQUEST, 'pubmail_enable', false) && !$private;
262 // if using the API, we won't see pubmail_enable - figure out if it should be set
263 if ($api_source && $profile_uid && $profile_uid == local_user() && !$private) {
264 if (function_exists('imap_open') && !Config::get('system', 'imap_disabled')) {
265 $pubmail_enabled = dba::exists('mailacct', ["`uid` = ? AND `server` != ?", local_user(), '']);
269 if (!strlen($body)) {
273 info(t('Empty post discarded.') . EOL);
274 if (x($_REQUEST, 'return')) {
275 goaway($return_path);
281 if (strlen($categories)) {
282 // get the "fileas" tags for this post
283 $filedas = file_tag_file_to_list($categories, 'file');
285 // save old and new categories, so we can determine what needs to be deleted from pconfig
286 $categories_old = $categories;
287 $categories = file_tag_list_to_file(trim($_REQUEST['category']), 'category');
288 $categories_new = $categories;
289 if (strlen($filedas)) {
290 // append the fileas stuff to the new categories list
291 $categories .= file_tag_list_to_file($filedas, 'file');
294 // get contact info for poster
300 if (local_user() && ((local_user() == $profile_uid) || $allow_comment)) {
302 $author = dba::selectFirst('contact', [], ['uid' => local_user(), 'self' => true]);
303 } elseif (remote_user()) {
304 if (x($_SESSION, 'remote') && is_array($_SESSION['remote'])) {
305 foreach ($_SESSION['remote'] as $v) {
306 if ($v['uid'] == $profile_uid) {
307 $contact_id = $v['cid'];
313 $author = dba::selectFirst('contact', [], ['id' => $contact_id]);
317 if (DBM::is_result($author)) {
318 $contact_id = $author['id'];
321 // get contact info for owner
322 if ($profile_uid == local_user() || $allow_comment) {
323 $contact_record = $author;
325 $contact_record = dba::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]);
328 $post_type = notags(trim($_REQUEST['type']));
330 if ($post_type === 'net-comment' && $parent_item !== null) {
331 if ($parent_item['wall'] == 1) {
332 $post_type = 'wall-comment';
334 $post_type = 'remote-comment';
338 // Look for any tags and linkify them
342 $tags = get_tags($body);
344 // Add a tag if the parent contact is from OStatus (This will notify them during delivery)
346 if ($thr_parent_contact['network'] == NETWORK_OSTATUS) {
347 $contact = '@[url=' . $thr_parent_contact['url'] . ']' . $thr_parent_contact['nick'] . '[/url]';
348 if (!in_array($contact, $tags)) {
353 if ($parent_contact['network'] == NETWORK_OSTATUS) {
354 $contact = '@[url=' . $parent_contact['url'] . ']' . $parent_contact['nick'] . '[/url]';
355 if (!in_array($contact, $tags)) {
363 $private_forum = false;
364 $only_to_forum = false;
368 foreach ($tags as $tag) {
370 $tag_type = substr($tag, 0, 1);
372 if ($tag_type == '#') {
377 * If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
378 * Robert Johnson should be first in the $tags array
380 $fullnametagged = false;
381 /// @TODO $tagged is initialized above if () block and is not filled, maybe old-lost code?
382 foreach ($tagged as $nextTag) {
383 if (stristr($nextTag, $tag . ' ')) {
384 $fullnametagged = true;
388 if ($fullnametagged) {
392 $success = handle_tag($a, $body, $inform, $str_tags, local_user() ? local_user() : $profile_uid, $tag, $network);
393 if ($success['replaced']) {
396 // When the forum is private or the forum is addressed with a "!" make the post private
397 if (is_array($success['contact']) && ($success['contact']['prv'] || ($tag_type == '!'))) {
398 $private_forum = $success['contact']['prv'];
399 $only_to_forum = ($tag_type == '!');
400 $private_id = $success['contact']['id'];
401 $forum_contact = $success['contact'];
402 } elseif (is_array($success['contact']) && $success['contact']['forum'] &&
403 ($str_contact_allow == '<' . $success['contact']['id'] . '>')) {
404 $private_forum = false;
405 $only_to_forum = true;
406 $private_id = $success['contact']['id'];
407 $forum_contact = $success['contact'];
412 $original_contact_id = $contact_id;
414 if (!$parent && count($forum_contact) && ($private_forum || $only_to_forum)) {
415 // we tagged a forum in a top level post. Now we change the post
416 $private = $private_forum;
418 $str_group_allow = '';
419 $str_contact_deny = '';
420 $str_group_deny = '';
421 if ($private_forum) {
422 $str_contact_allow = '<' . $private_id . '>';
424 $str_contact_allow = '';
426 $contact_id = $private_id;
427 $contact_record = $forum_contact;
428 $_REQUEST['origin'] = false;
432 * When a photo was uploaded into the message using the (profile wall) ajax
433 * uploader, The permissions are initially set to disallow anybody but the
434 * owner from seeing it. This is because the permissions may not yet have been
435 * set for the post. If it's private, the photo permissions should be set
436 * appropriately. But we didn't know the final permissions on the post until
437 * now. So now we'll look for links of uploaded messages that are in the
438 * post and set them to the same permissions as the post itself.
443 if (!$preview && preg_match_all("/\[img([\=0-9x]*?)\](.*?)\[\/img\]/",$body,$match)) {
445 if (count($images)) {
447 $objecttype = ACTIVITY_OBJ_IMAGE;
449 foreach ($images as $image) {
450 if (!stristr($image, System::baseUrl() . '/photo/')) {
453 $image_uri = substr($image,strrpos($image,'/') + 1);
454 $image_uri = substr($image_uri,0, strpos($image_uri,'-'));
455 if (!strlen($image_uri)) {
459 /// @todo these lines should be moved to Model/Photo
460 $srch = '<' . intval($original_contact_id) . '>';
462 $condition = ['allow_cid' => $srch, 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '',
463 'resource-id' => $image_uri, 'uid' => $profile_uid];
464 if (!dba::exists('photo', $condition)) {
468 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
469 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
470 $condition = ['resource-id' => $image_uri, 'uid' => $profile_uid, 'album' => t('Wall Photos')];
471 dba::update('photo', $fields, $condition);
478 * Next link in any attachment references we find in the post.
482 if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) {
483 $attaches = $match[1];
484 if (count($attaches)) {
485 foreach ($attaches as $attach) {
486 $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow,
487 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny];
488 $condition = ['id' => $attach];
489 dba::update('attach', $fields, $condition);
494 // embedded bookmark or attachment in post? set bookmark flag
497 $data = get_attachment_data($body);
498 if (preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) {
499 $objecttype = ACTIVITY_OBJ_BOOKMARK;
503 $body = bb_translate_video($body);
506 // Fold multi-line [code] sequences
507 $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body);
509 $body = scale_external_images($body, false);
511 // Setting the object type if not defined before
513 $objecttype = ACTIVITY_OBJ_NOTE; // Default value
514 require_once 'include/plaintext.php';
515 $objectdata = get_attached_data($body);
517 if ($objectdata["type"] == "link") {
518 $objecttype = ACTIVITY_OBJ_BOOKMARK;
519 } elseif ($objectdata["type"] == "video") {
520 $objecttype = ACTIVITY_OBJ_VIDEO;
521 } elseif ($objectdata["type"] == "photo") {
522 $objecttype = ACTIVITY_OBJ_IMAGE;
530 if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) {
531 foreach ($match[2] as $mtch) {
532 $fields = ['id', 'filename', 'filesize', 'filetype'];
533 $attachment = dba::selectFirst('attach', $fields, ['id' => $mtch]);
534 if (DBM::is_result($attachment)) {
535 if (strlen($attachments)) {
538 $attachments .= '[attach]href="' . System::baseUrl() . '/attach/' . $attachment['id'] .
539 '" length="' . $attachment['filesize'] . '" type="' . $attachment['filetype'] .
540 '" title="' . ($attachment['filename'] ? $attachment['filename'] : '') . '"[/attach]';
542 $body = str_replace($match[1],'',$body);
548 if (($post_type === 'wall' || $post_type === 'wall-comment') && !count($forum_contact)) {
552 if (!strlen($verb)) {
553 $verb = ACTIVITY_POST;
556 if ($network == "") {
557 $network = NETWORK_DFRN;
560 $gravity = ($parent ? 6 : 0);
562 // even if the post arrived via API we are considering that it
563 // originated on this site by default for determining relayability.
565 $origin = intval(defaults($_REQUEST, 'origin', 1));
567 $notify_type = ($parent ? 'comment-new' : 'wall-new');
569 $uri = ($message_id ? $message_id : item_new_uri($a->get_hostname(), $profile_uid, $guid));
571 // Fallback so that we alway have a parent uri
572 if (!$thr_parent_uri || !$parent) {
573 $thr_parent_uri = $uri;
577 $datarray['uid'] = $profile_uid;
578 $datarray['type'] = $post_type;
579 $datarray['wall'] = $wall;
580 $datarray['gravity'] = $gravity;
581 $datarray['network'] = $network;
582 $datarray['contact-id'] = $contact_id;
583 $datarray['owner-name'] = $contact_record['name'];
584 $datarray['owner-link'] = $contact_record['url'];
585 $datarray['owner-avatar'] = $contact_record['thumb'];
586 $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link'], 0);
587 $datarray['author-name'] = $author['name'];
588 $datarray['author-link'] = $author['url'];
589 $datarray['author-avatar'] = $author['thumb'];
590 $datarray['author-id'] = Contact::getIdForURL($datarray['author-link'], 0);
591 $datarray['created'] = datetime_convert();
592 $datarray['edited'] = datetime_convert();
593 $datarray['commented'] = datetime_convert();
594 $datarray['received'] = datetime_convert();
595 $datarray['changed'] = datetime_convert();
596 $datarray['extid'] = $extid;
597 $datarray['guid'] = $guid;
598 $datarray['uri'] = $uri;
599 $datarray['title'] = $title;
600 $datarray['body'] = $body;
601 $datarray['app'] = $app;
602 $datarray['location'] = $location;
603 $datarray['coord'] = $coord;
604 $datarray['tag'] = $str_tags;
605 $datarray['file'] = $categories;
606 $datarray['inform'] = $inform;
607 $datarray['verb'] = $verb;
608 $datarray['object-type'] = $objecttype;
609 $datarray['allow_cid'] = $str_contact_allow;
610 $datarray['allow_gid'] = $str_group_allow;
611 $datarray['deny_cid'] = $str_contact_deny;
612 $datarray['deny_gid'] = $str_group_deny;
613 $datarray['private'] = $private;
614 $datarray['pubmail'] = $pubmail_enabled;
615 $datarray['attach'] = $attachments;
616 $datarray['bookmark'] = intval($bookmark);
618 // This is not a bug. The item store function changes 'parent-uri' to 'thr-parent' and fetches 'parent-uri' new. (We should change this)
619 $datarray['parent-uri'] = $thr_parent_uri;
621 $datarray['postopts'] = $postopts;
622 $datarray['origin'] = $origin;
623 $datarray['moderated'] = false;
624 $datarray['gcontact-id'] = GContact::getId(["url" => $datarray['author-link'], "network" => $datarray['network'],
625 "photo" => $datarray['author-avatar'], "name" => $datarray['author-name']]);
626 $datarray['object'] = $object;
629 * These fields are for the convenience of plugins...
630 * 'self' if true indicates the owner is posting on their own wall
631 * If parent is 0 it is a top-level post.
633 $datarray['parent'] = $parent;
634 $datarray['self'] = $self;
636 // This triggers posts via API and the mirror functions
637 $datarray['api_source'] = $api_source;
639 // This field is for storing the raw conversation data
640 $datarray['protocol'] = PROTOCOL_DFRN;
642 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $datarray['parent-uri']);
643 if (DBM::is_result($r)) {
644 if ($r['conversation-uri'] != '') {
645 $datarray['conversation-uri'] = $r['conversation-uri'];
647 if ($r['conversation-href'] != '') {
648 $datarray['conversation-href'] = $r['conversation-href'];
653 $datarray['edit'] = true;
656 // Search for hashtags
657 item_body_set_hashtags($datarray);
659 // preview mode - prepare the body for display and send it via json
661 require_once 'include/conversation.php';
662 // We set the datarray ID to -1 because in preview mode the dataray
663 // doesn't have an ID.
664 $datarray["id"] = -1;
665 $o = conversation($a,[array_merge($contact_record,$datarray)],'search', false, true);
666 logger('preview: ' . $o);
667 echo json_encode(['preview' => $o]);
671 call_hooks('post_local',$datarray);
673 if (x($datarray, 'cancel')) {
674 logger('mod_item: post cancelled by plugin.');
676 goaway($return_path);
679 $json = ['cancel' => 1];
680 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
681 $json['reload'] = System::baseUrl() . '/' . $_REQUEST['jsreload'];
684 echo json_encode($json);
690 // Fill the cache field
691 // This could be done in Item::update as well - but we have to check for the existance of some fields.
692 put_item_in_cache($datarray);
695 'title' => $datarray['title'],
696 'body' => $datarray['body'],
697 'tag' => $datarray['tag'],
698 'attach' => $datarray['attach'],
699 'file' => $datarray['file'],
700 'rendered-html' => $datarray['rendered-html'],
701 'rendered-hash' => $datarray['rendered-hash'],
702 'edited' => datetime_convert(),
703 'changed' => datetime_convert()];
705 Item::update($fields, ['id' => $post_id]);
707 // update filetags in pconfig
708 file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
710 if (x($_REQUEST, 'return') && strlen($return_path)) {
711 logger('return: ' . $return_path);
712 goaway($return_path);
719 unset($datarray['edit']);
720 unset($datarray['self']);
721 unset($datarray['api_source']);
723 $post_id = item_store($datarray);
726 logger("Item wasn't stored.");
727 goaway($return_path);
730 $datarray = dba::selectFirst('item', [], ['id' => $post_id]);
732 if (!DBM::is_result($datarray)) {
733 logger("Item with id ".$post_id." couldn't be fetched.");
734 goaway($return_path);
737 // update filetags in pconfig
738 file_tag_update_pconfig($uid, $categories_old, $categories_new, 'category');
740 // These notifications are sent if someone else is commenting other your wall
742 if ($contact_record != $author) {
744 'type' => NOTIFY_COMMENT,
745 'notify_flags' => $user['notify-flags'],
746 'language' => $user['language'],
747 'to_name' => $user['username'],
748 'to_email' => $user['email'],
749 'uid' => $user['uid'],
751 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
752 'source_name' => $datarray['author-name'],
753 'source_link' => $datarray['author-link'],
754 'source_photo' => $datarray['author-avatar'],
755 'verb' => ACTIVITY_POST,
758 'parent_uri' => $parent_item['uri']
762 // Store the comment signature information in case we need to relay to Diaspora
763 Diaspora::storeCommentSignature($datarray, $author, ($self ? $user['prvkey'] : false), $post_id);
765 if (($contact_record != $author) && !count($forum_contact)) {
767 'type' => NOTIFY_WALL,
768 'notify_flags' => $user['notify-flags'],
769 'language' => $user['language'],
770 'to_name' => $user['username'],
771 'to_email' => $user['email'],
772 'uid' => $user['uid'],
774 'link' => System::baseUrl().'/display/'.urlencode($datarray['guid']),
775 'source_name' => $datarray['author-name'],
776 'source_link' => $datarray['author-link'],
777 'source_photo' => $datarray['author-avatar'],
778 'verb' => ACTIVITY_POST,
784 call_hooks('post_local_end', $datarray);
786 if (strlen($emailcc) && $profile_uid == local_user()) {
787 $erecips = explode(',', $emailcc);
788 if (count($erecips)) {
789 foreach ($erecips as $recip) {
790 $addr = trim($recip);
791 if (!strlen($addr)) {
794 $disclaimer = '<hr />' . sprintf(t('This message was sent to you by %s, a member of the Friendica social network.'), $a->user['username'])
796 $disclaimer .= sprintf(t('You may visit them online at %s'), System::baseUrl() . '/profile/' . $a->user['nickname']) . EOL;
797 $disclaimer .= t('Please contact the sender by replying to this post if you do not wish to receive these messages.') . EOL;
798 if (!$datarray['title']=='') {
799 $subject = Email::encodeHeader($datarray['title'], 'UTF-8');
801 $subject = Email::encodeHeader('[Friendica]' . ' ' . sprintf(t('%s posted an update.'), $a->user['username']), 'UTF-8');
803 $link = '<a href="' . System::baseUrl() . '/profile/' . $a->user['nickname'] . '"><img src="' . $author['thumb'] . '" alt="' . $a->user['username'] . '" /></a><br /><br />';
804 $html = prepare_body($datarray);
805 $message = '<html><body>' . $link . $html . $disclaimer . '</body></html>';
806 include_once 'include/html2plain.php';
808 'fromName' => $a->user['username'],
809 'fromEmail' => $a->user['email'],
811 'replyTo' => $a->user['email'],
812 'messageSubject' => $subject,
813 'htmlVersion' => $message,
814 'textVersion' => html2plain($html.$disclaimer)
816 Emailer::send($params);
821 // Insert an item entry for UID=0 for global entries.
822 // We now do it in the background to save some time.
823 // This is important in interactive environments like the frontend or the API.
824 // We don't fork a new process since this is done anyway with the following command
825 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
827 // Call the background process that is delivering the item to the receivers
828 Worker::add(PRIORITY_HIGH, "Notifier", $notify_type, $post_id);
830 logger('post_complete');
832 item_post_return(System::baseUrl(), $api_source, $return_path);
836 function item_post_return($baseurl, $api_source, $return_path) {
837 // figure out how to return, depending on from whence we came
844 goaway($return_path);
847 $json = ['success' => 1];
848 if (x($_REQUEST, 'jsreload') && strlen($_REQUEST['jsreload'])) {
849 $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
852 logger('post_json: ' . print_r($json,true), LOGGER_DEBUG);
854 echo json_encode($json);
860 function item_content(App $a) {
862 if (!local_user() && !remote_user()) {
866 require_once 'include/security.php';
869 if (($a->argc == 3) && ($a->argv[1] === 'drop') && intval($a->argv[2])) {
871 $o = Item::delete($a->argv[2]);
873 $o = drop_item($a->argv[2]);
876 // ajax return: [<item id>, 0 (no perm) | <owner id>]
877 echo json_encode([intval($a->argv[2]), intval($o)]);
885 * This function removes the tag $tag from the text $body and replaces it with
886 * the appropiate link.
888 * @param App $a Application instance @TODO is unused in this function's scope (excluding included files)
889 * @param unknown_type $body the text to replace the tag in
890 * @param string $inform a comma-seperated string containing everybody to inform
891 * @param string $str_tags string to add the tag to
892 * @param integer $profile_uid
893 * @param string $tag the tag to replace
894 * @param string $network The network of the post
896 * @return boolean true if replaced, false if not replaced
898 function handle_tag(App $a, &$body, &$inform, &$str_tags, $profile_uid, $tag, $network = "")
904 //is it a person tag?
905 if ((strpos($tag, '@') === 0) || (strpos($tag, '!') === 0)) {
906 $tag_type = substr($tag, 0, 1);
907 //is it already replaced?
908 if (strpos($tag, '[url=')) {
909 //append tag to str_tags
910 if (!stristr($str_tags, $tag)) {
911 if (strlen($str_tags)) {
917 // Checking for the alias that is used for OStatus
918 $pattern = "/[@!]\[url\=(.*?)\](.*?)\[\/url\]/ism";
919 if (preg_match($pattern, $tag, $matches)) {
921 $r = q("SELECT `alias`, `name` FROM `contact` WHERE `nurl` = '%s' AND `alias` != '' AND `uid` = 0",
922 normalise_link($matches[1]));
923 if (!DBM::is_result($r)) {
924 $r = q("SELECT `alias`, `name` FROM `gcontact` WHERE `nurl` = '%s' AND `alias` != ''",
925 normalise_link($matches[1]));
927 if (DBM::is_result($r)) {
930 $data = Probe::uri($matches[1]);
933 if ($data["alias"] != "") {
934 $newtag = '@[url=' . $data["alias"] . ']' . $data["name"] . '[/url]';
935 if (!stristr($str_tags, $newtag)) {
936 if (strlen($str_tags)) {
939 $str_tags .= $newtag;
947 //get the person's name
948 $name = substr($tag, 1);
950 // Sometimes the tag detection doesn't seem to work right
951 // This is some workaround
952 $nameparts = explode(" ", $name);
953 $name = $nameparts[0];
955 // Try to detect the contact in various ways
956 if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
957 // Is it in format @user@domain.tld or @http://domain.tld/...?
959 // First check the contact table for the address
960 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
961 WHERE `addr` = '%s' AND `uid` = %d AND
962 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
965 intval($profile_uid),
966 dbesc(NETWORK_OSTATUS)
969 // Then check in the contact table for the url
970 if (!DBM::is_result($r)) {
971 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network`, `notify`, `forum`, `prv` FROM `contact`
972 WHERE `nurl` = '%s' AND `uid` = %d AND
973 (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
975 dbesc(normalise_link($name)),
976 intval($profile_uid),
977 dbesc(NETWORK_OSTATUS)
981 // Then check in the global contacts for the address
982 if (!DBM::is_result($r)) {
983 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
984 WHERE `addr` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
987 dbesc(NETWORK_OSTATUS)
991 // Then check in the global contacts for the url
992 if (!DBM::is_result($r)) {
993 $r = q("SELECT `url`, `nick`, `name`, `alias`, `network`, `notify` FROM `gcontact`
994 WHERE `nurl` = '%s' AND (`network` != '%s' OR (`notify` != '' AND `alias` != ''))
996 dbesc(normalise_link($name)),
997 dbesc(NETWORK_OSTATUS)
1001 if (!DBM::is_result($r)) {
1002 $probed = Probe::uri($name);
1003 if ($result['network'] != NETWORK_PHANTOM) {
1004 GContact::update($probed);
1005 $r = q("SELECT `url`, `name`, `nick`, `network`, `alias`, `notify` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1006 dbesc(normalise_link($probed["url"])));
1011 if (strrpos($name, '+')) {
1012 // Is it in format @nick+number?
1013 $tagcid = intval(substr($name, strrpos($name, '+') + 1));
1015 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1017 intval($profile_uid)
1021 // select someone by attag or nick and the name passed in the current network
1022 if (!DBM::is_result($r) && ($network != ""))
1023 $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",
1027 intval($profile_uid)
1030 //select someone from this user's contacts by name in the current network
1031 if (!DBM::is_result($r) && ($network != "")) {
1032 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `network` = '%s' AND `uid` = %d LIMIT 1",
1035 intval($profile_uid)
1039 // select someone by attag or nick and the name passed in
1040 if (!DBM::is_result($r)) {
1041 $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",
1044 intval($profile_uid)
1048 // select someone from this user's contacts by name
1049 if (!DBM::is_result($r)) {
1050 $r = q("SELECT `id`, `url`, `nick`, `name`, `alias`, `network` FROM `contact` WHERE `name` = '%s' AND `uid` = %d LIMIT 1",
1052 intval($profile_uid)
1057 if (DBM::is_result($r)) {
1058 if (strlen($inform) && (isset($r[0]["notify"]) || isset($r[0]["id"]))) {
1062 if (isset($r[0]["id"])) {
1063 $inform .= 'cid:' . $r[0]["id"];
1064 } elseif (isset($r[0]["notify"])) {
1065 $inform .= $r[0]["notify"];
1068 $profile = $r[0]["url"];
1069 $alias = $r[0]["alias"];
1070 $newname = $r[0]["nick"];
1071 if (($newname == "") || (($r[0]["network"] != NETWORK_OSTATUS) && ($r[0]["network"] != NETWORK_TWITTER)
1072 && ($r[0]["network"] != NETWORK_STATUSNET) && ($r[0]["network"] != NETWORK_APPNET))) {
1073 $newname = $r[0]["name"];
1077 //if there is an url for this persons profile
1078 if (isset($profile) && ($newname != "")) {
1080 // create profile link
1081 $profile = str_replace(',', '%2c', $profile);
1082 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
1083 $body = str_replace($tag_type . $name, $newtag, $body);
1084 // append tag to str_tags
1085 if (!stristr($str_tags, $newtag)) {
1086 if (strlen($str_tags)) {
1089 $str_tags .= $newtag;
1093 * Status.Net seems to require the numeric ID URL in a mention if the person isn't
1094 * subscribed to you. But the nickname URL is OK if they are. Grrr. We'll tag both.
1096 if (strlen($alias)) {
1097 $newtag = '@[url=' . $alias . ']' . $newname . '[/url]';
1098 if (!stristr($str_tags, $newtag)) {
1099 if (strlen($str_tags)) {
1102 $str_tags .= $newtag;
1108 return ['replaced' => $replaced, 'contact' => $r[0]];