diff --git a/.travis.yml b/.travis.yml index c3d009201..4ea3ac7ab 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,7 @@ services: - redis-server - memcached env: - - MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_USERNAME=travis MYSQL_PASSWORD= MYSQL_DATABASE=test + - MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_USERNAME=travis MYSQL_PASSWORD="" MYSQL_DATABASE=test install: - composer install diff --git a/database.sql b/database.sql index 9d4086994..04a35634e 100644 --- a/database.sql +++ b/database.sql @@ -1,6 +1,6 @@ -- ------------------------------------------ -- Friendica 2020.03-dev (Dalmatian Bellflower) --- DB_UPDATE_VERSION 1333 +-- DB_UPDATE_VERSION 1334 -- ------------------------------------------ @@ -179,7 +179,7 @@ CREATE TABLE IF NOT EXISTS `contact` ( `location` varchar(255) DEFAULT '' COMMENT '', `about` text COMMENT '', `keywords` text COMMENT 'public keywords (interests) of the contact', - `gender` varchar(32) NOT NULL DEFAULT '' COMMENT '', + `gender` varchar(32) NOT NULL DEFAULT '' COMMENT 'Deprecated', `xmpp` varchar(255) NOT NULL DEFAULT '' COMMENT '', `attag` varchar(255) NOT NULL DEFAULT '' COMMENT '', `avatar` varchar(255) NOT NULL DEFAULT '' COMMENT '', @@ -397,7 +397,7 @@ CREATE TABLE IF NOT EXISTS `gcontact` ( `location` varchar(255) NOT NULL DEFAULT '' COMMENT '', `about` text COMMENT '', `keywords` text COMMENT 'puplic keywords (interests)', - `gender` varchar(32) NOT NULL DEFAULT '' COMMENT '', + `gender` varchar(32) NOT NULL DEFAULT '' COMMENT 'Deprecated', `birthday` varchar(32) NOT NULL DEFAULT '0001-01-01' COMMENT '', `community` boolean NOT NULL DEFAULT '0' COMMENT '1 if contact is forum account', `contact-type` tinyint NOT NULL DEFAULT -1 COMMENT '', @@ -568,7 +568,7 @@ CREATE TABLE IF NOT EXISTS `item` ( `extid` varchar(255) NOT NULL DEFAULT '' COMMENT '', `post-type` tinyint unsigned NOT NULL DEFAULT 0 COMMENT 'Post type (personal note, bookmark, ...)', `global` boolean NOT NULL DEFAULT '0' COMMENT '', - `private` boolean NOT NULL DEFAULT '0' COMMENT 'distribution is restricted', + `private` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '0=public, 1=private, 2=unlisted', `visible` boolean NOT NULL DEFAULT '0' COMMENT '', `moderated` boolean NOT NULL DEFAULT '0' COMMENT '', `deleted` boolean NOT NULL DEFAULT '0' COMMENT 'item has been deleted', @@ -1057,19 +1057,18 @@ CREATE TABLE IF NOT EXISTS `profile_check` ( -- TABLE profile_field -- CREATE TABLE IF NOT EXISTS `profile_field` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'sequential ID', - `uid` mediumint(8) unsigned NOT NULL DEFAULT 0 COMMENT 'Owner user id', - `psid` int(10) unsigned DEFAULT NULL COMMENT 'ID of the permission set of this profile field - 0 = public', - `name` varchar(255) NOT NULL DEFAULT '' COMMENT 'Name of the field', - `value` text COMMENT 'Value of the field', - `order` mediumint(8) unsigned NOT NULL DEFAULT 1 COMMENT 'Field ordering per user', - `label` varchar(255) NOT NULL DEFAULT '' COMMENT 'Label of the field', - `created` datetime NOT NULL DEFAULT '0001-01-01 00:00:00' COMMENT '', - `edited` datetime NOT NULL DEFAULT '0001-01-01 00:00:00' COMMENT '', - PRIMARY KEY (`id`), - KEY `uid` (`uid`), - KEY `psid` (`psid`), - KEY `order` (`order`) + `id` int unsigned NOT NULL auto_increment COMMENT 'sequential ID', + `uid` mediumint unsigned NOT NULL DEFAULT 0 COMMENT 'Owner user id', + `order` mediumint unsigned NOT NULL DEFAULT 1 COMMENT 'Field ordering per user', + `psid` int unsigned COMMENT 'ID of the permission set of this profile field - 0 = public', + `label` varchar(255) NOT NULL DEFAULT '' COMMENT 'Label of the field', + `value` text COMMENT 'Value of the field', + `created` datetime NOT NULL DEFAULT '0001-01-01 00:00:00' COMMENT 'creation time', + `edited` datetime NOT NULL DEFAULT '0001-01-01 00:00:00' COMMENT 'last edit time', + PRIMARY KEY(`id`), + INDEX `uid` (`uid`), + INDEX `order` (`order`), + INDEX `psid` (`psid`) ) DEFAULT COLLATE utf8mb4_general_ci COMMENT='Custom profile fields'; -- @@ -1179,7 +1178,7 @@ CREATE TABLE IF NOT EXISTS `thread` ( `received` datetime NOT NULL DEFAULT '0001-01-01 00:00:00' COMMENT '', `changed` datetime NOT NULL DEFAULT '0001-01-01 00:00:00' COMMENT '', `wall` boolean NOT NULL DEFAULT '0' COMMENT '', - `private` boolean NOT NULL DEFAULT '0' COMMENT '', + `private` tinyint unsigned NOT NULL DEFAULT 0 COMMENT '0=public, 1=private, 2=unlisted', `pubmail` boolean NOT NULL DEFAULT '0' COMMENT '', `moderated` boolean NOT NULL DEFAULT '0' COMMENT '', `visible` boolean NOT NULL DEFAULT '0' COMMENT '', diff --git a/doc/BBCode.md b/doc/BBCode.md index b13d08119..cab51bd09 100644 --- a/doc/BBCode.md +++ b/doc/BBCode.md @@ -113,17 +113,17 @@ table.bbcodes > * > tr > th { [bookmark]http://friendi.ca[/bookmark]

#^[url]http://friendi.ca[/url] -

Friendica: http://friendi.ca

+

Friendica: http://friendi.ca

[bookmark=http://friendi.ca]Bookmark[/bookmark]

#^[url=http://friendi.ca]Bookmark[/url]

#[url=http://friendi.ca]^[/url][url=http://friendi.ca]Bookmark[/url] -

Friendica: Bookmark

+

Friendica: Bookmark

[url=/posts/f16d77b0630f0134740c0cc47a0ea02a]Diaspora post with GUID[/url] - Diaspora post with GUID + Diaspora post with GUID #Friendica diff --git a/doc/de/BBCode.md b/doc/de/BBCode.md index 5789be2e5..1db798427 100644 --- a/doc/de/BBCode.md +++ b/doc/de/BBCode.md @@ -113,17 +113,17 @@ table.bbcodes > * > tr > th { [bookmark]http://friendi.ca[/bookmark]

#^[url]http://friendi.ca[/url] -

Friendica: http://friendi.ca

+

Friendica: http://friendi.ca

[bookmark=http://friendi.ca]Lesezeichen[/bookmark]

#^[url=http://friendi.ca]Lesezeichen[/url]

#[url=http://friendi.ca]^[/url][url=http://friendi.ca]Lesezeichen[/url] -

Friendica: Lesezeichen

+

Friendica: Lesezeichen

[url=/posts/f16d77b0630f0134740c0cc47a0ea02a]Diaspora Beitrag mit GUID[/url] - Diaspora Beitrag mit GUID + Diaspora Beitrag mit GUID #Friendica diff --git a/doc/de/Chats.md b/doc/de/Chats.md index 77dfdeb44..9c1a82b18 100644 --- a/doc/de/Chats.md +++ b/doc/de/Chats.md @@ -25,13 +25,13 @@ In den ersten Zeilen wird Dir Dein Name und Deine aktuelle IP-Adresse angezeigt. Rechts im Fenster siehst Du alle Teilnehmer des Chats. Unten hast Du ein Eingabefeld, um Beiträge zu schreiben. -Weiter Informationen zu IRC findest Du zum Beispiel auf ubuntuusers.de, in Wikipedia oder bei icrhelp.org (in Englisch). +Weiter Informationen zu IRC findest Du zum Beispiel auf ubuntuusers.de, in Wikipedia oder bei icrhelp.org (in Englisch). ## Jappix Mini Das Jappix Mini Addon erlaubt das Erstellen einer Chatbox für Jabber/XMPP-Kontakte. Ein Jabber/XMPP Account sollte vor der Installation bereits vorhanden sein. -Die ausführliche Anleitung dazu und eine Kontrolle, ob Du nicht sogar schon über Deinen E-Mail Anbieter einen Jabber-Account hast, findest Du unter einfachjabber.de. +Die ausführliche Anleitung dazu und eine Kontrolle, ob Du nicht sogar schon über Deinen E-Mail Anbieter einen Jabber-Account hast, findest Du unter einfachjabber.de. Einige Server zum Anmelden eines neuen Accounts: diff --git a/doc/de/Developers.md b/doc/de/Developers.md index 2b44e405f..4c5e4a62b 100644 --- a/doc/de/Developers.md +++ b/doc/de/Developers.md @@ -26,4 +26,4 @@ Dies gilt vor allem für Übersetzungen, da wir hier möglicherweise nicht alle Außerdem: **teste Deine Änderungen!** Vergiss nicht, dass eine simple Fehlerlösung einen anderen Fehler auslösen kann. Lass Deine Änderungen von einem erfahrenen Friendica-Entwickler gegenprüfen. -Eine ausführliche Anleitung zu Git findest Du unter https://git-scm.com/book/de/v1. +Eine ausführliche Anleitung zu Git findest Du unter https://git-scm.com/book/de/v1. diff --git a/include/api.php b/include/api.php index 567e3cc43..3a29184ec 100644 --- a/include/api.php +++ b/include/api.php @@ -25,7 +25,6 @@ use Friendica\App; use Friendica\Content\ContactSelector; -use Friendica\Content\Feature; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; use Friendica\Core\Hook; @@ -42,7 +41,6 @@ use Friendica\Model\Item; use Friendica\Model\Mail; use Friendica\Model\Notify; use Friendica\Model\Photo; -use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Model\UserItem; use Friendica\Network\FKOAuth1; @@ -785,7 +783,7 @@ function api_item_get_user(App $a, $item) $author_user = $status_user; - $status_user["protected"] = $item['private'] ?? 0; + $status_user["protected"] = isset($item['private']) && ($item['private'] == Item::PRIVATE); if (($item['thr-parent'] ?? '') == ($item['uri'] ?? '')) { $owner_user = api_get_user($a, $item['owner-id'] ?? null); @@ -1344,7 +1342,7 @@ function api_get_last_status($ownerId, $uid) 'author-id'=> $ownerId, 'uid' => $uid, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], - 'private' => false + 'private' => [Item::PUBLIC, Item::UNLISTED] ]; $item = api_get_item($condition); @@ -1734,8 +1732,8 @@ function api_statuses_public_timeline($type) $start = max(0, ($page - 1) * $count); if ($exclude_replies && !$conversation_id) { - $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND NOT `author`.`hidden`", - GRAVITY_PARENT, GRAVITY_COMMENT, $since_id]; + $condition = ["`gravity` IN (?, ?) AND `iid` > ? AND `private` = ? AND `wall` AND NOT `author`.`hidden`", + GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC]; if ($max_id > 0) { $condition[0] .= " AND `thread`.`iid` <= ?"; @@ -1747,8 +1745,8 @@ function api_statuses_public_timeline($type) $r = Item::inArray($statuses); } else { - $condition = ["`gravity` IN (?, ?) AND `id` > ? AND NOT `private` AND `wall` AND NOT `user`.`hidewall` AND `item`.`origin` AND NOT `author`.`hidden`", - GRAVITY_PARENT, GRAVITY_COMMENT, $since_id]; + $condition = ["`gravity` IN (?, ?) AND `id` > ? AND `private` = ? AND `wall` AND `item`.`origin` AND NOT `author`.`hidden`", + GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC]; if ($max_id > 0) { $condition[0] .= " AND `item`.`id` <= ?"; @@ -1813,8 +1811,8 @@ function api_statuses_networkpublic_timeline($type) $start = max(0, ($page - 1) * $count); - $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND NOT `private`", - GRAVITY_PARENT, GRAVITY_COMMENT, $since_id]; + $condition = ["`uid` = 0 AND `gravity` IN (?, ?) AND `thread`.`iid` > ? AND `private` = ?", + GRAVITY_PARENT, GRAVITY_COMMENT, $since_id, Item::PUBLIC]; if ($max_id > 0) { $condition[0] .= " AND `thread`.`iid` <= ?"; @@ -2042,7 +2040,7 @@ function api_statuses_repeat($type) Logger::log('API: api_statuses_repeat: '.$id); $fields = ['body', 'title', 'attach', 'tag', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink']; - $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]); + $item = Item::selectFirst($fields, ['id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED]]); if (DBA::isResult($item) && $item['body'] != "") { if (strpos($item['body'], "[/share]") !== false) { @@ -3007,7 +3005,7 @@ function api_format_item($item, $type = "json", $status_user = null, $author_use 'user' => $status_user, 'friendica_author' => $author_user, 'friendica_owner' => $owner_user, - 'friendica_private' => $item['private'] == 1, + 'friendica_private' => $item['private'] == Item::PRIVATE, //'entities' => NULL, 'statusnet_html' => $converted["html"], 'statusnet_conversation_id' => $item['parent'], @@ -5920,7 +5918,7 @@ function api_friendica_notification_seen($type) $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0); try { - $notify = DI::notify()->getByID($id); + $notify = DI::notify()->getByID($id, api_user()); DI::notify()->setSeen(true, $notify); if ($notify->otype === Notify\ObjectType::ITEM) { diff --git a/include/conversation.php b/include/conversation.php index f29e6d325..8c09fa98b 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -579,12 +579,12 @@ function conversation(App $a, array $items, $mode, $update, $preview = false, $o $items = $cb['items']; $conv_responses = [ - 'like' => ['title' => DI::l10n()->t('Likes','title')], - 'dislike' => ['title' => DI::l10n()->t('Dislikes','title')], - 'attendyes' => ['title' => DI::l10n()->t('Attending','title')], - 'attendno' => ['title' => DI::l10n()->t('Not attending','title')], - 'attendmaybe' => ['title' => DI::l10n()->t('Might attend','title')], - 'announce' => ['title' => DI::l10n()->t('Reshares','title')] + 'like' => [], + 'dislike' => [], + 'attendyes' => [], + 'attendno' => [], + 'attendmaybe' => [], + 'announce' => [], ]; if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) { @@ -1572,56 +1572,3 @@ function render_location_dummy(array $item) { return $item['coord']; } } - -function get_responses(array $conv_responses, array $response_verbs, array $item, Post $ob = null) { - $ret = []; - foreach ($response_verbs as $v) { - $ret[$v] = []; - $ret[$v]['count'] = $conv_responses[$v][$item['uri']] ?? 0; - $ret[$v]['list'] = $conv_responses[$v][$item['uri'] . '-l'] ?? []; - $ret[$v]['self'] = $conv_responses[$v][$item['uri'] . '-self'] ?? '0'; - if (count($ret[$v]['list']) > MAX_LIKERS) { - $ret[$v]['list_part'] = array_slice($ret[$v]['list'], 0, MAX_LIKERS); - array_push($ret[$v]['list_part'], '' . DI::l10n()->t('View all') . ''); - } else { - $ret[$v]['list_part'] = ''; - } - $ret[$v]['button'] = get_response_button_text($v, $ret[$v]['count']); - $ret[$v]['title'] = $conv_responses[$v]['title']; - } - - $count = 0; - foreach ($ret as $key) { - if ($key['count'] == true) { - $count++; - } - } - $ret['count'] = $count; - - return $ret; -} - -function get_response_button_text($v, $count) -{ - $return = ''; - switch ($v) { - case 'like': - $return = DI::l10n()->tt('Like', 'Likes', $count); - break; - case 'dislike': - $return = DI::l10n()->tt('Dislike', 'Dislikes', $count); - break; - case 'attendyes': - $return = DI::l10n()->tt('Attending', 'Attending', $count); - break; - case 'attendno': - $return = DI::l10n()->tt('Not Attending', 'Not Attending', $count); - break; - case 'attendmaybe': - $return = DI::l10n()->tt('Undecided', 'Undecided', $count); - break; - } - - return $return; -} diff --git a/mod/display.php b/mod/display.php index dce8b25b9..fd0079f9f 100644 --- a/mod/display.php +++ b/mod/display.php @@ -70,7 +70,7 @@ function display_init(App $a) // Is this item private but could be visible to the remove visitor? if (!DBA::isResult($item) && remote_user()) { - $item = Item::selectFirst($fields, ['guid' => $a->argv[1], 'private' => 1, 'origin' => true]); + $item = Item::selectFirst($fields, ['guid' => $a->argv[1], 'private' => Item::PRIVATE, 'origin' => true]); if (DBA::isResult($item)) { if (!Contact::isFollower(remote_user(), $item['uid'])) { $item = null; @@ -82,14 +82,14 @@ function display_init(App $a) // Is it an item with uid=0? if (!DBA::isResult($item)) { - $item = Item::selectFirstForUser(local_user(), $fields, ['guid' => $a->argv[1], 'private' => [0, 2], 'uid' => 0]); + $item = Item::selectFirstForUser(local_user(), $fields, ['guid' => $a->argv[1], 'private' => [Item::PUBLIC, Item::UNLISTED], 'uid' => 0]); } } elseif ($a->argc >= 3 && $nick == 'feed-item') { $item_id = $a->argv[2]; if (substr($item_id, -5) == '.atom') { $item_id = substr($item_id, 0, -5); } - $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $item_id, 'private' => [0, 2], 'uid' => 0]); + $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $item_id, 'private' => [Item::PUBLIC, Item::UNLISTED], 'uid' => 0]); } if (!DBA::isResult($item)) { @@ -216,7 +216,7 @@ function display_content(App $a, $update = false, $update_uid = 0) } if (($item_parent == 0) && remote_user()) { - $item = Item::selectFirst($fields, ['guid' => $a->argv[1], 'private' => 1, 'origin' => true]); + $item = Item::selectFirst($fields, ['guid' => $a->argv[1], 'private' => Item::PRIVATE, 'origin' => true]); if (DBA::isResult($item) && Contact::isFollower(remote_user(), $item['uid'])) { $item_id = $item["id"]; $item_parent = $item["parent"]; @@ -225,7 +225,7 @@ function display_content(App $a, $update = false, $update_uid = 0) } if ($item_parent == 0) { - $condition = ['private' => [0, 2], 'guid' => $a->argv[1], 'uid' => 0]; + $condition = ['private' => [Item::PUBLIC, Item::UNLISTED], 'guid' => $a->argv[1], 'uid' => 0]; $item = Item::selectFirstForUser(local_user(), $fields, $condition); if (DBA::isResult($item)) { $item_id = $item["id"]; @@ -241,7 +241,7 @@ function display_content(App $a, $update = false, $update_uid = 0) } // We are displaying an "alternate" link if that post was public. See issue 2864 - $is_public = Item::exists(['id' => $item_id, 'private' => [0, 2]]); + $is_public = Item::exists(['id' => $item_id, 'private' => [Item::PUBLIC, Item::UNLISTED]]); if ($is_public) { // For the atom feed the nickname doesn't matter at all, we only need the item id. $alternate = DI::baseUrl().'/display/feed-item/'.$item_id.'.atom'; diff --git a/mod/item.php b/mod/item.php index 2e5a08203..a9f1ef808 100644 --- a/mod/item.php +++ b/mod/item.php @@ -300,7 +300,13 @@ function item_post(App $a) { $postopts = $_REQUEST['postopts'] ?? ''; - $private = ((strlen($str_group_allow) || strlen($str_contact_allow) || strlen($str_group_deny) || strlen($str_contact_deny)) ? 1 : 0); + 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. diff --git a/mod/lockview.php b/mod/lockview.php index d3eceb4e0..e48debfc6 100644 --- a/mod/lockview.php +++ b/mod/lockview.php @@ -66,7 +66,7 @@ function lockview_content(App $a) } if (isset($item['private']) - && $item['private'] == 1 + && $item['private'] == Item::PRIVATE && empty($item['allow_cid']) && empty($item['allow_gid']) && empty($item['deny_cid']) diff --git a/mod/photos.php b/mod/photos.php index 951126155..ef957ad5b 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -204,13 +204,13 @@ function photos_post(App $a) if (!DBA::isResult($r)) { notice(DI::l10n()->t('Album not found.') . EOL); - DI::baseUrl()->redirect($_SESSION['photo_return']); + DI::baseUrl()->redirect('photos/' . $a->data['user']['nickname'] . '/album'); return; // NOTREACHED } // Check if the user has responded to a delete confirmation query if (!empty($_REQUEST['canceled'])) { - DI::baseUrl()->redirect($_SESSION['photo_return']); + DI::baseUrl()->redirect('photos/' . $a->data['user']['nickname'] . '/album/' . $a->argv[3]); } // RENAME photo album @@ -267,7 +267,7 @@ function photos_post(App $a) } } - DI::baseUrl()->redirect('photos/' . $a->argv[1]); + DI::baseUrl()->redirect('photos/' . $a->data['user']['nickname'] . '/album'); } if ($a->argc > 3 && $a->argv[2] === 'image') { @@ -1372,7 +1372,6 @@ function photos_content(App $a) $likebuttons = ''; $comments = ''; $paginate = ''; - $responses = ''; if (!empty($link_item['id']) && !empty($link_item['uri'])) { $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl'); @@ -1413,11 +1412,11 @@ function photos_content(App $a) } $conv_responses = [ - 'like' => ['title' => DI::l10n()->t('Likes','title')], - 'dislike' => ['title' => DI::l10n()->t('Dislikes','title')], - 'attendyes' => ['title' => DI::l10n()->t('Attending','title')], - 'attendno' => ['title' => DI::l10n()->t('Not attending','title')], - 'attendmaybe' => ['title' => DI::l10n()->t('Might attend','title')] + 'like' => [], + 'dislike' => [], + 'attendyes' => [], + 'attendno' => [], + 'attendmaybe' => [] ]; if (DI::pConfig()->get(local_user(), 'system', 'hide_dislike')) { @@ -1460,7 +1459,6 @@ function photos_content(App $a) foreach ($items as $item) { $comment = ''; $template = $tpl; - $sparkle = ''; $activity = DI::activity(); @@ -1523,8 +1521,6 @@ function photos_content(App $a) } } - $responses = get_responses($conv_responses, ['like', 'dislike'], $link_item); - $paginate = $pager->renderFull($total); } @@ -1544,7 +1540,6 @@ function photos_content(App $a) '$likebuttons' => $likebuttons, '$like' => $like, '$dislike' => $dislike, - 'responses' => $responses, '$comments' => $comments, '$paginate' => $paginate, ]); diff --git a/mod/poke.php b/mod/poke.php index 0034a2d87..a683b1141 100644 --- a/mod/poke.php +++ b/mod/poke.php @@ -84,7 +84,7 @@ function poke_init(App $a) $deny_gid = $item['deny_gid']; } } else { - $private = (!empty($_GET['private']) ? intval($_GET['private']) : 0); + $private = (!empty($_GET['private']) ? intval($_GET['private']) : Item::PUBLIC); $allow_cid = ($private ? '<' . $target['id']. '>' : $a->user['allow_cid']); $allow_gid = ($private ? '' : $a->user['allow_gid']); diff --git a/mod/pubsubhubbub.php b/mod/pubsubhubbub.php index 3d6b48fd4..4d3350379 100644 --- a/mod/pubsubhubbub.php +++ b/mod/pubsubhubbub.php @@ -84,18 +84,12 @@ function pubsubhubbub_init(App $a) { // fetch user from database given the nickname $condition = ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]; - $owner = DBA::selectFirst('user', ['uid', 'hidewall', 'nickname'], $condition); + $owner = DBA::selectFirst('user', ['uid', 'nickname'], $condition); if (!DBA::isResult($owner)) { Logger::log('Local account not found: ' . $nick . ' - topic: ' . $hub_topic . ' - callback: ' . $hub_callback); throw new \Friendica\Network\HTTPException\NotFoundException(); } - // abort if user's wall is supposed to be private - if ($owner['hidewall']) { - Logger::log('Local user ' . $nick . 'has chosen to hide wall, ignoring.'); - throw new \Friendica\Network\HTTPException\ForbiddenException(); - } - // get corresponding row from contact table $condition = ['uid' => $owner['uid'], 'blocked' => false, 'pending' => false, 'self' => true]; diff --git a/mod/regmod.php b/mod/regmod.php deleted file mode 100644 index df1020b9f..000000000 --- a/mod/regmod.php +++ /dev/null @@ -1,120 +0,0 @@ -. - * - */ - -use Friendica\App; -use Friendica\Core\Worker; -use Friendica\Database\DBA; -use Friendica\DI; -use Friendica\Model\Register; -use Friendica\Model\User; -use Friendica\Module\Security\Login; - -function user_allow($hash) -{ - $register = Register::getByHash($hash); - if (!DBA::isResult($register)) { - return false; - } - - $user = User::getById($register['uid']); - if (!DBA::isResult($user)) { - exit(); - } - - Register::deleteByHash($hash); - - DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]); - - $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]); - - if (DBA::isResult($profile) && $profile['net-publish'] && DI::config()->get('system', 'directory')) { - $url = DI::baseUrl() . '/profile/' . $user['nickname']; - Worker::add(PRIORITY_LOW, "Directory", $url); - } - - $l10n = DI::l10n()->withLang($register['language']); - - $res = User::sendRegisterOpenEmail( - $l10n, - $user, - DI::config()->get('config', 'sitename'), - DI::baseUrl()->get(), - ($register['password'] ?? '') ?: 'Sent in a previous email' - ); - - if ($res) { - info(DI::l10n()->t('Account approved.') . EOL); - return true; - } -} - -// This does not have to go through user_remove() and save the nickname -// permanently against re-registration, as the person was not yet -// allowed to have friends on this system -function user_deny($hash) -{ - $register = Register::getByHash($hash); - if (!DBA::isResult($register)) { - return false; - } - - $user = User::getById($register['uid']); - if (!DBA::isResult($user)) { - exit(); - } - - DBA::delete('user', ['uid' => $register['uid']]); - - Register::deleteByHash($register['hash']); - - notice(DI::l10n()->t('Registration revoked for %s', $user['username']) . EOL); - return true; -} - -function regmod_content(App $a) -{ - if (!local_user()) { - info(DI::l10n()->t('Please login.') . EOL); - return Login::form(DI::args()->getQueryString(), intval(DI::config()->get('config', 'register_policy')) === \Friendica\Module\Register::CLOSED ? 0 : 1); - } - - if (!is_site_admin() || !empty($_SESSION['submanage'])) { - notice(DI::l10n()->t('Permission denied.') . EOL); - return ''; - } - - if ($a->argc != 3) { - exit(); - } - - $cmd = $a->argv[1]; - $hash = $a->argv[2]; - - if ($cmd === 'deny') { - user_deny($hash); - DI::baseUrl()->redirect('admin/users/'); - } - - if ($cmd === 'allow') { - user_allow($hash); - DI::baseUrl()->redirect('admin/users/'); - } -} diff --git a/mod/settings.php b/mod/settings.php index fcbd8208d..9a73b83e6 100644 --- a/mod/settings.php +++ b/mod/settings.php @@ -27,7 +27,6 @@ use Friendica\Core\ACL; use Friendica\Core\Hook; use Friendica\Core\Logger; use Friendica\Core\Renderer; -use Friendica\Core\Theme; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; @@ -252,6 +251,8 @@ function settings_post(App $a) unlink($_FILES['importcontact-filename']['tmp_name']); } } + + return; } if (!empty($_POST['resend_relocate'])) { @@ -317,6 +318,7 @@ function settings_post(App $a) $cntunkmail = (!empty($_POST['cntunkmail']) ? intval($_POST['cntunkmail']) : 0); $hide_friends = (($_POST['hide-friends'] == 1) ? 1: 0); $hidewall = (($_POST['hidewall'] == 1) ? 1: 0); + $unlisted = (($_POST['unlisted'] == 1) ? 1: 0); $email_textonly = (($_POST['email_textonly'] == 1) ? 1 : 0); $detailed_notif = (($_POST['detailed_notif'] == 1) ? 1 : 0); @@ -363,17 +365,17 @@ function settings_post(App $a) if ($username != $a->user['username']) { if (strlen($username) > 40) { - $err .= DI::l10n()->t(' Please use a shorter name.'); + $err .= DI::l10n()->t('Please use a shorter name.'); } if (strlen($username) < 3) { - $err .= DI::l10n()->t(' Name too short.'); + $err .= DI::l10n()->t('Name too short.'); } } if ($email != $a->user['email']) { // check for the correct password if (!User::authenticate(intval(local_user()), $_POST['mpassword'])) { - $err .= DI::l10n()->t('Wrong Password') . EOL; + $err .= DI::l10n()->t('Wrong Password.'); $email = $a->user['email']; } // check the email is valid @@ -391,7 +393,7 @@ function settings_post(App $a) } if (strlen($err)) { - notice($err . EOL); + notice($err); return; } @@ -414,6 +416,7 @@ function settings_post(App $a) DI::pConfig()->set(local_user(), 'system', 'email_textonly', $email_textonly); DI::pConfig()->set(local_user(), 'system', 'detailed_notif', $detailed_notif); + DI::pConfig()->set(local_user(), 'system', 'unlisted', $unlisted); if ($page_flags == User::PAGE_FLAGS_PRVGROUP) { $hidewall = 1; @@ -597,7 +600,7 @@ function settings_content(App $a) $arr[$fname] = []; $arr[$fname][0] = $fdata[0]; foreach (array_slice($fdata,1) as $f) { - $arr[$fname][1][] = ['feature_' .$f[0], $f[1],((intval(Feature::isEnabled(local_user(), $f[0]))) ? "1" : ''), $f[2],[DI::l10n()->t('Off'), DI::l10n()->t('On')]]; + $arr[$fname][1][] = ['feature_' . $f[0], $f[1], Feature::isEnabled(local_user(), $f[0]), $f[2]]; } } @@ -836,6 +839,10 @@ function settings_content(App $a) '$field' => ['hidewall', DI::l10n()->t('Hide your profile details from anonymous viewers?'), $a->user['hidewall'], DI::l10n()->t('Anonymous visitors will only see your profile picture, your display name and the nickname you are using on your profile page. Your public posts and replies will still be accessible by other means.')], ]); + $unlisted = Renderer::replaceMacros($opt_tpl, [ + '$field' => ['unlisted', DI::l10n()->t('Make public posts unlisted'), DI::pConfig()->get(local_user(), 'system', 'unlisted'), DI::l10n()->t('Your public posts will not appear on the community pages or in search results, nor be sent to relay servers. However they can still appear on public feeds on remote servers.')], + ]); + $blockwall = Renderer::replaceMacros($opt_tpl, [ '$field' => ['blockwall', DI::l10n()->t('Allow friends to post to your profile page?'), (intval($a->user['blockwall']) ? '0' : '1'), DI::l10n()->t('Your contacts may write posts on your profile wall. These posts will be distributed to your contacts')], ]); @@ -949,6 +956,7 @@ function settings_content(App $a) '$profile_in_net_dir' => $profile_in_net_dir, '$hide_friends' => $hide_friends, '$hide_wall' => $hide_wall, + '$unlisted' => $unlisted, '$unkmail' => $unkmail, '$cntunkmail' => ['cntunkmail', DI::l10n()->t('Maximum private messages per day from unknown people:'), $cntunkmail , DI::l10n()->t("\x28to prevent spam abuse\x29")], diff --git a/mod/share.php b/mod/share.php index 998ebe5fd..3e9b6aee6 100644 --- a/mod/share.php +++ b/mod/share.php @@ -34,7 +34,7 @@ function share_init(App $a) { 'guid', 'created', 'plink', 'title']; $item = Item::selectFirst($fields, ['id' => $post_id]); - if (!DBA::isResult($item) || $item['private'] == 1) { + if (!DBA::isResult($item) || $item['private'] == Item::PRIVATE) { exit(); } diff --git a/mod/update_contact.php b/mod/update_contact.php index 5fb62e6a0..4863ad02d 100644 --- a/mod/update_contact.php +++ b/mod/update_contact.php @@ -28,7 +28,7 @@ use Friendica\Module\Contact; function update_contact_content(App $a) { - if ($_GET["force"] == 1) { + if (!empty($_GET['force']) || !DI::pConfig()->get(local_user(), 'system', 'no_auto_update')) { $text = Contact::content([], true); } else { $text = ''; diff --git a/src/Console/NewPassword.php b/src/Console/NewPassword.php deleted file mode 100644 index 118428866..000000000 --- a/src/Console/NewPassword.php +++ /dev/null @@ -1,126 +0,0 @@ -. - * - */ - -namespace Friendica\Console; - -use Friendica\App; -use Friendica\Core\L10n; -use Friendica\Database\Database; -use Friendica\Model\User; -use RuntimeException; - -/** - * tool to set a new password for a user - * - * With this tool, you can set a new password for a user - */ -class NewPassword extends \Asika\SimpleConsole\Console -{ - protected $helpOptions = ['h', 'help', '?']; - - /** - * @var App\Mode - */ - private $appMode; - /** - * @var L10n - */ - private $l10n; - /** - * @var Database - */ - private $dba; - - protected function getHelp() - { - $help = << [] [-h|--help|-?] [-v] - -Description - Creates a new password for a user without using the "forgot password" functionality. - -Options - -h|--help|-? Show help information - -v Show more debug information. -HELP; - return $help; - } - - public function __construct(App\Mode $appMode, L10n $l10n, Database $dba, array $argv = null) - { - parent::__construct($argv); - - $this->appMode = $appMode; - $this->l10n = $l10n; - $this->dba = $dba; - } - - protected function doExecute() - { - if ($this->getOption('v')) { - $this->out('Class: ' . __CLASS__); - $this->out('Arguments: ' . var_export($this->args, true)); - $this->out('Options: ' . var_export($this->options, true)); - } - - if (count($this->args) == 0) { - $this->out($this->getHelp()); - return 0; - } - - if (count($this->args) > 2) { - throw new \Asika\SimpleConsole\CommandArgsException('Too many arguments'); - } - - if ($this->appMode->isInstall()) { - throw new RuntimeException('Database isn\'t ready or populated yet'); - } - - $nick = $this->getArgument(0); - - $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]); - if (!$this->dba->isResult($user)) { - throw new RuntimeException($this->l10n->t('User not found')); - } - - $password = $this->getArgument(1); - if (is_null($password)) { - $this->out($this->l10n->t('Enter new password: '), false); - $password = \Seld\CliPrompt\CliPrompt::hiddenPrompt(true); - } - - try { - $result = User::updatePassword($user['uid'], $password); - - if (!$this->dba->isResult($result)) { - throw new \Exception($this->l10n->t('Password update failed. Please try again.')); - } - - $this->out($this->l10n->t('Password changed.')); - } catch (\Exception $e) { - throw new RuntimeException($e->getMessage(), $e->getCode(), $e); - } - - return 0; - } -} diff --git a/src/Console/User.php b/src/Console/User.php new file mode 100644 index 000000000..b12a3a6ad --- /dev/null +++ b/src/Console/User.php @@ -0,0 +1,423 @@ +. + * + */ + +namespace Friendica\Console; + +use Console_Table; +use Friendica\App; +use Friendica\Content\Pager; +use Friendica\Core\L10n; +use Friendica\Database\Database; +use Friendica\Model\Register; +use Friendica\Model\User as UserModel; +use Friendica\Util\Temporal; +use RuntimeException; +use Seld\CliPrompt\CliPrompt; + +/** + * tool to manage users of the current node + */ +class User extends \Asika\SimpleConsole\Console +{ + protected $helpOptions = ['h', 'help', '?']; + + /** + * @var App\Mode + */ + private $appMode; + /** + * @var L10n + */ + private $l10n; + /** + * @var Database + */ + private $dba; + + protected function getHelp() + { + $help = << [] [-h|--help|-?] [-v] + bin/console user add [ [ [ []]]] [-h|--help|-?] [-v] + bin/console user delete [] [-q] [-h|--help|-?] [-v] + bin/console user allow [] [-h|--help|-?] [-v] + bin/console user deny [] [-h|--help|-?] [-v] + bin/console user block [] [-h|--help|-?] [-v] + bin/console user unblock [] [-h|--help|-?] [-v] + bin/console user list pending [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v] + bin/console user list removed [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v] + bin/console user list active [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v] + bin/console user list all [-s|--start=0] [-c|--count=50] [-h|--help|-?] [-v] + bin/console user search id [-h|--help|-?] [-v] + bin/console user search nick [-h|--help|-?] [-v] + bin/console user search mail [-h|--help|-?] [-v] + bin/console user search guid [-h|--help|-?] [-v] + +Description + Modify user settings per console commands. + +Options + -h|--help|-? Show help information + -v Show more debug information. + -q Quiet mode (don't ask for a command). +HELP; + return $help; + } + + public function __construct(App\Mode $appMode, L10n $l10n, Database $dba, array $argv = null) + { + parent::__construct($argv); + + $this->appMode = $appMode; + $this->l10n = $l10n; + $this->dba = $dba; + } + + protected function doExecute() + { + if ($this->getOption('v')) { + $this->out('Class: ' . __CLASS__); + $this->out('Arguments: ' . var_export($this->args, true)); + $this->out('Options: ' . var_export($this->options, true)); + } + + if (count($this->args) == 0) { + $this->out($this->getHelp()); + return 0; + } + + if ($this->appMode->isInstall()) { + throw new RuntimeException('Database isn\'t ready or populated yet'); + } + + $command = $this->getArgument(0); + + switch ($command) { + case 'password': + return $this->password(); + case 'add': + return $this->addUser(); + case 'allow': + return $this->pendingUser(true); + case 'deny': + return $this->pendingUser(false); + case 'block': + return $this->blockUser(true); + case 'unblock': + return $this->blockUser(false); + case 'delete': + return $this->deleteUser(); + case 'list': + return $this->listUser(); + case 'search': + return $this->searchUser(); + default: + throw new \Asika\SimpleConsole\CommandArgsException('Wrong command.'); + } + } + + /** + * Sets a new password + * + * @return int Return code of this command + * + * @throws \Exception + */ + private function password() + { + $nick = $this->getArgument(1); + + $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]); + if (!$this->dba->isResult($user)) { + throw new RuntimeException($this->l10n->t('User not found')); + } + + $password = $this->getArgument(2); + + if (is_null($password)) { + $this->out($this->l10n->t('Enter new password: '), false); + $password = CliPrompt::hiddenPrompt(true); + } + + try { + $result = UserModel::updatePassword($user['uid'], $password); + + if (!$this->dba->isResult($result)) { + throw new \Exception($this->l10n->t('Password update failed. Please try again.')); + } + + $this->out($this->l10n->t('Password changed.')); + } catch (\Exception $e) { + throw new RuntimeException($e->getMessage(), $e->getCode(), $e); + } + + return 0; + } + + /** + * Adds a new user based on given console arguments + * + * @return bool True, if the command was successful + * @throws \ErrorException + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws \ImagickException + */ + private function addUser() + { + $name = $this->getArgument(1); + $nick = $this->getArgument(2); + $email = $this->getArgument(3); + $lang = $this->getArgument(4); + + if (empty($name)) { + $this->out($this->l10n->t('Enter user name: ')); + $name = CliPrompt::prompt(); + if (empty($name)) { + throw new RuntimeException('A name must be set.'); + } + } + + if (empty($nick)) { + $this->out($this->l10n->t('Enter user nickname: ')); + $nick = CliPrompt::prompt(); + if (empty($nick)) { + throw new RuntimeException('A nick name must be set.'); + } + } + + if (empty($email)) { + $this->out($this->l10n->t('Enter user email address: ')); + $email = CliPrompt::prompt(); + if (empty($email)) { + throw new RuntimeException('A email address must be set.'); + } + } + + if (empty($lang)) { + $this->out($this->l10n->t('Enter a language (optional): ')); + $lang = CliPrompt::prompt(); + } + + if (empty($lang)) { + return UserModel::createMinimal($name, $email, $nick); + } else { + return UserModel::createMinimal($name, $email, $nick, $lang); + } + } + + /** + * Allows or denys a user based on it's nickname + * + * @param bool $allow True, if the pending user is allowed, false if denies + * + * @return bool True, if allow was successful + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + */ + private function pendingUser(bool $allow = true) + { + $nick = $this->getArgument(1); + + if (!$nick) { + $this->out($this->l10n->t('Enter user nickname: ')); + $nick = CliPrompt::prompt(); + if (empty($nick)) { + throw new RuntimeException('A nick name must be set.'); + } + } + + $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]); + if (empty($user)) { + throw new RuntimeException($this->l10n->t('User not found')); + } + + $pending = Register::getPendingForUser($user['uid'] ?? 0); + if (empty($pending)) { + throw new RuntimeException($this->l10n->t('User is not pending.')); + } + + return ($allow) ? UserModel::allow($pending['hash']) : UserModel::deny($pending['hash']); + } + + /** + * Blocks/unblocks a user + * + * @param bool $block True, if the given user should get blocked + * + * @return bool True, if the command was successful + * @throws \Exception + */ + private function blockUser(bool $block = true) + { + $nick = $this->getArgument(1); + + if (!$nick) { + $this->out($this->l10n->t('Enter user nickname: ')); + $nick = CliPrompt::prompt(); + if (empty($nick)) { + throw new RuntimeException('A nick name must be set.'); + } + } + + $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]); + if (empty($user)) { + throw new RuntimeException($this->l10n->t('User not found')); + } + + return $block ? UserModel::block($user['uid'] ?? 0) : UserModel::block($user['uid'] ?? 0, false); + } + + /** + * Deletes a user + * + * @return bool True, if the delete was successful + * @throws \Exception + */ + private function deleteUser() + { + $nick = $this->getArgument(1); + + if (!$nick) { + $this->out($this->l10n->t('Enter user nickname: ')); + $nick = CliPrompt::prompt(); + if (empty($nick)) { + throw new RuntimeException('A nick name must be set.'); + } + } + + $user = $this->dba->selectFirst('user', ['uid'], ['nickname' => $nick]); + if (empty($user)) { + throw new RuntimeException($this->l10n->t('User not found')); + } + + if (!$this->getOption('q')) { + $this->out($this->l10n->t('Type "yes" to delete %s', $nick)); + if (CliPrompt::prompt() !== 'yes') { + throw new RuntimeException('Delete abort.'); + } + } + + return UserModel::remove($user['uid'] ?? -1); + } + + /** + * List users of the current node + * + * @return bool True, if the command was successful + */ + private function listUser() + { + $subCmd = $this->getArgument(1); + $start = $this->getOption(['s', 'start'], 0); + $count = $this->getOption(['c', 'count'], Pager::ITEMS_PER_PAGE); + + $table = new Console_Table(); + + switch ($subCmd) { + case 'pending': + $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register Date', 'Comment']); + $pending = Register::getPending($start, $count); + foreach ($pending as $contact) { + $table->addRow([ + $contact['nick'], + $contact['name'], + $contact['url'], + $contact['email'], + Temporal::getRelativeDate($contact['created']), + $contact['note'], + ]); + } + $this->out($table->getTable()); + return true; + case 'all': + case 'active': + case 'removed': + $table->setHeaders(['Nick', 'Name', 'URL', 'E-Mail', 'Register', 'Login', 'Last Item']); + $contacts = UserModel::getList($start, $count, $subCmd); + foreach ($contacts as $contact) { + $table->addRow([ + $contact['nick'], + $contact['name'], + $contact['url'], + $contact['email'], + Temporal::getRelativeDate($contact['created']), + Temporal::getRelativeDate($contact['login_date']), + Temporal::getRelativeDate($contact['lastitem_date']), + ]); + } + $this->out($table->getTable()); + return true; + default: + $this->out($this->getHelp()); + return false; + } + } + + /** + * Returns a user based on search parameter + * + * @return bool True, if the command was successful + */ + private function searchUser() + { + $fields = [ + 'uid', + 'guid', + 'username', + 'nickname', + 'email', + 'register_date', + 'login_date', + 'verified', + 'blocked', + ]; + + $subCmd = $this->getArgument(1); + $param = $this->getArgument(2); + + $table = new Console_Table(); + $table->setHeaders(['UID', 'GUID', 'Name', 'Nick', 'E-Mail', 'Register', 'Login', 'Verified', 'Blocked']); + + switch ($subCmd) { + case 'id': + $user = UserModel::getById($param, $fields); + break; + case 'guid': + $user = UserModel::getByGuid($param, $fields); + break; + case 'email': + $user = UserModel::getByEmail($param, $fields); + break; + case 'nick': + $user = UserModel::getByNickname($param, $fields); + break; + default: + $this->out($this->getHelp()); + return false; + } + + $table->addRow($user); + $this->out($table->getTable()); + + return true; + } +} diff --git a/src/Content/BoundariesPager.php b/src/Content/BoundariesPager.php index b8b7f67bb..8bbbde2b4 100644 --- a/src/Content/BoundariesPager.php +++ b/src/Content/BoundariesPager.php @@ -57,7 +57,7 @@ class BoundariesPager extends Pager $this->last_item_id = $last_item_id; $parsed = parse_url($this->getBaseQueryString()); - if ($parsed) { + if (!empty($parsed['query'])) { parse_str($parsed['query'], $queryParameters); $this->first_page = !($queryParameters['since_id'] ?? null) && !($queryParameters['max_id'] ?? null); diff --git a/src/Content/Pager.php b/src/Content/Pager.php index 5b4345a4c..a5e61bbf9 100644 --- a/src/Content/Pager.php +++ b/src/Content/Pager.php @@ -30,10 +30,13 @@ use Friendica\Util\Strings; */ class Pager { + /** @var int Default count of items per page */ + const ITEMS_PER_PAGE = 50; + /** @var integer */ private $page = 1; /** @var integer */ - protected $itemsPerPage = 50; + protected $itemsPerPage = self::ITEMS_PER_PAGE; /** @var string */ protected $baseQueryString = ''; diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php index 7b4b7b73d..9cf7df4e3 100644 --- a/src/Content/Text/BBCode.php +++ b/src/Content/Text/BBCode.php @@ -634,12 +634,12 @@ class BBCode if (!empty($data['title']) && !empty($data['url'])) { if (!empty($data['image']) && empty($data['text']) && ($data['type'] == 'photo')) { - $return .= sprintf('', $data['url'], self::proxyUrl($data['image'], $simplehtml), $data['title']); + $return .= sprintf('', $data['url'], self::proxyUrl($data['image'], $simplehtml), $data['title']); } else { if (!empty($data['image'])) { - $return .= sprintf('
', $data['url'], self::proxyUrl($data['image'], $simplehtml), $data['title']); + $return .= sprintf('
', $data['url'], self::proxyUrl($data['image'], $simplehtml), $data['title']); } elseif (!empty($data['preview'])) { - $return .= sprintf('
', $data['url'], self::proxyUrl($data['preview'], $simplehtml), $data['title']); + $return .= sprintf('
', $data['url'], self::proxyUrl($data['preview'], $simplehtml), $data['title']); } $return .= sprintf('

%s

', $data['url'], $data['title']); } @@ -732,7 +732,7 @@ class BBCode */ private static function convertUrlForActivityPub($url) { - $html = '%s'; + $html = '%s'; return sprintf($html, $url, self::getStyledURL($url)); } @@ -975,7 +975,8 @@ class BBCode Contact::getIdForURL($attributes['profile'], 0, true, $default); $author_contact = Contact::getDetailsByURL($attributes['profile']); - $author_contact['addr'] = ($author_contact['addr'] ?? '') ?: Protocol::getAddrFromProfileUrl($attributes['profile']); + $author_contact['url'] = ($author_contact['url'] ?? $attributes['profile']); + $author_contact['addr'] = ($author_contact['addr'] ?? '') ?: Protocol::getAddrFromProfileUrl($attributes['profile']); $attributes['author'] = ($author_contact['name'] ?? '') ?: $attributes['author']; $attributes['avatar'] = ($author_contact['micro'] ?? '') ?: $attributes['avatar']; @@ -1038,7 +1039,7 @@ class BBCode break; case 4: $headline = '

' . html_entity_decode('♲ ', ENT_QUOTES, 'UTF-8'); - $headline .= DI::l10n()->t('%2$s %3$s', $attributes['link'], $mention, $attributes['posted']); + $headline .= DI::l10n()->t('%2$s %3$s', $attributes['link'], $mention, $attributes['posted']); $headline .= ':

' . "\n"; $text = ($is_quote_share? '
' : '') . $headline . '
' . trim($content) . '
' . "\n"; @@ -1636,9 +1637,9 @@ class BBCode $text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", $try_oembed_callback, $text); } else { $text = preg_replace("/\[video\](.*?)\[\/video\]/ism", - '$1', $text); + '$1', $text); $text = preg_replace("/\[audio\](.*?)\[\/audio\]/ism", - '$1', $text); + '$1', $text); } // html5 video and audio @@ -1665,7 +1666,7 @@ class BBCode $text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '', $text); } else { $text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", - 'https://www.youtube.com/watch?v=$1', $text); + 'https://www.youtube.com/watch?v=$1', $text); } if ($try_oembed) { @@ -1680,7 +1681,7 @@ class BBCode $text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", '', $text); } else { $text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", - 'https://vimeo.com/$1', $text); + 'https://vimeo.com/$1', $text); } // oembed tag @@ -1801,17 +1802,17 @@ class BBCode . ''; }, $text); - // We need no target="_blank" for local links - // convert links start with DI::baseUrl() as local link without the target="_blank" attribute + // We need no target="_blank" rel="noopener noreferrer" for local links + // convert links start with DI::baseUrl() as local link without the target="_blank" rel="noopener noreferrer" attribute $escapedBaseUrl = preg_quote(DI::baseUrl(), '/'); $text = preg_replace("/\[url\](".$escapedBaseUrl.".*?)\[\/url\]/ism", '$1', $text); $text = preg_replace("/\[url\=(".$escapedBaseUrl.".*?)\](.*?)\[\/url\]/ism", '$2', $text); - $text = preg_replace("/\[url\](.*?)\[\/url\]/ism", '$1', $text); - $text = preg_replace("/\[url\=(.*?)\](.*?)\[\/url\]/ism", '$2', $text); + $text = preg_replace("/\[url\](.*?)\[\/url\]/ism", '$1', $text); + $text = preg_replace("/\[url\=(.*?)\](.*?)\[\/url\]/ism", '$2', $text); // Red compatibility, though the link can't be authenticated on Friendica - $text = preg_replace("/\[zrl\=(.*?)\](.*?)\[\/zrl\]/ism", '$2', $text); + $text = preg_replace("/\[zrl\=(.*?)\](.*?)\[\/zrl\]/ism", '$2', $text); // we may need to restrict this further if it picks up too many strays @@ -2004,8 +2005,6 @@ class BBCode */ public static function toMarkdown($text, $for_diaspora = true) { - $a = DI::app(); - $original_text = $text; // Since Diaspora is creating a summary for links, this function removes them before posting diff --git a/src/Content/Text/HTML.php b/src/Content/Text/HTML.php index 089c5d368..593be7d5f 100644 --- a/src/Content/Text/HTML.php +++ b/src/Content/Text/HTML.php @@ -943,7 +943,7 @@ class HTML */ public static function toLink($s) { - $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' $1', $s); + $s = preg_replace("/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\'\%\$\!\+]*)/", ' $1', $s); $s = preg_replace("/\<(.*?)(src|href)=(.*?)\&\;(.*?)\>/ism", '<$1$2=$3&$4>', $s); return $s; } diff --git a/src/Content/Text/Markdown.php b/src/Content/Text/Markdown.php index bcbf5191a..8dfe00190 100644 --- a/src/Content/Text/Markdown.php +++ b/src/Content/Text/Markdown.php @@ -53,6 +53,8 @@ class Markdown return $url; }; + $text = self::convertDiasporaMentionsToHtml($text); + $html = $MarkdownParser->transform($text); DI::profiler()->saveTimestamp($stamp1, "parser", System::callstack()); @@ -61,35 +63,42 @@ class Markdown } /** - * Callback function to replace a Diaspora style mention in a mention for Friendica + * Replace Diaspora-style mentions in a text since they trip the Markdown parser autolinker. * - * @param array $match Matching values for the callback - * [1] = mention type (@ or !) - * [2] = name (optional) - * [3] = address - * @return string Replaced mention - * @throws \Friendica\Network\HTTPException\InternalServerErrorException - * @throws \ImagickException + * @param string $text + * @return string */ - private static function diasporaMention2BBCodeCallback($match) + private static function convertDiasporaMentionsToHtml(string $text) { - if ($match[3] == '') { - return; - } + return preg_replace_callback( + '/([@!]){(?:([^}]+?); ?)?([^} ]+)}/', + /* + * Matching values for the callback + * [1] = mention type (@ or !) + * [2] = name (optional) + * [3] = profile URL + */ + function ($matches) { + if ($matches[3] == '') { + return ''; + } - $data = Contact::getDetailsByAddr($match[3]); + $data = Contact::getDetailsByAddr($matches[3]); - if (empty($data)) { - return; - } + if (empty($data)) { + return ''; + } - $name = $match[2]; + $name = $matches[2]; - if ($name == '') { - $name = $data['name']; - } + if ($name == '') { + $name = $data['name']; + } - return $match[1] . '[url=' . $data['url'] . ']' . $name . '[/url]'; + return $matches[1] . '' . $name . ''; + }, + $text + ); } /* @@ -110,9 +119,6 @@ class Markdown $s = self::convert($s); - $regexp = "/([@!])\{(?:([^\}]+?); ?)?([^\} ]+)\}/"; - $s = preg_replace_callback($regexp, ['self', 'diasporaMention2BBCodeCallback'], $s); - $s = HTML::toBBCode($s); // protect the recycle symbol from turning into a tag, but without unescaping angles and naked ampersands diff --git a/src/Core/Console.php b/src/Core/Console.php index 70835db9c..86178c209 100644 --- a/src/Core/Console.php +++ b/src/Core/Console.php @@ -57,7 +57,7 @@ Commands: autoinstall Starts automatic installation of friendica based on values from htconfig.php lock Edit site locks maintenance Set maintenance mode for this node - newpassword Set a new password for a given user + user User management php2po Generate a messages.po file from a strings.php file po2php Generate a strings.php file from a messages.po file typo Checks for parse errors in Friendica files @@ -85,7 +85,7 @@ HELP; 'autoinstall' => Friendica\Console\AutomaticInstallation::class, 'lock' => Friendica\Console\Lock::class, 'maintenance' => Friendica\Console\Maintenance::class, - 'newpassword' => Friendica\Console\NewPassword::class, + 'user' => Friendica\Console\User::class, 'php2po' => Friendica\Console\PhpToPo::class, 'po2php' => Friendica\Console\PoToPhp::class, 'typo' => Friendica\Console\Typo::class, diff --git a/src/Core/L10n.php b/src/Core/L10n.php index cda83ac3f..8e6ee171c 100644 --- a/src/Core/L10n.php +++ b/src/Core/L10n.php @@ -33,6 +33,9 @@ use Psr\Log\LoggerInterface; */ class L10n { + /** @var string The default language */ + const DEFAULT = 'en'; + /** * A string indicating the current language used for translation: * - Two-letter ISO 639-1 code. @@ -64,7 +67,7 @@ class L10n $this->dba = $dba; $this->logger = $logger; - $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', 'en'))); + $this->loadTranslationTable(L10n::detectLanguage($server, $get, $config->get('system', 'language', self::DEFAULT))); $this->setSessionVariable($session); $this->setLangFromSession($session); } @@ -158,7 +161,7 @@ class L10n * * @return string The two-letter language code */ - public static function detectLanguage(array $server, array $get, string $sysLang = 'en') + public static function detectLanguage(array $server, array $get, string $sysLang = self::DEFAULT) { $lang_variable = $server['HTTP_ACCEPT_LANGUAGE'] ?? null; diff --git a/src/Core/Theme.php b/src/Core/Theme.php index c17c67c4d..03f1dfd9c 100644 --- a/src/Core/Theme.php +++ b/src/Core/Theme.php @@ -98,7 +98,7 @@ class Theme $comment_lines = explode("\n", $matches[0]); foreach ($comment_lines as $comment_line) { $comment_line = trim($comment_line, "\t\n\r */"); - if ($comment_line != "") { + if (strpos($comment_line, ':') !== false) { list($key, $value) = array_map("trim", explode(":", $comment_line, 2)); $key = strtolower($key); if ($key == "author") { diff --git a/src/Model/Contact.php b/src/Model/Contact.php index f86d3f378..68bd0986a 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -1037,6 +1037,7 @@ class Contact } if (DBA::isResult($r)) { + $authoritativeResult = true; // If there is more than one entry we filter out the connector networks if (count($r) > 1) { foreach ($r as $id => $result) { @@ -1070,6 +1071,7 @@ class Contact $profile["bd"] = DBA::NULL_DATE; } } else { + $authoritativeResult = false; $profile = $default; } @@ -1106,7 +1108,11 @@ class Contact $profile["birthday"] = DBA::NULL_DATE; } - $cache[$url][$uid] = $profile; + // Only cache the result if it came from the DB since this method is used in widely different contexts + // @see display_fetch_author for an example of $default parameter diverging from the DB result + if ($authoritativeResult) { + $cache[$url][$uid] = $profile; + } return $profile; } diff --git a/src/Model/Item.php b/src/Model/Item.php index b960ba38f..eac3b7028 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -113,6 +113,10 @@ class Item Activity::FOLLOW, Activity::ANNOUNCE]; + const PUBLIC = 0; + const PRIVATE = 1; + const UNLISTED = 2; + private static $legacy_mode = null; public static function isLegacyMode() @@ -1112,6 +1116,7 @@ class Item */ public static function deleteById($item_id, $priority = PRIORITY_HIGH) { + Logger::notice('Delete item by id', ['id' => $item_id, 'callstack' => System::callstack()]); // locate item to be deleted $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin', 'deleted', 'file', 'resource-id', 'event-id', 'attach', @@ -1541,7 +1546,7 @@ class Item $item['allow_gid'] = trim($item['allow_gid'] ?? ''); $item['deny_cid'] = trim($item['deny_cid'] ?? ''); $item['deny_gid'] = trim($item['deny_gid'] ?? ''); - $item['private'] = intval($item['private'] ?? 0); + $item['private'] = intval($item['private'] ?? self::PUBLIC); $item['body'] = trim($item['body'] ?? ''); $item['tag'] = trim($item['tag'] ?? ''); $item['attach'] = trim($item['attach'] ?? ''); @@ -1737,8 +1742,8 @@ class Item * The original author commented, but as this is a comment, the permissions * weren't fixed up so it will still show the comment as private unless we fix it here. */ - if ((intval($parent['forum_mode']) == 1) && $parent['private']) { - $item['private'] = 0; + if ((intval($parent['forum_mode']) == 1) && ($parent['private'] != self::PUBLIC)) { + $item['private'] = self::PUBLIC; } // If its a post that originated here then tag the thread as "mention" @@ -1808,7 +1813,7 @@ class Item // ACL settings if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) { - $private = 1; + $private = self::PRIVATE; } else { $private = $item['private']; } @@ -1934,7 +1939,7 @@ class Item if ($entries > 1) { // There are duplicates. We delete our just created entry. - Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']); + Logger::notice('Delete duplicated item', ['id' => $current_post, 'uri' => $item['uri'], 'uid' => $item['uid']]); // Yes, we could do a rollback here - but we are having many users with MyISAM. DBA::delete('item', ['id' => $current_post]); @@ -2217,7 +2222,7 @@ class Item // Only distribute public items from native networks $condition = ['id' => $itemid, 'uid' => 0, 'network' => array_merge(Protocol::FEDERATED ,['']), - 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false]; + 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]]; $item = self::selectFirst(self::ITEM_FIELDLIST, $condition); if (!DBA::isResult($item)) { return; @@ -2367,7 +2372,7 @@ class Item } // Is it a visible public post? - if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) { + if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) { return; } @@ -2558,7 +2563,7 @@ class Item Contact::unmarkForArchival($contact); } - $update = (!$arr['private'] && ((($arr['author-link'] ?? '') === ($arr['owner-link'] ?? '')) || ($arr["parent-uri"] === $arr["uri"]))); + $update = (($arr['private'] != self::PRIVATE) && ((($arr['author-link'] ?? '') === ($arr['owner-link'] ?? '')) || ($arr["parent-uri"] === $arr["uri"]))); // Is it a forum? Then we don't care about the rules from above if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) { @@ -2572,7 +2577,7 @@ class Item ['id' => $arr['contact-id']]); } // Now do the same for the system wide contacts with uid=0 - if (!$arr['private']) { + if ($arr['private'] != self::PRIVATE) { DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']], ['id' => $arr['owner-id']]); @@ -2717,9 +2722,7 @@ class Item if (!$mention) { if (($community_page || $prvgroup) && !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) { - // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment) - // delete it! - Logger::log("no-mention top-level post to community or private group. delete."); + Logger::notice('Delete private group/communiy top-level item without mention', ['id' => $item_id]); DBA::delete('item', ['id' => $item_id]); return true; } @@ -2753,7 +2756,7 @@ class Item // also reset all the privacy bits to the forum default permissions - $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0; + $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC; $psid = PermissionSet::getIdFromACL( $user['uid'], @@ -2800,7 +2803,7 @@ class Item return false; } - if (($contact['network'] != Protocol::FEED) && $datarray['private']) { + if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) { Logger::log('Not public', Logger::DEBUG); return false; } @@ -2838,7 +2841,7 @@ class Item $urlpart = parse_url($datarray2['author-link']); $datarray["app"] = $urlpart["host"]; } else { - $datarray['private'] = 0; + $datarray['private'] = self::PUBLIC; } } @@ -3367,7 +3370,7 @@ class Item $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]]; if (!self::exists($condition)) { DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]); - Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG); + Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]); } } } @@ -3382,7 +3385,7 @@ class Item * * default permissions - anonymous user */ - $sql = " AND NOT `item`.`private`"; + $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE); // Profile owner - everything is visible if ($local_user && ($local_user == $owner_id)) { @@ -3398,12 +3401,12 @@ class Item $set = PermissionSet::get($owner_id, $remote_user); if (!empty($set)) { - $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))"; + $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))"; } else { $sql_set = ''; } - $sql = " AND (NOT `item`.`private`" . $sql_set . ")"; + $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")"; } return $sql; @@ -3505,7 +3508,7 @@ class Item continue; } - if ((local_user() == $item['uid']) && ($item['private'] == 1) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) { + if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) { $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]); $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']); } @@ -3630,7 +3633,7 @@ class Item $title .= ' ' . $mtch[2] . ' ' . DI::l10n()->t('bytes'); $icon = '
'; - $as .= '' . $icon . ''; + $as .= '' . $icon . ''; } if ($as != '') { @@ -3683,7 +3686,7 @@ class Item $ret["title"] = DI::l10n()->t('link to source'); } - } elseif (!empty($item['plink']) && ($item['private'] != 1)) { + } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) { $ret = [ 'href' => $item['plink'], 'orig' => $item['plink'], diff --git a/src/Model/Profile.php b/src/Model/Profile.php index cf9e7c620..867a6db4f 100644 --- a/src/Model/Profile.php +++ b/src/Model/Profile.php @@ -330,7 +330,8 @@ class Profile if (!$local_user_is_self && $show_connect) { if (!$visitor_is_authenticated) { - if (!empty($profile['nickname'])) { + // Remote follow is only available for local profiles + if (!empty($profile['nickname']) && strpos($profile_url, DI::baseUrl()->get()) === 0) { $follow_link = 'remote_follow/' . $profile['nickname']; } } elseif ($profile_is_native) { diff --git a/src/Model/Register.php b/src/Model/Register.php index fa8fb7bdb..be00699bf 100644 --- a/src/Model/Register.php +++ b/src/Model/Register.php @@ -21,6 +21,7 @@ namespace Friendica\Model; +use Friendica\Content\Pager; use Friendica\Database\DBA; use Friendica\Util\DateTimeFormat; use Friendica\Util\Strings; @@ -33,21 +34,46 @@ class Register /** * Return the list of pending registrations * + * @param int $start Start count (Default is 0) + * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE) + * * @return array * @throws \Exception */ - public static function getPending() + public static function getPending($start = 0, $count = Pager::ITEMS_PER_PAGE) { $stmt = DBA::p( - "SELECT `register`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`email` + "SELECT `register`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`email`, `contact`.`nick` FROM `register` INNER JOIN `contact` ON `register`.`uid` = `contact`.`uid` - INNER JOIN `user` ON `register`.`uid` = `user`.`uid`" + INNER JOIN `user` ON `register`.`uid` = `user`.`uid` + LIMIT ?, ?", $start, $count ); return DBA::toArray($stmt); } + /** + * Returns the pending user based on a given user id + * + * @param int $uid The user id + * + * @return array The pending user information + * + * @throws \Exception + */ + public static function getPendingForUser(int $uid) + { + return DBA::fetchFirst( + "SELECT `register`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`email` + FROM `register` + INNER JOIN `contact` ON `register`.`uid` = `contact`.`uid` + INNER JOIN `user` ON `register`.`uid` = `user`.`uid` + WHERE `register`.uid = ?", + $uid + ); + } + /** * Returns the pending registration count * diff --git a/src/Model/Term.php b/src/Model/Term.php index 6e92c9ce1..868f2bf05 100644 --- a/src/Model/Term.php +++ b/src/Model/Term.php @@ -82,7 +82,7 @@ class Term WHERE `thread`.`visible` AND NOT `thread`.`deleted` AND NOT `thread`.`moderated` - AND NOT `thread`.`private` + AND `thread`.`private` = ? AND t.`uid` = 0 AND t.`otype` = ? AND t.`type` = ? @@ -91,6 +91,7 @@ class Term GROUP BY `term` ORDER BY `score` DESC LIMIT ?", + Item::PUBLIC, Term::OBJECT_TYPE_POST, Term::HASHTAG, $period, @@ -122,11 +123,10 @@ class Term FROM `term` t JOIN `item` i ON i.`id` = t.`oid` AND i.`uid` = t.`uid` JOIN `thread` ON `thread`.`iid` = i.`id` - JOIN `user` ON `user`.`uid` = `thread`.`uid` AND NOT `user`.`hidewall` WHERE `thread`.`visible` AND NOT `thread`.`deleted` AND NOT `thread`.`moderated` - AND NOT `thread`.`private` + AND `thread`.`private` = ? AND `thread`.`wall` AND `thread`.`origin` AND t.`otype` = ? @@ -136,6 +136,7 @@ class Term GROUP BY `term` ORDER BY `score` DESC LIMIT ?", + Item::PUBLIC, Term::OBJECT_TYPE_POST, Term::HASHTAG, $period, @@ -462,13 +463,13 @@ class Term $item['body'] = str_replace($orig_tag, $tag['url'], $item['body']); } - $return['hashtags'][] = $prefix . '' . htmlspecialchars($tag['term']) . ''; - $return['tags'][] = $prefix . '' . htmlspecialchars($tag['term']) . ''; + $return['hashtags'][] = $prefix . '' . htmlspecialchars($tag['term']) . ''; + $return['tags'][] = $prefix . '' . htmlspecialchars($tag['term']) . ''; break; case self::MENTION: $tag['url'] = Contact::magicLink($tag['url']); - $return['mentions'][] = $prefix . '' . htmlspecialchars($tag['term']) . ''; - $return['tags'][] = $prefix . '' . htmlspecialchars($tag['term']) . ''; + $return['mentions'][] = $prefix . '' . htmlspecialchars($tag['term']) . ''; + $return['tags'][] = $prefix . '' . htmlspecialchars($tag['term']) . ''; break; case self::IMPLICIT_MENTION: $return['implicit_mentions'][] = $prefix . $tag['term']; diff --git a/src/Model/User.php b/src/Model/User.php index e4ef07e47..351982e8a 100644 --- a/src/Model/User.php +++ b/src/Model/User.php @@ -23,7 +23,9 @@ namespace Friendica\Model; use DivineOmega\PasswordExposed; use Exception; +use Friendica\Content\Pager; use Friendica\Core\Hook; +use Friendica\Core\L10n; use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; @@ -31,6 +33,7 @@ use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\TwoFactor\AppSpecificPassword; +use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Object\Image; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; @@ -279,7 +282,7 @@ class User * @param string $network network name * * @return int group id - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws InternalServerErrorException */ public static function getDefaultGroup($uid, $network = '') { @@ -556,7 +559,7 @@ class User * * @param string $nickname The nickname that should be checked * @return boolean True is the nickname is blocked on the node - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws InternalServerErrorException */ public static function isNicknameBlocked($nickname) { @@ -593,7 +596,7 @@ class User * @param array $data * @return array * @throws \ErrorException - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws InternalServerErrorException * @throws \ImagickException * @throws Exception */ @@ -880,6 +883,166 @@ class User return $return; } + /** + * Sets block state for a given user + * + * @param int $uid The user id + * @param bool $block Block state (default is true) + * + * @return bool True, if successfully blocked + + * @throws Exception + */ + public static function block(int $uid, bool $block = true) + { + return DBA::update('user', ['blocked' => $block], ['uid' => $uid]); + } + + /** + * Allows a registration based on a hash + * + * @param string $hash + * + * @return bool True, if the allow was successful + * + * @throws InternalServerErrorException + * @throws Exception + */ + public static function allow(string $hash) + { + $register = Register::getByHash($hash); + if (!DBA::isResult($register)) { + return false; + } + + $user = User::getById($register['uid']); + if (!DBA::isResult($user)) { + return false; + } + + Register::deleteByHash($hash); + + DBA::update('user', ['blocked' => false, 'verified' => true], ['uid' => $register['uid']]); + + $profile = DBA::selectFirst('profile', ['net-publish'], ['uid' => $register['uid']]); + + if (DBA::isResult($profile) && $profile['net-publish'] && DI::config()->get('system', 'directory')) { + $url = DI::baseUrl() . '/profile/' . $user['nickname']; + Worker::add(PRIORITY_LOW, "Directory", $url); + } + + $l10n = DI::l10n()->withLang($register['language']); + + return User::sendRegisterOpenEmail( + $l10n, + $user, + DI::config()->get('config', 'sitename'), + DI::baseUrl()->get(), + ($register['password'] ?? '') ?: 'Sent in a previous email' + ); + } + + /** + * Denys a pending registration + * + * @param string $hash The hash of the pending user + * + * This does not have to go through user_remove() and save the nickname + * permanently against re-registration, as the person was not yet + * allowed to have friends on this system + * + * @return bool True, if the deny was successfull + * @throws Exception + */ + public static function deny(string $hash) + { + $register = Register::getByHash($hash); + if (!DBA::isResult($register)) { + return false; + } + + $user = User::getById($register['uid']); + if (!DBA::isResult($user)) { + return false; + } + + return DBA::delete('user', ['uid' => $register['uid']]) && + Register::deleteByHash($register['hash']); + } + + /** + * Creates a new user based on a minimal set and sends an email to this user + * + * @param string $name The user's name + * @param string $email The user's email address + * @param string $nick The user's nick name + * @param string $lang The user's language (default is english) + * + * @return bool True, if the user was created successfully + * @throws InternalServerErrorException + * @throws \ErrorException + * @throws \ImagickException + */ + public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT) + { + if (empty($name) || + empty($email) || + empty($nick)) { + throw new InternalServerErrorException('Invalid arguments.'); + } + + $result = self::create([ + 'username' => $name, + 'email' => $email, + 'nickname' => $nick, + 'verified' => 1, + 'language' => $lang + ]); + + $user = $result['user']; + $preamble = Strings::deindent(DI::l10n()->t(' + Dear %1$s, + the administrator of %2$s has set up an account for you.')); + $body = Strings::deindent(DI::l10n()->t(' + The login details are as follows: + + Site Location: %1$s + Login Name: %2$s + Password: %3$s + + You may change your password from your account "Settings" page after logging + in. + + Please take a few moments to review the other account settings on that page. + + You may also wish to add some basic information to your default profile + (on the "Profiles" page) so that other people can easily find you. + + We recommend setting your full name, adding a profile photo, + adding some profile "keywords" (very useful in making new friends) - and + perhaps what country you live in; if you do not wish to be more specific + than that. + + We fully respect your right to privacy, and none of these items are necessary. + If you are new and do not know anybody here, they may help + you to make some new and interesting friends. + + If you ever want to delete your account, you can do so at %1$s/removeme + + Thank you and welcome to %4$s.')); + + $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename')); + $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename')); + + $email = DI::emailer() + ->newSystemMail() + ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body) + ->forUser($user) + ->withRecipient($user['email']) + ->build(); + return DI::emailer()->send($email); + } + /** * Sends pending registration confirmation email * @@ -888,7 +1051,7 @@ class User * @param string $siteurl * @param string $password Plaintext password * @return NULL|boolean from notification() and email() inherited - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws InternalServerErrorException */ public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password) { @@ -931,7 +1094,7 @@ class User * @param string $password Plaintext password * * @return NULL|boolean from notification() and email() inherited - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws InternalServerErrorException */ public static function sendRegisterOpenEmail(\Friendica\Core\L10n $l10n, $user, $sitename, $siteurl, $password) { @@ -988,11 +1151,11 @@ class User } /** - * @param object $uid user to remove + * @param int $uid user to remove * @return bool - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws InternalServerErrorException */ - public static function remove($uid) + public static function remove(int $uid) { if (!$uid) { return false; @@ -1154,4 +1317,47 @@ class User return $statistics; } + + /** + * Get all users of the current node + * + * @param int $start Start count (Default is 0) + * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE) + * @param string $type The type of users, which should get (all, bocked, removed) + * @param string $order Order of the user list (Default is 'contact.name') + * @param string $order_direction Order direction (Default is ASC) + * + * @return array The list of the users + * @throws Exception + */ + public static function getList($start = 0, $count = Pager::ITEMS_PER_PAGE, $type = 'all', $order = 'contact.name', $order_direction = '+') + { + $sql_order = '`' . str_replace('.', '`.`', $order) . '`'; + $sql_order_direction = ($order_direction === '+') ? 'ASC' : 'DESC'; + + switch ($type) { + case 'active': + $sql_extra = 'AND `user`.`blocked` = 0'; + break; + case 'blocked': + $sql_extra = 'AND `user`.`blocked` = 1'; + break; + case 'removed': + $sql_extra = 'AND `user`.`account_removed` = 1'; + break; + case 'all': + default: + $sql_extra = ''; + break; + } + + $usersStmt = DBA::p("SELECT `user`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`account_expired`, `contact`.`last-item` AS `lastitem_date`, `contact`.`nick`, `contact`.`created` + FROM `user` + INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self` + WHERE `user`.`verified` $sql_extra + ORDER BY $sql_order $sql_order_direction LIMIT ?, ?", $start, $count + ); + + return DBA::toArray($usersStmt); + } } diff --git a/src/Module/Admin/Features.php b/src/Module/Admin/Features.php index 62136f423..46c0a1384 100644 --- a/src/Module/Admin/Features.php +++ b/src/Module/Admin/Features.php @@ -73,8 +73,8 @@ class Features extends BaseAdmin foreach (array_slice($fdata, 1) as $f) { $set = DI::config()->get('feature', $f[0], $f[3]); $arr[$fname][1][] = [ - ['feature_' . $f[0], $f[1], $set, $f[2], [DI::l10n()->t('Off'), DI::l10n()->t('On')]], - ['featurelock_' . $f[0], DI::l10n()->t('Lock feature %s', $f[1]), (($f[4] !== false) ? "1" : ''), '', [DI::l10n()->t('Off'), DI::l10n()->t('On')]] + ['feature_' . $f[0], $f[1], $set, $f[2]], + ['featurelock_' . $f[0], DI::l10n()->t('Lock feature %s', $f[1]), $f[4], ''] ]; } } diff --git a/src/Module/Admin/Tos.php b/src/Module/Admin/Tos.php index c9dd3d879..811a0eb25 100644 --- a/src/Module/Admin/Tos.php +++ b/src/Module/Admin/Tos.php @@ -60,7 +60,7 @@ class Tos extends BaseAdmin '$title' => DI::l10n()->t('Administration'), '$page' => DI::l10n()->t('Terms of Service'), '$displaytos' => ['displaytos', DI::l10n()->t('Display Terms of Service'), DI::config()->get('system', 'tosdisplay'), DI::l10n()->t('Enable the Terms of Service page. If this is enabled a link to the terms will be added to the registration form and the general information page.')], - '$displayprivstatement' => ['displayprivstatement', DI::l10n()->t('Display Privacy Statement'), DI::config()->get('system', 'tosprivstatement'), DI::l10n()->t('Show some informations regarding the needed information to operate the node according e.g. to EU-GDPR.', 'https://en.wikipedia.org/wiki/General_Data_Protection_Regulation')], + '$displayprivstatement' => ['displayprivstatement', DI::l10n()->t('Display Privacy Statement'), DI::config()->get('system', 'tosprivstatement'), DI::l10n()->t('Show some informations regarding the needed information to operate the node according e.g. to EU-GDPR.', 'https://en.wikipedia.org/wiki/General_Data_Protection_Regulation')], '$preview' => DI::l10n()->t('Privacy Statement Preview'), '$privtext' => $tos->privacy_complete, '$tostext' => ['tostext', DI::l10n()->t('The Terms of Service'), DI::config()->get('system', 'tostext'), DI::l10n()->t('Enter the Terms of Service for your node here. You can use BBCode. Headers of sections should be [h2] and below.')], diff --git a/src/Module/Admin/Users.php b/src/Module/Admin/Users.php index b446a2c47..3ef91aadf 100644 --- a/src/Module/Admin/Users.php +++ b/src/Module/Admin/Users.php @@ -28,7 +28,6 @@ use Friendica\DI; use Friendica\Model\Register; use Friendica\Model\User; use Friendica\Module\BaseAdmin; -use Friendica\Util\Strings; use Friendica\Util\Temporal; class Users extends BaseAdmin @@ -48,71 +47,24 @@ class Users extends BaseAdmin if ($nu_name !== '' && $nu_email !== '' && $nu_nickname !== '') { try { - $result = User::create([ - 'username' => $nu_name, - 'email' => $nu_email, - 'nickname' => $nu_nickname, - 'verified' => 1, - 'language' => $nu_language - ]); + User::createMinimal($nu_name, $nu_email, $nu_nickname, $nu_language); } catch (\Exception $ex) { notice($ex->getMessage()); return; } - - $user = $result['user']; - $preamble = Strings::deindent(DI::l10n()->t(' - Dear %1$s, - the administrator of %2$s has set up an account for you.')); - $body = Strings::deindent(DI::l10n()->t(' - The login details are as follows: - - Site Location: %1$s - Login Name: %2$s - Password: %3$s - - You may change your password from your account "Settings" page after logging - in. - - Please take a few moments to review the other account settings on that page. - - You may also wish to add some basic information to your default profile - (on the "Profiles" page) so that other people can easily find you. - - We recommend setting your full name, adding a profile photo, - adding some profile "keywords" (very useful in making new friends) - and - perhaps what country you live in; if you do not wish to be more specific - than that. - - We fully respect your right to privacy, and none of these items are necessary. - If you are new and do not know anybody here, they may help - you to make some new and interesting friends. - - If you ever want to delete your account, you can do so at %1$s/removeme - - Thank you and welcome to %4$s.')); - - $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename')); - $body = sprintf($body, DI::baseUrl()->get(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename')); - - $email = DI::emailer() - ->newSystemMail() - ->withMessage(DI::l10n()->t('Registration details for %s', DI::config()->get('config', 'sitename')), $preamble, $body) - ->forUser($user) - ->withRecipient($user['email']) - ->build(); - return DI::emailer()->send($email); } if (!empty($_POST['page_users_block'])) { - // @TODO Move this to Model\User:block($users); - DBA::update('user', ['blocked' => 1], ['uid' => $users]); + foreach ($users as $uid) { + User::block($uid); + } notice(DI::l10n()->tt('%s user blocked', '%s users blocked', count($users))); } if (!empty($_POST['page_users_unblock'])) { - // @TODO Move this to Model\User:unblock($users); - DBA::update('user', ['blocked' => 0], ['uid' => $users]); + foreach ($users as $uid) { + User::block($uid, false); + } notice(DI::l10n()->tt('%s user unblocked', '%s users unblocked', count($users))); } @@ -129,17 +81,17 @@ class Users extends BaseAdmin } if (!empty($_POST['page_users_approve'])) { - require_once 'mod/regmod.php'; foreach ($pending as $hash) { - user_allow($hash); + User::allow($hash); } + notice(DI::l10n()->tt('%s user approved', '%s users approved', count($pending))); } if (!empty($_POST['page_users_deny'])) { - require_once 'mod/regmod.php'; foreach ($pending as $hash) { - user_deny($hash); + User::deny($hash); } + notice(DI::l10n()->tt('%s registration revoked', '%s registrations revoked', count($pending))); } DI::baseUrl()->redirect('admin/users'); @@ -176,16 +128,24 @@ class Users extends BaseAdmin break; case 'block': parent::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't'); - // @TODO Move this to Model\User:block([$uid]); - DBA::update('user', ['blocked' => 1], ['uid' => $uid]); + User::block($uid); notice(DI::l10n()->t('User "%s" blocked', $user['username'])); break; case 'unblock': parent::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't'); - // @TODO Move this to Model\User:unblock([$uid]); - DBA::update('user', ['blocked' => 0], ['uid' => $uid]); + User::block($uid, false); notice(DI::l10n()->t('User "%s" unblocked', $user['username'])); break; + case 'allow': + parent::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't'); + User::allow(Register::getPendingForUser($uid)['hash'] ?? ''); + notice(DI::l10n()->t('Account approved.')); + break; + case 'deny': + parent::checkFormSecurityTokenRedirectOnError('/admin/users', 'admin_users', 't'); + User::deny(Register::getPendingForUser($uid)['hash'] ?? ''); + notice(DI::l10n()->t('Registration revoked')); + break; } DI::baseUrl()->redirect('admin/users'); @@ -196,7 +156,6 @@ class Users extends BaseAdmin $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), 100); - // @TODO Move below block to Model\User::getUsers($start, $count, $order = 'contact.name', $order_direction = '+') $valid_orders = [ 'contact.name', 'user.email', @@ -219,16 +178,8 @@ class Users extends BaseAdmin $order = $new_order; } } - $sql_order = '`' . str_replace('.', '`.`', $order) . '`'; - $sql_order_direction = ($order_direction === '+') ? 'ASC' : 'DESC'; - $usersStmt = DBA::p("SELECT `user`.*, `contact`.`name`, `contact`.`url`, `contact`.`micro`, `user`.`account_expired`, `contact`.`last-item` AS `lastitem_date` - FROM `user` - INNER JOIN `contact` ON `contact`.`uid` = `user`.`uid` AND `contact`.`self` - WHERE `user`.`verified` - ORDER BY $sql_order $sql_order_direction LIMIT ?, ?", $pager->getStart(), $pager->getItemsPerPage() - ); - $users = DBA::toArray($usersStmt); + $users = User::getList($pager->getStart(), $pager->getItemsPerPage(), 'all', $order, $order_direction); $adminlist = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email'))); $_setup_users = function ($e) use ($adminlist) { @@ -283,7 +234,7 @@ class Users extends BaseAdmin } } - $th_users = array_map(null, [DI::l10n()->t('Name'), DI::l10n()->t('Email'), DI::l10n()->t('Register date'), DI::l10n()->t('Last login'), DI::l10n()->t('Last item'), DI::l10n()->t('Type')], $valid_orders); + $th_users = array_map(null, [DI::l10n()->t('Name'), DI::l10n()->t('Email'), DI::l10n()->t('Register date'), DI::l10n()->t('Last login'), DI::l10n()->t('Last public item'), DI::l10n()->t('Type')], $valid_orders); $t = Renderer::getMarkupTemplate('admin/users.tpl'); $o = Renderer::replaceMacros($t, [ @@ -308,7 +259,7 @@ class Users extends BaseAdmin '$h_users' => DI::l10n()->t('Users'), '$h_newuser' => DI::l10n()->t('New User'), - '$th_deleted' => [DI::l10n()->t('Name'), DI::l10n()->t('Email'), DI::l10n()->t('Register date'), DI::l10n()->t('Last login'), DI::l10n()->t('Last item'), DI::l10n()->t('Permanent deletion')], + '$th_deleted' => [DI::l10n()->t('Name'), DI::l10n()->t('Email'), DI::l10n()->t('Register date'), DI::l10n()->t('Last login'), DI::l10n()->t('Last public item'), DI::l10n()->t('Permanent deletion')], '$th_users' => $th_users, '$order_users' => $order, '$order_direction_users' => $order_direction, diff --git a/src/Module/Conversation/Community.php b/src/Module/Conversation/Community.php index 58af38eb1..5637c6f41 100644 --- a/src/Module/Conversation/Community.php +++ b/src/Module/Conversation/Community.php @@ -280,58 +280,33 @@ class Community extends BaseModule $r = false; if (self::$content == 'local') { - $values = []; - - $sql_accounttype = ''; - $sql_boundaries = ''; if (!is_null(self::$accounttype)) { - $sql_accounttype = " AND `user`.`account-type` = ?"; - $values[] = [self::$accounttype]; + $condition = ["`wall` AND `origin` AND `private` = ? AND `owner`.`contact-type` = ?", Item::PUBLIC, self::$accounttype]; + } else { + $condition = ["`wall` AND `origin` AND `private` = ?", Item::PUBLIC]; } - - if (isset($since_id)) { - $sql_boundaries .= " AND `thread`.`commented` > ?"; - $values[] = $since_id; - } - - if (isset($max_id)) { - $sql_boundaries .= " AND `thread`.`commented` < ?"; - $values[] = $max_id; - } - - $values[] = $itemspage; - - /// @todo Use "unsearchable" here as well (instead of "hidewall") - $r = DBA::p("SELECT `item`.`uri`, `author`.`url` AS `author-link`, `thread`.`commented` FROM `thread` - STRAIGHT_JOIN `user` ON `user`.`uid` = `thread`.`uid` AND NOT `user`.`hidewall` - STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` - STRAIGHT_JOIN `contact` AS `author` ON `author`.`id`=`item`.`author-id` - WHERE `thread`.`visible` AND NOT `thread`.`deleted` AND NOT `thread`.`moderated` - AND NOT `thread`.`private` AND `thread`.`wall` AND `thread`.`origin` - $sql_accounttype - $sql_boundaries - ORDER BY `thread`.`commented` DESC - LIMIT ?", $values); } elseif (self::$content == 'global') { if (!is_null(self::$accounttype)) { - $condition = ["`uid` = ? AND NOT `author`.`unsearchable` AND NOT `owner`.`unsearchable` AND `owner`.`contact-type` = ?", 0, self::$accounttype]; + $condition = ["`uid` = ? AND `private` = ? AND `owner`.`contact-type` = ?", 0, Item::PUBLIC, self::$accounttype]; } else { - $condition = ["`uid` = ? AND NOT `author`.`unsearchable` AND NOT `owner`.`unsearchable`", 0]; + $condition = ["`uid` = ? AND `private` = ?", 0, Item::PUBLIC]; } - - if (isset($max_id)) { - $condition[0] .= " AND `commented` < ?"; - $condition[] = $max_id; - } - - if (isset($since_id)) { - $condition[0] .= " AND `commented` > ?"; - $condition[] = $since_id; - } - - $r = Item::selectThreadForUser(0, ['uri', 'commented'], $condition, ['order' => ['commented' => true], 'limit' => $itemspage]); + } else { + return []; } + if (isset($max_id)) { + $condition[0] .= " AND `commented` < ?"; + $condition[] = $max_id; + } + + if (isset($since_id)) { + $condition[0] .= " AND `commented` > ?"; + $condition[] = $since_id; + } + + $r = Item::selectThreadForUser(0, ['uri', 'commented', 'author-link'], $condition, ['order' => ['commented' => true], 'limit' => $itemspage]); + return DBA::toArray($r); } } diff --git a/src/Module/Diaspora/Fetch.php b/src/Module/Diaspora/Fetch.php index 70f982f70..aba9d33be 100644 --- a/src/Module/Diaspora/Fetch.php +++ b/src/Module/Diaspora/Fetch.php @@ -54,7 +54,7 @@ class Fetch extends BaseModule 'uid', 'title', 'body', 'guid', 'contact-id', 'private', 'created', 'received', 'app', 'location', 'coord', 'network', 'event-id', 'resource-id', 'author-link', 'author-avatar', 'author-name', 'plink', 'owner-link', 'attach' ]; - $condition = ['wall' => true, 'private' => false, 'guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]]; + $condition = ['wall' => true, 'private' => [Item::PUBLIC, Item::UNLISTED], 'guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]]; $item = Item::selectFirst($fields, $condition); if (empty($item)) { $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]]; diff --git a/src/Module/Notifications/Notification.php b/src/Module/Notifications/Notification.php index 2f5cfa869..2dc008248 100644 --- a/src/Module/Notifications/Notification.php +++ b/src/Module/Notifications/Notification.php @@ -24,6 +24,7 @@ namespace Friendica\Module\Notifications; use Friendica\BaseModule; use Friendica\Core\System; use Friendica\DI; +use Friendica\Module\Security\Login; use Friendica\Network\HTTPException; /** @@ -31,15 +32,21 @@ use Friendica\Network\HTTPException; */ class Notification extends BaseModule { - public static function init(array $parameters = []) + /** + * {@inheritDoc} + * + * @throws HTTPException\InternalServerErrorException + * @throws HTTPException\NotFoundException + * @throws HTTPException\UnauthorizedException + * @throws \ImagickException + * @throws \Exception + */ + public static function post(array $parameters = []) { if (!local_user()) { throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.')); } - } - public static function post(array $parameters = []) - { $request_id = $parameters['id'] ?? false; if ($request_id) { @@ -58,9 +65,17 @@ class Notification extends BaseModule } } + /** + * {@inheritDoc} + * + * @throws HTTPException\UnauthorizedException + */ public static function rawContent(array $parameters = []) { - // @TODO: Replace with parameter from router + if (!local_user()) { + throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.')); + } + if (DI::args()->get(1) === 'mark' && DI::args()->get(2) === 'all') { try { $success = DI::notify()->setSeen(); @@ -74,31 +89,36 @@ class Notification extends BaseModule } /** + * {@inheritDoc} + * * Redirect to the notifications main page or to the url for the chosen notifications * - * @return string|void + * @throws HTTPException\NotFoundException In case the notification is either not existing or is not for this user * @throws HTTPException\InternalServerErrorException + * @throws \Exception */ public static function content(array $parameters = []) { + if (!local_user()) { + notice(DI::l10n()->t('You must be logged in to show this page.')); + return Login::form(); + } + $request_id = $parameters['id'] ?? false; if ($request_id) { - try { - $notify = DI::notify()->getByID($request_id); - DI::notify()->setSeen(true, $notify); + $notify = DI::notify()->getByID($request_id, local_user()); + DI::notify()->setSeen(true, $notify); - if (!empty($notify->link)) { - System::externalRedirect($notify->link); - } - - } catch (HTTPException\NotFoundException $e) { - info(DI::l10n()->t('Invalid notification.')); + if (!empty($notify->link)) { + System::externalRedirect($notify->link); } DI::baseUrl()->redirect(); } DI::baseUrl()->redirect('notifications/system'); + + throw new HTTPException\InternalServerErrorException('Invalid situation.'); } } diff --git a/src/Module/Objects.php b/src/Module/Objects.php index 9c57665ff..023ced08c 100644 --- a/src/Module/Objects.php +++ b/src/Module/Objects.php @@ -49,11 +49,11 @@ class Objects extends BaseModule // At first we try the original post with that guid // @TODO: Replace with parameter from router - $item = Item::selectFirst(['id'], ['guid' => $a->argv[1], 'origin' => true, 'private' => false]); + $item = Item::selectFirst(['id'], ['guid' => $a->argv[1], 'origin' => true, 'private' => [item::PRIVATE, Item::UNLISTED]]); if (!DBA::isResult($item)) { // If no original post could be found, it could possibly be a forum post, there we remove the "origin" field. // @TODO: Replace with parameter from router - $item = Item::selectFirst(['id', 'author-link'], ['guid' => $a->argv[1], 'private' => false]); + $item = Item::selectFirst(['id', 'author-link'], ['guid' => $a->argv[1], 'private' => [item::PRIVATE, Item::UNLISTED]]); if (!DBA::isResult($item) || !strstr($item['author-link'], DI::baseUrl()->get())) { throw new \Friendica\Network\HTTPException\NotFoundException(); } diff --git a/src/Module/Settings/Display.php b/src/Module/Settings/Display.php index 644453756..bde049718 100644 --- a/src/Module/Settings/Display.php +++ b/src/Module/Settings/Display.php @@ -197,7 +197,7 @@ class Display extends BaseSettings '$itemspage_network' => ['itemspage_network' , DI::l10n()->t('Number of items to display per page:'), $itemspage_network, DI::l10n()->t('Maximum of 100 items')], '$itemspage_mobile_network' => ['itemspage_mobile_network', DI::l10n()->t('Number of items to display per page when viewed from mobile device:'), $itemspage_mobile_network, DI::l10n()->t('Maximum of 100 items')], '$ajaxint' => ['browser_update' , DI::l10n()->t('Update browser every xx seconds'), $browser_update, DI::l10n()->t('Minimum of 10 seconds. Enter -1 to disable it.')], - '$no_auto_update' => ['no_auto_update' , DI::l10n()->t('Automatic updates only at the top of the network page'), $no_auto_update, DI::l10n()->t('When disabled, the network page is updated all the time, which could be confusing while reading.')], + '$no_auto_update' => ['no_auto_update' , DI::l10n()->t('Automatic updates only at the top of the post stream pages'), $no_auto_update, DI::l10n()->t('Auto update may add new posts at the top of the post stream pages, which can affect the scroll position and perturb normal reading if it happens anywhere else the top of the page.')], '$nosmile' => ['nosmile' , DI::l10n()->t('Don\'t show emoticons'), $nosmile, DI::l10n()->t('Normally emoticons are replaced with matching symbols. This setting disables this behaviour.')], '$infinite_scroll' => ['infinite_scroll' , DI::l10n()->t('Infinite scroll'), $infinite_scroll, DI::l10n()->t('Automatic fetch new items when reaching the page end.')], '$no_smart_threading' => ['no_smart_threading' , DI::l10n()->t('Disable Smart Threading'), $no_smart_threading, DI::l10n()->t('Disable the automatic suppression of extraneous thread indentation.')], diff --git a/src/Module/Update/Community.php b/src/Module/Update/Community.php index e0bc6c067..b064b4e86 100644 --- a/src/Module/Update/Community.php +++ b/src/Module/Update/Community.php @@ -37,7 +37,10 @@ class Community extends CommunityModule { self::parseRequest($parameters); - $o = conversation(DI::app(), self::getItems(), 'community', true, false, 'commented', local_user()); + $o = ''; + if (!empty($_GET['force']) || !DI::pConfig()->get(local_user(), 'system', 'no_auto_update')) { + $o = conversation(DI::app(), self::getItems(), 'community', true, false, 'commented', local_user()); + } System::htmlUpdateExit($o); } diff --git a/src/Module/Update/Profile.php b/src/Module/Update/Profile.php index 662042eb1..38ef3b09e 100644 --- a/src/Module/Update/Profile.php +++ b/src/Module/Update/Profile.php @@ -42,8 +42,6 @@ class Profile extends BaseModule throw new ForbiddenException(); } - $o = ''; - $profile_uid = intval($_GET['p'] ?? 0); // Ensure we've got a profile owner if updating. @@ -57,6 +55,12 @@ class Profile extends BaseModule throw new ForbiddenException(DI::l10n()->t('Access to this profile has been restricted.')); } + $o = ''; + + if (empty($_GET['force']) && DI::pConfig()->get(local_user(), 'system', 'no_auto_update')) { + System::htmlUpdateExit($o); + } + // Get permissions SQL - if $remote_contact is true, our remote user has been pre-verified and we already have fetched his/her groups $sql_extra = Item::getPermissionsSQLByUserId($a->profile['uid']); diff --git a/src/Object/Post.php b/src/Object/Post.php index c92c5a32b..1c1f85e2a 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -170,12 +170,12 @@ class Post $conv = $this->getThread(); - $lock = ((($item['private'] == 1) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid']) + $lock = ((($item['private'] == Item::PRIVATE) || (($item['uid'] == local_user()) && (strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])))) ? DI::l10n()->t('Private Message') : false); - $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != 1; + $shareable = in_array($conv->getProfileOwner(), [0, local_user()]) && $item['private'] != Item::PRIVATE; $edpost = false; @@ -272,10 +272,12 @@ class Post } } - $responses = get_responses($conv_responses, $response_verbs, $item, $this); - - foreach ($response_verbs as $value => $verbs) { - $responses[$verbs]['output'] = !empty($conv_responses[$verbs][$item['uri']]) ? format_like($conv_responses[$verbs][$item['uri']], $conv_responses[$verbs][$item['uri'] . '-l'], $verbs, $item['uri']) : ''; + $responses = []; + foreach ($response_verbs as $value => $verb) { + $responses[$verb] = [ + 'self' => $conv_responses[$verb][$item['uri'] . '-self'] ?? 0, + 'output' => !empty($conv_responses[$verb][$item['uri']]) ? format_like($conv_responses[$verb][$item['uri']], $conv_responses[$verb][$item['uri'] . '-l'], $verb, $item['uri']) : '', + ]; } /* diff --git a/src/Object/Thread.php b/src/Object/Thread.php index b574e300b..f62b14c71 100644 --- a/src/Object/Thread.php +++ b/src/Object/Thread.php @@ -34,6 +34,7 @@ use Friendica\Util\Security; */ class Thread { + /** @var Post[] */ private $parents = []; private $mode = null; private $writable = false; diff --git a/src/Protocol/ActivityPub/Processor.php b/src/Protocol/ActivityPub/Processor.php index 65f101746..6d6c652fd 100644 --- a/src/Protocol/ActivityPub/Processor.php +++ b/src/Protocol/ActivityPub/Processor.php @@ -29,6 +29,7 @@ use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\APContact; use Friendica\Model\Contact; +use Friendica\Model\Conversation; use Friendica\Model\Event; use Friendica\Model\Item; use Friendica\Model\Mail; @@ -375,7 +376,7 @@ class Processor Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]); return false; } - if ($item_private && !$parent['private']) { + if ($item_private && ($parent['private'] == Item::PRIVATE)) { Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]); return false; } @@ -442,12 +443,26 @@ class Processor } $item['network'] = Protocol::ACTIVITYPUB; - $item['private'] = !in_array(0, $activity['receiver']); $item['author-link'] = $activity['author']; $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true); $item['owner-link'] = $activity['actor']; $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true); + if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) { + $item['private'] = Item::UNLISTED; + } elseif (in_array(0, $activity['receiver'])) { + $item['private'] = Item::PUBLIC; + } else { + $item['private'] = Item::PRIVATE; + } + + if (!empty($activity['raw'])) { + $item['source'] = $activity['raw']; + $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB; + $item['conversation-href'] = $activity['context'] ?? ''; + $item['conversation-uri'] = $activity['conversation'] ?? ''; + } + $isForum = false; if (!empty($activity['thread-completion'])) { @@ -490,6 +505,10 @@ class Processor $stored = false; foreach ($activity['receiver'] as $receiver) { + if ($receiver == -1) { + continue; + } + $item['uid'] = $receiver; if ($isForum) { @@ -539,7 +558,7 @@ class Processor } // Store send a follow request for every reshare - but only when the item had been stored - if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) { + if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) { $author = APContact::getByURL($item['owner-link'], false); // We send automatic follow requests for reshared messages. (We don't need though for forum posts) if ($author['type'] != 'Group') { diff --git a/src/Protocol/ActivityPub/Receiver.php b/src/Protocol/ActivityPub/Receiver.php index 96e1588d4..39655f45d 100644 --- a/src/Protocol/ActivityPub/Receiver.php +++ b/src/Protocol/ActivityPub/Receiver.php @@ -28,7 +28,6 @@ use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Model\Contact; use Friendica\Model\APContact; -use Friendica\Model\Conversation; use Friendica\Model\Item; use Friendica\Model\User; use Friendica\Protocol\Activity; @@ -306,33 +305,6 @@ class Receiver return 0; } - /** - * Store the unprocessed data into the conversation table - * This has to be done outside the regular function, - * since we store everything - not only item posts. - * - * @param array $activity Array with activity data - * @param string $body The raw message - * @throws \Exception - */ - private static function storeConversation($activity, $body) - { - if (empty($body) || empty($activity['id'])) { - return; - } - - $conversation = [ - 'protocol' => Conversation::PARCEL_ACTIVITYPUB, - 'item-uri' => $activity['id'], - 'reply-to-uri' => $activity['reply-to-id'] ?? '', - 'conversation-href' => $activity['context'] ?? '', - 'conversation-uri' => $activity['conversation'] ?? '', - 'source' => $body, - 'received' => DateTimeFormat::utcNow()]; - - DBA::insert('conversation', $conversation, true); - } - /** * Processes the activity object * @@ -383,9 +355,8 @@ class Receiver return; } - // Only store content related stuff - and no announces, since they possibly overwrite the original content - if (in_array($object_data['object_type'], self::CONTENT_TYPES) && ($type != 'as:Announce')) { - self::storeConversation($object_data, $body); + if (!empty($body)) { + $object_data['raw'] = $body; } // Internal flag for thread completion. See Processor.php @@ -509,14 +480,15 @@ class Receiver /** * Fetch the receiver list from an activity array * - * @param array $activity - * @param string $actor - * @param array $tags + * @param array $activity + * @param string $actor + * @param array $tags + * @param boolean $fetch_unlisted * * @return array with receivers (user id) * @throws \Exception */ - private static function getReceivers($activity, $actor, $tags = []) + private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false) { $receivers = []; @@ -554,6 +526,11 @@ class Receiver $receivers['uid:0'] = 0; } + // Add receiver "-1" for unlisted posts + if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) { + $receivers['uid:-1'] = -1; + } + if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) { // This will most likely catch all OStatus connections to Mastodon $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND] @@ -1025,7 +1002,9 @@ class Receiver } } - $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']); + $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true); + $object_data['unlisted'] = in_array(-1, $object_data['receiver']); + unset($object_data['receiver']['uid:-1']); // Common object data: diff --git a/src/Protocol/ActivityPub/Transmitter.php b/src/Protocol/ActivityPub/Transmitter.php index 38f102294..0b80e9786 100644 --- a/src/Protocol/ActivityPub/Transmitter.php +++ b/src/Protocol/ActivityPub/Transmitter.php @@ -173,7 +173,7 @@ class Transmitter $public_contact = Contact::getIdForURL($owner['url'], 0, true); $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact, - 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], + 'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'deleted' => false, 'visible' => true, 'moderated' => false]; $count = DBA::count('item', $condition); @@ -264,7 +264,7 @@ class Transmitter $data['name'] = $contact['name']; $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'], 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']]; - $data['summary'] = $contact['about']; + $data['summary'] = BBCode::convert($contact['about'], false); $data['url'] = $contact['url']; $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]); $data['publicKey'] = ['id' => $contact['url'] . '#main-key', @@ -401,7 +401,7 @@ class Transmitter $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]); - if (!$item['private']) { + if ($item['private'] != Item::PRIVATE) { // Directly mention the original author upon a quoted reshare. // Else just ensure that the original author receives the reshare. $announce = self::getAnnounceArray($item); @@ -413,7 +413,12 @@ class Transmitter $data = array_merge($data, self::fetchPermissionBlockFromConversation($item)); - $data['to'][] = ActivityPub::PUBLIC_COLLECTION; + // Check if the item is completely public or unlisted + if ($item['private'] == Item::PUBLIC) { + $data['to'][] = ActivityPub::PUBLIC_COLLECTION; + } else { + $data['cc'][] = ActivityPub::PUBLIC_COLLECTION; + } foreach ($terms as $term) { $profile = APContact::getByURL($term['url'], false); @@ -467,13 +472,13 @@ class Transmitter $data['to'][] = $profile['url']; } else { $data['cc'][] = $profile['url']; - if (!$item['private'] && !empty($actor_profile['followers'])) { + if (($item['private'] != Item::PRIVATE) && $item['private'] && !empty($actor_profile['followers'])) { $data['cc'][] = $actor_profile['followers']; } } } else { // Public thread parent post always are directed to the followers - if (!$item['private'] && !$forum_mode) { + if (($item['private'] != Item::PRIVATE) && !$forum_mode) { $data['cc'][] = $actor_profile['followers']; } } diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index f065cd67e..4c88db1d9 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -182,7 +182,7 @@ class DFRN // default permissions - anonymous user - $sql_extra = " AND NOT `item`.`private` "; + $sql_extra = sprintf(" AND `item`.`private` != %s ", Item::PRIVATE); $r = q( "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type` @@ -234,7 +234,7 @@ class DFRN if (!empty($set)) { $sql_extra = " AND `item`.`psid` IN (" . implode(',', $set) .")"; } else { - $sql_extra = " AND NOT `item`.`private`"; + $sql_extra = sprintf(" AND `item`.`private` != %s", Item::PRIVATE); } } @@ -332,7 +332,7 @@ class DFRN if ($public_feed) { $type = 'html'; // catch any email that's in a public conversation and make sure it doesn't leak - if ($item['private']) { + if ($item['private'] == Item::PRIVATE) { continue; } } else { @@ -955,7 +955,7 @@ class DFRN $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET); } - if ($item['private']) { + if ($item['private'] == Item::PRIVATE) { $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid); } else { $body = $item['body']; @@ -1050,7 +1050,9 @@ class DFRN } if ($item['private']) { - XML::addElement($doc, $entry, "dfrn:private", ($item['private'] ? $item['private'] : 1)); + // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private + XML::addElement($doc, $entry, "dfrn:private", ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC)); + XML::addElement($doc, $entry, "dfrn:unlisted", $item['private'] == Item::UNLISTED); } if ($item['extid']) { @@ -2404,6 +2406,11 @@ class DFRN $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry); + $unlisted = XML::getFirstNodeValue($xpath, "dfrn:unlisted/text()", $entry); + if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) { + $item['private'] = Item::UNLISTED; + } + $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry); if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") { diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index fd2099110..cda428021 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -2211,7 +2211,7 @@ class Diaspora return false; } - $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]); + $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => [Item::PUBLIC, Item::UNLISTED]]); if (!DBA::isResult($item)) { Logger::log('Item not found, no origin or private: '.$parent_guid); return false; @@ -2523,7 +2523,7 @@ class Diaspora // Do we already have this item? $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid', 'author-name', 'author-link', 'author-avatar']; - $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false]; + $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]]; $item = Item::selectFirst($fields, $condition); if (DBA::isResult($item)) { @@ -2567,7 +2567,7 @@ class Diaspora if ($stored) { $fields = ['body', 'title', 'attach', 'tag', 'app', 'created', 'object-type', 'uri', 'guid', 'author-name', 'author-link', 'author-avatar']; - $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false]; + $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => [Item::PUBLIC, Item::UNLISTED]]; $item = Item::selectFirst($fields, $condition); if (DBA::isResult($item)) { @@ -2711,7 +2711,7 @@ class Diaspora $datarray["app"] = $original_item["app"]; $datarray["plink"] = self::plink($author, $guid); - $datarray["private"] = (($public == "false") ? 1 : 0); + $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC); $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at; $datarray["object-type"] = $original_item["object-type"]; @@ -2941,7 +2941,7 @@ class Diaspora } $datarray["plink"] = self::plink($author, $guid); - $datarray["private"] = (($public == "false") ? 1 : 0); + $datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC); $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at; if (isset($address["address"])) { @@ -3245,7 +3245,7 @@ class Diaspora private static function sendParticipation(array $contact, array $item) { // Don't send notifications for private postings - if ($item['private']) { + if ($item['private'] == Item::PRIVATE) { return; } @@ -3536,12 +3536,12 @@ class Diaspora $myaddr = self::myHandle($owner); - $public = ($item["private"] ? "false" : "true"); + $public = ($item["private"] == Item::PRIVATE ? "false" : "true"); $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM); $edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM); // Detect a share element and do a reshare - if (!$item['private'] && ($ret = self::isReshare($item["body"]))) { + if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) { $message = ["author" => $myaddr, "guid" => $item["guid"], "created_at" => $created, @@ -4135,8 +4135,7 @@ class Diaspora $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d'); } - $about = $profile['about']; - $about = strip_tags(BBCode::convert($about)); + $about = BBCode::toMarkdown($profile['about']); $location = Profile::formatLocation($profile); $tags = ''; diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index cbd50a097..4eb6c7294 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -220,7 +220,7 @@ class Feed { $header["wall"] = 0; $header["origin"] = 0; $header["gravity"] = GRAVITY_PARENT; - $header["private"] = 2; + $header["private"] = Item::PUBLIC; $header["verb"] = Activity::POST; $header["object-type"] = Activity\ObjectType::NOTE; diff --git a/src/Protocol/OStatus.php b/src/Protocol/OStatus.php index b5167aa72..96b8447b4 100644 --- a/src/Protocol/OStatus.php +++ b/src/Protocol/OStatus.php @@ -1682,7 +1682,7 @@ class OStatus $entry = self::entryHeader($doc, $owner, $item, $toplevel); - $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false, + $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED], 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]]; $repeated_item = Item::selectFirst([], $condition); if (!DBA::isResult($repeated_item)) { @@ -1827,7 +1827,7 @@ class OStatus { $item["id"] = $item["parent"] = 0; $item["created"] = $item["edited"] = date("c"); - $item["private"] = true; + $item["private"] = Item::PRIVATE; $contact = Probe::uri($item['follow']); @@ -2120,7 +2120,7 @@ class OStatus ]); } - if (!$item["private"] && !$feed_mode) { + if (($item['private'] != Item::PRIVATE) && !$feed_mode) { XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention", "href" => "http://activityschema.org/collection/public"]); XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned", @@ -2212,8 +2212,8 @@ class OStatus $authorid = Contact::getIdForURL($owner["url"], 0, true); $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` - AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)", - $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN]; + AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)", + $owner["uid"], $check_date, Item::PRIVATE, Protocol::OSTATUS, Protocol::DFRN]; if ($filter === 'comments') { $condition[0] .= " AND `object-type` = ? "; diff --git a/src/Repository/Notify.php b/src/Repository/Notify.php index d8887affd..b72ccecf0 100644 --- a/src/Repository/Notify.php +++ b/src/Repository/Notify.php @@ -23,9 +23,9 @@ namespace Friendica\Repository; use Exception; use Friendica\BaseRepository; +use Friendica\Collection; use Friendica\Core\Hook; use Friendica\Model; -use Friendica\Collection; use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\NotFoundException; use Friendica\Util\DateTimeFormat; @@ -61,14 +61,17 @@ class Notify extends BaseRepository } /** - * {@inheritDoc} + * Return one notify instance based on ID / UID + * + * @param int $id The ID of the notify instance + * @param int $uid The user ID, bound to this notify instance (= security check) * * @return Model\Notify * @throws NotFoundException */ - public function getByID(int $id) + public function getByID(int $id, int $uid) { - return $this->selectFirst(['id' => $id, 'uid' => local_user()]); + return $this->selectFirst(['id' => $id, 'uid' => $uid]); } /** diff --git a/src/Util/JsonLD.php b/src/Util/JsonLD.php index 1452318b5..b4ff53fdb 100644 --- a/src/Util/JsonLD.php +++ b/src/Util/JsonLD.php @@ -122,7 +122,9 @@ class JsonLD 'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'], 'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'], 'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id'], - 'litepub' => (object)['@id' => 'http://litepub.social/ns#', '@type' => '@id']]; + 'litepub' => (object)['@id' => 'http://litepub.social/ns#', '@type' => '@id'], + 'sc' => (object)['@id' => 'http://schema.org#', '@type' => '@id'], + 'pt' => (object)['@id' => 'https://joinpeertube.org/ns#', '@type' => '@id']]; // Preparation for adding possibly missing content to the context if (!empty($json['@context']) && is_string($json['@context'])) { diff --git a/src/Worker/DBClean.php b/src/Worker/DBClean.php index 4144fc95e..7fbc65e29 100644 --- a/src/Worker/DBClean.php +++ b/src/Worker/DBClean.php @@ -107,6 +107,7 @@ class DBClean { Logger::log("found global item orphans: ".$count); while ($orphan = DBA::fetch($r)) { $last_id = $orphan["id"]; + Logger::notice('Delete global orphan item', ['id' => $orphan["id"]]); DBA::delete('item', ['id' => $orphan["id"]]); } Worker::add(PRIORITY_MEDIUM, 'DBClean', 1, $last_id); @@ -129,6 +130,7 @@ class DBClean { Logger::log("found item orphans without parents: ".$count); while ($orphan = DBA::fetch($r)) { $last_id = $orphan["id"]; + Logger::notice('Delete orphan item', ['id' => $orphan["id"]]); DBA::delete('item', ['id' => $orphan["id"]]); } Worker::add(PRIORITY_MEDIUM, 'DBClean', 2, $last_id); @@ -326,6 +328,7 @@ class DBClean { Logger::log("found global item entries from expired threads: ".$count); while ($orphan = DBA::fetch($r)) { $last_id = $orphan["id"]; + Logger::notice('Delete expired thread item', ['id' => $orphan["id"]]); DBA::delete('item', ['id' => $orphan["id"]]); } Worker::add(PRIORITY_MEDIUM, 'DBClean', 9, $last_id); diff --git a/src/Worker/Delivery.php b/src/Worker/Delivery.php index c69545bbd..01f747644 100644 --- a/src/Worker/Delivery.php +++ b/src/Worker/Delivery.php @@ -176,7 +176,7 @@ class Delivery && empty($parent['allow_gid']) && empty($parent['deny_cid']) && empty($parent['deny_gid']) - && !$parent["private"]) { + && ($parent["private"] != Model\Item::PRIVATE)) { $public_message = true; } } diff --git a/src/Worker/Expire.php b/src/Worker/Expire.php index e1e671532..dfbf9738e 100644 --- a/src/Worker/Expire.php +++ b/src/Worker/Expire.php @@ -45,6 +45,7 @@ class Expire $condition = ["`deleted` AND `changed` < UTC_TIMESTAMP() - INTERVAL 60 DAY"]; $rows = DBA::select('item', ['id'], $condition); while ($row = DBA::fetch($rows)) { + Logger::notice('Delete expired item', ['id' => $row["id"]]); DBA::delete('item', ['id' => $row['id']]); } DBA::close($rows); diff --git a/src/Worker/Notifier.php b/src/Worker/Notifier.php index b3741e546..35a228fce 100644 --- a/src/Worker/Notifier.php +++ b/src/Worker/Notifier.php @@ -151,6 +151,8 @@ class Notifier // If this is a public conversation, notify the feed hub $public_message = true; + $unlisted = false; + // Do a PuSH $push_notify = false; @@ -183,6 +185,8 @@ class Notifier Logger::info('Threaded comment', ['diaspora_delivery' => (int)$diaspora_delivery]); } + $unlisted = $target_item['private'] == Item::UNLISTED; + // This is IMPORTANT!!!! // We will only send a "notify owner to relay" or followup message if the referenced post @@ -245,8 +249,7 @@ class Notifier Logger::info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]); - //if (!$target_item['private'] && $target_item['wall'] && - if (!$target_item['private'] && + if (($target_item['private'] != Item::PRIVATE) && (strlen($target_item['allow_cid'].$target_item['allow_gid']. $target_item['deny_cid'].$target_item['deny_gid']) == 0)) $push_notify = true; @@ -410,7 +413,7 @@ class Notifier if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) { $relay_list = []; - if ($diaspora_delivery) { + if ($diaspora_delivery && !$unlisted) { $batch_delivery = true; $relay_list_stmt = DBA::p( diff --git a/src/Worker/OnePoll.php b/src/Worker/OnePoll.php index c87bfcf25..959d28237 100644 --- a/src/Worker/OnePoll.php +++ b/src/Worker/OnePoll.php @@ -657,11 +657,11 @@ class OnePoll $datarray['owner-avatar'] = $contact['photo']; if ($datarray['parent-uri'] === $datarray['uri']) { - $datarray['private'] = 1; + $datarray['private'] = Item::PRIVATE; } if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) { - $datarray['private'] = 1; + $datarray['private'] = Item::PRIVATE; $datarray['allow_cid'] = '<' . $contact['id'] . '>'; } diff --git a/src/Worker/RemoveContact.php b/src/Worker/RemoveContact.php index ba464f75f..40e3a67fc 100644 --- a/src/Worker/RemoveContact.php +++ b/src/Worker/RemoveContact.php @@ -21,6 +21,7 @@ namespace Friendica\Worker; +use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Core\Protocol; use Friendica\Model\Item; @@ -42,6 +43,7 @@ class RemoveContact { do { $items = Item::select(['id'], $condition, ['limit' => 100]); while ($item = Item::fetch($items)) { + Logger::notice('Delete removed contact item', ['id' => $item["id"]]); DBA::delete('item', ['id' => $item['id']]); } DBA::close($items); diff --git a/static/dbstructure.config.php b/static/dbstructure.config.php index 978666460..5b2e3bc09 100755 --- a/static/dbstructure.config.php +++ b/static/dbstructure.config.php @@ -51,7 +51,7 @@ use Friendica\Database\DBA; if (!defined('DB_UPDATE_VERSION')) { - define('DB_UPDATE_VERSION', 1333); + define('DB_UPDATE_VERSION', 1334); } return [ @@ -647,7 +647,7 @@ return [ "extid" => ["type" => "varchar(255)", "not null" => "1", "default" => "", "comment" => ""], "post-type" => ["type" => "tinyint unsigned", "not null" => "1", "default" => "0", "comment" => "Post type (personal note, bookmark, ...)"], "global" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => ""], - "private" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => "distribution is restricted"], + "private" => ["type" => "tinyint unsigned", "not null" => "1", "default" => "0", "comment" => "0=public, 1=private, 2=unlisted"], "visible" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => ""], "moderated" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => ""], "deleted" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => "item has been deleted"], @@ -1294,7 +1294,7 @@ return [ "received" => ["type" => "datetime", "not null" => "1", "default" => DBA::NULL_DATETIME, "comment" => ""], "changed" => ["type" => "datetime", "not null" => "1", "default" => DBA::NULL_DATETIME, "comment" => ""], "wall" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => ""], - "private" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => ""], + "private" => ["type" => "tinyint unsigned", "not null" => "1", "default" => "0", "comment" => "0=public, 1=private, 2=unlisted"], "pubmail" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => ""], "moderated" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => ""], "visible" => ["type" => "boolean", "not null" => "1", "default" => "0", "comment" => ""], diff --git a/tests/datasets/content/text/html/bug-7474.html b/tests/datasets/content/text/html/bug-7474.html index 0bba94e63..1ed97bce6 100644 --- a/tests/datasets/content/text/html/bug-7474.html +++ b/tests/datasets/content/text/html/bug-7474.html @@ -1 +1 @@ -

I recently released a PHP package that makes executing commands over SSH super simple. You can also upload/download files via SCP.

github.com/DivineOmega/php-ssh

\ No newline at end of file +

I recently released a PHP package that makes executing commands over SSH super simple. You can also upload/download files via SCP.

github.com/DivineOmega/php-ssh

\ No newline at end of file diff --git a/tests/src/Content/Text/BBCodeTest.php b/tests/src/Content/Text/BBCodeTest.php index f827eb5b1..1a1d06dc7 100644 --- a/tests/src/Content/Text/BBCodeTest.php +++ b/tests/src/Content/Text/BBCodeTest.php @@ -164,7 +164,7 @@ class BBCodeTest extends MockedTest public function testAutoLinking($data, $assertHTML) { $output = BBCode::convert($data); - $assert = '' . $data . ''; + $assert = '' . $data . ''; if ($assertHTML) { $this->assertEquals($assert, $output); } else { @@ -176,21 +176,21 @@ class BBCodeTest extends MockedTest { return [ 'bug-7271-condensed-space' => [ - 'expectedHtml' => '', + 'expectedHtml' => '', 'text' => '[ol][*] http://example.com/[/ol]', ], 'bug-7271-condensed-nospace' => [ - 'expectedHtml' => '', + 'expectedHtml' => '', 'text' => '[ol][*]http://example.com/[/ol]', ], 'bug-7271-indented-space' => [ - 'expectedHtml' => '', + 'expectedHtml' => '', 'text' => '[ul] [*] http://example.com/ [/ul]', ], 'bug-7271-indented-nospace' => [ - 'expectedHtml' => '', + 'expectedHtml' => '', 'text' => '[ul] [*]http://example.com/ [/ul]', diff --git a/view/templates/admin/users.tpl b/view/templates/admin/users.tpl index 6ca85fe7a..8bbffbb7d 100644 --- a/view/templates/admin/users.tpl +++ b/view/templates/admin/users.tpl @@ -35,8 +35,8 @@ {{$u.email}} - - + + diff --git a/view/templates/event.tpl b/view/templates/event.tpl index f1d2bf102..f318c909b 100644 --- a/view/templates/event.tpl +++ b/view/templates/event.tpl @@ -4,7 +4,7 @@ {{if $event.item.author_name}}{{$event.item.author_name}}{{/if}} {{$event.html nofilter}} - {{if $event.item.plink}}{{/if}} + {{if $event.item.plink}}{{/if}} {{if $event.edit}}{{/if}} {{if $event.copy}}{{/if}} {{if $event.drop}}{{/if}} diff --git a/view/templates/events.tpl b/view/templates/events.tpl index cae7b3282..7f55e52d8 100644 --- a/view/templates/events.tpl +++ b/view/templates/events.tpl @@ -17,7 +17,7 @@ {{if $event.is_first}}
{{$event.d}}
{{/if}} {{if $event.item.author_name}}{{$event.item.author_name}}{{/if}} {{$event.html nofilter}} - {{if $event.item.plink}}{{/if}} + {{if $event.item.plink}}{{/if}} {{if $event.edit}}{{/if}}
diff --git a/view/templates/photo_album.tpl b/view/templates/photo_album.tpl index 5080663ab..724a2abb3 100644 --- a/view/templates/photo_album.tpl +++ b/view/templates/photo_album.tpl @@ -1,8 +1,5 @@

{{$album}}

-{{if $edit}} - -{{/if}} {{if $edit}} {{/if}} diff --git a/view/templates/profile/vcard.tpl b/view/templates/profile/vcard.tpl index 0f27284cd..521738107 100644 --- a/view/templates/profile/vcard.tpl +++ b/view/templates/profile/vcard.tpl @@ -41,7 +41,7 @@ {{if $updated}}{{/if}} - {{if $homepage}}
{{$homepage}}
{{$profile.homepage}}
{{/if}} + {{if $homepage}}
{{$homepage}}
{{$profile.homepage}}
{{/if}} {{if $about}}
{{$about}}
{{$profile.about nofilter}}
{{/if}} diff --git a/view/templates/settings/settings.tpl b/view/templates/settings/settings.tpl index e232ec177..f8b199180 100644 --- a/view/templates/settings/settings.tpl +++ b/view/templates/settings/settings.tpl @@ -53,6 +53,8 @@ {{$hide_wall nofilter}} +{{$unlisted nofilter}} + {{$blockwall nofilter}} {{$blocktags nofilter}} diff --git a/view/templates/shared_content.tpl b/view/templates/shared_content.tpl index 2e892d334..32cfbe372 100644 --- a/view/templates/shared_content.tpl +++ b/view/templates/shared_content.tpl @@ -1,12 +1,12 @@
{{if $avatar}} - + {{/if}} - - + +
{{$content nofilter}}
diff --git a/view/templates/wall_thread.tpl b/view/templates/wall_thread.tpl index 390f99b46..7b205504d 100644 --- a/view/templates/wall_thread.tpl +++ b/view/templates/wall_thread.tpl @@ -84,10 +84,10 @@ {{/if}} {{if $item.remote_comment}} - + {{/if}} {{if $item.plink}} - + {{/if}} {{if $item.edpost}} diff --git a/view/templates/widget_forumlist.tpl b/view/templates/widget_forumlist.tpl index 01f61d603..1d35b1948 100644 --- a/view/templates/widget_forumlist.tpl +++ b/view/templates/widget_forumlist.tpl @@ -24,7 +24,7 @@ function showHideForumlist() { {{if $forum.id <= $visible_forums}}