From: Michael Date: Wed, 4 Jan 2023 05:44:52 +0000 (+0000) Subject: Code cleanup for mod/item.php X-Git-Url: https://git.mxchange.org/?a=commitdiff_plain;h=0d56f156f7103ca15221d97fefb67696b837e33c;p=friendica.git Code cleanup for mod/item.php --- diff --git a/mod/item.php b/mod/item.php index 7be92a73f3..808641132e 100644 --- a/mod/item.php +++ b/mod/item.php @@ -29,7 +29,6 @@ */ use Friendica\App; -use Friendica\Content\PageInfo; use Friendica\Content\Text\BBCode; use Friendica\Core\Hook; use Friendica\Core\Logger; @@ -38,31 +37,24 @@ use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; -use Friendica\Model\Attach; use Friendica\Model\Contact; -use Friendica\Model\Conversation; -use Friendica\Model\FileTag; use Friendica\Model\Item; use Friendica\Model\ItemURI; -use Friendica\Model\Notification; use Friendica\Model\Photo; use Friendica\Model\Post; use Friendica\Model\Tag; -use Friendica\Model\User; use Friendica\Network\HTTPException; use Friendica\Object\EMail\ItemCCEMail; use Friendica\Protocol\Activity; -use Friendica\Security\Security; use Friendica\Util\DateTimeFormat; -use Friendica\Util\ParseUrl; function item_post(App $a) { - if (!DI::userSession()->isAuthenticated()) { + $uid = DI::userSession()->getLocalUserId(); + + if (!DI::userSession()->isAuthenticated() || !$uid) { throw new HTTPException\ForbiddenException(); } - $uid = DI::userSession()->getLocalUserId(); - if (!empty($_REQUEST['dropitems'])) { $arr_drop = explode(',', $_REQUEST['dropitems']); foreach ($arr_drop as $item) { @@ -75,10 +67,8 @@ function item_post(App $a) { Hook::callAll('post_local_start', $_REQUEST); - Logger::debug('postvars', ['_REQUEST' => $_REQUEST]); - $return_path = $_REQUEST['return'] ?? ''; - $preview = intval($_REQUEST['preview'] ?? 0); + $preview = intval($_REQUEST['preview'] ?? 0); /* * Check for doubly-submitted posts, and reject duplicates @@ -94,30 +84,50 @@ function item_post(App $a) { } } - // Is this a reply to something? - $parent_item_id = intval($_REQUEST['parent'] ?? 0); - $thr_parent_uri = trim($_REQUEST['parent_uri'] ?? ''); - - $parent_item = null; - $toplevel_item = null; - $toplevel_item_id = 0; - $toplevel_user_id = null; - - $objecttype = null; - $profile_uid = DI::userSession()->getLocalUserId(); - $posttype = ($_REQUEST['post_type'] ?? '') ?: Item::PT_ARTICLE; + $post_id = intval($_REQUEST['post_id'] ?? 0); - if ($parent_item_id || $thr_parent_uri) { - if ($parent_item_id) { - $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $parent_item_id]); - } elseif ($thr_parent_uri) { - $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['uri' => $thr_parent_uri, 'uid' => $profile_uid]); + // is this an edited post? + if ($post_id > 0) { + $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]); + } else { + $orig_post = null; + } + + $emailcc = trim($_REQUEST['emailcc'] ?? ''); + + $post = ['uid' => $uid]; + + $post = DI::contentItem()->initializePost($post); + + $post['self'] = true; + $post['api_source'] = false; + $post['edit'] = $orig_post; + $post['file'] = ''; + $post['attach'] = ''; + $post['inform'] = ''; + $post['postopts'] = ''; + + $post['wall'] = $_REQUEST['wall'] ?? true; + $post['post-type'] = $_REQUEST['post_type'] ?? ''; + $post['title'] = trim($_REQUEST['title'] ?? ''); + $post['body'] = $_REQUEST['body'] ?? ''; + $post['location'] = trim($_REQUEST['location'] ?? ''); + $post['coord'] = trim($_REQUEST['coord'] ?? ''); + $post['parent'] = intval($_REQUEST['parent'] ?? 0); + $post['pubmail'] = $_REQUEST['pubmail_enable'] ?? false; + $post['created'] = $_REQUEST['created_at'] ?? DateTimeFormat::utcNow(); + $post['edited'] = $post['changed'] = $post['commented'] = $post['created']; + $post['app'] = ''; + + if ($post['parent']) { + if ($post['parent']) { + $parent_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post['parent']]); } // if this isn't the top-level parent of the conversation, find it if (DBA::isResult($parent_item)) { // The URI and the contact is taken from the direct parent which needn't to be the top parent - $thr_parent_uri = $parent_item['uri']; + $post['thr-parent'] = $parent_item['uri']; $toplevel_item = $parent_item; if ($parent_item['gravity'] != Item::GRAVITY_PARENT) { @@ -136,502 +146,108 @@ function item_post(App $a) { // When commenting on a public post then store the post for the current user // This enables interaction like starring and saving into folders if ($toplevel_item['uid'] == 0) { - $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], DI::userSession()->getLocalUserId(), ['post-reason' => Item::PR_ACTIVITY]); - Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $uid, 'stored' => $stored]); + $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], $post['uid'], ['post-reason' => Item::PR_ACTIVITY]); + Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $post['uid'], 'stored' => $stored]); if ($stored) { $toplevel_item = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $stored]); } } - $toplevel_item_id = $toplevel_item['id']; - $toplevel_user_id = $toplevel_item['uid']; - - $objecttype = Activity\ObjectType::COMMENT; - } - - if ($toplevel_item_id) { - Logger::info('mod_item: item_post', ['parent' => $toplevel_item_id]); - } - - $post_id = intval($_REQUEST['post_id'] ?? 0); - $app = strip_tags($_REQUEST['source'] ?? ''); - $extid = strip_tags($_REQUEST['extid'] ?? ''); - $object = $_REQUEST['object'] ?? ''; - - // Don't use "defaults" here. It would turn 0 to 1 - if (!isset($_REQUEST['wall'])) { - $wall = 1; + $post['parent'] = $toplevel_item['id']; + $post['gravity'] = Item::GRAVITY_COMMENT; + $post['wall'] = $toplevel_item['wall']; } else { - $wall = $_REQUEST['wall']; - } - - // Ensure that the user id in a thread always stay the same - if (!is_null($toplevel_user_id) && in_array($toplevel_user_id, [DI::userSession()->getLocalUserId(), 0])) { - $profile_uid = $toplevel_user_id; - } - - // Allow commenting if it is an answer to a public post - $allow_comment = DI::userSession()->getLocalUserId() && $toplevel_item_id && in_array($toplevel_item['private'], [Item::PUBLIC, Item::UNLISTED]) && in_array($toplevel_item['network'], Protocol::FEDERATED); - - // Now check that valid personal details have been provided - if (!Security::canWriteToUserWall($profile_uid) && !$allow_comment) { - Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'toplevel_item_id' => $toplevel_item_id, 'network' => $toplevel_item['network']]); - DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.')); - if ($return_path) { - DI::baseUrl()->redirect($return_path); - } - - throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.')); - } - - // Init post instance - $orig_post = null; - - // is this an edited post? - if ($post_id > 0) { - $orig_post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]); - } - - $user = User::getById($profile_uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']); - if (!DBA::isResult($user) && !$toplevel_item_id) { - return 0; + $parent_item = []; + $post['parent'] = 0; + $post['gravity'] = Item::GRAVITY_PARENT; + $post['thr-parent'] = $post['uri']; } - $categories = ''; - $postopts = ''; - $emailcc = ''; - $body = $_REQUEST['body'] ?? ''; - $has_attachment = $_REQUEST['has_attachment'] ?? 0; - - // If we have a speparate attachment, we need to add it to the body. - if (!empty($has_attachment)) { - $attachment_type = $_REQUEST['attachment_type'] ?? ''; - $attachment_title = $_REQUEST['attachment_title'] ?? ''; - $attachment_text = $_REQUEST['attachment_text'] ?? ''; - - $attachment_url = hex2bin($_REQUEST['attachment_url'] ?? ''); - $attachment_img_src = hex2bin($_REQUEST['attachment_img_src'] ?? ''); - - $attachment_img_width = $_REQUEST['attachment_img_width'] ?? 0; - $attachment_img_height = $_REQUEST['attachment_img_height'] ?? 0; - - // Fetch the basic attachment data - $attachment = ParseUrl::getSiteinfoCached($attachment_url); - unset($attachment['keywords']); - - // Overwrite the basic data with possible changes from the frontend - $attachment['type'] = $attachment_type; - $attachment['title'] = $attachment_title; - $attachment['text'] = $attachment_text; - $attachment['url'] = $attachment_url; - - if (!empty($attachment_img_src)) { - $attachment['images'] = [ - 0 => [ - 'src' => $attachment_img_src, - 'width' => $attachment_img_width, - 'height' => $attachment_img_height - ] - ]; - } else { - unset($attachment['images']); - } - - $att_bbcode = "\n" . PageInfo::getFooterFromData($attachment); - $body .= $att_bbcode; - } elseif (preg_match("/\[attachment\](.*?)\[\/attachment\]/ism", $body, $matches)) { - $body = preg_replace("/\[attachment].*?\[\/attachment\]/ism", PageInfo::getFooterFromUrl($matches[1]), $body); - } + $post = DI::contentItem()->getACL($post, $parent_item, $_REQUEST); - // Convert links with empty descriptions to links without an explicit description - $body = preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $body); + $post['pubmail'] = $post['pubmail'] && !$post['private']; if (!empty($orig_post)) { - $str_group_allow = $orig_post['allow_gid']; - $str_contact_allow = $orig_post['allow_cid']; - $str_group_deny = $orig_post['deny_gid']; - $str_contact_deny = $orig_post['deny_cid']; - $location = $orig_post['location']; - $coord = $orig_post['coord']; - $verb = $orig_post['verb']; - $objecttype = $orig_post['object-type']; - $app = $orig_post['app']; - $categories = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']); - $title = trim($_REQUEST['title'] ?? ''); - $body = trim($body); - $private = $orig_post['private']; - $pubmail_enabled = $orig_post['pubmail']; - $network = $orig_post['network']; - $guid = $orig_post['guid']; - $extid = $orig_post['extid']; - } else { - $aclFormatter = DI::aclFormatter(); - $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $user['allow_cid'] ?? ''; - $str_group_allow = isset($_REQUEST['group_allow']) ? $aclFormatter->toString($_REQUEST['group_allow']) : $user['allow_gid'] ?? ''; - $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $user['deny_cid'] ?? ''; - $str_group_deny = isset($_REQUEST['group_deny']) ? $aclFormatter->toString($_REQUEST['group_deny']) : $user['deny_gid'] ?? ''; - - $visibility = $_REQUEST['visibility'] ?? ''; - if ($visibility === 'public') { - // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected - $str_contact_allow = $str_group_allow = $str_contact_deny = $str_group_deny = ''; - } else if ($visibility === 'custom') { - // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL - // case that would make it public. So we always append the author's contact id to the allowed contacts. - // See https://github.com/friendica/friendica/issues/9672 - $str_contact_allow .= $aclFormatter->toString(Contact::getPublicIdByUserId($uid)); - } - - $title = trim($_REQUEST['title'] ?? ''); - $location = trim($_REQUEST['location'] ?? ''); - $coord = trim($_REQUEST['coord'] ?? ''); - $verb = trim($_REQUEST['verb'] ?? ''); - $emailcc = trim($_REQUEST['emailcc'] ?? ''); - $body = trim($body); - $network = trim(($_REQUEST['network'] ?? '') ?: Protocol::DFRN); - $guid = System::createUUID(); - - $postopts = $_REQUEST['postopts'] ?? ''; - - if (strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) { - $private = Item::PRIVATE; - } elseif (DI::pConfig()->get($profile_uid, 'system', 'unlisted')) { - $private = Item::UNLISTED; - } else { - $private = Item::PUBLIC; - } - - // If this is a comment, set the permissions from the parent. - - if ($toplevel_item) { - // for non native networks use the network of the original post as network of the item - if (($toplevel_item['network'] != Protocol::DIASPORA) - && ($toplevel_item['network'] != Protocol::OSTATUS) - && ($network == '')) { - $network = $toplevel_item['network']; - } - - $str_contact_allow = $toplevel_item['allow_cid'] ?? ''; - $str_group_allow = $toplevel_item['allow_gid'] ?? ''; - $str_contact_deny = $toplevel_item['deny_cid'] ?? ''; - $str_group_deny = $toplevel_item['deny_gid'] ?? ''; - $private = $toplevel_item['private']; - - $wall = $toplevel_item['wall']; - } - - $pubmail_enabled = ($_REQUEST['pubmail_enable'] ?? false) && !$private; - - if (!strlen($body)) { - if ($preview) { - System::jsonExit(['preview' => '']); - } - - DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.')); - if ($return_path) { - DI::baseUrl()->redirect($return_path); - } - - throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.')); - } - } - - if (!empty($categories)) { - // get the "fileas" tags for this post - $filedas = FileTag::fileToArray($categories); + $post['uri'] = $orig_post['uri']; + $post['file'] = Post\Category::getTextByURIId($orig_post['uri-id'], $orig_post['uid']); } - $list_array = explode(',', trim($_REQUEST['category'] ?? '')); - $categories = FileTag::arrayToFile($list_array, 'category'); + $post = DI::contentItem()->addCategories($post, $_REQUEST['category'] ?? ''); - if (!empty($filedas) && is_array($filedas)) { - // append the fileas stuff to the new categories list - $categories .= FileTag::arrayToFile($filedas); - } - - // get contact info for poster - - $author = null; - $self = false; - $contact_id = 0; - - if (DI::userSession()->getLocalUserId() && ((DI::userSession()->getLocalUserId() == $profile_uid) || $allow_comment)) { - $self = true; - $author = DBA::selectFirst('contact', [], ['uid' => DI::userSession()->getLocalUserId(), 'self' => true]); - } elseif (!empty(DI::userSession()->getRemoteContactID($profile_uid))) { - $author = DBA::selectFirst('contact', [], ['id' => DI::userSession()->getRemoteContactID($profile_uid)]); - } - - if (DBA::isResult($author)) { - $contact_id = $author['id']; - } - - // get contact info for owner - if ($profile_uid == DI::userSession()->getLocalUserId() || $allow_comment) { - $contact_record = $author ?: []; - } else { - $contact_record = DBA::selectFirst('contact', [], ['uid' => $profile_uid, 'self' => true]) ?: []; - } - - // Personal notes must never be altered to a forum post. - if ($posttype != Item::PT_PERSONAL_NOTE) { - // Look for any tags and linkify them - $item = [ - 'uid' => DI::userSession()->getLocalUserId() ? DI::userSession()->getLocalUserId() : $profile_uid, - 'gravity' => $toplevel_item_id ? Item::GRAVITY_COMMENT : Item::GRAVITY_PARENT, - 'network' => $network, - 'body' => $body, - 'postopts' => $postopts, - 'private' => $private, - 'allow_cid' => $str_contact_allow, - 'allow_gid' => $str_group_allow, - 'deny_cid' => $str_contact_deny, - 'deny_gid' => $str_group_deny, - ]; - - $item = DI::contentItem()->expandTags($item); - - $body = $item['body']; - $inform = $item['inform']; - $postopts = $item['postopts']; - $private = $item['private']; - $str_contact_allow = $item['allow_cid']; - $str_group_allow = $item['allow_gid']; - $str_contact_deny = $item['deny_cid']; - $str_group_deny = $item['deny_gid']; - } else { - $inform = ''; - } - - /* - * When a photo was uploaded into the message using the (profile wall) ajax - * uploader, The permissions are initially set to disallow anybody but the - * owner from seeing it. This is because the permissions may not yet have been - * set for the post. If it's private, the photo permissions should be set - * appropriately. But we didn't know the final permissions on the post until - * now. So now we'll look for links of uploaded messages that are in the - * post and set them to the same permissions as the post itself. - */ - - $match = null; - - if (!$preview && Photo::setPermissionFromBody($body, $uid, $contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) { - $objecttype = Activity\ObjectType::IMAGE; - } - - /* - * Next link in any attachment references we find in the post. - */ - $match = []; - - /// @todo these lines should be moved to Model/Attach (Once it exists) - if (!$preview && preg_match_all("/\[attachment\](.*?)\[\/attachment\]/", $body, $match)) { - $attaches = $match[1]; - if (count($attaches)) { - foreach ($attaches as $attach) { - // Ensure to only modify attachments that you own - $srch = '<' . intval($contact_id) . '>'; - - $condition = [ - 'allow_cid' => $srch, - 'allow_gid' => '', - 'deny_cid' => '', - 'deny_gid' => '', - 'id' => $attach, - ]; - if (!Attach::exists($condition)) { - continue; - } - - $fields = ['allow_cid' => $str_contact_allow, 'allow_gid' => $str_group_allow, - 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_group_deny]; - $condition = ['id' => $attach]; - Attach::update($fields, $condition); - } + if (!$preview) { + if (Photo::setPermissionFromBody($post['body'], $post['uid'], $post['contact-id'], $post['allow_cid'], $post['allow_gid'], $post['deny_cid'], $post['deny_gid'])) { + $post['object-type'] = Activity\ObjectType::IMAGE; } - } - - // embedded bookmark or attachment in post? set bookmark flag - $data = BBCode::getAttachmentData($body); - $match = []; - if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data['type'])) - && ($posttype != Item::PT_PERSONAL_NOTE)) { - $posttype = Item::PT_PAGE; - $objecttype = Activity\ObjectType::BOOKMARK; + $post = DI::contentItem()->moveAttachmentsFromBodyToAttach($post); } - $body = DI::bbCodeVideo()->transform($body); - - $body = BBCode::scaleExternalImages($body); - - // Setting the object type if not defined before - if (!$objecttype) { - $objecttype = Activity\ObjectType::NOTE; // Default value - $objectdata = BBCode::getAttachedData($body); - - if ($objectdata['type'] == 'link') { - $objecttype = Activity\ObjectType::BOOKMARK; - } elseif ($objectdata['type'] == 'video') { - $objecttype = Activity\ObjectType::VIDEO; - } elseif ($objectdata['type'] == 'photo') { - $objecttype = Activity\ObjectType::IMAGE; - } - + // Add the attachment to the body. + if (!empty($_REQUEST['has_attachment'])) { + $post['body'] .= DI::contentItem()->storeAttachmentFromRequest($_REQUEST); } - $attachments = ''; - $match = []; + $post = DI::contentItem()->finalizePost($post); - if (preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$body,$match)) { - foreach ($match[2] as $mtch) { - $fields = ['id', 'filename', 'filesize', 'filetype']; - $attachment = Attach::selectFirst($fields, ['id' => $mtch]); - if ($attachment !== false) { - if (strlen($attachments)) { - $attachments .= ','; - } - $attachments .= Post\Media::getAttachElement(DI::baseUrl() . '/attach/' . $attachment['id'], - $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? ''); - } - $body = str_replace($match[1],'',$body); + if (!strlen($post['body'])) { + if ($preview) { + System::jsonExit(['preview' => '']); } - } - - if (!strlen($verb)) { - $verb = Activity::POST; - } - - if ($network == '') { - $network = Protocol::DFRN; - } - - $gravity = ($toplevel_item_id ? Item::GRAVITY_COMMENT : Item::GRAVITY_PARENT); - - // even if the post arrived via API we are considering that it - // originated on this site by default for determining relayability. - - // Don't use "defaults" here. It would turn 0 to 1 - if (!isset($_REQUEST['origin'])) { - $origin = 1; - } else { - $origin = $_REQUEST['origin']; - } - $uri = Item::newURI($guid); + DI::sysmsg()->addNotice(DI::l10n()->t('Empty post discarded.')); + if ($return_path) { + DI::baseUrl()->redirect($return_path); + } - // Fallback so that we alway have a parent uri - if (!$thr_parent_uri || !$toplevel_item_id) { - $thr_parent_uri = $uri; + throw new HTTPException\BadRequestException(DI::l10n()->t('Empty post discarded.')); } - $datarray = [ - 'uid' => $profile_uid, - 'wall' => $wall, - 'gravity' => $gravity, - 'network' => $network, - 'contact-id' => $contact_id, - 'owner-name' => $contact_record['name'] ?? '', - 'owner-link' => $contact_record['url'] ?? '', - 'owner-avatar' => $contact_record['thumb'] ?? '', - 'author-name' => $author['name'], - 'author-link' => $author['url'], - 'author-avatar' => $author['thumb'], - 'created' => empty($_REQUEST['created_at']) ? DateTimeFormat::utcNow() : $_REQUEST['created_at'], - 'received' => DateTimeFormat::utcNow(), - 'extid' => $extid, - 'guid' => $guid, - 'uri' => $uri, - 'title' => $title, - 'body' => $body, - 'app' => $app, - 'location' => $location, - 'coord' => $coord, - 'file' => $categories, - 'inform' => $inform, - 'verb' => $verb, - 'post-type' => $posttype, - 'object-type' => $objecttype, - 'allow_cid' => $str_contact_allow, - 'allow_gid' => $str_group_allow, - 'deny_cid' => $str_contact_deny, - 'deny_gid' => $str_group_deny, - 'private' => $private, - 'pubmail' => $pubmail_enabled, - 'attach' => $attachments, - 'thr-parent' => $thr_parent_uri, - 'postopts' => $postopts, - 'origin' => $origin, - 'object' => $object, - 'attachments' => $_REQUEST['attachments'] ?? [], - /* - * These fields are for the convenience of addons... - * 'self' if true indicates the owner is posting on their own wall - * If parent is 0 it is a top-level post. - */ - 'parent' => $toplevel_item_id, - 'self' => $self, - // This triggers posts via API and the mirror functions - 'api_source' => false, - // This field is for storing the raw conversation data - 'protocol' => Conversation::PARCEL_DIRECT, - 'direction' => Conversation::PUSH, - ]; - - // These cannot be part of above initialization ... - $datarray['edited'] = $datarray['created']; - $datarray['commented'] = $datarray['created']; - $datarray['changed'] = $datarray['created']; - $datarray['owner-id'] = Contact::getIdForURL($datarray['owner-link']); - $datarray['author-id'] = Contact::getIdForURL($datarray['author-link']); - - $datarray['edit'] = $orig_post; - // Check for hashtags in the body and repair or add hashtag links if ($preview || $orig_post) { - $datarray['body'] = Item::setHashtags($datarray['body']); + $post['body'] = Item::setHashtags($post['body']); } // preview mode - prepare the body for display and send it via json if ($preview) { // We set the datarray ID to -1 because in preview mode the dataray // doesn't have an ID. - $datarray['id'] = -1; - $datarray['uri-id'] = -1; - $datarray['author-network'] = Protocol::DFRN; - $datarray['author-updated'] = ''; - $datarray['author-gsid'] = 0; - $datarray['author-uri-id'] = ItemURI::getIdByURI($datarray['author-link']); - $datarray['owner-updated'] = ''; - $datarray['has-media'] = false; - $datarray['quote-uri-id'] = Item::getQuoteUriId($datarray['body'], $datarray['uid']); - $datarray['body'] = BBCode::removeSharedData($datarray['body']); - - $o = DI::conversation()->create([array_merge($contact_record, $datarray)], 'search', false, true); + $post['id'] = -1; + $post['uri-id'] = -1; + $post['author-network'] = Protocol::DFRN; + $post['author-updated'] = ''; + $post['author-gsid'] = 0; + $post['author-uri-id'] = ItemURI::getIdByURI($post['author-link']); + $post['owner-updated'] = ''; + $post['has-media'] = false; + $post['quote-uri-id'] = Item::getQuoteUriId($post['body'], $post['uid']); + $post['body'] = BBCode::removeSharedData($post['body']); + $post['writable'] = true; + + $o = DI::conversation()->create([$post], 'search', false, true); System::jsonExit(['preview' => $o]); } - Hook::callAll('post_local',$datarray); + Hook::callAll('post_local',$post); if (!empty($_REQUEST['scheduled_at'])) { $scheduled_at = DateTimeFormat::convert($_REQUEST['scheduled_at'], 'UTC', $a->getTimeZone()); if ($scheduled_at > DateTimeFormat::utcNow()) { - unset($datarray['created']); - unset($datarray['edited']); - unset($datarray['commented']); - unset($datarray['received']); - unset($datarray['changed']); - unset($datarray['edit']); - unset($datarray['self']); - unset($datarray['api_source']); - - Post\Delayed::add($datarray['uri'], $datarray, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at); + unset($post['created']); + unset($post['edited']); + unset($post['commented']); + unset($post['received']); + unset($post['changed']); + unset($post['edit']); + unset($post['self']); + unset($post['api_source']); + + Post\Delayed::add($post['uri'], $post, Worker::PRIORITY_HIGH, Post\Delayed::PREPARED_NO_HOOK, $scheduled_at); item_post_return(DI::baseUrl(), $return_path); } } - if (!empty($datarray['cancel'])) { + if (!empty($post['cancel'])) { Logger::info('mod_item: post cancelled by addon.'); if ($return_path) { DI::baseUrl()->redirect($return_path); @@ -645,26 +261,26 @@ function item_post(App $a) { System::jsonExit($json); } - $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']); + $post['uri-id'] = ItemURI::getIdByURI($post['uri']); - $quote_uri_id = Item::getQuoteUriId($datarray['body'], $datarray['uid']); + $quote_uri_id = Item::getQuoteUriId($post['body'], $post['uid']); if (!empty($quote_uri_id)) { - $datarray['quote-uri-id'] = $quote_uri_id; - $datarray['body'] = BBCode::removeSharedData($datarray['body']); + $post['quote-uri-id'] = $quote_uri_id; + $post['body'] = BBCode::removeSharedData($post['body']); } if ($orig_post) { $fields = [ - 'title' => $datarray['title'], - 'body' => $datarray['body'], - 'attach' => $datarray['attach'], - 'file' => $datarray['file'], + 'title' => $post['title'], + 'body' => $post['body'], + 'attach' => $post['attach'], + 'file' => $post['file'], 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow() ]; Item::update($fields, ['id' => $post_id]); - Item::updateDisplayCache($datarray['uri-id']); + Item::updateDisplayCache($post['uri-id']); if ($return_path) { DI::baseUrl()->redirect($return_path); @@ -673,12 +289,11 @@ function item_post(App $a) { throw new HTTPException\OKException(DI::l10n()->t('Post updated.')); } - unset($datarray['edit']); - unset($datarray['self']); - unset($datarray['api_source']); - - $post_id = Item::insert($datarray); + unset($post['edit']); + unset($post['self']); + unset($post['api_source']); + $post_id = Item::insert($post); if (!$post_id) { DI::sysmsg()->addNotice(DI::l10n()->t('Item wasn\'t stored.')); if ($return_path) { @@ -688,9 +303,8 @@ function item_post(App $a) { throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item wasn\'t stored.')); } - $datarray = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]); - - if (!DBA::isResult($datarray)) { + $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]); + if (!DBA::isResult($post)) { Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]); if ($return_path) { DI::baseUrl()->redirect($return_path); @@ -699,50 +313,24 @@ function item_post(App $a) { throw new HTTPException\InternalServerErrorException(DI::l10n()->t('Item couldn\'t be fetched.')); } - Tag::storeFromBody($datarray['uri-id'], $datarray['body']); - - if (!\Friendica\Content\Feature::isEnabled($uid, 'explicit_mentions') && ($datarray['gravity'] == Item::GRAVITY_COMMENT)) { - Tag::createImplicitMentions($datarray['uri-id'], $datarray['thr-parent-id']); - } - - // These notifications are sent if someone else is commenting other your wall - if ($contact_record != $author) { - if ($toplevel_item_id) { - DI::notify()->createFromArray([ - 'type' => Notification\Type::COMMENT, - 'otype' => Notification\ObjectType::ITEM, - 'verb' => Activity::POST, - 'uid' => $profile_uid, - 'cid' => $datarray['author-id'], - 'item' => $datarray, - 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']), - ]); - } elseif (empty($forum_contact)) { - DI::notify()->createFromArray([ - 'type' => Notification\Type::WALL, - 'otype' => Notification\ObjectType::ITEM, - 'verb' => Activity::POST, - 'uid' => $profile_uid, - 'cid' => $datarray['author-id'], - 'item' => $datarray, - 'link' => DI::baseUrl() . '/display/' . urlencode($datarray['guid']), - ]); - } + if (!\Friendica\Content\Feature::isEnabled($post['uid'], 'explicit_mentions') && ($post['gravity'] == Item::GRAVITY_COMMENT)) { + Tag::createImplicitMentions($post['uri-id'], $post['thr-parent-id']); } - Hook::callAll('post_local_end', $datarray); + Hook::callAll('post_local_end', $post); - if (strlen($emailcc) && $profile_uid == DI::userSession()->getLocalUserId()) { - $recipients = explode(',', $emailcc); - if (count($recipients)) { - foreach ($recipients as $recipient) { - $address = trim($recipient); - if (!strlen($address)) { - continue; - } - DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(), - $datarray, $address, $author['thumb'] ?? '')); + $recipients = explode(',', $emailcc); + if (count($recipients)) { + foreach ($recipients as $recipient) { + $address = trim($recipient); + if (!strlen($address)) { + continue; } + + $author = DBA::selectFirst('contact', ['thumb'], ['uid' => $uid, 'self' => true]); + + DI::emailer()->send(new ItemCCEMail(DI::app(), DI::l10n(), DI::baseUrl(), + $post, $address, $author['thumb'] ?? '')); } } diff --git a/src/Content/Item.php b/src/Content/Item.php index 2cccf722ad..76a3a1f4a9 100644 --- a/src/Content/Item.php +++ b/src/Content/Item.php @@ -21,22 +21,33 @@ namespace Friendica\Content; +use Friendica\App\BaseURL; use Friendica\Content\Text\BBCode; +use Friendica\Content\Text\BBCode\Video; use Friendica\Content\Text\HTML; use Friendica\Core\Hook; use Friendica\Core\L10n; use Friendica\Core\Logger; +use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues; use Friendica\Core\Protocol; use Friendica\Core\Session\Capability\IHandleUserSessions; use Friendica\Core\System; use Friendica\Database\DBA; +use Friendica\Model\Attach; use Friendica\Model\Contact; +use Friendica\Model\Conversation; +use Friendica\Model\FileTag; use Friendica\Model\Group; use Friendica\Model\Item as ItemModel; use Friendica\Model\Photo; use Friendica\Model\Tag; use Friendica\Model\Post; +use Friendica\Model\User; +use Friendica\Network\HTTPException; use Friendica\Protocol\Activity; +use Friendica\Util\ACLFormatter; +use Friendica\Util\DateTimeFormat; +use Friendica\Util\ParseUrl; use Friendica\Util\Profiler; use Friendica\Util\Proxy; use Friendica\Util\XML; @@ -54,13 +65,25 @@ class Item private $profiler; /** @var IHandleUserSessions */ private $userSession; - - public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession) + /** @var Video */ + private $bbCodeVideo; + /** @var ACLFormatter */ + private $aclFormatter; + /** @var IManagePersonalConfigValues */ + private $pConfig; + /** @var BaseURL */ + private $baseURL; + + public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession, Video $bbCodeVideo, ACLFormatter $aclFormatter, IManagePersonalConfigValues $pConfig, BaseURL $baseURL) { - $this->profiler = $profiler; - $this->activity = $activity; - $this->l10n = $l10n; - $this->userSession = $userSession; + $this->profiler = $profiler; + $this->activity = $activity; + $this->l10n = $l10n; + $this->userSession = $userSession; + $this->bbCodeVideo = $bbCodeVideo; + $this->aclFormatter = $aclFormatter; + $this->baseURL = $baseURL; + $this->pConfig = $pConfig; } /** @@ -756,4 +779,216 @@ class Item return $body; } + + public function storeAttachmentFromRequest(array $request): string + { + $attachment_type = $request['attachment_type'] ?? ''; + $attachment_title = $request['attachment_title'] ?? ''; + $attachment_text = $request['attachment_text'] ?? ''; + + $attachment_url = hex2bin($request['attachment_url'] ?? ''); + $attachment_img_src = hex2bin($request['attachment_img_src'] ?? ''); + + $attachment_img_width = $request['attachment_img_width'] ?? 0; + $attachment_img_height = $request['attachment_img_height'] ?? 0; + + // Fetch the basic attachment data + $attachment = ParseUrl::getSiteinfoCached($attachment_url); + unset($attachment['keywords']); + + // Overwrite the basic data with possible changes from the frontend + $attachment['type'] = $attachment_type; + $attachment['title'] = $attachment_title; + $attachment['text'] = $attachment_text; + $attachment['url'] = $attachment_url; + + if (!empty($attachment_img_src)) { + $attachment['images'] = [ + 0 => [ + 'src' => $attachment_img_src, + 'width' => $attachment_img_width, + 'height' => $attachment_img_height + ] + ]; + } else { + unset($attachment['images']); + } + + return "\n" . PageInfo::getFooterFromData($attachment); + } + + public function addCategories(array $post, string $category): array + { + if (!empty($post['file'])) { + // get the "fileas" tags for this post + $filedas = FileTag::fileToArray($post['file']); + } + + $list_array = explode(',', trim($category)); + $post['file'] = FileTag::arrayToFile($list_array, 'category'); + + if (!empty($filedas) && is_array($filedas)) { + // append the fileas stuff to the new categories list + $post['file'] .= FileTag::arrayToFile($filedas); + } + return $post; + } + + public function getACL(array $post, array $toplevel_item, array $request): array + { + // If this is a comment, set the permissions from the parent. + if ($toplevel_item) { + $post['allow_cid'] = $toplevel_item['allow_cid'] ?? ''; + $post['allow_gid'] = $toplevel_item['allow_gid'] ?? ''; + $post['deny_cid'] = $toplevel_item['deny_cid'] ?? ''; + $post['deny_gid'] = $toplevel_item['deny_gid'] ?? ''; + $post['private'] = $toplevel_item['private']; + return $post; + } + + $user = User::getById($post['uid'], ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']); + if (!DBA::isResult($user)) { + throw new HTTPException\NotFoundException($this->l10n->t('Unable to locate original post.')); + } + + $post['allow_cid'] = isset($request['contact_allow']) ? $this->aclFormatter->toString($request['contact_allow']) : $user['allow_cid'] ?? ''; + $post['allow_gid'] = isset($request['group_allow']) ? $this->aclFormatter->toString($request['group_allow']) : $user['allow_gid'] ?? ''; + $post['deny_cid'] = isset($request['contact_deny']) ? $this->aclFormatter->toString($request['contact_deny']) : $user['deny_cid'] ?? ''; + $post['deny_gid'] = isset($request['group_deny']) ? $this->aclFormatter->toString($request['group_deny']) : $user['deny_gid'] ?? ''; + + $visibility = $request['visibility'] ?? ''; + if ($visibility === 'public') { + // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected + $post['allow_cid'] = $post['allow_gid'] = $post['deny_cid'] = $post['deny_gid'] = ''; + } else if ($visibility === 'custom') { + // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL + // case that would make it public. So we always append the author's contact id to the allowed contacts. + // See https://github.com/friendica/friendica/issues/9672 + $post['allow_cid'] .= $this->aclFormatter->toString(Contact::getPublicIdByUserId($post['uid'])); + } + + if (strlen($post['allow_gid']) || strlen($post['allow_cid']) || strlen($post['deny_gid']) || strlen($post['deny_cid'])) { + $post['private'] = ItemModel::PRIVATE; + } elseif ($this->pConfig->get($post['uid'], 'system', 'unlisted')) { + $post['private'] = ItemModel::UNLISTED; + } else { + $post['private'] = ItemModel::PUBLIC; + } + + return $post; + } + + public function moveAttachmentsFromBodyToAttach(array $post): array + { + if (!preg_match_all('/(\[attachment\]([0-9]+)\[\/attachment\])/',$post['body'], $match)) { + return $post; + } + + foreach ($match[2] as $attachment_id) { + $attachment = Attach::selectFirst(['id', 'uid', 'filename', 'filesize', 'filetype'], ['id' => $attachment_id, 'uid' => $post['uid']]); + if (empty($attachment)) { + continue; + } + if (strlen($post['attach'])) { + $post['attach'] .= ','; + } + $post['attach'] .= Post\Media::getAttachElement($this->baseURL->get() . '/attach/' . $attachment['id'], + $attachment['filesize'], $attachment['filetype'], $attachment['filename'] ?? ''); + + $fields = ['allow_cid' => $post['allow_cid'], 'allow_gid' => $post['allow_gid'], + 'deny_cid' => $post['deny_cid'], 'deny_gid' => $post['deny_gid']]; + $condition = ['id' => $attachment_id]; + Attach::update($fields, $condition); + } + + $post['body'] = str_replace($match[1], '', $post['body']); + + return $post; + } + + private function setObjectType(array $post): array + { + if (empty($post['post-type'])) { + $post['post-type'] = empty($post['title']) ? ItemModel::PT_NOTE : ItemModel::PT_ARTICLE; + } + + // embedded bookmark or attachment in post? set bookmark flag + $data = BBCode::getAttachmentData($post['body']); + if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $post['body'], $match, PREG_SET_ORDER) || isset($data['type'])) + && ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE)) { + $post['post-type'] = ItemModel::PT_PAGE; + $post['object-type'] = Activity\ObjectType::BOOKMARK; + } + + // Setting the object type if not defined before + if (empty($post['object-type'])) { + $post['object-type'] = ($post['gravity'] == ItemModel::GRAVITY_PARENT) ? Activity\ObjectType::NOTE : Activity\ObjectType::COMMENT; + + $objectdata = BBCode::getAttachedData($post['body']); + + if ($objectdata['type'] == 'link') { + $post['object-type'] = Activity\ObjectType::BOOKMARK; + } elseif ($objectdata['type'] == 'video') { + $post['object-type'] = Activity\ObjectType::VIDEO; + } elseif ($objectdata['type'] == 'photo') { + $post['object-type'] = Activity\ObjectType::IMAGE; + } + } + return $post; + } + + public function initializePost(array $post): array + { + $post['wall'] = true; + $post['origin'] = true; + $post['network'] = Protocol::DFRN; + $post['protocol'] = Conversation::PARCEL_DIRECT; + $post['direction'] = Conversation::PUSH; + $post['guid'] = System::createUUID(); + $post['uri'] = ItemModel::newURI($post['guid']); + $post['verb'] = Activity::POST; + $post['received'] = DateTimeFormat::utcNow(); + $owner = User::getOwnerDataById($post['uid']); + + if (empty($post['contact-id'])) { + $post['contact-id'] = $owner['id']; + } + + if (empty($post['author-link']) && empty($post['author-id'])) { + $post['author-link'] = $owner['url']; + $post['author-id'] = Contact::getIdForURL($post['author-link']); + $post['author-name'] = $owner['name']; + $post['author-avatar'] = $owner['thumb']; + } + + if (empty($post['owner-link']) && empty($post['owner-id'])) { + $post['owner-link'] = $post['author-link']; + $post['owner-id'] = Contact::getIdForURL($post['owner-link']); + $post['owner-name'] = $post['author-name']; + $post['owner-avatar'] = $post['author-avatar']; + } + + return $post; + } + + public function finalizePost(array $post): array + { + if (preg_match("/\[attachment\](.*?)\[\/attachment\]/ism", $post['body'], $matches)) { + $post['body'] = preg_replace("/\[attachment].*?\[\/attachment\]/ism", PageInfo::getFooterFromUrl($matches[1]), $post['body']); + } + + // Convert links with empty descriptions to links without an explicit description + $post['body'] = trim(preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $post['body'])); + $post['body'] = $this->bbCodeVideo->transform($post['body']); + $post['body'] = BBCode::scaleExternalImages($post['body']); + $post = $this->setObjectType($post); + + // Personal notes must never be altered to a forum post. + if ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE) { + // Look for any tags and linkify them + $post = $this->expandTags($post); + } + + return $post; + } } diff --git a/src/Model/Item.php b/src/Model/Item.php index 039a106e7d..d5a72c73e7 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -819,43 +819,8 @@ class Item private static function prepareOriginPost(array $item): array { - $item['wall'] = 1; - $item['origin'] = 1; - $item['network'] = Protocol::DFRN; - $item['protocol'] = Conversation::PARCEL_DIRECT; - $item['direction'] = Conversation::PUSH; - - $owner = User::getOwnerDataById($item['uid']); - - if (empty($item['contact-id'])) { - $item['contact-id'] = $owner['id']; - } - - if (empty($item['author-link']) && empty($item['author-id'])) { - $item['author-link'] = $owner['url']; - $item['author-name'] = $owner['name']; - $item['author-avatar'] = $owner['thumb']; - } - - if (empty($item['owner-link']) && empty($item['owner-id'])) { - $item['owner-link'] = $item['author-link']; - $item['owner-name'] = $item['author-name']; - $item['owner-avatar'] = $item['author-avatar']; - } - - // Setting the object type if not defined before - if (empty($item['object-type'])) { - $item['object-type'] = Activity\ObjectType::NOTE; // Default value - $objectdata = BBCode::getAttachedData($item['body']); - - if ($objectdata['type'] == 'link') { - $item['object-type'] = Activity\ObjectType::BOOKMARK; - } elseif ($objectdata['type'] == 'video') { - $item['object-type'] = Activity\ObjectType::VIDEO; - } elseif ($objectdata['type'] == 'photo') { - $item['object-type'] = Activity\ObjectType::IMAGE; - } - } + $item = DI::contentItem()->initializePost($item); + $item = DI::contentItem()->finalizePost($item); return $item; }