From 17aca9bee85f8c13d7723e1d0e5ec990c0885497 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 21 Oct 2019 21:18:59 +0200 Subject: [PATCH 01/46] move mod/ignored to src/Module/Item/Ignored --- mod/ignored.php | 52 --------------------------- src/Module/Item/Ignored.php | 70 +++++++++++++++++++++++++++++++++++++ static/routes.config.php | 11 +++--- 3 files changed, 76 insertions(+), 57 deletions(-) delete mode 100644 mod/ignored.php create mode 100644 src/Module/Item/Ignored.php diff --git a/mod/ignored.php b/mod/ignored.php deleted file mode 100644 index 6e0cf92a6..000000000 --- a/mod/ignored.php +++ /dev/null @@ -1,52 +0,0 @@ -argc > 1) { - $message_id = intval($a->argv[1]); - } - - if (empty($message_id)) { - exit(); - } - - $thread = Item::selectFirstThreadForUser(local_user(), ['uid', 'ignored'], ['iid' => $message_id]); - if (!DBA::isResult($thread)) { - exit(); - } - - // Numeric values are needed for the json output further below - $ignored = ($thread['ignored'] ? 0 : 1); - - if ($thread['uid'] != 0) { - DBA::update('thread', ['ignored' => $ignored], ['iid' => $message_id]); - } else { - DBA::update('user-item', ['ignored' => $ignored], ['iid' => $message_id, 'uid' => local_user()], true); - } - - // See if we've been passed a return path to redirect to - $return_path = $_REQUEST['return'] ?? ''; - if ($return_path) { - $rand = '_=' . time(); - if (strpos($return_path, '?')) { - $rand = "&$rand"; - } else { - $rand = "?$rand"; - } - - $a->internalRedirect($return_path . $rand); - } - - // the json doesn't really matter, it will either be 0 or 1 - - echo json_encode($ignored); - exit(); -} diff --git a/src/Module/Item/Ignored.php b/src/Module/Item/Ignored.php new file mode 100644 index 000000000..474f01dbe --- /dev/null +++ b/src/Module/Item/Ignored.php @@ -0,0 +1,70 @@ +t('Access denied.')); + } + + /** @var App\Arguments $args */ + $args = self::getClass(App\Arguments::class); + /** @var Database $dba */ + $dba = self::getClass(Database::class); + + $message_id = intval($args->get(1)); + + if (empty($message_id) || !is_int($message_id)) { + throw new HTTPException\BadRequestException(); + } + + $thread = Item::selectFirstThreadForUser(local_user(), ['uid', 'ignored'], ['iid' => $message_id]); + if (!$dba->isResult($thread)) { + throw new HTTPException\BadRequestException(); + } + + // Numeric values are needed for the json output further below + $ignored = !empty($thread['ignored']) ? 0 : 1; + + if (!empty($thread['uid']) && $thread['uid'] != 0) { + $dba->update('thread', ['ignored' => $ignored], ['iid' => $message_id]); + } else { + $dba->update('user-item', ['ignored' => $ignored], ['iid' => $message_id, 'uid' => local_user()], true); + } + + // See if we've been passed a return path to redirect to + $return_path = $_REQUEST['return'] ?? ''; + if (!empty($return_path)) { + $rand = '_=' . time(); + if (strpos($return_path, '?')) { + $rand = "&$rand"; + } else { + $rand = "?$rand"; + } + + self::getApp()->internalRedirect($return_path . $rand); + } + + // the json doesn't really matter, it will either be 0 or 1 + + echo json_encode($ignored); + exit(); + } +} diff --git a/static/routes.config.php b/static/routes.config.php index 7cc9fdaa6..32a9f12ed 100644 --- a/static/routes.config.php +++ b/static/routes.config.php @@ -128,11 +128,12 @@ return [ '/{group:\d+}/add/{contact:\d+}' => [Module\Group::class, [R::GET, R::POST]], '/{group:\d+}/remove/{contact:\d+}' => [Module\Group::class, [R::GET, R::POST]], ], - '/hashtag' => [Module\Hashtag::class, [R::GET]], - '/home' => [Module\Home::class, [R::GET]], - '/help[/{doc:.+}]' => [Module\Help::class, [R::GET]], - '/inbox[/{nickname}]' => [Module\Inbox::class, [R::GET, R::POST]], - '/invite' => [Module\Invite::class, [R::GET, R::POST]], + '/hashtag' => [Module\Hashtag::class, [R::GET]], + '/home' => [Module\Home::class, [R::GET]], + '/help[/{doc:.+}]' => [Module\Help::class, [R::GET]], + '/ignored/{id}' => [Module\Item\Ignored::class, [R::GET]], + '/inbox[/{nickname}]' => [Module\Inbox::class, [R::GET, R::POST]], + '/invite' => [Module\Invite::class, [R::GET, R::POST]], '/install' => [ '[/]' => [Module\Install::class, [R::GET, R::POST]], From 0e84a843a4e9c77df3a6191b1a6906059fb22fe5 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 21 Oct 2019 21:53:55 +0200 Subject: [PATCH 02/46] Add Fallback in case the logfile isn't accessible. - Fixes https://github.com/friendica/friendica/issues/7756#issuecomment-544227862 --- src/Factory/LoggerFactory.php | 34 ++++++++++++++++++++------------ src/Util/Logger/StreamLogger.php | 2 ++ 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/Factory/LoggerFactory.php b/src/Factory/LoggerFactory.php index 55091a487..b25d35838 100644 --- a/src/Factory/LoggerFactory.php +++ b/src/Factory/LoggerFactory.php @@ -53,9 +53,6 @@ class LoggerFactory * @param Profiler $profiler The profiler of the app * * @return LoggerInterface The PSR-3 compliant logger instance - * - * @throws \Exception - * @throws InternalServerErrorException */ public function create( Database $database, Configuration $config, Profiler $profiler) { @@ -84,12 +81,22 @@ class LoggerFactory // just add a stream in case it's either writable or not file if (!is_file($stream) || is_writable($stream)) { - static::addStreamHandler($logger, $stream, $loglevel); + try { + static::addStreamHandler($logger, $stream, $loglevel); + } catch (\Throwable $e) { + // No Logger .. + $logger = new VoidLogger(); + } } break; case 'syslog': - $logger = new SyslogLogger($this->channel, $introspection, $loglevel); + try { + $logger = new SyslogLogger($this->channel, $introspection, $loglevel); + } catch (\Throwable $e) { + // No logger ... + $logger = new VoidLogger(); + } break; case 'stream': @@ -97,7 +104,12 @@ class LoggerFactory $stream = $config->get('system', 'logfile'); // just add a stream in case it's either writable or not file if (!is_file($stream) || is_writable($stream)) { - $logger = new StreamLogger($this->channel, $stream, $introspection, $loglevel); + try { + $logger = new StreamLogger($this->channel, $stream, $introspection, $loglevel); + } catch (\Throwable $t) { + // No logger ... + $logger = new VoidLogger(); + } } else { $logger = new VoidLogger(); } @@ -210,11 +222,10 @@ class LoggerFactory case "3": return LogLevel::INFO; // legacy DATA - case "4": - return LogLevel::DEBUG; - // legacy ALL case "5": - return LogLevel::DEBUG; + // legacy ALL + case "4": + return LogLevel::DEBUG; // default if nothing set default: return $level; @@ -230,7 +241,6 @@ class LoggerFactory * * @return void * - * @throws InternalServerErrorException if the logger is incompatible to the logger factory * @throws \Exception in case of general failures */ public static function addStreamHandler($logger, $stream, $level = LogLevel::NOTICE) @@ -249,8 +259,6 @@ class LoggerFactory $fileHandler->setFormatter($formatter); $logger->pushHandler($fileHandler); - } else { - throw new InternalServerErrorException('Logger instance incompatible for MonologFactory'); } } diff --git a/src/Util/Logger/StreamLogger.php b/src/Util/Logger/StreamLogger.php index 303146106..c9c245d63 100644 --- a/src/Util/Logger/StreamLogger.php +++ b/src/Util/Logger/StreamLogger.php @@ -81,6 +81,8 @@ class StreamLogger extends AbstractLogger } else { throw new \InvalidArgumentException(sprintf('The level "%s" is not valid.', $level)); } + + $this->checkStream(); } public function close() From 6b2c28e2d72d618bd46b9264f9e348725d7b5f5f Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 22 Oct 2019 22:47:37 +0200 Subject: [PATCH 03/46] Add checks & realpath() usage - New util class "FileSystem" - Add check in admin summary too --- src/Factory/LoggerFactory.php | 13 +++-- src/Module/Admin/Summary.php | 19 +++++-- src/Util/FileSystem.php | 64 ++++++++++++++++++++++ src/Util/Logger/StreamLogger.php | 50 +++-------------- tests/src/Util/Logger/StreamLoggerTest.php | 43 ++++++++++++--- 5 files changed, 129 insertions(+), 60 deletions(-) create mode 100644 src/Util/FileSystem.php diff --git a/src/Factory/LoggerFactory.php b/src/Factory/LoggerFactory.php index b25d35838..d177faf7a 100644 --- a/src/Factory/LoggerFactory.php +++ b/src/Factory/LoggerFactory.php @@ -6,6 +6,7 @@ use Friendica\Core\Config\Configuration; use Friendica\Core\Logger; use Friendica\Database\Database; use Friendica\Network\HTTPException\InternalServerErrorException; +use Friendica\Util\FileSystem; use Friendica\Util\Introspection; use Friendica\Util\Logger\Monolog\DevelopHandler; use Friendica\Util\Logger\Monolog\IntrospectionProcessor; @@ -51,10 +52,11 @@ class LoggerFactory * @param Database $database The Friendica Database instance * @param Configuration $config The config * @param Profiler $profiler The profiler of the app + * @param FileSystem $fileSystem FileSystem utils * * @return LoggerInterface The PSR-3 compliant logger instance */ - public function create( Database $database, Configuration $config, Profiler $profiler) + public function create(Database $database, Configuration $config, Profiler $profiler, FileSystem $fileSystem) { if (empty($config->get('system', 'debugging', false))) { $logger = new VoidLogger(); @@ -105,7 +107,7 @@ class LoggerFactory // just add a stream in case it's either writable or not file if (!is_file($stream) || is_writable($stream)) { try { - $logger = new StreamLogger($this->channel, $stream, $introspection, $loglevel); + $logger = new StreamLogger($this->channel, $stream, $introspection, $fileSystem, $loglevel); } catch (\Throwable $t) { // No logger ... $logger = new VoidLogger(); @@ -137,13 +139,14 @@ class LoggerFactory * * @param Configuration $config The config * @param Profiler $profiler The profiler of the app + * @param FileSystem $fileSystem FileSystem utils * * @return LoggerInterface The PSR-3 compliant logger instance * * @throws InternalServerErrorException * @throws \Exception */ - public static function createDev(Configuration $config, Profiler $profiler) + public static function createDev(Configuration $config, Profiler $profiler, FileSystem $fileSystem) { $debugging = $config->get('system', 'debugging'); $stream = $config->get('system', 'dlogfile'); @@ -183,7 +186,7 @@ class LoggerFactory case 'stream': default: - $logger = new StreamLogger(self::DEV_CHANNEL, $stream, $introspection, LogLevel::DEBUG); + $logger = new StreamLogger(self::DEV_CHANNEL, $stream, $introspection, $fileSystem, LogLevel::DEBUG); break; } @@ -225,7 +228,7 @@ class LoggerFactory case "5": // legacy ALL case "4": - return LogLevel::DEBUG; + return LogLevel::DEBUG; // default if nothing set default: return $level; diff --git a/src/Module/Admin/Summary.php b/src/Module/Admin/Summary.php index d0bb4347a..e1952f294 100644 --- a/src/Module/Admin/Summary.php +++ b/src/Module/Admin/Summary.php @@ -14,6 +14,7 @@ use Friendica\Model\Register; use Friendica\Module\BaseAdminModule; use Friendica\Util\ConfigFileLoader; use Friendica\Util\DateTimeFormat; +use Friendica\Util\FileSystem; use Friendica\Util\Network; class Summary extends BaseAdminModule @@ -76,11 +77,21 @@ class Summary extends BaseAdminModule // Check logfile permission if (Config::get('system', 'debugging')) { - $stream = Config::get('system', 'logfile'); + $file = Config::get('system', 'logfile'); - if (is_file($stream) && - !is_writeable($stream)) { - $warningtext[] = L10n::t('The logfile \'%s\' is not writable. No logging possible', $stream); + /** @var FileSystem $fileSystem */ + $fileSystem = self::getClass(FileSystem::class); + + try { + $stream = $fileSystem->createStream($file); + + if (is_file($stream) && + !is_writeable($stream)) { + $warningtext[] = L10n::t('The logfile \'%s\' is not writable. No logging possible', $stream); + } + + } catch (\Throwable $exception) { + $warningtext[] = L10n::t('The logfile \'%s\' is not usable. No logging possible (error: \'%s\')', $file, $exception->getMessage()); } $stream = Config::get('system', 'dlogfile'); diff --git a/src/Util/FileSystem.php b/src/Util/FileSystem.php new file mode 100644 index 000000000..33e04788e --- /dev/null +++ b/src/Util/FileSystem.php @@ -0,0 +1,64 @@ +errorMessage, $dirname)); + } + + return $dirname; + } elseif (isset($dirname) && is_dir($dirname)) { + return $dirname; + } else { + return ''; + } + } + + public function createStream(string $url) + { + $directory = $this->createDir($url); + set_error_handler([$this, 'customErrorHandler']); + if (!empty($directory)) { + $url = $directory . DIRECTORY_SEPARATOR . pathinfo($url, PATHINFO_BASENAME); + } + + $stream = fopen($url, 'ab'); + restore_error_handler(); + + if (!is_resource($stream)) { + throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $url)); + } + + return $stream; + } + + private function customErrorHandler($code, $msg) + { + $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg); + } +} diff --git a/src/Util/Logger/StreamLogger.php b/src/Util/Logger/StreamLogger.php index c9c245d63..600da14fc 100644 --- a/src/Util/Logger/StreamLogger.php +++ b/src/Util/Logger/StreamLogger.php @@ -3,6 +3,7 @@ namespace Friendica\Util\Logger; use Friendica\Util\DateTimeFormat; +use Friendica\Util\FileSystem; use Friendica\Util\Introspection; use Psr\Log\LogLevel; @@ -35,11 +36,11 @@ class StreamLogger extends AbstractLogger */ private $pid; + /** - * An error message - * @var string + * @var FileSystem */ - private $errorMessage; + private $fileSystem; /** * Translates LogLevel log levels to integer values @@ -63,8 +64,10 @@ class StreamLogger extends AbstractLogger * * @throws \Exception */ - public function __construct($channel, $stream, Introspection $introspection, $level = LogLevel::DEBUG) + public function __construct($channel, $stream, Introspection $introspection, FileSystem $fileSystem, $level = LogLevel::DEBUG) { + $this->fileSystem = $fileSystem; + parent::__construct($channel, $introspection); if (is_resource($stream)) { @@ -157,43 +160,6 @@ class StreamLogger extends AbstractLogger throw new \LogicException('Missing stream URL.'); } - $this->createDir(); - set_error_handler([$this, 'customErrorHandler']); - $this->stream = fopen($this->url, 'ab'); - restore_error_handler(); - - if (!is_resource($this->stream)) { - $this->stream = null; - - throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: ' . $this->errorMessage, $this->url)); - } - } - - private function createDir() - { - $dirname = null; - $pos = strpos($this->url, '://'); - if (!$pos) { - $dirname = dirname($this->url); - } - - if (substr($this->url, 0, 7) === 'file://') { - $dirname = dirname(substr($this->url, 7)); - } - - if (isset($dirname) && !is_dir($dirname)) { - set_error_handler([$this, 'customErrorHandler']); - $status = mkdir($dirname, 0777, true); - restore_error_handler(); - - if (!$status && !is_dir($dirname)) { - throw new \UnexpectedValueException(sprintf('Directory "%s" cannot get created: ' . $this->errorMessage, $dirname)); - } - } - } - - private function customErrorHandler($code, $msg) - { - $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg); + $this->stream = $this->fileSystem->createStream($this->url); } } diff --git a/tests/src/Util/Logger/StreamLoggerTest.php b/tests/src/Util/Logger/StreamLoggerTest.php index d42ba1d91..7dcb08ba6 100644 --- a/tests/src/Util/Logger/StreamLoggerTest.php +++ b/tests/src/Util/Logger/StreamLoggerTest.php @@ -2,6 +2,7 @@ namespace Friendica\Test\src\Util\Logger; +use Friendica\Util\FileSystem; use Friendica\Test\Util\VFSTrait; use Friendica\Util\Logger\StreamLogger; use org\bovigo\vfs\vfsStream; @@ -22,11 +23,18 @@ class StreamLoggerTest extends AbstractLoggerTest */ private $logfile; + /** + * @var Filesystem + */ + private $fileSystem; + protected function setUp() { parent::setUp(); $this->setUpVfsDir(); + + $this->fileSystem = new Filesystem(); } /** @@ -37,7 +45,7 @@ class StreamLoggerTest extends AbstractLoggerTest $this->logfile = vfsStream::newFile('friendica.log') ->at($this->root); - $this->logger = new StreamLogger('test', $this->logfile->url(), $this->introspection, $level); + $this->logger = new StreamLogger('test', $this->logfile->url(), $this->introspection, $this->fileSystem, $level); return $this->logger; } @@ -60,7 +68,7 @@ class StreamLoggerTest extends AbstractLoggerTest $filehandler = fopen($logfile->url(), 'ab'); - $logger = new StreamLogger('test', $filehandler, $this->introspection); + $logger = new StreamLogger('test', $filehandler, $this->introspection, $this->fileSystem); $logger->emergency('working'); $text = $logfile->getContent(); @@ -76,7 +84,7 @@ class StreamLoggerTest extends AbstractLoggerTest $logfile = vfsStream::newFile('friendica.log') ->at($this->root); - $logger = new StreamLogger('test', $logfile->url(), $this->introspection); + $logger = new StreamLogger('test', $logfile->url(), $this->introspection, $this->fileSystem); $logger->emergency('working'); $logger->close(); // close doesn't affect @@ -94,7 +102,7 @@ class StreamLoggerTest extends AbstractLoggerTest */ public function testNoUrl() { - $logger = new StreamLogger('test', '', $this->introspection); + $logger = new StreamLogger('test', '', $this->introspection, $this->fileSystem); $logger->emergency('not working'); } @@ -109,7 +117,7 @@ class StreamLoggerTest extends AbstractLoggerTest $logfile = vfsStream::newFile('friendica.log') ->at($this->root)->chmod(0); - $logger = new StreamLogger('test', $logfile->url(), $this->introspection); + $logger = new StreamLogger('test', $logfile->url(), $this->introspection, $this->fileSystem); $logger->emergency('not working'); } @@ -123,7 +131,7 @@ class StreamLoggerTest extends AbstractLoggerTest { $this->markTestIncomplete('We need a platform independent way to set directory to readonly'); - $logger = new StreamLogger('test', '/$%/wrong/directory/file.txt', $this->introspection); + $logger = new StreamLogger('test', '/$%/wrong/directory/file.txt', $this->introspection, $this->fileSystem); $logger->emergency('not working'); } @@ -135,7 +143,7 @@ class StreamLoggerTest extends AbstractLoggerTest */ public function testWrongMinimumLevel() { - $logger = new StreamLogger('test', 'file.text', $this->introspection, 'NOPE'); + $logger = new StreamLogger('test', 'file.text', $this->introspection, $this->fileSystem, 'NOPE'); } /** @@ -148,7 +156,7 @@ class StreamLoggerTest extends AbstractLoggerTest $logfile = vfsStream::newFile('friendica.log') ->at($this->root); - $logger = new StreamLogger('test', $logfile->url(), $this->introspection); + $logger = new StreamLogger('test', $logfile->url(), $this->introspection, $this->fileSystem); $logger->log('NOPE', 'a test'); } @@ -160,6 +168,23 @@ class StreamLoggerTest extends AbstractLoggerTest */ public function testWrongFile() { - $logger = new StreamLogger('test', null, $this->introspection); + $logger = new StreamLogger('test', null, $this->introspection, $this->fileSystem); + } + + /** + * Test a relative path + */ + public function testRealPath() + { + $this->markTestSkipped('vfsStream isn\'t compatible with chdir, so not testable.'); + + $logfile = vfsStream::newFile('friendica.log') + ->at($this->root); + + chdir($this->root->getChild('logs')->url()); + + $logger = new StreamLogger('test', '../friendica.log' , $this->introspection, $this->fileSystem); + + $logger->info('Test'); } } From 4e32d46f97c8b342720ce919193a04eca10dc586 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 22 Oct 2019 22:48:54 +0200 Subject: [PATCH 04/46] switch case --- src/Factory/LoggerFactory.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Factory/LoggerFactory.php b/src/Factory/LoggerFactory.php index d177faf7a..f21fe9b7f 100644 --- a/src/Factory/LoggerFactory.php +++ b/src/Factory/LoggerFactory.php @@ -225,9 +225,9 @@ class LoggerFactory case "3": return LogLevel::INFO; // legacy DATA - case "5": - // legacy ALL case "4": + // legacy ALL + case "5": return LogLevel::DEBUG; // default if nothing set default: From 1fe9b789f3bceafa0cf44096d47b360d61e45276 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 22 Oct 2019 22:51:52 +0200 Subject: [PATCH 05/46] Add some PHP doc --- src/Util/FileSystem.php | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/Util/FileSystem.php b/src/Util/FileSystem.php index 33e04788e..b3a0ae74d 100644 --- a/src/Util/FileSystem.php +++ b/src/Util/FileSystem.php @@ -2,6 +2,9 @@ namespace Friendica\Util; +/** + * Util class for filesystem manipulation + */ final class FileSystem { /** @@ -9,6 +12,13 @@ final class FileSystem */ private $errorMessage; + /** + * Creates a directory based on a file, which gets accessed + * + * @param string $file The file + * + * @return string The directory name (empty if no directory is found, like urls) + */ public function createDir(string $file) { $dirname = null; @@ -39,6 +49,13 @@ final class FileSystem } } + /** + * Creates a stream based on a URL (could be a local file or a real URL) + * + * @param string $url The file/url + * + * @return false|resource the open stream ressource + */ public function createStream(string $url) { $directory = $this->createDir($url); From 04a86dad753c8cea0df87016255a52660165bfb3 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 22 Oct 2019 22:52:40 +0200 Subject: [PATCH 06/46] remove superfluous line --- src/Util/Logger/StreamLogger.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Util/Logger/StreamLogger.php b/src/Util/Logger/StreamLogger.php index 600da14fc..7485e750b 100644 --- a/src/Util/Logger/StreamLogger.php +++ b/src/Util/Logger/StreamLogger.php @@ -36,7 +36,6 @@ class StreamLogger extends AbstractLogger */ private $pid; - /** * @var FileSystem */ From 7f49c73730f71df75433627a7d0a6696bfbbf296 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Tue, 22 Oct 2019 23:57:44 +0200 Subject: [PATCH 07/46] Move undo_post_tagging to mod/editpost because of the only occurrence --- include/text.php | 16 ---------------- mod/editpost.php | 18 +++++++++++++++++- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/include/text.php b/include/text.php index 2050e5702..0935c5e74 100644 --- a/include/text.php +++ b/include/text.php @@ -6,7 +6,6 @@ use Friendica\App; use Friendica\Content\Text\BBCode; use Friendica\Core\Protocol; -use Friendica\Model\Contact; use Friendica\Model\FileTag; use Friendica\Model\Group; use Friendica\Util\Strings; @@ -240,21 +239,6 @@ function bb_translate_video($s) { return $s; } -function undo_post_tagging($s) { - $matches = null; - $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER); - if ($cnt) { - foreach ($matches as $mtch) { - if (in_array($mtch[1], ['!', '@'])) { - $contact = Contact::getDetailsByURL($mtch[2]); - $mtch[3] = empty($contact['addr']) ? $mtch[2] : $contact['addr']; - } - $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s); - } - } - return $s; -} - /// @TODO Rewrite this function is_a_date_arg($s) { $i = intval($s); diff --git a/mod/editpost.php b/mod/editpost.php index e14baffa2..690cb2ac0 100644 --- a/mod/editpost.php +++ b/mod/editpost.php @@ -8,9 +8,10 @@ use Friendica\Content\Feature; use Friendica\Core\Hook; use Friendica\Core\L10n; use Friendica\Core\Renderer; +use Friendica\Database\DBA; +use Friendica\Model\Contact; use Friendica\Model\FileTag; use Friendica\Model\Item; -use Friendica\Database\DBA; use Friendica\Util\Crypto; function editpost_content(App $a) @@ -118,3 +119,18 @@ function editpost_content(App $a) return $o; } + +function undo_post_tagging($s) { + $matches = null; + $cnt = preg_match_all('/([!#@])\[url=(.*?)\](.*?)\[\/url\]/ism', $s, $matches, PREG_SET_ORDER); + if ($cnt) { + foreach ($matches as $mtch) { + if (in_array($mtch[1], ['!', '@'])) { + $contact = Contact::getDetailsByURL($mtch[2]); + $mtch[3] = empty($contact['addr']) ? $mtch[2] : $contact['addr']; + } + $s = str_replace($mtch[0], $mtch[1] . $mtch[3],$s); + } + } + return $s; +} From 2870f42ca2d5c1fc75e6ce32ed5d2839e8e51425 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 00:14:47 +0200 Subject: [PATCH 08/46] Move bb_translate_video - To new Class BBCode\Video - Adding tests - Make BaseObject::getClass() public --- include/text.php | 16 -------- mod/item.php | 7 ++-- src/BaseObject.php | 2 +- src/Content/Text/BBCode/Video.php | 32 +++++++++++++++ tests/src/Content/Text/BBCode/VideoTest.php | 43 +++++++++++++++++++++ 5 files changed, 80 insertions(+), 20 deletions(-) create mode 100644 src/Content/Text/BBCode/Video.php create mode 100644 tests/src/Content/Text/BBCode/VideoTest.php diff --git a/include/text.php b/include/text.php index 0935c5e74..6eb1e46ff 100644 --- a/include/text.php +++ b/include/text.php @@ -223,22 +223,6 @@ function return_bytes($size_str) { } } -function bb_translate_video($s) { - - $matches = null; - $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER); - if ($r) { - foreach ($matches as $mtch) { - if ((stristr($mtch[1], 'youtube')) || (stristr($mtch[1], 'youtu.be'))) { - $s = str_replace($mtch[0], '[youtube]' . $mtch[1] . '[/youtube]', $s); - } elseif (stristr($mtch[1], 'vimeo')) { - $s = str_replace($mtch[0], '[vimeo]' . $mtch[1] . '[/vimeo]', $s); - } - } - } - return $s; -} - /// @TODO Rewrite this function is_a_date_arg($s) { $i = intval($s); diff --git a/mod/item.php b/mod/item.php index 7c8ebee4a..c9a33cc20 100644 --- a/mod/item.php +++ b/mod/item.php @@ -24,8 +24,8 @@ use Friendica\Core\Hook; use Friendica\Core\L10n; use Friendica\Core\Logger; use Friendica\Core\Protocol; -use Friendica\Core\System; use Friendica\Core\Session; +use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\Model\Attach; @@ -499,8 +499,9 @@ function item_post(App $a) { $objecttype = ACTIVITY_OBJ_BOOKMARK; } - $body = bb_translate_video($body); - + /** @var BBCode\Video $bbCodeVideo */ + $bbCodeVideo = \Friendica\BaseObject::getClass(BBCode\Video::class); + $body = $bbCodeVideo->transform($body); // Fold multi-line [code] sequences $body = preg_replace('/\[\/code\]\s*\[code\]/ism', "\n", $body); diff --git a/src/BaseObject.php b/src/BaseObject.php index 996824f4a..204818845 100644 --- a/src/BaseObject.php +++ b/src/BaseObject.php @@ -54,7 +54,7 @@ class BaseObject * * @throws InternalServerErrorException */ - protected static function getClass(string $name) + public static function getClass(string $name) { if (empty(self::$dice)) { throw new InternalServerErrorException('DICE isn\'t initialized.'); diff --git a/src/Content/Text/BBCode/Video.php b/src/Content/Text/BBCode/Video.php new file mode 100644 index 000000000..b73ddce0b --- /dev/null +++ b/src/Content/Text/BBCode/Video.php @@ -0,0 +1,32 @@ + [ + 'input' => '[video]https://youtube.link/4523[/video]', + 'assert' => '[youtube]https://youtube.link/4523[/youtube]', + ], + 'youtu.be' => [ + 'input' => '[video]https://youtu.be.link/4523[/video]', + 'assert' => '[youtube]https://youtu.be.link/4523[/youtube]', + ], + 'vimeo' => [ + 'input' => '[video]https://vimeo.link/2343[/video]', + 'assert' => '[vimeo]https://vimeo.link/2343[/vimeo]', + ], + 'mixed' => [ + 'input' => '[video]https://vimeo.link/2343[/video] With other [b]string[/b] [video]https://youtu.be/blaa[/video]', + 'assert' => '[vimeo]https://vimeo.link/2343[/vimeo] With other [b]string[/b] [youtube]https://youtu.be/blaa[/youtube]', + ] + ]; + } + + /** + * Test if the BBCode is successfully transformed for video links + * + * @dataProvider dataVideo + */ + public function testTransform(string $input, string $assert) + { + $bbCodeVideo = new Video(); + + $this->assertEquals($assert, $bbCodeVideo->transform($input)); + } +} From 4704bf6394d97185c46a39992d920479ef5f0273 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 00:15:17 +0200 Subject: [PATCH 09/46] Remove unused function return_bytes --- include/text.php | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/include/text.php b/include/text.php index 6eb1e46ff..cc4b8e128 100644 --- a/include/text.php +++ b/include/text.php @@ -209,20 +209,6 @@ function get_cats_and_terms($item) return [$categories, $folders]; } -/** - * return number of bytes in size (K, M, G) - * @param string $size_str - * @return int - */ -function return_bytes($size_str) { - switch (substr ($size_str, -1)) { - case 'M': case 'm': return (int)$size_str * 1048576; - case 'K': case 'k': return (int)$size_str * 1024; - case 'G': case 'g': return (int)$size_str * 1073741824; - default: return $size_str; - } -} - /// @TODO Rewrite this function is_a_date_arg($s) { $i = intval($s); From a3e350313d5332ebe6ee40b544e34900daeeb004 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 00:20:44 +0200 Subject: [PATCH 10/46] Move redir_private_images to Item::addRedirLinkToImageLinks() --- include/text.php | 24 ------------------------ src/Model/Item.php | 28 ++++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/include/text.php b/include/text.php index cc4b8e128..1b0681957 100644 --- a/include/text.php +++ b/include/text.php @@ -104,30 +104,6 @@ function qp($s) { return str_replace("%", "=", rawurlencode($s)); } -/** - * @brief Find any non-embedded images in private items and add redir links to them - * - * @param App $a - * @param array &$item The field array of an item row - */ -function redir_private_images($a, &$item) -{ - $matches = []; - $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER); - if ($cnt) { - foreach ($matches as $mtch) { - if (strpos($mtch[1], '/redir') !== false) { - continue; - } - - if ((local_user() == $item['uid']) && ($item['private'] == 1) && ($item['contact-id'] != $a->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']); - } - } - } -} - /** * @brief Given a text string, convert from bbcode to html and add smilie icons. * diff --git a/src/Model/Item.php b/src/Model/Item.php index ff0f46676..650390e52 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -3342,8 +3342,7 @@ class Item extends BaseObject || $rendered_hash != hash("md5", $item["body"]) || Config::get("system", "ignore_cache") ) { - $a = self::getApp(); - redir_private_images($a, $item); + self::addRedirLinkToImageLinks($item); $item["rendered-html"] = prepare_text($item["body"]); $item["rendered-hash"] = hash("md5", $item["body"]); @@ -3378,6 +3377,31 @@ class Item extends BaseObject $item["body"] = $body; } + /** + * @brief Find any non-embedded images in private items and add redir links to them + * + * @param array &$item The field array of an item row + */ + private static function addRedirLinkToImageLinks(array &$item) + { + $app = self::getApp(); + + $matches = []; + $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER); + if ($cnt) { + foreach ($matches as $mtch) { + if (strpos($mtch[1], '/redir') !== false) { + continue; + } + + if ((local_user() == $item['uid']) && ($item['private'] == 1) && ($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']); + } + } + } + } + /** * @brief Given an item array, convert the body element from bbcode to html and add smilie icons. * If attach is true, also add icons for item attachments. From 7a9c5d10ee85e411779cee9a710ab23ff62c27c0 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 00:22:39 +0200 Subject: [PATCH 11/46] Remove unused function attribute_contains --- include/text.php | 19 ------------------- tests/include/TextTest.php | 38 -------------------------------------- 2 files changed, 57 deletions(-) diff --git a/include/text.php b/include/text.php index 1b0681957..216e87ed8 100644 --- a/include/text.php +++ b/include/text.php @@ -64,25 +64,6 @@ function perms2str($p) { return $ret; } -/** - * for html,xml parsing - let's say you've got - * an attribute foobar="class1 class2 class3" - * and you want to find out if it contains 'class3'. - * you can't use a normal sub string search because you - * might match 'notclass3' and a regex to do the job is - * possible but a bit complicated. - * pass the attribute string as $attr and the attribute you - * are looking for as $s - returns true if found, otherwise false - * - * @param string $attr attribute value - * @param string $s string to search - * @return boolean True if found, False otherwise - */ -function attribute_contains($attr, $s) { - $a = explode(' ', $attr); - return (count($a) && in_array($s,$a)); -} - /** * Compare activity uri. Knows about activity namespace. * diff --git a/tests/include/TextTest.php b/tests/include/TextTest.php index 5676da8f6..1137c0415 100644 --- a/tests/include/TextTest.php +++ b/tests/include/TextTest.php @@ -13,44 +13,6 @@ use PHPUnit\Framework\TestCase; */ class TextTest extends TestCase { - /** - * test attribute contains - */ - public function testAttributeContains1() - { - $testAttr="class1 notclass2 class3"; - $this->assertTrue(attribute_contains($testAttr, "class3")); - $this->assertFalse(attribute_contains($testAttr, "class2")); - } - - /** - * test attribute contains - */ - public function testAttributeContains2() - { - $testAttr="class1 not-class2 class3"; - $this->assertTrue(attribute_contains($testAttr, "class3")); - $this->assertFalse(attribute_contains($testAttr, "class2")); - } - - /** - * test with empty input - */ - public function testAttributeContainsEmpty() - { - $testAttr=""; - $this->assertFalse(attribute_contains($testAttr, "class2")); - } - - /** - * test input with special chars - */ - public function testAttributeContainsSpecialChars() - { - $testAttr="--... %\$รค() /(=?}"; - $this->assertFalse(attribute_contains($testAttr, "class2")); - } - /** * test expand_acl, perfect input */ From f65f7f11c3e7158e90b7660e08b7b94f5795d41e Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 00:40:14 +0200 Subject: [PATCH 12/46] Move expand_acl to ACLFormatter::expand() - including tests --- include/text.php | 17 --- mod/lockview.php | 13 ++- src/Model/Item.php | 12 ++- src/Module/Item/Compose.php | 12 ++- src/Util/ACLFormatter.php | 27 +++++ src/Worker/Notifier.php | 12 ++- tests/include/TextTest.php | 127 ---------------------- tests/src/Util/ACLFormaterTest.php | 164 +++++++++++++++++++++++++++++ 8 files changed, 224 insertions(+), 160 deletions(-) create mode 100644 src/Util/ACLFormatter.php create mode 100644 tests/src/Util/ACLFormaterTest.php diff --git a/include/text.php b/include/text.php index 216e87ed8..289802136 100644 --- a/include/text.php +++ b/include/text.php @@ -3,28 +3,11 @@ * @file include/text.php */ -use Friendica\App; use Friendica\Content\Text\BBCode; -use Friendica\Core\Protocol; use Friendica\Model\FileTag; use Friendica\Model\Group; use Friendica\Util\Strings; -/** - * Turn user/group ACLs stored as angle bracketed text into arrays - * - * @param string $s - * @return array - */ -function expand_acl($s) { - // turn string array of angle-bracketed elements into numeric array - // e.g. "<1><2><3>" => array(1,2,3); - preg_match_all('/<(' . Group::FOLLOWERS . '|'. Group::MUTUALS . '|[0-9]+)>/', $s, $matches, PREG_PATTERN_ORDER); - - return $matches[1]; -} - - /** * Wrap ACL elements in angle brackets for storage * @param string $item diff --git a/mod/lockview.php b/mod/lockview.php index eede1b6a0..9f9dcfea4 100644 --- a/mod/lockview.php +++ b/mod/lockview.php @@ -3,11 +3,13 @@ * @file mod/lockview.php */ use Friendica\App; +use Friendica\BaseObject; use Friendica\Core\Hook; use Friendica\Core\L10n; use Friendica\Database\DBA; use Friendica\Model\Group; use Friendica\Model\Item; +use Friendica\Util\ACLFormatter; function lockview_content(App $a) { @@ -59,10 +61,13 @@ function lockview_content(App $a) exit(); } - $allowed_users = expand_acl($item['allow_cid']); - $allowed_groups = expand_acl($item['allow_gid']); - $deny_users = expand_acl($item['deny_cid']); - $deny_groups = expand_acl($item['deny_gid']); + /** @var ACLFormatter $aclFormatter */ + $aclFormatter = BaseObject::getClass(ACLFormatter::class); + + $allowed_users = $aclFormatter->expand($item['allow_cid']); + $allowed_groups = $aclFormatter->expand($item['allow_gid']); + $deny_users = $aclFormatter->expand($item['deny_cid']); + $deny_groups = $aclFormatter->expand($item['deny_gid']); $o = L10n::t('Visible to:') . '
'; $l = []; diff --git a/src/Model/Item.php b/src/Model/Item.php index 650390e52..456d77026 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -24,6 +24,7 @@ use Friendica\Database\DBA; use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Diaspora; use Friendica\Protocol\OStatus; +use Friendica\Util\ACLFormatter; use Friendica\Util\DateTimeFormat; use Friendica\Util\Map; use Friendica\Util\Network; @@ -2892,10 +2893,13 @@ class Item extends BaseObject */ public static function enumeratePermissions(array $obj, bool $check_dead = false) { - $allow_people = expand_acl($obj['allow_cid']); - $allow_groups = Group::expand($obj['uid'], expand_acl($obj['allow_gid']), $check_dead); - $deny_people = expand_acl($obj['deny_cid']); - $deny_groups = Group::expand($obj['uid'], expand_acl($obj['deny_gid']), $check_dead); + /** @var ACLFormatter $aclFormater */ + $aclFormater = self::getClass(ACLFormatter::class); + + $allow_people = $aclFormater->expand($obj['allow_cid']); + $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead); + $deny_people = $aclFormater->expand($obj['deny_cid']); + $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead); $recipients = array_unique(array_merge($allow_people, $allow_groups)); $deny = array_unique(array_merge($deny_people, $deny_groups)); $recipients = array_diff($recipients, $deny); diff --git a/src/Module/Item/Compose.php b/src/Module/Item/Compose.php index 11b886a2e..c44e4c61a 100644 --- a/src/Module/Item/Compose.php +++ b/src/Module/Item/Compose.php @@ -16,6 +16,7 @@ use Friendica\Model\Item; use Friendica\Model\User; use Friendica\Module\Login; use Friendica\Network\HTTPException\NotImplementedException; +use Friendica\Util\ACLFormatter; use Friendica\Util\Crypto; class Compose extends BaseModule @@ -58,6 +59,9 @@ class Compose extends BaseModule $user = User::getById(local_user(), ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'hidewall', 'default-location']); + /** @var ACLFormatter $aclFormatter */ + $aclFormatter = self::getClass(ACLFormatter::class); + switch ($posttype) { case Item::PT_PERSONAL_NOTE: $compose_title = L10n::t('Compose new personal note'); @@ -70,8 +74,8 @@ class Compose extends BaseModule $compose_title = L10n::t('Compose new post'); $type = 'post'; $doesFederate = true; - $contact_allow = implode(',', expand_acl($user['allow_cid'])); - $group_allow = implode(',', expand_acl($user['allow_gid'])) ?: Group::FOLLOWERS; + $contact_allow = implode(',', $aclFormatter->expand($user['allow_cid'])); + $group_allow = implode(',', $aclFormatter->expand($user['allow_gid'])) ?: Group::FOLLOWERS; break; } @@ -82,8 +86,8 @@ class Compose extends BaseModule $wall = $_REQUEST['wall'] ?? $type == 'post'; $contact_allow = $_REQUEST['contact_allow'] ?? $contact_allow; $group_allow = $_REQUEST['group_allow'] ?? $group_allow; - $contact_deny = $_REQUEST['contact_deny'] ?? implode(',', expand_acl($user['deny_cid'])); - $group_deny = $_REQUEST['group_deny'] ?? implode(',', expand_acl($user['deny_gid'])); + $contact_deny = $_REQUEST['contact_deny'] ?? implode(',', $aclFormatter->expand($user['deny_cid'])); + $group_deny = $_REQUEST['group_deny'] ?? implode(',', $aclFormatter->expand($user['deny_gid'])); $visibility = ($contact_allow . $user['allow_gid'] . $user['deny_cid'] . $user['deny_gid']) ? 'custom' : 'public'; $acl_contacts = Contact::selectToArray(['id', 'name', 'addr', 'micro'], ['uid' => local_user(), 'pending' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]); diff --git a/src/Util/ACLFormatter.php b/src/Util/ACLFormatter.php new file mode 100644 index 000000000..4e3d32b15 --- /dev/null +++ b/src/Util/ACLFormatter.php @@ -0,0 +1,27 @@ +<2><3>" => array(1,2,3); + preg_match_all('/<(' . Group::FOLLOWERS . '|'. Group::MUTUALS . '|[0-9]+)>/', $ids, $matches, PREG_PATTERN_ORDER); + + return $matches[1]; + } +} diff --git a/src/Worker/Notifier.php b/src/Worker/Notifier.php index 4bf97aca5..ebc70ffb5 100644 --- a/src/Worker/Notifier.php +++ b/src/Worker/Notifier.php @@ -24,6 +24,7 @@ use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Diaspora; use Friendica\Protocol\OStatus; use Friendica\Protocol\Salmon; +use Friendica\Util\ACLFormatter; require_once 'include/items.php'; @@ -272,10 +273,13 @@ class Notifier $public_message = false; // private recipients, not public } - $allow_people = expand_acl($parent['allow_cid']); - $allow_groups = Group::expand($uid, expand_acl($parent['allow_gid']),true); - $deny_people = expand_acl($parent['deny_cid']); - $deny_groups = Group::expand($uid, expand_acl($parent['deny_gid'])); + /** @var ACLFormatter $aclFormatter */ + $aclFormatter = BaseObject::getClass(ACLFormatter::class); + + $allow_people = $aclFormatter->expand($parent['allow_cid']); + $allow_groups = Group::expand($uid, $aclFormatter->expand($parent['allow_gid']),true); + $deny_people = $aclFormatter->expand($parent['deny_cid']); + $deny_groups = Group::expand($uid, $aclFormatter->expand($parent['deny_gid'])); // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing // a delivery fork. private groups (forum_mode == 2) do not uplink diff --git a/tests/include/TextTest.php b/tests/include/TextTest.php index 1137c0415..e41b71b87 100644 --- a/tests/include/TextTest.php +++ b/tests/include/TextTest.php @@ -13,133 +13,6 @@ use PHPUnit\Framework\TestCase; */ class TextTest extends TestCase { - /** - * test expand_acl, perfect input - */ - public function testExpandAclNormal() - { - $text='<1><2><3><' . Group::FOLLOWERS . '><' . Group::MUTUALS . '>'; - $this->assertEquals(array('1', '2', '3', Group::FOLLOWERS, Group::MUTUALS), expand_acl($text)); - } - - /** - * test with a big number - */ - public function testExpandAclBigNumber() - { - $text='<1><' . PHP_INT_MAX . '><15>'; - $this->assertEquals(array('1', (string)PHP_INT_MAX, '15'), expand_acl($text)); - } - - /** - * test with a string in it. - * - * @todo is this valid input? Otherwise: should there be an exception? - */ - public function testExpandAclString() - { - $text="<1><279012>"; - $this->assertEquals(array('1', '279012'), expand_acl($text)); - } - - /** - * test with a ' ' in it. - * - * @todo is this valid input? Otherwise: should there be an exception? - */ - public function testExpandAclSpace() - { - $text="<1><279 012><32>"; - $this->assertEquals(array('1', '32'), expand_acl($text)); - } - - /** - * test empty input - */ - public function testExpandAclEmpty() - { - $text=""; - $this->assertEquals(array(), expand_acl($text)); - } - - /** - * test invalid input, no < at all - * - * @todo should there be an exception? - */ - public function testExpandAclNoBrackets() - { - $text="According to documentation, that's invalid. "; //should be invalid - $this->assertEquals(array(), expand_acl($text)); - } - - /** - * test invalid input, just open < - * - * @todo should there be an exception? - */ - public function testExpandAclJustOneBracket1() - { - $text="assertEquals(array(), expand_acl($text)); - } - - /** - * test invalid input, just close > - * - * @todo should there be an exception? - */ - public function testExpandAclJustOneBracket2() - { - $text="Another invalid> string"; //should be invalid - $this->assertEquals(array(), expand_acl($text)); - } - - /** - * test invalid input, just close > - * - * @todo should there be an exception? - */ - public function testExpandAclCloseOnly() - { - $text="Another> invalid> string>"; //should be invalid - $this->assertEquals(array(), expand_acl($text)); - } - - /** - * test invalid input, just open < - * - * @todo should there be an exception? - */ - public function testExpandAclOpenOnly() - { - $text="assertEquals(array(), expand_acl($text)); - } - - /** - * test invalid input, open and close do not match - * - * @todo should there be an exception? - */ - public function testExpandAclNoMatching1() - { - $text=" invalid "; //should be invalid - $this->assertEquals(array(), expand_acl($text)); - } - - /** - * test invalid input, empty <> - * - * @todo should there be an exception? Or array(1, 3) - * (This should be array(1,3) - mike) - */ - public function testExpandAclEmptyMatch() - { - $text="<1><><3>"; - $this->assertEquals(array('1', '3'), expand_acl($text)); - } - /** * test hex2bin and reverse */ diff --git a/tests/src/Util/ACLFormaterTest.php b/tests/src/Util/ACLFormaterTest.php new file mode 100644 index 000000000..c3cfb7051 --- /dev/null +++ b/tests/src/Util/ACLFormaterTest.php @@ -0,0 +1,164 @@ +<2><3><' . Group::FOLLOWERS . '><' . Group::MUTUALS . '>'; + $this->assertEquals(array('1', '2', '3', Group::FOLLOWERS, Group::MUTUALS), $aclFormatter->expand($text)); + } + + /** + * test with a big number + */ + public function testExpandAclBigNumber() + { + $aclFormatter = new ACLFormatter(); + + $text='<1><' . PHP_INT_MAX . '><15>'; + $this->assertEquals(array('1', (string)PHP_INT_MAX, '15'), $aclFormatter->expand($text)); + } + + /** + * test with a string in it. + * + * @todo is this valid input? Otherwise: should there be an exception? + */ + public function testExpandAclString() + { + $aclFormatter = new ACLFormatter(); + + $text="<1><279012>"; + $this->assertEquals(array('1', '279012'), $aclFormatter->expand($text)); + } + + /** + * test with a ' ' in it. + * + * @todo is this valid input? Otherwise: should there be an exception? + */ + public function testExpandAclSpace() + { + $aclFormatter = new ACLFormatter(); + + $text="<1><279 012><32>"; + $this->assertEquals(array('1', '32'), $aclFormatter->expand($text)); + } + + /** + * test empty input + */ + public function testExpandAclEmpty() + { + $aclFormatter = new ACLFormatter(); + + $text=""; + $this->assertEquals(array(), $aclFormatter->expand($text)); + } + + /** + * test invalid input, no < at all + * + * @todo should there be an exception? + */ + public function testExpandAclNoBrackets() + { + $aclFormatter = new ACLFormatter(); + + $text="According to documentation, that's invalid. "; //should be invalid + $this->assertEquals(array(), $aclFormatter->expand($text)); + } + + /** + * test invalid input, just open < + * + * @todo should there be an exception? + */ + public function testExpandAclJustOneBracket1() + { + $aclFormatter = new ACLFormatter(); + + $text="assertEquals(array(), $aclFormatter->expand($text)); + } + + /** + * test invalid input, just close > + * + * @todo should there be an exception? + */ + public function testExpandAclJustOneBracket2() + { + $aclFormatter = new ACLFormatter(); + + $text="Another invalid> string"; //should be invalid + $this->assertEquals(array(), $aclFormatter->expand($text)); + } + + /** + * test invalid input, just close > + * + * @todo should there be an exception? + */ + public function testExpandAclCloseOnly() + { + $aclFormatter = new ACLFormatter(); + + $text="Another> invalid> string>"; //should be invalid + $this->assertEquals(array(), $aclFormatter->expand($text)); + } + + /** + * test invalid input, just open < + * + * @todo should there be an exception? + */ + public function testExpandAclOpenOnly() + { + $aclFormatter = new ACLFormatter(); + + $text="assertEquals(array(), $aclFormatter->expand($text)); + } + + /** + * test invalid input, open and close do not match + * + * @todo should there be an exception? + */ + public function testExpandAclNoMatching1() + { + $aclFormatter = new ACLFormatter(); + + $text=" invalid "; //should be invalid + $this->assertEquals(array(), $aclFormatter->expand($text)); + } + + /** + * test invalid input, empty <> + * + * @todo should there be an exception? Or array(1, 3) + * (This should be array(1,3) - mike) + */ + public function testExpandAclEmptyMatch() + { + $aclFormatter = new ACLFormatter(); + + $text="<1><><3>"; + $this->assertEquals(array('1', '3'), $aclFormatter->expand($text)); + } +} From 5843a80b6c952e9f788656e7fe0f88f9b1500a6b Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 00:54:34 +0200 Subject: [PATCH 13/46] Move perms2str to ACLFormatter::aclToString() - including new tests --- include/text.php | 41 ------------------------------ mod/events.php | 14 +++++++--- mod/item.php | 16 ++++++++---- mod/photos.php | 24 +++++++++++------ mod/settings.php | 13 +++++++--- src/Util/ACLFormatter.php | 40 +++++++++++++++++++++++++++++ tests/src/Util/ACLFormaterTest.php | 36 ++++++++++++++++++++++++++ 7 files changed, 122 insertions(+), 62 deletions(-) diff --git a/include/text.php b/include/text.php index 289802136..13300c1e1 100644 --- a/include/text.php +++ b/include/text.php @@ -5,47 +5,6 @@ use Friendica\Content\Text\BBCode; use Friendica\Model\FileTag; -use Friendica\Model\Group; -use Friendica\Util\Strings; - -/** - * Wrap ACL elements in angle brackets for storage - * @param string $item - */ -function sanitise_acl(&$item) { - if (intval($item)) { - $item = '<' . intval(Strings::escapeTags(trim($item))) . '>'; - } elseif (in_array($item, [Group::FOLLOWERS, Group::MUTUALS])) { - $item = '<' . $item . '>'; - } else { - unset($item); - } -} - - -/** - * Convert an ACL array to a storable string - * - * Normally ACL permissions will be an array. - * We'll also allow a comma-separated string. - * - * @param string|array $p - * @return string - */ -function perms2str($p) { - $ret = ''; - if (is_array($p)) { - $tmp = $p; - } else { - $tmp = explode(',', $p); - } - - if (is_array($tmp)) { - array_walk($tmp, 'sanitise_acl'); - $ret = implode('', $tmp); - } - return $ret; -} /** * Compare activity uri. Knows about activity namespace. diff --git a/mod/events.php b/mod/events.php index 649a25ab1..75cbc6b43 100644 --- a/mod/events.php +++ b/mod/events.php @@ -5,6 +5,7 @@ */ use Friendica\App; +use Friendica\BaseObject; use Friendica\Content\Nav; use Friendica\Content\Widget\CalendarExport; use Friendica\Core\ACL; @@ -18,6 +19,7 @@ use Friendica\Model\Event; use Friendica\Model\Item; use Friendica\Model\Profile; use Friendica\Module\Login; +use Friendica\Util\ACLFormatter; use Friendica\Util\DateTimeFormat; use Friendica\Util\Strings; use Friendica\Util\Temporal; @@ -146,10 +148,14 @@ function events_post(App $a) if ($share) { - $str_group_allow = perms2str($_POST['group_allow'] ?? ''); - $str_contact_allow = perms2str($_POST['contact_allow'] ?? ''); - $str_group_deny = perms2str($_POST['group_deny'] ?? ''); - $str_contact_deny = perms2str($_POST['contact_deny'] ?? ''); + + /** @var ACLFormatter $aclFormatter */ + $aclFormatter = BaseObject::getClass(ACLFormatter::class); + + $str_group_allow = $aclFormatter->aclToString($_POST['group_allow'] ?? ''); + $str_contact_allow = $aclFormatter->aclToString($_POST['contact_allow'] ?? ''); + $str_group_deny = $aclFormatter->aclToString($_POST['group_deny'] ?? ''); + $str_contact_deny = $aclFormatter->aclToString($_POST['contact_deny'] ?? ''); // Undo the pseudo-contact of self, since there are real contacts now if (strpos($str_contact_allow, '<' . $self . '>') !== false) { diff --git a/mod/item.php b/mod/item.php index c9a33cc20..5539e28c6 100644 --- a/mod/item.php +++ b/mod/item.php @@ -16,6 +16,7 @@ */ use Friendica\App; +use Friendica\BaseObject; use Friendica\Content\Pager; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; @@ -37,6 +38,7 @@ use Friendica\Model\Photo; use Friendica\Model\Term; use Friendica\Protocol\Diaspora; use Friendica\Protocol\Email; +use Friendica\Util\ACLFormatter; use Friendica\Util\DateTimeFormat; use Friendica\Util\Emailer; use Friendica\Util\Security; @@ -269,10 +271,14 @@ function item_post(App $a) { $str_contact_deny = $user['deny_cid']; } else { // use the posted permissions - $str_group_allow = perms2str($_REQUEST['group_allow'] ?? ''); - $str_contact_allow = perms2str($_REQUEST['contact_allow'] ?? ''); - $str_group_deny = perms2str($_REQUEST['group_deny'] ?? ''); - $str_contact_deny = perms2str($_REQUEST['contact_deny'] ?? ''); + + /** @var ACLFormatter $aclFormatter */ + $aclFormatter = BaseObject::getClass(ACLFormatter::class); + + $str_group_allow = $aclFormatter->aclToString($_REQUEST['group_allow'] ?? ''); + $str_contact_allow = $aclFormatter->aclToString($_REQUEST['contact_allow'] ?? ''); + $str_group_deny = $aclFormatter->aclToString($_REQUEST['group_deny'] ?? ''); + $str_contact_deny = $aclFormatter->aclToString($_REQUEST['contact_deny'] ?? ''); } $title = Strings::escapeTags(trim($_REQUEST['title'] ?? '')); @@ -500,7 +506,7 @@ function item_post(App $a) { } /** @var BBCode\Video $bbCodeVideo */ - $bbCodeVideo = \Friendica\BaseObject::getClass(BBCode\Video::class); + $bbCodeVideo = BaseObject::getClass(BBCode\Video::class); $body = $bbCodeVideo->transform($body); // Fold multi-line [code] sequences diff --git a/mod/photos.php b/mod/photos.php index 1789c0710..528f78b61 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -4,6 +4,7 @@ */ use Friendica\App; +use Friendica\BaseObject; use Friendica\Content\Feature; use Friendica\Content\Nav; use Friendica\Content\Pager; @@ -26,6 +27,7 @@ use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; use Friendica\Protocol\DFRN; +use Friendica\Util\ACLFormatter; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Map; @@ -296,10 +298,13 @@ function photos_post(App $a) $albname = !empty($_POST['albname']) ? Strings::escapeTags(trim($_POST['albname'])) : ''; $origaname = !empty($_POST['origaname']) ? Strings::escapeTags(trim($_POST['origaname'])) : ''; - $str_group_allow = !empty($_POST['group_allow']) ? perms2str($_POST['group_allow']) : ''; - $str_contact_allow = !empty($_POST['contact_allow']) ? perms2str($_POST['contact_allow']) : ''; - $str_group_deny = !empty($_POST['group_deny']) ? perms2str($_POST['group_deny']) : ''; - $str_contact_deny = !empty($_POST['contact_deny']) ? perms2str($_POST['contact_deny']) : ''; + /** @var ACLFormatter $aclFormatter */ + $aclFormatter = BaseObject::getClass(ACLFormatter::class); + + $str_group_allow = !empty($_POST['group_allow']) ? $aclFormatter->aclToString($_POST['group_allow']) : ''; + $str_contact_allow = !empty($_POST['contact_allow']) ? $aclFormatter->aclToString($_POST['contact_allow']) : ''; + $str_group_deny = !empty($_POST['group_deny']) ? $aclFormatter->aclToString($_POST['group_deny']) : ''; + $str_contact_deny = !empty($_POST['contact_deny']) ? $aclFormatter->aclToString($_POST['contact_deny']) : ''; $resource_id = $a->argv[3]; @@ -635,10 +640,13 @@ function photos_post(App $a) $group_deny = $_REQUEST['group_deny'] ?? []; $contact_deny = $_REQUEST['contact_deny'] ?? []; - $str_group_allow = perms2str(is_array($group_allow) ? $group_allow : explode(',', $group_allow)); - $str_contact_allow = perms2str(is_array($contact_allow) ? $contact_allow : explode(',', $contact_allow)); - $str_group_deny = perms2str(is_array($group_deny) ? $group_deny : explode(',', $group_deny)); - $str_contact_deny = perms2str(is_array($contact_deny) ? $contact_deny : explode(',', $contact_deny)); + /** @var ACLFormatter $aclFormatter */ + $aclFormatter = BaseObject::getClass(ACLFormatter::class); + + $str_group_allow = $aclFormatter->aclToString(is_array($group_allow) ? $group_allow : explode(',', $group_allow)); + $str_contact_allow = $aclFormatter->aclToString(is_array($contact_allow) ? $contact_allow : explode(',', $contact_allow)); + $str_group_deny = $aclFormatter->aclToString(is_array($group_deny) ? $group_deny : explode(',', $group_deny)); + $str_contact_deny = $aclFormatter->aclToString(is_array($contact_deny) ? $contact_deny : explode(',', $contact_deny)); $ret = ['src' => '', 'filename' => '', 'filesize' => 0, 'type' => '']; diff --git a/mod/settings.php b/mod/settings.php index b5011881c..3ab3d6212 100644 --- a/mod/settings.php +++ b/mod/settings.php @@ -5,6 +5,7 @@ use Friendica\App; use Friendica\BaseModule; +use Friendica\BaseObject; use Friendica\Content\Feature; use Friendica\Content\Nav; use Friendica\Core\ACL; @@ -25,6 +26,7 @@ use Friendica\Model\Group; use Friendica\Model\User; use Friendica\Module\Login; use Friendica\Protocol\Email; +use Friendica\Util\ACLFormatter; use Friendica\Util\Network; use Friendica\Util\Strings; use Friendica\Util\Temporal; @@ -533,10 +535,13 @@ function settings_post(App $a) date_default_timezone_set($timezone); } - $str_group_allow = !empty($_POST['group_allow']) ? perms2str($_POST['group_allow']) : ''; - $str_contact_allow = !empty($_POST['contact_allow']) ? perms2str($_POST['contact_allow']) : ''; - $str_group_deny = !empty($_POST['group_deny']) ? perms2str($_POST['group_deny']) : ''; - $str_contact_deny = !empty($_POST['contact_deny']) ? perms2str($_POST['contact_deny']) : ''; + /** @var ACLFormatter $aclFormatter */ + $aclFormatter = BaseObject::getClass(ACLFormatter::class); + + $str_group_allow = !empty($_POST['group_allow']) ? $aclFormatter->aclToString($_POST['group_allow']) : ''; + $str_contact_allow = !empty($_POST['contact_allow']) ? $aclFormatter->aclToString($_POST['contact_allow']) : ''; + $str_group_deny = !empty($_POST['group_deny']) ? $aclFormatter->aclToString($_POST['group_deny']) : ''; + $str_contact_deny = !empty($_POST['contact_deny']) ? $aclFormatter->aclToString($_POST['contact_deny']) : ''; $openidserver = $a->user['openidserver']; //$openid = Strings::normaliseOpenID($openid); diff --git a/src/Util/ACLFormatter.php b/src/Util/ACLFormatter.php index 4e3d32b15..e724a8948 100644 --- a/src/Util/ACLFormatter.php +++ b/src/Util/ACLFormatter.php @@ -24,4 +24,44 @@ final class ACLFormatter return $matches[1]; } + + /** + * Wrap ACL elements in angle brackets for storage + * + * @param string $item The item to sanitise + */ + private function sanitiseAcl(string &$item) { + if (intval($item)) { + $item = '<' . intval(Strings::escapeTags(trim($item))) . '>'; + } elseif (in_array($item, [Group::FOLLOWERS, Group::MUTUALS])) { + $item = '<' . $item . '>'; + } else { + $item = ''; + } + } + + /** + * Convert an ACL array to a storable string + * + * Normally ACL permissions will be an array. + * We'll also allow a comma-separated string. + * + * @param string|array $permissions + * + * @return string + */ + function aclToString($permissions) { + $return = ''; + if (is_array($permissions)) { + $item = $permissions; + } else { + $item = explode(',', $permissions); + } + + if (is_array($item)) { + array_walk($item, [$this, 'sanitiseAcl']); + $return = implode('', $item); + } + return $return; + } } diff --git a/tests/src/Util/ACLFormaterTest.php b/tests/src/Util/ACLFormaterTest.php index c3cfb7051..19332f495 100644 --- a/tests/src/Util/ACLFormaterTest.php +++ b/tests/src/Util/ACLFormaterTest.php @@ -161,4 +161,40 @@ class ACLFormaterTest extends TestCase $text="<1><><3>"; $this->assertEquals(array('1', '3'), $aclFormatter->expand($text)); } + + public function dataAclToString() + { + return [ + 'empty' => [ + 'input' => '', + 'assert' => '', + ], + 'string' => [ + 'input' => '1,2,3,4', + 'assert' => '<1><2><3><4>', + ], + 'array' => [ + 'input' => [1, 2, 3, 4], + 'assert' => '<1><2><3><4>', + ], + 'invalid' => [ + 'input' => [1, 'a', 3, 4], + 'assert' => '<1><3><4>', + ], + 'invalidString' => [ + 'input' => 'a,bsd23,4', + 'assert' => '<4>', + ], + ]; + } + + /** + * @dataProvider dataAclToString + */ + public function testAclToString($input, string $assert) + { + $aclFormatter = new ACLFormatter(); + + $this->assertEquals($assert, $aclFormatter->aclToString($input)); + } } From 2c3191675745b662fd0ff16ab77b32e99933ab68 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 00:55:14 +0200 Subject: [PATCH 14/46] Remove unused function qp() --- include/text.php | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/include/text.php b/include/text.php index 13300c1e1..e4393b09c 100644 --- a/include/text.php +++ b/include/text.php @@ -17,16 +17,6 @@ function activity_match($haystack,$needle) { return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA))); } -/** - * quick and dirty quoted_printable encoding - * - * @param string $s - * @return string - */ -function qp($s) { - return str_replace("%", "=", rawurlencode($s)); -} - /** * @brief Given a text string, convert from bbcode to html and add smilie icons. * From 9e94e8b48c6759d920a58fc719d6f5d7286c5e25 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 00:58:13 +0200 Subject: [PATCH 15/46] Remove function prepare_text and use BBCode::convert() instead --- include/text.php | 13 ------------- src/Model/Event.php | 6 +++--- src/Model/Item.php | 2 +- src/Model/Profile.php | 24 ++++++++++++------------ 4 files changed, 16 insertions(+), 29 deletions(-) diff --git a/include/text.php b/include/text.php index e4393b09c..84efebac2 100644 --- a/include/text.php +++ b/include/text.php @@ -17,19 +17,6 @@ function activity_match($haystack,$needle) { return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA))); } -/** - * @brief Given a text string, convert from bbcode to html and add smilie icons. - * - * @param string $text String with bbcode. - * @return string Formatted HTML - * @throws \Friendica\Network\HTTPException\InternalServerErrorException - */ -function prepare_text($text) -{ - $s = BBCode::convert($text); - return trim($s); -} - /** * return array with details for categories and folders for an item * diff --git a/src/Model/Event.php b/src/Model/Event.php index 915218084..cbd245a23 100644 --- a/src/Model/Event.php +++ b/src/Model/Event.php @@ -911,7 +911,7 @@ class Event extends BaseObject $tpl = Renderer::getMarkupTemplate('event_stream_item.tpl'); $return = Renderer::replaceMacros($tpl, [ '$id' => $item['event-id'], - '$title' => prepare_text($item['event-summary']), + '$title' => BBCode::convert($item['event-summary']), '$dtstart_label' => L10n::t('Starts:'), '$dtstart_title' => $dtstart_title, '$dtstart_dt' => $dtstart_dt, @@ -929,7 +929,7 @@ class Event extends BaseObject '$author_name' => $item['author-name'], '$author_link' => $profile_link, '$author_avatar' => $item['author-avatar'], - '$description' => prepare_text($item['event-desc']), + '$description' => BBCode::convert($item['event-desc']), '$location_label' => L10n::t('Location:'), '$show_map_label' => L10n::t('Show map'), '$hide_map_label' => L10n::t('Hide map'), @@ -979,7 +979,7 @@ class Event extends BaseObject } } - $location['name'] = prepare_text($location['name']); + $location['name'] = BBCode::convert($location['name']); // Construct the map HTML. if (isset($location['address'])) { diff --git a/src/Model/Item.php b/src/Model/Item.php index 456d77026..4c98eb504 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -3348,7 +3348,7 @@ class Item extends BaseObject ) { self::addRedirLinkToImageLinks($item); - $item["rendered-html"] = prepare_text($item["body"]); + $item["rendered-html"] = BBCode::convert($item["body"]); $item["rendered-hash"] = hash("md5", $item["body"]); $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']]; diff --git a/src/Model/Profile.php b/src/Model/Profile.php index b69860edf..de3290389 100644 --- a/src/Model/Profile.php +++ b/src/Model/Profile.php @@ -823,51 +823,51 @@ class Profile $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']]; } - if ($txt = prepare_text($a->profile['about'])) { + if ($txt = BBCode::convert($a->profile['about'])) { $profile['about'] = [L10n::t('About:'), $txt]; } - if ($txt = prepare_text($a->profile['interest'])) { + if ($txt = BBCode::convert($a->profile['interest'])) { $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt]; } - if ($txt = prepare_text($a->profile['likes'])) { + if ($txt = BBCode::convert($a->profile['likes'])) { $profile['likes'] = [L10n::t('Likes:'), $txt]; } - if ($txt = prepare_text($a->profile['dislikes'])) { + if ($txt = BBCode::convert($a->profile['dislikes'])) { $profile['dislikes'] = [L10n::t('Dislikes:'), $txt]; } - if ($txt = prepare_text($a->profile['contact'])) { + if ($txt = BBCode::convert($a->profile['contact'])) { $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt]; } - if ($txt = prepare_text($a->profile['music'])) { + if ($txt = BBCode::convert($a->profile['music'])) { $profile['music'] = [L10n::t('Musical interests:'), $txt]; } - if ($txt = prepare_text($a->profile['book'])) { + if ($txt = BBCode::convert($a->profile['book'])) { $profile['book'] = [L10n::t('Books, literature:'), $txt]; } - if ($txt = prepare_text($a->profile['tv'])) { + if ($txt = BBCode::convert($a->profile['tv'])) { $profile['tv'] = [L10n::t('Television:'), $txt]; } - if ($txt = prepare_text($a->profile['film'])) { + if ($txt = BBCode::convert($a->profile['film'])) { $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt]; } - if ($txt = prepare_text($a->profile['romance'])) { + if ($txt = BBCode::convert($a->profile['romance'])) { $profile['romance'] = [L10n::t('Love/Romance:'), $txt]; } - if ($txt = prepare_text($a->profile['work'])) { + if ($txt = BBCode::convert($a->profile['work'])) { $profile['work'] = [L10n::t('Work/employment:'), $txt]; } - if ($txt = prepare_text($a->profile['education'])) { + if ($txt = BBCode::convert($a->profile['education'])) { $profile['education'] = [L10n::t('School/education:'), $txt]; } From 52c42491c4e1c42a386ffa78698052a82007b63e Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 02:05:11 +0200 Subject: [PATCH 16/46] Move activity_match() to Protocol\Activity::match() - With tests --- include/conversation.php | 43 ++++++++++------ include/text.php | 12 ----- mod/photos.php | 7 ++- src/Model/Item.php | 8 ++- src/Object/Post.php | 8 ++- src/Protocol/Activity.php | 23 +++++++++ src/Protocol/DFRN.php | 12 +++-- tests/src/Content/Text/BBCode/VideoTest.php | 2 +- tests/src/Protocol/ActivityTest.php | 57 +++++++++++++++++++++ 9 files changed, 135 insertions(+), 37 deletions(-) create mode 100644 src/Protocol/Activity.php create mode 100644 tests/src/Protocol/ActivityTest.php diff --git a/include/conversation.php b/include/conversation.php index b6faa4d2c..c857336e3 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -4,6 +4,7 @@ */ use Friendica\App; +use Friendica\BaseObject; use Friendica\Content\ContactSelector; use Friendica\Content\Feature; use Friendica\Content\Pager; @@ -24,6 +25,7 @@ use Friendica\Model\Profile; use Friendica\Model\Term; use Friendica\Object\Post; use Friendica\Object\Thread; +use Friendica\Protocol\Activity; use Friendica\Util\DateTimeFormat; use Friendica\Util\Proxy as ProxyUtils; use Friendica\Util\Temporal; @@ -138,12 +140,15 @@ function localize_item(&$item) During the further steps of the database restructuring I would like to address this issue. */ + /** @var Activity $activity */ + $activity = BaseObject::getClass(Activity::class); + $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">"; - if (activity_match($item['verb'], ACTIVITY_LIKE) - || activity_match($item['verb'], ACTIVITY_DISLIKE) - || activity_match($item['verb'], ACTIVITY_ATTEND) - || activity_match($item['verb'], ACTIVITY_ATTENDNO) - || activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) { + if ($activity->match($item['verb'], ACTIVITY_LIKE) + || $activity->match($item['verb'], ACTIVITY_DISLIKE) + || $activity->match($item['verb'], ACTIVITY_ATTEND) + || $activity->match($item['verb'], ACTIVITY_ATTENDNO) + || $activity->match($item['verb'], ACTIVITY_ATTENDMAYBE)) { $fields = ['author-link', 'author-name', 'verb', 'object-type', 'resource-id', 'body', 'plink']; $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]); @@ -178,22 +183,22 @@ function localize_item(&$item) $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]'; $bodyverb = ''; - if (activity_match($item['verb'], ACTIVITY_LIKE)) { + if ($activity->match($item['verb'], ACTIVITY_LIKE)) { $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s'); - } elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) { + } elseif ($activity->match($item['verb'], ACTIVITY_DISLIKE)) { $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s'); - } elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) { + } elseif ($activity->match($item['verb'], ACTIVITY_ATTEND)) { $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s'); - } elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) { + } elseif ($activity->match($item['verb'], ACTIVITY_ATTENDNO)) { $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s'); - } elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) { + } elseif ($activity->match($item['verb'], ACTIVITY_ATTENDMAYBE)) { $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s'); } $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink); } - if (activity_match($item['verb'], ACTIVITY_FRIEND)) { + if ($activity->match($item['verb'], ACTIVITY_FRIEND)) { if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return; @@ -275,7 +280,7 @@ function localize_item(&$item) } - if (activity_match($item['verb'], ACTIVITY_TAG)) { + if ($activity->match($item['verb'], ACTIVITY_TAG)) { $fields = ['author-id', 'author-link', 'author-name', 'author-network', 'verb', 'object-type', 'resource-id', 'body', 'plink']; $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]); @@ -320,7 +325,7 @@ function localize_item(&$item) $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag); } - if (activity_match($item['verb'], ACTIVITY_FAVORITE)) { + if ($activity->match($item['verb'], ACTIVITY_FAVORITE)) { if ($item['object-type'] == "") { return; } @@ -393,19 +398,22 @@ function count_descendants($item) { function visible_activity($item) { + /** @var Activity $activity */ + $activity = BaseObject::getClass(Activity::class); + /* * likes (etc.) can apply to other things besides posts. Check if they are post children, * in which case we handle them specially */ $hidden_activities = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE, ACTIVITY_FOLLOW, ACTIVITY2_ANNOUNCE]; foreach ($hidden_activities as $act) { - if (activity_match($item['verb'], $act)) { + if ($activity->match($item['verb'], $act)) { return false; } } // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere; - if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) { + if ($activity->match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) { return false; } @@ -1017,7 +1025,10 @@ function builtin_activity_puller($item, &$conv_responses) { return; } - if (activity_match($item['verb'], $verb) && ($item['id'] != $item['parent'])) { + /** @var Activity $activity */ + $activity = BaseObject::getClass(Activity::class); + + if ($activity->match($item['verb'], $verb) && ($item['id'] != $item['parent'])) { $author = ['uid' => 0, 'id' => $item['author-id'], 'network' => $item['author-network'], 'url' => $item['author-link']]; $url = Contact::magicLinkByContact($author); diff --git a/include/text.php b/include/text.php index 84efebac2..775931c6f 100644 --- a/include/text.php +++ b/include/text.php @@ -3,20 +3,8 @@ * @file include/text.php */ -use Friendica\Content\Text\BBCode; use Friendica\Model\FileTag; -/** - * Compare activity uri. Knows about activity namespace. - * - * @param string $haystack - * @param string $needle - * @return boolean - */ -function activity_match($haystack,$needle) { - return (($haystack === $needle) || ((basename($needle) === $haystack) && strstr($needle, NAMESPACE_ACTIVITY_SCHEMA))); -} - /** * return array with details for categories and folders for an item * diff --git a/mod/photos.php b/mod/photos.php index 528f78b61..3a94813e5 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -1446,7 +1446,12 @@ function photos_content(App $a) $template = $tpl; $sparkle = ''; - if ((activity_match($item['verb'], ACTIVITY_LIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)) && ($item['id'] != $item['parent'])) { + /** @var \Friendica\Protocol\Activity $activity */ + $activity = BaseObject::getClass(\Friendica\Protocol\Activity::class); + + if (($activity->match($item['verb'], ACTIVITY_LIKE) || + $activity->match($item['verb'], ACTIVITY_DISLIKE)) && + ($item['id'] != $item['parent'])) { continue; } diff --git a/src/Model/Item.php b/src/Model/Item.php index 4c98eb504..6f84de427 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -21,6 +21,7 @@ use Friendica\Core\System; use Friendica\Core\Session; use Friendica\Core\Worker; use Friendica\Database\DBA; +use Friendica\Protocol\Activity; use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Diaspora; use Friendica\Protocol\OStatus; @@ -1358,13 +1359,16 @@ class Item extends BaseObject $item['parent-uri'] = $item['thr-parent']; } + /** @var Activity $activity */ + $activity = self::getClass(Activity::class); + if (isset($item['gravity'])) { $item['gravity'] = intval($item['gravity']); } elseif ($item['parent-uri'] === $item['uri']) { $item['gravity'] = GRAVITY_PARENT; - } elseif (activity_match($item['verb'], ACTIVITY_POST)) { + } elseif ($activity->match($item['verb'], ACTIVITY_POST)) { $item['gravity'] = GRAVITY_COMMENT; - } elseif (activity_match($item['verb'], ACTIVITY_FOLLOW)) { + } elseif ($activity->match($item['verb'], ACTIVITY_FOLLOW)) { $item['gravity'] = GRAVITY_ACTIVITY; } else { $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen diff --git a/src/Object/Post.php b/src/Object/Post.php index 04775bbd0..12de457a5 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -21,6 +21,7 @@ use Friendica\Model\Contact; use Friendica\Model\Item; use Friendica\Model\Term; use Friendica\Model\User; +use Friendica\Protocol\Activity; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Proxy as ProxyUtils; @@ -517,12 +518,17 @@ class Post extends BaseObject Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG); return false; } + + /** @var Activity $activity */ + $activity = self::getClass(Activity::class); + /* * Only add what will be displayed */ if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) { return false; - } elseif (activity_match($item->getDataValue('verb'), ACTIVITY_LIKE) || activity_match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) { + } elseif ($activity->match($item->getDataValue('verb'), ACTIVITY_LIKE) || + $activity->match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) { return false; } diff --git a/src/Protocol/Activity.php b/src/Protocol/Activity.php new file mode 100644 index 000000000..64253b065 --- /dev/null +++ b/src/Protocol/Activity.php @@ -0,0 +1,23 @@ + $importer['id']]); + /** @var Activity $activity */ + $activity = BaseObject::getClass(Activity::class); + // Big question: Do we need these functions? They were part of the "consume_feed" function. // This function once was responsible for DFRN and OStatus. - if (activity_match($item["verb"], ACTIVITY_FOLLOW)) { + if ($activity->match($item["verb"], ACTIVITY_FOLLOW)) { Logger::log("New follower"); Contact::addRelationship($importer, $contact, $item); return false; } - if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) { + if ($activity->match($item["verb"], ACTIVITY_UNFOLLOW)) { Logger::log("Lost follower"); Contact::removeFollower($importer, $contact, $item); return false; } - if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) { + if ($activity->match($item["verb"], ACTIVITY_REQ_FRIEND)) { Logger::log("New friend request"); Contact::addRelationship($importer, $contact, $item, true); return false; } - if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) { + if ($activity->match($item["verb"], ACTIVITY_UNFRIEND)) { Logger::log("Lost sharer"); Contact::removeSharer($importer, $contact, $item); return false; diff --git a/tests/src/Content/Text/BBCode/VideoTest.php b/tests/src/Content/Text/BBCode/VideoTest.php index dcdbf937a..4a176871a 100644 --- a/tests/src/Content/Text/BBCode/VideoTest.php +++ b/tests/src/Content/Text/BBCode/VideoTest.php @@ -1,6 +1,6 @@ [ + 'haystack' => '', + 'needle' => '', + 'assert' => true, + ], + 'simple' => [ + 'haystack' => ACTIVITY_OBJ_TAGTERM, + 'needle' => ACTIVITY_OBJ_TAGTERM, + 'assert' => true, + ], + 'withNamespace' => [ + 'haystack' => 'tagterm', + 'needle' => NAMESPACE_ACTIVITY_SCHEMA . ACTIVITY_OBJ_TAGTERM, + 'assert' => true, + ], + 'invalidSimple' => [ + 'haystack' => 'tagterm', + 'needle' => '', + 'assert' => false, + ], + 'invalidWithOutNamespace' => [ + 'haystack' => 'tagterm', + 'needle' => ACTIVITY_OBJ_TAGTERM, + 'assert' => false, + ], + 'withSubPath' => [ + 'haystack' => 'tagterm', + 'needle' => NAMESPACE_ACTIVITY_SCHEMA . '/bla/' . ACTIVITY_OBJ_TAGTERM, + 'assert' => true, + ], + ]; + } + + /** + * Test the different, possible matchings + * + * @dataProvider dataMatch + */ + public function testMatch(string $haystack, string $needle, bool $assert) + { + $activity = new Activity(); + + $this->assertEquals($assert, $activity->match($haystack, $needle)); + } +} From ad67fd3aa894048e9023c18e83f13fc72954f6fd Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 02:39:28 +0200 Subject: [PATCH 17/46] Move is_a_date_arg to DateTimeFormat::isYearMonth - Improved functionality - Added tests --- include/text.php | 19 --------- mod/network.php | 11 ++++- src/Module/Profile.php | 5 ++- src/Util/DateTimeFormat.php | 33 +++++++++++++++ tests/src/Util/DateTimeFormatTest.php | 61 +++++++++++++++++++++++++++ 5 files changed, 107 insertions(+), 22 deletions(-) create mode 100644 tests/src/Util/DateTimeFormatTest.php diff --git a/include/text.php b/include/text.php index 775931c6f..89c07000f 100644 --- a/include/text.php +++ b/include/text.php @@ -72,22 +72,3 @@ function get_cats_and_terms($item) return [$categories, $folders]; } - -/// @TODO Rewrite this -function is_a_date_arg($s) { - $i = intval($s); - - if ($i > 1900) { - $y = date('Y'); - - if ($i <= $y + 1 && strpos($s, '-') == 4) { - $m = intval(substr($s, 5)); - - if ($m > 0 && $m <= 12) { - return true; - } - } - } - - return false; -} diff --git a/mod/network.php b/mod/network.php index 0438be705..64f5cf505 100644 --- a/mod/network.php +++ b/mod/network.php @@ -5,6 +5,7 @@ */ use Friendica\App; +use Friendica\BaseObject; use Friendica\Content\Feature; use Friendica\Content\ForumManager; use Friendica\Content\Nav; @@ -51,9 +52,12 @@ function network_init(App $a) $group_id = 0; } + /** @var DateTimeFormat $dtFormat */ + $dtFormat = BaseObject::getClass(DateTimeFormat::class); + if ($a->argc > 1) { for ($x = 1; $x < $a->argc; $x ++) { - if (is_a_date_arg($a->argv[$x])) { + if ($dtFormat->isYearMonth($a->argv[$x])) { $is_a_date_query = true; break; } @@ -461,9 +465,12 @@ function networkThreadedView(App $a, $update, $parent) $default_permissions = []; + /** @var DateTimeFormat $dtFormat */ + $dtFormat = BaseObject::getClass(DateTimeFormat::class); + if ($a->argc > 1) { for ($x = 1; $x < $a->argc; $x ++) { - if (is_a_date_arg($a->argv[$x])) { + if ($dtFormat->isYearMonth($a->argv[$x])) { if ($datequery) { $datequery2 = Strings::escapeHtml($a->argv[$x]); } else { diff --git a/src/Module/Profile.php b/src/Module/Profile.php index ed3754075..f38c77f2c 100644 --- a/src/Module/Profile.php +++ b/src/Module/Profile.php @@ -131,9 +131,12 @@ class Profile extends BaseModule $category = $datequery = $datequery2 = ''; + /** @var DateTimeFormat $dtFormat */ + $dtFormat = self::getClass(DateTimeFormat::class); + if ($a->argc > 2) { for ($x = 2; $x < $a->argc; $x ++) { - if (is_a_date_arg($a->argv[$x])) { + if ($dtFormat->isYearMonth($a->argv[$x])) { if ($datequery) { $datequery2 = Strings::escapeHtml($a->argv[$x]); } else { diff --git a/src/Util/DateTimeFormat.php b/src/Util/DateTimeFormat.php index 0b47a16f1..e29420e9e 100644 --- a/src/Util/DateTimeFormat.php +++ b/src/Util/DateTimeFormat.php @@ -148,4 +148,37 @@ class DateTimeFormat return $d->format($format); } + + /** + * Checks, if the given string is a date with the pattern YYYY-MM + * + * @param string $dateString The given date + * + * @return boolean True, if the date is a valid pattern + */ + public function isYearMonth(string $dateString) + { + // Check format (2019-01, 2019-1, 2019-10) + if (!preg_match('/^([12]\d{3}-(1[0-2]|0[1-9]|\d))$/', $dateString)) { + return false; + } + + $date = DateTime::createFromFormat('Y-m', $dateString); + + if (!$date) { + return false; + } + + try { + $now = new DateTime(); + } catch (\Throwable $t) { + return false; + } + + if ($date > $now) { + return false; + } + + return true; + } } diff --git a/tests/src/Util/DateTimeFormatTest.php b/tests/src/Util/DateTimeFormatTest.php new file mode 100644 index 000000000..bdc902eab --- /dev/null +++ b/tests/src/Util/DateTimeFormatTest.php @@ -0,0 +1,61 @@ + [ + 'input' => '1990-10', + 'assert' => true, + ], + 'validOneCharMonth' => [ + 'input' => '1990-1', + 'assert' => true, + ], + 'validTwoCharMonth' => [ + 'input' => '1990-01', + 'assert' => true, + ], + 'invalidFormat' => [ + 'input' => '199-11', + 'assert' => false, + ], + 'invalidFormat2' => [ + 'input' => '1990-15', + 'assert' => false, + ], + 'invalidFormat3' => [ + 'input' => '99-101', + 'assert' => false, + ], + 'invalidFormat4' => [ + 'input' => '11-1990', + 'assert' => false, + ], + 'invalidFuture' => [ + 'input' => '3030-12', + 'assert' => false, + ], + 'invalidYear' => [ + 'input' => '-100-10', + 'assert' => false, + ], + ]; + } + + /** + * @dataProvider dataYearMonth + */ + public function testIsYearMonth(string $input, bool $assert) + { + $dtFormat = new DateTimeFormat(); + + $this->assertEquals($assert, $dtFormat->isYearMonth($input)); + } +} From edf006905b5108d16eb5d4a5974198e0a93e41e7 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 02:48:46 +0200 Subject: [PATCH 18/46] Move (last) get_cats_and_terms to Content\Item::determineCategoriesTerms() - Added incomplete test --- include/conversation.php | 6 ++- include/text.php | 74 ------------------------------- src/Content/Item.php | 79 ++++++++++++++++++++++++++++++++++ src/Object/Post.php | 6 ++- tests/src/Content/ItemTest.php | 13 ++++++ 5 files changed, 102 insertions(+), 76 deletions(-) delete mode 100644 include/text.php create mode 100644 src/Content/Item.php create mode 100644 tests/src/Content/ItemTest.php diff --git a/include/conversation.php b/include/conversation.php index c857336e3..8bcd1b338 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -7,6 +7,7 @@ use Friendica\App; use Friendica\BaseObject; use Friendica\Content\ContactSelector; use Friendica\Content\Feature; +use Friendica\Content\Item as ContentItem; use Friendica\Content\Pager; use Friendica\Content\Text\BBCode; use Friendica\Core\Config; @@ -671,7 +672,10 @@ function conversation(App $a, array $items, Pager $pager, $mode, $update, $previ $body = Item::prepareBody($item, true, $preview); - list($categories, $folders) = get_cats_and_terms($item); + /** @var ContentItem $contItem */ + $contItem = BaseObject::getClass(ContentItem::class); + + list($categories, $folders) = $contItem->determineCategoriesTerms($item); if (!empty($item['content-warning']) && PConfig::get(local_user(), 'system', 'disable_cw', false)) { $title = ucfirst($item['content-warning']); diff --git a/include/text.php b/include/text.php deleted file mode 100644 index 89c07000f..000000000 --- a/include/text.php +++ /dev/null @@ -1,74 +0,0 @@ - $savedFolderName, - 'url' => "#", - 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&cat=' . rawurlencode($savedFolderName) : ""), - 'first' => $first, - 'last' => false - ]; - $first = false; - } - - if (count($categories)) { - $categories[count($categories) - 1]['last'] = true; - } - - if (local_user() == $item['uid']) { - foreach (FileTag::fileToArray($item['file'] ?? '') as $savedFolderName) { - $folders[] = [ - 'name' => $savedFolderName, - 'url' => "#", - 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . rawurlencode($savedFolderName) : ""), - 'first' => $first, - 'last' => false - ]; - $first = false; - } - } - - if (count($folders)) { - $folders[count($folders) - 1]['last'] = true; - } - - return [$categories, $folders]; -} diff --git a/src/Content/Item.php b/src/Content/Item.php new file mode 100644 index 000000000..ed6ec9c87 --- /dev/null +++ b/src/Content/Item.php @@ -0,0 +1,79 @@ + $savedFolderName, + 'url' => "#", + 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&cat=' . rawurlencode($savedFolderName) : ""), + 'first' => $first, + 'last' => false + ]; + $first = false; + } + + if (count($categories)) { + $categories[count($categories) - 1]['last'] = true; + } + + if (local_user() == $item['uid']) { + foreach (FileTag::fileToArray($item['file'] ?? '') as $savedFolderName) { + $folders[] = [ + 'name' => $savedFolderName, + 'url' => "#", + 'removeurl' => ((local_user() == $item['uid']) ? 'filerm/' . $item['id'] . '?f=&term=' . rawurlencode($savedFolderName) : ""), + 'first' => $first, + 'last' => false + ]; + $first = false; + } + } + + if (count($folders)) { + $folders[count($folders) - 1]['last'] = true; + } + + return [$categories, $folders]; + } +} diff --git a/src/Object/Post.php b/src/Object/Post.php index 12de457a5..7dd530801 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -7,6 +7,7 @@ namespace Friendica\Object; use Friendica\BaseObject; use Friendica\Content\ContactSelector; use Friendica\Content\Feature; +use Friendica\Content\Item as ContentItem; use Friendica\Core\Addon; use Friendica\Core\Config; use Friendica\Core\Hook; @@ -324,7 +325,10 @@ class Post extends BaseObject $body = Item::prepareBody($item, true); - list($categories, $folders) = get_cats_and_terms($item); + /** @var ContentItem $contItem */ + $contItem = self::getClass(ContentItem::class); + + list($categories, $folders) = $contItem->determineCategoriesTerms($item); $body_e = $body; $text_e = strip_tags($body); diff --git a/tests/src/Content/ItemTest.php b/tests/src/Content/ItemTest.php new file mode 100644 index 000000000..5cdfa978b --- /dev/null +++ b/tests/src/Content/ItemTest.php @@ -0,0 +1,13 @@ +markTestIncomplete('Test data needed.'); + } +} From f9f2c9e4b257d83d5180d40eee261be1156df1e5 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 02:50:09 +0200 Subject: [PATCH 19/46] Remove unneeded TextTest class --- tests/include/TextTest.php | 26 -------------------------- 1 file changed, 26 deletions(-) delete mode 100644 tests/include/TextTest.php diff --git a/tests/include/TextTest.php b/tests/include/TextTest.php deleted file mode 100644 index e41b71b87..000000000 --- a/tests/include/TextTest.php +++ /dev/null @@ -1,26 +0,0 @@ -assertEquals(-3, hex2bin(bin2hex(-3))); - $this->assertEquals(0, hex2bin(bin2hex(0))); - $this->assertEquals(12, hex2bin(bin2hex(12))); - $this->assertEquals(PHP_INT_MAX, hex2bin(bin2hex(PHP_INT_MAX))); - } -} From b8b1b1c1b39feca677c4b1a385b9a390dbe9eb2f Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 03:02:38 +0200 Subject: [PATCH 20/46] remove references --- composer.json | 1 - doc/Addons.md | 23 +++++++++++++---------- doc/de/Addons.md | 31 +++++++++++++++++++++---------- 3 files changed, 34 insertions(+), 21 deletions(-) diff --git a/composer.json b/composer.json index 9ed9017d8..83b51a174 100644 --- a/composer.json +++ b/composer.json @@ -83,7 +83,6 @@ "include/dba.php", "include/enotify.php", "include/items.php", - "include/text.php", "boot.php" ] }, diff --git a/doc/Addons.md b/doc/Addons.md index 0382cee49..69b591a82 100644 --- a/doc/Addons.md +++ b/doc/Addons.md @@ -503,16 +503,6 @@ Here is a complete list of all hook callbacks with file locations (as of 24-Sep- Hook::callAll('item_photo_menu', $args); Hook::callAll('jot_tool', $jotplugins); -### include/text.php - - Hook::callAll('contact_block_end', $arr); - Hook::callAll('poke_verbs', $arr); - Hook::callAll('put_item_in_cache', $hook_data); - Hook::callAll('prepare_body_init', $item); - Hook::callAll('prepare_body_content_filter', $hook_data); - Hook::callAll('prepare_body', $hook_data); - Hook::callAll('prepare_body_final', $hook_data); - ### include/items.php Hook::callAll('page_info_data', $data); @@ -649,6 +639,11 @@ Here is a complete list of all hook callbacks with file locations (as of 24-Sep- Hook::callAll('post_remote_end', $posted_item); Hook::callAll('tagged', $arr); Hook::callAll('post_local_end', $new_item); + Hook::callAll('put_item_in_cache', $hook_data); + Hook::callAll('prepare_body_init', $item); + Hook::callAll('prepare_body_content_filter', $hook_data); + Hook::callAll('prepare_body', $hook_data); + Hook::callAll('prepare_body_final', $hook_data); ### src/Model/Contact.php @@ -673,6 +668,10 @@ Here is a complete list of all hook callbacks with file locations (as of 24-Sep- Hook::callAll('register_account', $uid); Hook::callAll('remove_user', $user); +### src/Content/ContactBlock.php + + Hook::callAll('contact_block_end', $arr); + ### src/Content/Text/BBCode.php Hook::callAll('bbcode', $text); @@ -746,6 +745,10 @@ Here is a complete list of all hook callbacks with file locations (as of 24-Sep- self::callSingle(self::getApp(), 'hook_fork', $fork_hook, $hookdata); +### src/Core/L10n/L10n.php + + Hook::callAll('poke_verbs', $arr); + ### src/Core/Worker.php Hook::callAll("proc_run", $arr); diff --git a/doc/de/Addons.md b/doc/de/Addons.md index 3cbbb4b0b..755db95d0 100644 --- a/doc/de/Addons.md +++ b/doc/de/Addons.md @@ -226,16 +226,6 @@ Eine komplette Liste aller Hook-Callbacks mit den zugehรถrigen Dateien (am 01-Ap Hook::callAll('item_photo_menu', $args); Hook::callAll('jot_tool', $jotplugins); -### include/text.php - - Hook::callAll('contact_block_end', $arr); - Hook::callAll('poke_verbs', $arr); - Hook::callAll('put_item_in_cache', $hook_data); - Hook::callAll('prepare_body_init', $item); - Hook::callAll('prepare_body_content_filter', $hook_data); - Hook::callAll('prepare_body', $hook_data); - Hook::callAll('prepare_body_final', $hook_data); - ### include/items.php Hook::callAll('page_info_data', $data); @@ -365,6 +355,11 @@ Eine komplette Liste aller Hook-Callbacks mit den zugehรถrigen Dateien (am 01-Ap Hook::callAll('post_remote_end', $posted_item); Hook::callAll('tagged', $arr); Hook::callAll('post_local_end', $new_item); + Hook::callAll('put_item_in_cache', $hook_data); + Hook::callAll('prepare_body_init', $item); + Hook::callAll('prepare_body_content_filter', $hook_data); + Hook::callAll('prepare_body', $hook_data); + Hook::callAll('prepare_body_final', $hook_data); ### src/Model/Contact.php @@ -387,6 +382,10 @@ Eine komplette Liste aller Hook-Callbacks mit den zugehรถrigen Dateien (am 01-Ap Hook::callAll('register_account', $uid); Hook::callAll('remove_user', $user); + +### src/Content/ContactBlock.php + + Hook::callAll('contact_block_end', $arr); ### src/Content/Text/BBCode.php @@ -457,6 +456,18 @@ Eine komplette Liste aller Hook-Callbacks mit den zugehรถrigen Dateien (am 01-Ap Hook::callAll($a->module.'_post_'.$selname, $o); Hook::callAll('jot_networks', $jotnets); +### src/Core/Authentication.php + + Hook::callAll('logged_in', $a->user); + +### src/Core/Hook.php + + self::callSingle(self::getApp(), 'hook_fork', $fork_hook, $hookdata); + +### src/Core/L10n/L10n.php + + Hook::callAll('poke_verbs', $arr); + ### src/Core/Worker.php Hook::callAll("proc_run", $arr); From 3eb3e0b5cea03a96f1f6745a2c7069cbf75cbb90 Mon Sep 17 00:00:00 2001 From: Philipp Date: Wed, 23 Oct 2019 03:22:03 +0200 Subject: [PATCH 21/46] Update InstallerTest.php Remove `text.php` usage --- tests/src/Core/InstallerTest.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/tests/src/Core/InstallerTest.php b/tests/src/Core/InstallerTest.php index a898dd295..735a52cd0 100644 --- a/tests/src/Core/InstallerTest.php +++ b/tests/src/Core/InstallerTest.php @@ -339,9 +339,6 @@ class InstallerTest extends MockedTest // Mocking that we can use CURL $this->setFunctions(['curl_init' => true]); - // needed because of "normalise_link" - require_once __DIR__ . '/../../../include/text.php'; - $install = new Installer(); $this->assertTrue($install->checkHtAccess('https://test')); From db25f5b6ca964bf9bd20d0109f889db57a39114e Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 16:24:19 +0200 Subject: [PATCH 22/46] Add jsonExit() and fix UID issue --- src/Module/Item/Ignored.php | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/Module/Item/Ignored.php b/src/Module/Item/Ignored.php index 474f01dbe..c629b0d2e 100644 --- a/src/Module/Item/Ignored.php +++ b/src/Module/Item/Ignored.php @@ -6,6 +6,7 @@ use Friendica\App; use Friendica\BaseModule; use Friendica\Core\L10n\L10n; use Friendica\Core\Session; +use Friendica\Core\System; use Friendica\Database\Database; use Friendica\Model\Item; use Friendica\Network\HTTPException; @@ -43,10 +44,20 @@ class Ignored extends BaseModule // Numeric values are needed for the json output further below $ignored = !empty($thread['ignored']) ? 0 : 1; - if (!empty($thread['uid']) && $thread['uid'] != 0) { - $dba->update('thread', ['ignored' => $ignored], ['iid' => $message_id]); - } else { - $dba->update('user-item', ['ignored' => $ignored], ['iid' => $message_id, 'uid' => local_user()], true); + switch ($thread['uid'] ?? 0) { + // if the thread is from the current user + case local_user(): + $dba->update('thread', ['ignored' => $ignored], ['iid' => $message_id]); + break; + // Empty or 0 (null will get transformed to 0) => it's a public post + case 0: + case '': + $dba->update('user-item', ['ignored' => $ignored], ['iid' => $message_id, 'uid' => local_user()], true); + break; + // In case we retrieved a thread which isn't our or a public, it's a forbidden action + // but due to security reason (brute force), we print a Bad request exception + default: + throw new HTTPException\BadRequestException(); } // See if we've been passed a return path to redirect to @@ -63,8 +74,6 @@ class Ignored extends BaseModule } // the json doesn't really matter, it will either be 0 or 1 - - echo json_encode($ignored); - exit(); + System::jsonExit([$ignored]); } } From dba2d574b1daf80c4fe834aae408ffc9a8e49e57 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 21:29:17 +0200 Subject: [PATCH 23/46] Adapt because of feedback --- src/Module/Item/Ignored.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Module/Item/Ignored.php b/src/Module/Item/Ignored.php index c629b0d2e..f37c5ab3a 100644 --- a/src/Module/Item/Ignored.php +++ b/src/Module/Item/Ignored.php @@ -49,13 +49,12 @@ class Ignored extends BaseModule case local_user(): $dba->update('thread', ['ignored' => $ignored], ['iid' => $message_id]); break; - // Empty or 0 (null will get transformed to 0) => it's a public post + // 0 (null will get transformed to 0) => it's a public post case 0: - case '': $dba->update('user-item', ['ignored' => $ignored], ['iid' => $message_id, 'uid' => local_user()], true); break; - // In case we retrieved a thread which isn't our or a public, it's a forbidden action - // but due to security reason (brute force), we print a Bad request exception + // Throws a BadRequestException and not a ForbiddenException on purpose + // Avoids harvesting existing, but forbidden IIDs (security issue) default: throw new HTTPException\BadRequestException(); } From c9e1098dd2a38d36dd1cc2e083f7a2ea74f5f4c4 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Wed, 23 Oct 2019 21:38:51 +0200 Subject: [PATCH 24/46] Adapt naming convention --- mod/events.php | 8 ++++---- mod/item.php | 8 ++++---- mod/photos.php | 20 +++++++++----------- mod/settings.php | 8 ++++---- src/Model/Item.php | 6 +++--- src/Util/ACLFormatter.php | 6 +++--- tests/src/Util/ACLFormaterTest.php | 2 +- 7 files changed, 28 insertions(+), 30 deletions(-) diff --git a/mod/events.php b/mod/events.php index 75cbc6b43..11bb25f51 100644 --- a/mod/events.php +++ b/mod/events.php @@ -152,10 +152,10 @@ function events_post(App $a) /** @var ACLFormatter $aclFormatter */ $aclFormatter = BaseObject::getClass(ACLFormatter::class); - $str_group_allow = $aclFormatter->aclToString($_POST['group_allow'] ?? ''); - $str_contact_allow = $aclFormatter->aclToString($_POST['contact_allow'] ?? ''); - $str_group_deny = $aclFormatter->aclToString($_POST['group_deny'] ?? ''); - $str_contact_deny = $aclFormatter->aclToString($_POST['contact_deny'] ?? ''); + $str_group_allow = $aclFormatter->toString($_POST['group_allow'] ?? ''); + $str_contact_allow = $aclFormatter->toString($_POST['contact_allow'] ?? ''); + $str_group_deny = $aclFormatter->toString($_POST['group_deny'] ?? ''); + $str_contact_deny = $aclFormatter->toString($_POST['contact_deny'] ?? ''); // Undo the pseudo-contact of self, since there are real contacts now if (strpos($str_contact_allow, '<' . $self . '>') !== false) { diff --git a/mod/item.php b/mod/item.php index 5539e28c6..a5875d258 100644 --- a/mod/item.php +++ b/mod/item.php @@ -275,10 +275,10 @@ function item_post(App $a) { /** @var ACLFormatter $aclFormatter */ $aclFormatter = BaseObject::getClass(ACLFormatter::class); - $str_group_allow = $aclFormatter->aclToString($_REQUEST['group_allow'] ?? ''); - $str_contact_allow = $aclFormatter->aclToString($_REQUEST['contact_allow'] ?? ''); - $str_group_deny = $aclFormatter->aclToString($_REQUEST['group_deny'] ?? ''); - $str_contact_deny = $aclFormatter->aclToString($_REQUEST['contact_deny'] ?? ''); + $str_group_allow = $aclFormatter->toString($_REQUEST['group_allow'] ?? ''); + $str_contact_allow = $aclFormatter->toString($_REQUEST['contact_allow'] ?? ''); + $str_group_deny = $aclFormatter->toString($_REQUEST['group_deny'] ?? ''); + $str_contact_deny = $aclFormatter->toString($_REQUEST['contact_deny'] ?? ''); } $title = Strings::escapeTags(trim($_REQUEST['title'] ?? '')); diff --git a/mod/photos.php b/mod/photos.php index 3a94813e5..d89cd04b0 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -15,18 +15,16 @@ use Friendica\Core\Hook; use Friendica\Core\L10n; use Friendica\Core\Logger; use Friendica\Core\Renderer; -use Friendica\Core\System; use Friendica\Core\Session; +use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Contact; -use Friendica\Model\Group; use Friendica\Model\Item; use Friendica\Model\Photo; use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; -use Friendica\Protocol\DFRN; use Friendica\Util\ACLFormatter; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; @@ -301,10 +299,10 @@ function photos_post(App $a) /** @var ACLFormatter $aclFormatter */ $aclFormatter = BaseObject::getClass(ACLFormatter::class); - $str_group_allow = !empty($_POST['group_allow']) ? $aclFormatter->aclToString($_POST['group_allow']) : ''; - $str_contact_allow = !empty($_POST['contact_allow']) ? $aclFormatter->aclToString($_POST['contact_allow']) : ''; - $str_group_deny = !empty($_POST['group_deny']) ? $aclFormatter->aclToString($_POST['group_deny']) : ''; - $str_contact_deny = !empty($_POST['contact_deny']) ? $aclFormatter->aclToString($_POST['contact_deny']) : ''; + $str_group_allow = !empty($_POST['group_allow']) ? $aclFormatter->toString($_POST['group_allow']) : ''; + $str_contact_allow = !empty($_POST['contact_allow']) ? $aclFormatter->toString($_POST['contact_allow']) : ''; + $str_group_deny = !empty($_POST['group_deny']) ? $aclFormatter->toString($_POST['group_deny']) : ''; + $str_contact_deny = !empty($_POST['contact_deny']) ? $aclFormatter->toString($_POST['contact_deny']) : ''; $resource_id = $a->argv[3]; @@ -643,10 +641,10 @@ function photos_post(App $a) /** @var ACLFormatter $aclFormatter */ $aclFormatter = BaseObject::getClass(ACLFormatter::class); - $str_group_allow = $aclFormatter->aclToString(is_array($group_allow) ? $group_allow : explode(',', $group_allow)); - $str_contact_allow = $aclFormatter->aclToString(is_array($contact_allow) ? $contact_allow : explode(',', $contact_allow)); - $str_group_deny = $aclFormatter->aclToString(is_array($group_deny) ? $group_deny : explode(',', $group_deny)); - $str_contact_deny = $aclFormatter->aclToString(is_array($contact_deny) ? $contact_deny : explode(',', $contact_deny)); + $str_group_allow = $aclFormatter->toString(is_array($group_allow) ? $group_allow : explode(',', $group_allow)); + $str_contact_allow = $aclFormatter->toString(is_array($contact_allow) ? $contact_allow : explode(',', $contact_allow)); + $str_group_deny = $aclFormatter->toString(is_array($group_deny) ? $group_deny : explode(',', $group_deny)); + $str_contact_deny = $aclFormatter->toString(is_array($contact_deny) ? $contact_deny : explode(',', $contact_deny)); $ret = ['src' => '', 'filename' => '', 'filesize' => 0, 'type' => '']; diff --git a/mod/settings.php b/mod/settings.php index 3ab3d6212..8c3ce6684 100644 --- a/mod/settings.php +++ b/mod/settings.php @@ -538,10 +538,10 @@ function settings_post(App $a) /** @var ACLFormatter $aclFormatter */ $aclFormatter = BaseObject::getClass(ACLFormatter::class); - $str_group_allow = !empty($_POST['group_allow']) ? $aclFormatter->aclToString($_POST['group_allow']) : ''; - $str_contact_allow = !empty($_POST['contact_allow']) ? $aclFormatter->aclToString($_POST['contact_allow']) : ''; - $str_group_deny = !empty($_POST['group_deny']) ? $aclFormatter->aclToString($_POST['group_deny']) : ''; - $str_contact_deny = !empty($_POST['contact_deny']) ? $aclFormatter->aclToString($_POST['contact_deny']) : ''; + $str_group_allow = !empty($_POST['group_allow']) ? $aclFormatter->toString($_POST['group_allow']) : ''; + $str_contact_allow = !empty($_POST['contact_allow']) ? $aclFormatter->toString($_POST['contact_allow']) : ''; + $str_group_deny = !empty($_POST['group_deny']) ? $aclFormatter->toString($_POST['group_deny']) : ''; + $str_contact_deny = !empty($_POST['contact_deny']) ? $aclFormatter->toString($_POST['contact_deny']) : ''; $openidserver = $a->user['openidserver']; //$openid = Strings::normaliseOpenID($openid); diff --git a/src/Model/Item.php b/src/Model/Item.php index 6f84de427..2c544a263 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -17,8 +17,8 @@ use Friendica\Core\Logger; use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Core\Renderer; -use Friendica\Core\System; use Friendica\Core\Session; +use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\Protocol\Activity; @@ -3350,7 +3350,7 @@ class Item extends BaseObject || $rendered_hash != hash("md5", $item["body"]) || Config::get("system", "ignore_cache") ) { - self::addRedirLinkToImageLinks($item); + self::addRedirToImageTags($item); $item["rendered-html"] = BBCode::convert($item["body"]); $item["rendered-hash"] = hash("md5", $item["body"]); @@ -3390,7 +3390,7 @@ class Item extends BaseObject * * @param array &$item The field array of an item row */ - private static function addRedirLinkToImageLinks(array &$item) + private static function addRedirToImageTags(array &$item) { $app = self::getApp(); diff --git a/src/Util/ACLFormatter.php b/src/Util/ACLFormatter.php index e724a8948..1fb778761 100644 --- a/src/Util/ACLFormatter.php +++ b/src/Util/ACLFormatter.php @@ -30,7 +30,7 @@ final class ACLFormatter * * @param string $item The item to sanitise */ - private function sanitiseAcl(string &$item) { + private function sanitize(string &$item) { if (intval($item)) { $item = '<' . intval(Strings::escapeTags(trim($item))) . '>'; } elseif (in_array($item, [Group::FOLLOWERS, Group::MUTUALS])) { @@ -50,7 +50,7 @@ final class ACLFormatter * * @return string */ - function aclToString($permissions) { + function toString($permissions) { $return = ''; if (is_array($permissions)) { $item = $permissions; @@ -59,7 +59,7 @@ final class ACLFormatter } if (is_array($item)) { - array_walk($item, [$this, 'sanitiseAcl']); + array_walk($item, [$this, 'sanitize']); $return = implode('', $item); } return $return; diff --git a/tests/src/Util/ACLFormaterTest.php b/tests/src/Util/ACLFormaterTest.php index 19332f495..76a566baa 100644 --- a/tests/src/Util/ACLFormaterTest.php +++ b/tests/src/Util/ACLFormaterTest.php @@ -195,6 +195,6 @@ class ACLFormaterTest extends TestCase { $aclFormatter = new ACLFormatter(); - $this->assertEquals($assert, $aclFormatter->aclToString($input)); + $this->assertEquals($assert, $aclFormatter->toString($input)); } } From 5aa73afa7e4ffcd005d7a2ff3af8330ce1c90b15 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 24 Oct 2019 09:09:47 +0200 Subject: [PATCH 25/46] Rename module class name --- src/Module/Item/{Ignored.php => Ignore.php} | 2 +- static/routes.config.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename src/Module/Item/{Ignored.php => Ignore.php} (98%) diff --git a/src/Module/Item/Ignored.php b/src/Module/Item/Ignore.php similarity index 98% rename from src/Module/Item/Ignored.php rename to src/Module/Item/Ignore.php index f37c5ab3a..362b6c9ba 100644 --- a/src/Module/Item/Ignored.php +++ b/src/Module/Item/Ignore.php @@ -14,7 +14,7 @@ use Friendica\Network\HTTPException; /** * Module for ignoring threads or user items */ -class Ignored extends BaseModule +class Ignore extends BaseModule { public static function rawContent() { diff --git a/static/routes.config.php b/static/routes.config.php index 32a9f12ed..cce7789cd 100644 --- a/static/routes.config.php +++ b/static/routes.config.php @@ -131,7 +131,7 @@ return [ '/hashtag' => [Module\Hashtag::class, [R::GET]], '/home' => [Module\Home::class, [R::GET]], '/help[/{doc:.+}]' => [Module\Help::class, [R::GET]], - '/ignored/{id}' => [Module\Item\Ignored::class, [R::GET]], + '/ignored/{id}' => [Module\Item\Ignore::class, [R::GET]], '/inbox[/{nickname}]' => [Module\Inbox::class, [R::GET, R::POST]], '/invite' => [Module\Invite::class, [R::GET, R::POST]], From b0987f637c378f71d49812ec81e2fa198b4f4484 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Thu, 24 Oct 2019 08:47:00 -0400 Subject: [PATCH 26/46] Expect outbox->first to be a Link structure in Model\GContact - See https://www.w3.org/TR/activitystreams-vocabulary/#dfn-first - Addresses https://github.com/friendica/friendica/issues/7675#issuecomment-545300597 --- src/Model/GContact.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Model/GContact.php b/src/Model/GContact.php index 21225cb23..2402d6b51 100644 --- a/src/Model/GContact.php +++ b/src/Model/GContact.php @@ -859,7 +859,9 @@ class GContact /** * Update a global contact via an ActivityPub Outbox * - * @param string $data Probing result + * @param string $feed + * @param array $data Probing result + * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ private static function updateFromOutbox(string $feed, array $data) { @@ -872,6 +874,9 @@ class GContact $items = $outbox['orderedItems']; } elseif (!empty($outbox['first']['orderedItems'])) { $items = $outbox['first']['orderedItems']; + } elseif (!empty($outbox['first']['href'])) { + self::updateFromOutbox($outbox['first']['href'], $data); + return; } elseif (!empty($outbox['first'])) { self::updateFromOutbox($outbox['first'], $data); return; From 062e47231437dfcc5df185bf50f82011eae31275 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 24 Oct 2019 17:18:29 +0200 Subject: [PATCH 27/46] Rename route '/ignored/{iid}' to '/item/ignore/{iid}' --- src/Module/Item/Ignore.php | 2 +- static/routes.config.php | 8 ++++++-- view/js/main.js | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Module/Item/Ignore.php b/src/Module/Item/Ignore.php index 362b6c9ba..6a28310b4 100644 --- a/src/Module/Item/Ignore.php +++ b/src/Module/Item/Ignore.php @@ -30,7 +30,7 @@ class Ignore extends BaseModule /** @var Database $dba */ $dba = self::getClass(Database::class); - $message_id = intval($args->get(1)); + $message_id = intval($args->get(2)); if (empty($message_id) || !is_int($message_id)) { throw new HTTPException\BadRequestException(); diff --git a/static/routes.config.php b/static/routes.config.php index cce7789cd..19d1b3156 100644 --- a/static/routes.config.php +++ b/static/routes.config.php @@ -131,9 +131,13 @@ return [ '/hashtag' => [Module\Hashtag::class, [R::GET]], '/home' => [Module\Home::class, [R::GET]], '/help[/{doc:.+}]' => [Module\Help::class, [R::GET]], - '/ignored/{id}' => [Module\Item\Ignore::class, [R::GET]], '/inbox[/{nickname}]' => [Module\Inbox::class, [R::GET, R::POST]], - '/invite' => [Module\Invite::class, [R::GET, R::POST]], + + '/item' => [ + '/ignore/{id}' => [Module\Item\Ignore::class, [R::GET]], + ], + + '/invite' => [Module\Invite::class, [R::GET, R::POST]], '/install' => [ '[/]' => [Module\Install::class, [R::GET, R::POST]], diff --git a/view/js/main.js b/view/js/main.js index 47e7b968d..40db7c2a1 100644 --- a/view/js/main.js +++ b/view/js/main.js @@ -629,7 +629,7 @@ function dostar(ident) { function doignore(ident) { ident = ident.toString(); $('#like-rotator-' + ident).show(); - $.get('ignored/' + ident, function(data) { + $.get('item/ignore/' + ident, function(data) { if (data.match(/1/)) { $('#ignored-' + ident).addClass('ignored'); $('#ignored-' + ident).removeClass('unignored'); From 488504314a729a6637787b2e235e45edf376225c Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 24 Oct 2019 17:32:03 +0200 Subject: [PATCH 28/46] sort route config --- static/routes.config.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/static/routes.config.php b/static/routes.config.php index 19d1b3156..3379ee113 100644 --- a/static/routes.config.php +++ b/static/routes.config.php @@ -132,17 +132,17 @@ return [ '/home' => [Module\Home::class, [R::GET]], '/help[/{doc:.+}]' => [Module\Help::class, [R::GET]], '/inbox[/{nickname}]' => [Module\Inbox::class, [R::GET, R::POST]], - - '/item' => [ - '/ignore/{id}' => [Module\Item\Ignore::class, [R::GET]], - ], - - '/invite' => [Module\Invite::class, [R::GET, R::POST]], + '/invite' => [Module\Invite::class, [R::GET, R::POST]], '/install' => [ '[/]' => [Module\Install::class, [R::GET, R::POST]], '/testrewrite' => [Module\Install::class, [R::GET]], ], + + '/item' => [ + '/ignore/{id}' => [Module\Item\Ignore::class, [R::GET]], + ], + '/like/{item:\d+}' => [Module\Like::class, [R::GET]], '/localtime' => [Module\Debug\Localtime::class, [R::GET, R::POST]], '/login' => [Module\Login::class, [R::GET, R::POST]], From 9a55e35887b215795688e8abef406163efb90497 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 24 Oct 2019 15:32:54 +0200 Subject: [PATCH 29/46] Fix Lock file --- composer.json | 24 ++++++++-------- composer.lock | 78 +++++++++++++++++++++++++++------------------------ 2 files changed, 54 insertions(+), 48 deletions(-) diff --git a/composer.json b/composer.json index 83b51a174..e372547aa 100644 --- a/composer.json +++ b/composer.json @@ -28,15 +28,15 @@ "ext-xml": "*", "asika/simple-console": "^1.0", "bacon/bacon-qr-code": "^1.0", - "divineomega/password_exposed": "^2.4", - "ezyang/htmlpurifier": "~4.7.0", + "divineomega/password_exposed": "^2.8", + "ezyang/htmlpurifier": "^4.7", "friendica/json-ld": "^1.0", - "league/html-to-markdown": "~4.8.0", - "level-2/dice": ">1.0", + "league/html-to-markdown": "^4.8", + "level-2/dice": "^4", "lightopenid/lightopenid": "dev-master", "michelf/php-markdown": "^1.7", - "mobiledetect/mobiledetectlib": "2.8.*", - "monolog/monolog": "^1.24", + "mobiledetect/mobiledetectlib": "^2.8", + "monolog/monolog": "^1.25", "nikic/fast-route": "^1.3", "paragonie/hidden-string": "^1.0", "pear/console_table": "^1.3", @@ -46,18 +46,18 @@ "psr/container": "^1.0", "seld/cli-prompt": "^1.0", "smarty/smarty": "^3.1", - "fxp/composer-asset-plugin": "~1.3", + "fxp/composer-asset-plugin": "^1.4", "bower-asset/base64": "^1.0", - "bower-asset/chart-js": "^2.7", + "bower-asset/chart-js": "^2.8", "bower-asset/dompurify": "^1.0", "bower-asset/perfect-scrollbar": "^0.6", - "bower-asset/vue": "^2.5", + "bower-asset/vue": "^2.6", "npm-asset/jquery": "^2.0", "npm-asset/jquery-colorbox": "^1.6", - "npm-asset/jquery-datetimepicker": "^2.4.0", + "npm-asset/jquery-datetimepicker": "^2.5", "npm-asset/jgrowl": "^1.4", - "npm-asset/moment": "^2.20.1", - "npm-asset/fullcalendar": "^3.0.1", + "npm-asset/moment": "^2.24", + "npm-asset/fullcalendar": "^3.10", "npm-asset/cropperjs": "1.2.2", "npm-asset/imagesloaded": "4.1.4", "npm-asset/typeahead.js": "^0.11.1", diff --git a/composer.lock b/composer.lock index 3aad3a154..8e55db88d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "eda94f02683bea49b3d506d770749277", + "content-hash": "34ad225ce21474eb84ce78047d9f2c01", "packages": [ { "name": "asika/simple-console", @@ -1128,6 +1128,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/cropperjs/-/cropperjs-1.2.2.tgz", + "reference": null, "shasum": "30dc7a7ce872155b23a33bd10ad4c76c0d613f55" }, "require-dev": { @@ -1221,6 +1222,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/ev-emitter/-/ev-emitter-1.1.1.tgz", + "reference": null, "shasum": "8f18b0ce5c76a5d18017f71c0a795c65b9138f2a" }, "type": "npm-asset-library", @@ -1263,6 +1265,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/fullcalendar/-/fullcalendar-3.10.1.tgz", + "reference": null, "shasum": "cca3f9a2656a7e978a3f3facb7f35934a91185db" }, "type": "npm-asset-library", @@ -1309,6 +1312,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/imagesloaded/-/imagesloaded-4.1.4.tgz", + "reference": null, "shasum": "1376efcd162bb768c34c3727ac89cc04051f3cc7" }, "require": { @@ -1372,6 +1376,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/jgrowl/-/jgrowl-1.4.6.tgz", + "reference": null, "shasum": "2736e332aaee73ccf0a14a5f0066391a0a13f4a3" }, "require-dev": { @@ -1412,6 +1417,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/jquery/-/jquery-2.2.4.tgz", + "reference": null, "shasum": "2c89d6889b5eac522a7eea32c14521559c6cbf02" }, "require-dev": { @@ -1482,6 +1488,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/jquery-colorbox/-/jquery-colorbox-1.6.4.tgz", + "reference": null, "shasum": "799452523a6c494839224ef702e807deb9c06cc5" }, "require": { @@ -1528,6 +1535,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/jquery-datetimepicker/-/jquery-datetimepicker-2.5.21.tgz", + "reference": null, "shasum": "00c388a78df2732fedfdb5c6529b6e84d53e0235" }, "require": { @@ -1585,6 +1593,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/jquery-mousewheel/-/jquery-mousewheel-3.1.13.tgz", + "reference": null, "shasum": "06f0335f16e353a695e7206bf50503cb523a6ee5" }, "require-dev": { @@ -1639,6 +1648,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/moment/-/moment-2.24.0.tgz", + "reference": null, "shasum": "0d055d53f5052aa653c9f6eb68bb5d12bf5c2b5b" }, "type": "npm-asset-library", @@ -1755,6 +1765,7 @@ "dist": { "type": "tar", "url": "https://registry.npmjs.org/typeahead.js/-/typeahead.js-0.11.1.tgz", + "reference": null, "shasum": "4e64e671b22310a8606f4aec805924ba84b015b8" }, "require": { @@ -2828,34 +2839,32 @@ "packages-dev": [ { "name": "doctrine/instantiator", - "version": "1.2.0", + "version": "1.0.5", "source": { "type": "git", "url": "https://github.com/doctrine/instantiator.git", - "reference": "a2c590166b2133a4633738648b6b064edae0814a" + "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/doctrine/instantiator/zipball/a2c590166b2133a4633738648b6b064edae0814a", - "reference": "a2c590166b2133a4633738648b6b064edae0814a", + "url": "https://api.github.com/repos/doctrine/instantiator/zipball/8e884e78f9f0eb1329e445619e04456e64d8051d", + "reference": "8e884e78f9f0eb1329e445619e04456e64d8051d", "shasum": "" }, "require": { - "php": "^7.1" + "php": ">=5.3,<8.0-DEV" }, "require-dev": { - "doctrine/coding-standard": "^6.0", + "athletic/athletic": "~0.1.8", "ext-pdo": "*", "ext-phar": "*", - "phpbench/phpbench": "^0.13", - "phpstan/phpstan-phpunit": "^0.11", - "phpstan/phpstan-shim": "^0.11", - "phpunit/phpunit": "^7.0" + "phpunit/phpunit": "~4.0", + "squizlabs/php_codesniffer": "~2.0" }, "type": "library", "extra": { "branch-alias": { - "dev-master": "1.2.x-dev" + "dev-master": "1.0.x-dev" } }, "autoload": { @@ -2875,12 +2884,12 @@ } ], "description": "A small, lightweight utility to instantiate objects in PHP without invoking their constructors", - "homepage": "https://www.doctrine-project.org/projects/instantiator.html", + "homepage": "https://github.com/doctrine/instantiator", "keywords": [ "constructor", "instantiate" ], - "time": "2019-03-17T17:37:11+00:00" + "time": "2015-06-14T21:17:01+00:00" }, { "name": "hamcrest/hamcrest-php", @@ -3091,28 +3100,25 @@ }, { "name": "myclabs/deep-copy", - "version": "1.9.3", + "version": "1.7.0", "source": { "type": "git", "url": "https://github.com/myclabs/DeepCopy.git", - "reference": "007c053ae6f31bba39dfa19a7726f56e9763bbea" + "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/007c053ae6f31bba39dfa19a7726f56e9763bbea", - "reference": "007c053ae6f31bba39dfa19a7726f56e9763bbea", + "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e", + "reference": "3b8a3a99ba1f6a3952ac2747d989303cbd6b7a3e", "shasum": "" }, "require": { - "php": "^7.1" - }, - "replace": { - "myclabs/deep-copy": "self.version" + "php": "^5.6 || ^7.0" }, "require-dev": { "doctrine/collections": "^1.0", "doctrine/common": "^2.6", - "phpunit/phpunit": "^7.1" + "phpunit/phpunit": "^4.1" }, "type": "library", "autoload": { @@ -3135,7 +3141,7 @@ "object", "object graph" ], - "time": "2019-08-09T12:45:53+00:00" + "time": "2017-10-19T19:58:43+00:00" }, { "name": "phpdocumentor/reflection-common", @@ -3838,7 +3844,7 @@ } ], "description": "Provides the functionality to compare PHP values for equality", - "homepage": "http://www.github.com/sebastianbergmann/comparator", + "homepage": "https://github.com/sebastianbergmann/comparator", "keywords": [ "comparator", "compare", @@ -3940,7 +3946,7 @@ } ], "description": "Provides functionality to handle HHVM/PHP environments", - "homepage": "http://www.github.com/sebastianbergmann/environment", + "homepage": "https://github.com/sebastianbergmann/environment", "keywords": [ "Xdebug", "environment", @@ -4008,7 +4014,7 @@ } ], "description": "Provides the functionality to export PHP variables for visualization", - "homepage": "http://www.github.com/sebastianbergmann/exporter", + "homepage": "https://github.com/sebastianbergmann/exporter", "keywords": [ "export", "exporter" @@ -4060,7 +4066,7 @@ } ], "description": "Snapshotting of global state", - "homepage": "http://www.github.com/sebastianbergmann/global-state", + "homepage": "https://github.com/sebastianbergmann/global-state", "keywords": [ "global state" ], @@ -4162,7 +4168,7 @@ } ], "description": "Provides functionality to recursively process PHP variables", - "homepage": "http://www.github.com/sebastianbergmann/recursion-context", + "homepage": "https://github.com/sebastianbergmann/recursion-context", "time": "2016-11-19T07:33:16+00:00" }, { @@ -4310,20 +4316,20 @@ }, { "name": "symfony/yaml", - "version": "v4.3.4", + "version": "v3.4.32", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "5a0b7c32dc3ec56fd4abae8a4a71b0cf05013686" + "reference": "768f817446da74a776a31eea335540f9dcb53942" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/5a0b7c32dc3ec56fd4abae8a4a71b0cf05013686", - "reference": "5a0b7c32dc3ec56fd4abae8a4a71b0cf05013686", + "url": "https://api.github.com/repos/symfony/yaml/zipball/768f817446da74a776a31eea335540f9dcb53942", + "reference": "768f817446da74a776a31eea335540f9dcb53942", "shasum": "" }, "require": { - "php": "^7.1.3", + "php": "^5.5.9|>=7.0.8", "symfony/polyfill-ctype": "~1.8" }, "conflict": { @@ -4338,7 +4344,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "4.3-dev" + "dev-master": "3.4-dev" } }, "autoload": { @@ -4365,7 +4371,7 @@ ], "description": "Symfony Yaml Component", "homepage": "https://symfony.com", - "time": "2019-08-20T14:27:59+00:00" + "time": "2019-09-10T10:38:46+00:00" }, { "name": "webmozart/assert", From 07cea24430420cb0ac2b1d8f870d7292002c7faf Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 24 Oct 2019 00:25:43 +0200 Subject: [PATCH 30/46] Move Activity/Namespaces defines to constants --- boot.php | 73 ------------ include/api.php | 13 ++- include/conversation.php | 74 ++++++------ include/enotify.php | 15 +-- mod/dfrn_confirm.php | 3 +- mod/dfrn_request.php | 3 +- mod/item.php | 21 ++-- mod/photos.php | 19 +-- mod/poke.php | 7 +- mod/salmon.php | 3 +- mod/subthread.php | 5 +- mod/tagger.php | 7 +- src/Content/Text/BBCode.php | 3 +- src/Core/NotificationsManager.php | 13 ++- src/Model/Contact.php | 7 +- src/Model/Event.php | 9 +- src/Model/Item.php | 48 ++++---- src/Model/Mail.php | 3 +- src/Model/Profile.php | 3 +- src/Module/Xrd.php | 7 +- src/Network/Probe.php | 19 +-- src/Object/Post.php | 6 +- src/Object/Thread.php | 3 +- src/Protocol/Activity.php | 81 ++++++++++++- src/Protocol/Activity/Namespaces.php | 27 +++++ src/Protocol/ActivityPub/Processor.php | 9 +- src/Protocol/ActivityPub/Receiver.php | 15 +-- src/Protocol/ActivityPub/Transmitter.php | 19 +-- src/Protocol/DFRN.php | 127 ++++++++++---------- src/Protocol/Diaspora.php | 51 ++++---- src/Protocol/Feed.php | 11 +- src/Protocol/OStatus.php | 143 ++++++++++++----------- src/Worker/OnePoll.php | 5 +- tests/src/Protocol/ActivityTest.php | 18 ++- 34 files changed, 467 insertions(+), 403 deletions(-) create mode 100644 src/Protocol/Activity/Namespaces.php diff --git a/boot.php b/boot.php index 3571a77c1..d2597b378 100644 --- a/boot.php +++ b/boot.php @@ -184,79 +184,6 @@ define('TERM_OBJ_POST', Term::OBJECT_TYPE_POST); /** @deprecated since 2019.03, use Term::OBJECT_TYPE_PHOTO instead */ define('TERM_OBJ_PHOTO', Term::OBJECT_TYPE_PHOTO); -/** - * @name Namespaces - * - * Various namespaces we may need to parse - * @{ - */ -define('NAMESPACE_ZOT', 'http://purl.org/zot'); -define('NAMESPACE_DFRN', 'http://purl.org/macgirvin/dfrn/1.0'); -define('NAMESPACE_THREAD', 'http://purl.org/syndication/thread/1.0'); -define('NAMESPACE_TOMB', 'http://purl.org/atompub/tombstones/1.0'); -define('NAMESPACE_ACTIVITY2', 'https://www.w3.org/ns/activitystreams#'); -define('NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/'); -define('NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/'); -define('NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia'); -define('NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env'); -define('NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe'); -define('NAMESPACE_GEORSS', 'http://www.georss.org/georss'); -define('NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0'); -define('NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from'); -define('NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0'); -define('NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/'); -define('NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom'); -define('NAMESPACE_MASTODON', 'http://mastodon.social/schema/1.0'); -/* @}*/ - -/** - * @name Activity - * - * Activity stream defines - * @{ - */ -define('ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like'); -define('ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike'); -define('ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes'); -define('ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno'); -define('ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe'); - -define('ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart'); - -define('ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend'); -define('ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend'); -define('ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend'); -define('ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow'); -define('ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following'); -define('ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join'); - -define('ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post'); -define('ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update'); -define('ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag'); -define('ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite'); -define('ACTIVITY_UNFAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'unfavorite'); -define('ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share'); -define('ACTIVITY_DELETE', NAMESPACE_ACTIVITY_SCHEMA . 'delete'); -define('ACTIVITY2_ANNOUNCE', NAMESPACE_ACTIVITY2 . 'Announce'); - -define('ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke'); - -define('ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark'); -define('ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment'); -define('ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note'); -define('ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person'); -define('ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image'); -define('ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo'); -define('ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video'); -define('ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo'); -define('ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album'); -define('ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event'); -define('ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group'); -define('ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm'); -define('ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile'); -define('ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question'); -/* @}*/ - /** * @name Gravity * diff --git a/include/api.php b/include/api.php index 7daf13455..91e31ac94 100644 --- a/include/api.php +++ b/include/api.php @@ -41,6 +41,7 @@ use Friendica\Network\HTTPException\NotImplementedException; use Friendica\Network\HTTPException\TooManyRequestsException; use Friendica\Network\HTTPException\UnauthorizedException; use Friendica\Object\Image; +use Friendica\Protocol\Activity; use Friendica\Protocol\Diaspora; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; @@ -2839,19 +2840,19 @@ function api_format_items_activities($item, $type = "json") // get user data and add it to the array of the activity $user = api_get_user($a, $parent_item['author-id']); switch ($parent_item['verb']) { - case ACTIVITY_LIKE: + case Activity::LIKE: $activities['like'][] = $user; break; - case ACTIVITY_DISLIKE: + case Activity::DISLIKE: $activities['dislike'][] = $user; break; - case ACTIVITY_ATTEND: + case Activity::ATTEND: $activities['attendyes'][] = $user; break; - case ACTIVITY_ATTENDNO: + case Activity::ATTENDNO: $activities['attendno'][] = $user; break; - case ACTIVITY_ATTENDMAYBE: + case Activity::ATTENDMAYBE: $activities['attendmaybe'][] = $user; break; default: @@ -5110,7 +5111,7 @@ function api_get_announce($item) } $fields = ['author-id', 'author-name', 'author-link', 'author-avatar']; - $activity = Item::activityToIndex(ACTIVITY2_ANNOUNCE); + $activity = Item::activityToIndex(Activity::ANNOUNCE); $condition = ['parent-uri' => $item['uri'], 'gravity' => GRAVITY_ACTIVITY, 'uid' => [0, $item['uid']], 'activity' => $activity]; $announce = Item::selectFirstForUser($item['uid'], $fields, $condition, ['order' => ['received' => true]]); if (!DBA::isResult($announce)) { diff --git a/include/conversation.php b/include/conversation.php index 8bcd1b338..75a8f020b 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -145,11 +145,11 @@ function localize_item(&$item) $activity = BaseObject::getClass(Activity::class); $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">"; - if ($activity->match($item['verb'], ACTIVITY_LIKE) - || $activity->match($item['verb'], ACTIVITY_DISLIKE) - || $activity->match($item['verb'], ACTIVITY_ATTEND) - || $activity->match($item['verb'], ACTIVITY_ATTENDNO) - || $activity->match($item['verb'], ACTIVITY_ATTENDMAYBE)) { + if ($activity->match($item['verb'], Activity::LIKE) + || $activity->match($item['verb'], Activity::DISLIKE) + || $activity->match($item['verb'], Activity::ATTEND) + || $activity->match($item['verb'], Activity::ATTENDNO) + || $activity->match($item['verb'], Activity::ATTENDMAYBE)) { $fields = ['author-link', 'author-name', 'verb', 'object-type', 'resource-id', 'body', 'plink']; $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]); @@ -161,9 +161,9 @@ function localize_item(&$item) $objauthor = '[url=' . $obj['author-link'] . ']' . $obj['author-name'] . '[/url]'; switch ($obj['verb']) { - case ACTIVITY_POST: + case Activity::POST: switch ($obj['object-type']) { - case ACTIVITY_OBJ_EVENT: + case Activity::OBJ_EVENT: $post_type = L10n::t('event'); break; default: @@ -184,24 +184,24 @@ function localize_item(&$item) $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]'; $bodyverb = ''; - if ($activity->match($item['verb'], ACTIVITY_LIKE)) { + if ($activity->match($item['verb'], Activity::LIKE)) { $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s'); - } elseif ($activity->match($item['verb'], ACTIVITY_DISLIKE)) { + } elseif ($activity->match($item['verb'], Activity::DISLIKE)) { $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s'); - } elseif ($activity->match($item['verb'], ACTIVITY_ATTEND)) { + } elseif ($activity->match($item['verb'], Activity::ATTEND)) { $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s'); - } elseif ($activity->match($item['verb'], ACTIVITY_ATTENDNO)) { + } elseif ($activity->match($item['verb'], Activity::ATTENDNO)) { $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s'); - } elseif ($activity->match($item['verb'], ACTIVITY_ATTENDMAYBE)) { + } elseif ($activity->match($item['verb'], Activity::ATTENDMAYBE)) { $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s'); } $item['body'] = sprintf($bodyverb, $author, $objauthor, $plink); } - if ($activity->match($item['verb'], ACTIVITY_FRIEND)) { + if ($activity->match($item['verb'], Activity::FRIEND)) { - if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return; + if ($item['object-type']=="" || $item['object-type']!== Activity::OBJ_PERSON) return; $Aname = $item['author-name']; $Alink = $item['author-link']; @@ -231,12 +231,12 @@ function localize_item(&$item) $item['body'] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$Bphoto; } - if (stristr($item['verb'], ACTIVITY_POKE)) { + if (stristr($item['verb'], Activity::POKE)) { $verb = urldecode(substr($item['verb'],strpos($item['verb'],'#')+1)); if (!$verb) { return; } - if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) { + if ($item['object-type']=="" || $item['object-type']!== Activity::OBJ_PERSON) { return; } @@ -281,7 +281,7 @@ function localize_item(&$item) } - if ($activity->match($item['verb'], ACTIVITY_TAG)) { + if ($activity->match($item['verb'], Activity::TAG)) { $fields = ['author-id', 'author-link', 'author-name', 'author-network', 'verb', 'object-type', 'resource-id', 'body', 'plink']; $obj = Item::selectFirst($fields, ['uri' => $item['parent-uri']]); @@ -298,9 +298,9 @@ function localize_item(&$item) $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]'; switch ($obj['verb']) { - case ACTIVITY_POST: + case Activity::POST: switch ($obj['object-type']) { - case ACTIVITY_OBJ_EVENT: + case Activity::OBJ_EVENT: $post_type = L10n::t('event'); break; default: @@ -326,7 +326,7 @@ function localize_item(&$item) $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag); } - if ($activity->match($item['verb'], ACTIVITY_FAVORITE)) { + if ($activity->match($item['verb'], Activity::FAVORITE)) { if ($item['object-type'] == "") { return; } @@ -402,19 +402,15 @@ function visible_activity($item) { /** @var Activity $activity */ $activity = BaseObject::getClass(Activity::class); - /* - * likes (etc.) can apply to other things besides posts. Check if they are post children, - * in which case we handle them specially - */ - $hidden_activities = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE, ACTIVITY_FOLLOW, ACTIVITY2_ANNOUNCE]; - foreach ($hidden_activities as $act) { - if ($activity->match($item['verb'], $act)) { - return false; - } + if ($activity->isHidden($item['verb'])) { + return false; } // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere; - if ($activity->match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) { + if ($activity->match($item['verb'], Activity::FOLLOW) && + $item['object-type'] === Activity::OBJ_NOTE && + empty($item['self']) && + $item['uid'] == local_user()) { return false; } @@ -816,7 +812,7 @@ function conversation_fetch_comments($thread_items) { $received = ''; while ($row = Item::fetch($thread_items)) { - if (($row['verb'] == ACTIVITY2_ANNOUNCE) && !empty($row['contact-uid']) && ($row['received'] > $received) && ($row['thr-parent'] == $row['parent-uri'])) { + if (($row['verb'] == Activity::ANNOUNCE) && !empty($row['contact-uid']) && ($row['received'] > $received) && ($row['thr-parent'] == $row['parent-uri'])) { $actor = ['link' => $row['author-link'], 'avatar' => $row['author-avatar'], 'name' => $row['author-name']]; $received = $row['received']; } @@ -1008,22 +1004,22 @@ function builtin_activity_puller($item, &$conv_responses) { switch ($mode) { case 'like': - $verb = ACTIVITY_LIKE; + $verb = Activity::LIKE; break; case 'dislike': - $verb = ACTIVITY_DISLIKE; + $verb = Activity::DISLIKE; break; case 'attendyes': - $verb = ACTIVITY_ATTEND; + $verb = Activity::ATTEND; break; case 'attendno': - $verb = ACTIVITY_ATTENDNO; + $verb = Activity::ATTENDNO; break; case 'attendmaybe': - $verb = ACTIVITY_ATTENDMAYBE; + $verb = Activity::ATTENDMAYBE; break; case 'announce': - $verb = ACTIVITY2_ANNOUNCE; + $verb = Activity::ANNOUNCE; break; default: return; @@ -1386,7 +1382,7 @@ function smart_flatten_conversation(array $parent) if (isset($child['children']) && count($child['children'])) { // This helps counting only the regular posts $count_post_closure = function($var) { - return $var['verb'] === ACTIVITY_POST; + return $var['verb'] === Activity::POST; }; $child_post_count = count(array_filter($child['children'], $count_post_closure)); @@ -1398,7 +1394,7 @@ function smart_flatten_conversation(array $parent) // Searches the post item in the children $j = 0; - while($child['children'][$j]['verb'] !== ACTIVITY_POST && $j < count($child['children'])) { + while($child['children'][$j]['verb'] !== Activity::POST && $j < count($child['children'])) { $j ++; } diff --git a/include/enotify.php b/include/enotify.php index 01c946d1f..a8090e35f 100644 --- a/include/enotify.php +++ b/include/enotify.php @@ -13,6 +13,7 @@ use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Item; use Friendica\Model\User; +use Friendica\Protocol\Activity; use Friendica\Util\DateTimeFormat; use Friendica\Util\Emailer; use Friendica\Util\Strings; @@ -338,7 +339,7 @@ function notification($params) $hsitelink = sprintf($sitelink, ''.$sitename.''); switch ($params['verb']) { - case ACTIVITY_FRIEND: + case Activity::FRIEND: // someone started to share with user (mostly OStatus) $subject = L10n::t('[Friendica:Notify] A new person is sharing with you'); @@ -348,7 +349,7 @@ function notification($params) $sitename ); break; - case ACTIVITY_FOLLOW: + case Activity::FOLLOW: // someone started to follow the user (mostly OStatus) $subject = L10n::t('[Friendica:Notify] You have a new follower'); @@ -385,7 +386,7 @@ function notification($params) } if ($params['type'] == NOTIFY_CONFIRM) { - if ($params['verb'] == ACTIVITY_FRIEND) { // mutual connection + if ($params['verb'] == Activity::FRIEND) { // mutual connection $itemlink = $params['link']; $subject = L10n::t('[Friendica:Notify] Connection accepted'); @@ -821,7 +822,7 @@ function check_item_notification($itemid, $uid, $defaulttype = "") { if ($send_notification) { $params["type"] = NOTIFY_SHARE; - $params["verb"] = ACTIVITY_TAG; + $params["verb"] = Activity::TAG; } } @@ -835,7 +836,7 @@ function check_item_notification($itemid, $uid, $defaulttype = "") { if ($item["mention"] || $tagged || ($defaulttype == NOTIFY_TAGSELF)) { $params["type"] = NOTIFY_TAGSELF; - $params["verb"] = ACTIVITY_TAG; + $params["verb"] = Activity::TAG; } // Is it a post that the user had started? @@ -844,7 +845,7 @@ function check_item_notification($itemid, $uid, $defaulttype = "") { if ($thread['mention'] && !$thread['ignored'] && !isset($params["type"])) { $params["type"] = NOTIFY_COMMENT; - $params["verb"] = ACTIVITY_POST; + $params["verb"] = Activity::POST; } // And now we check for participation of one of our contacts in the thread @@ -852,7 +853,7 @@ function check_item_notification($itemid, $uid, $defaulttype = "") { if (!$thread['ignored'] && !isset($params["type"]) && Item::exists($condition)) { $params["type"] = NOTIFY_COMMENT; - $params["verb"] = ACTIVITY_POST; + $params["verb"] = Activity::POST; } if (isset($params["type"])) { diff --git a/mod/dfrn_confirm.php b/mod/dfrn_confirm.php index 944ba98be..c92e5493a 100644 --- a/mod/dfrn_confirm.php +++ b/mod/dfrn_confirm.php @@ -28,6 +28,7 @@ use Friendica\Model\Contact; use Friendica\Model\Group; use Friendica\Model\User; use Friendica\Network\Probe; +use Friendica\Protocol\Activity; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; @@ -538,7 +539,7 @@ function dfrn_confirm_post(App $a, $handsfree = null) 'source_name' => ((strlen(stripslashes($combined['name']))) ? stripslashes($combined['name']) : L10n::t('[Name Withheld]')), 'source_link' => $combined['url'], 'source_photo' => $combined['photo'], - 'verb' => ($mutual?ACTIVITY_FRIEND:ACTIVITY_FOLLOW), + 'verb' => ($mutual ? Activity::FRIEND : Activity::FOLLOW), 'otype' => 'intro' ]); } diff --git a/mod/dfrn_request.php b/mod/dfrn_request.php index f37064573..a9e17b34b 100644 --- a/mod/dfrn_request.php +++ b/mod/dfrn_request.php @@ -27,6 +27,7 @@ use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Module\Login; use Friendica\Network\Probe; +use Friendica\Protocol\Activity; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\Strings; @@ -561,7 +562,7 @@ function dfrn_request_content(App $a) 'source_name' => ((strlen(stripslashes($r[0]['name']))) ? stripslashes($r[0]['name']) : L10n::t('[Name Withheld]')), 'source_link' => $r[0]['url'], 'source_photo' => $r[0]['photo'], - 'verb' => ACTIVITY_REQ_FRIEND, + 'verb' => Activity::REQ_FRIEND, 'otype' => 'intro' ]); } diff --git a/mod/item.php b/mod/item.php index a5875d258..bc69ff7c3 100644 --- a/mod/item.php +++ b/mod/item.php @@ -36,6 +36,7 @@ use Friendica\Model\FileTag; use Friendica\Model\Item; use Friendica\Model\Photo; use Friendica\Model\Term; +use Friendica\Protocol\Activity; use Friendica\Protocol\Diaspora; use Friendica\Protocol\Email; use Friendica\Util\ACLFormatter; @@ -133,7 +134,7 @@ function item_post(App $a) { $toplevel_item_id = $toplevel_item['id']; $parent_user = $toplevel_item['uid']; - $objecttype = ACTIVITY_OBJ_COMMENT; + $objecttype = Activity::OBJ_COMMENT; } if ($toplevel_item_id) { @@ -466,7 +467,7 @@ function item_post(App $a) { $match = null; if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) { - $objecttype = ACTIVITY_OBJ_IMAGE; + $objecttype = Activity::OBJ_IMAGE; } /* @@ -502,7 +503,7 @@ function item_post(App $a) { if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) && ($posttype != Item::PT_PERSONAL_NOTE)) { $posttype = Item::PT_PAGE; - $objecttype = ACTIVITY_OBJ_BOOKMARK; + $objecttype = Activity::OBJ_BOOKMARK; } /** @var BBCode\Video $bbCodeVideo */ @@ -516,15 +517,15 @@ function item_post(App $a) { // Setting the object type if not defined before if (!$objecttype) { - $objecttype = ACTIVITY_OBJ_NOTE; // Default value + $objecttype = Activity::OBJ_NOTE; // Default value $objectdata = BBCode::getAttachedData($body); if ($objectdata["type"] == "link") { - $objecttype = ACTIVITY_OBJ_BOOKMARK; + $objecttype = Activity::OBJ_BOOKMARK; } elseif ($objectdata["type"] == "video") { - $objecttype = ACTIVITY_OBJ_VIDEO; + $objecttype = Activity::OBJ_VIDEO; } elseif ($objectdata["type"] == "photo") { - $objecttype = ACTIVITY_OBJ_IMAGE; + $objecttype = Activity::OBJ_IMAGE; } } @@ -549,7 +550,7 @@ function item_post(App $a) { } if (!strlen($verb)) { - $verb = ACTIVITY_POST; + $verb = Activity::POST; } if ($network == "") { @@ -761,7 +762,7 @@ function item_post(App $a) { 'source_name' => $datarray['author-name'], 'source_link' => $datarray['author-link'], 'source_photo' => $datarray['author-avatar'], - 'verb' => ACTIVITY_POST, + 'verb' => Activity::POST, 'otype' => 'item', 'parent' => $toplevel_item_id, 'parent_uri' => $toplevel_item['uri'] @@ -781,7 +782,7 @@ function item_post(App $a) { 'source_name' => $datarray['author-name'], 'source_link' => $datarray['author-link'], 'source_photo' => $datarray['author-avatar'], - 'verb' => ACTIVITY_POST, + 'verb' => Activity::POST, 'otype' => 'item' ]); } diff --git a/mod/photos.php b/mod/photos.php index d89cd04b0..c1195284c 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -25,6 +25,7 @@ use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; +use Friendica\Protocol\Activity; use Friendica\Util\ACLFormatter; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; @@ -566,24 +567,24 @@ function photos_post(App $a) $arr['deny_cid'] = $photo['deny_cid']; $arr['deny_gid'] = $photo['deny_gid']; $arr['visible'] = 1; - $arr['verb'] = ACTIVITY_TAG; + $arr['verb'] = Activity::TAG; $arr['gravity'] = GRAVITY_PARENT; - $arr['object-type'] = ACTIVITY_OBJ_PERSON; - $arr['target-type'] = ACTIVITY_OBJ_IMAGE; + $arr['object-type'] = Activity::OBJ_PERSON; + $arr['target-type'] = Activity::OBJ_IMAGE; $arr['tag'] = $tagged[4]; $arr['inform'] = $tagged[2]; $arr['origin'] = 1; $arr['body'] = L10n::t('%1$s was tagged in %2$s by %3$s', '[url=' . $tagged[1] . ']' . $tagged[0] . '[/url]', '[url=' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ']' . L10n::t('a photo') . '[/url]', '[url=' . $owner_record['url'] . ']' . $owner_record['name'] . '[/url]') ; $arr['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ']' . '[img]' . System::baseUrl() . "/photo/" . $photo['resource-id'] . '-' . $best . '.' . $ext . '[/img][/url]' . "\n" ; - $arr['object'] = '' . ACTIVITY_OBJ_PERSON . '' . $tagged[0] . '' . $tagged[1] . '/' . $tagged[0] . ''; + $arr['object'] = '' . Activity::OBJ_PERSON . '' . $tagged[0] . '' . $tagged[1] . '/' . $tagged[0] . ''; $arr['object'] .= '' . XML::escape('' . "\n"); if ($tagged[3]) { $arr['object'] .= XML::escape('' . "\n"); } $arr['object'] .= '' . "\n"; - $arr['target'] = '' . ACTIVITY_OBJ_IMAGE . '' . $photo['desc'] . '' + $arr['target'] = '' . Activity::OBJ_IMAGE . '' . $photo['desc'] . '' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ''; $arr['target'] .= '' . XML::escape('' . "\n" . '') . ''; @@ -1444,11 +1445,11 @@ function photos_content(App $a) $template = $tpl; $sparkle = ''; - /** @var \Friendica\Protocol\Activity $activity */ - $activity = BaseObject::getClass(\Friendica\Protocol\Activity::class); + /** @var Activity $activity */ + $activity = BaseObject::getClass(Activity::class); - if (($activity->match($item['verb'], ACTIVITY_LIKE) || - $activity->match($item['verb'], ACTIVITY_DISLIKE)) && + if (($activity->match($item['verb'], Activity::LIKE) || + $activity->match($item['verb'], Activity::DISLIKE)) && ($item['id'] != $item['parent'])) { continue; } diff --git a/mod/poke.php b/mod/poke.php index e8ddf86cd..d667d1448 100644 --- a/mod/poke.php +++ b/mod/poke.php @@ -21,6 +21,7 @@ use Friendica\Core\Renderer; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Item; +use Friendica\Protocol\Activity; use Friendica\Util\Strings; use Friendica\Util\XML; @@ -44,7 +45,7 @@ function poke_init(App $a) return; } - $activity = ACTIVITY_POKE . '#' . urlencode($verbs[$verb][0]); + $activity = Activity::POKE . '#' . urlencode($verbs[$verb][0]); $contact_id = intval($_GET['cid']); if (!$contact_id) { @@ -117,12 +118,12 @@ function poke_init(App $a) $arr['visible'] = 1; $arr['verb'] = $activity; $arr['private'] = $private; - $arr['object-type'] = ACTIVITY_OBJ_PERSON; + $arr['object-type'] = Activity::OBJ_PERSON; $arr['origin'] = 1; $arr['body'] = '[url=' . $poster['url'] . ']' . $poster['name'] . '[/url]' . ' ' . L10n::t($verbs[$verb][0]) . ' ' . '[url=' . $target['url'] . ']' . $target['name'] . '[/url]'; - $arr['object'] = '' . ACTIVITY_OBJ_PERSON . '' . $target['name'] . '' . $target['url'] . ''; + $arr['object'] = '' . Activity::OBJ_PERSON . '' . $target['name'] . '' . $target['url'] . ''; $arr['object'] .= '' . XML::escape('' . "\n"); $arr['object'] .= XML::escape('' . "\n"); diff --git a/mod/salmon.php b/mod/salmon.php index 67e467a73..e59931539 100644 --- a/mod/salmon.php +++ b/mod/salmon.php @@ -9,6 +9,7 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Contact; +use Friendica\Protocol\Activity\Namespaces; use Friendica\Protocol\OStatus; use Friendica\Protocol\Salmon; use Friendica\Util\Crypto; @@ -36,7 +37,7 @@ function salmon_post(App $a, $xml = '') { // parse the xml - $dom = simplexml_load_string($xml,'SimpleXMLElement',0,NAMESPACE_SALMON_ME); + $dom = simplexml_load_string($xml,'SimpleXMLElement',0, Namespaces::SALMON_ME); $base = null; diff --git a/mod/subthread.php b/mod/subthread.php index 0399ac0ce..58bf26534 100644 --- a/mod/subthread.php +++ b/mod/subthread.php @@ -10,6 +10,7 @@ use Friendica\Core\Session; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Item; +use Friendica\Protocol\Activity; use Friendica\Util\Security; use Friendica\Util\Strings; use Friendica\Util\XML; @@ -20,7 +21,7 @@ function subthread_content(App $a) { return; } - $activity = ACTIVITY_FOLLOW; + $activity = Activity::FOLLOW; $item_id = (($a->argc > 1) ? Strings::escapeTags(trim($a->argv[1])) : 0); @@ -87,7 +88,7 @@ function subthread_content(App $a) { $uri = Item::newURI($owner_uid); $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status')); - $objtype = (($item['resource-id']) ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ); + $objtype = (($item['resource-id']) ? Activity::OBJ_IMAGE : Activity::OBJ_NOTE ); $link = XML::escape('' . "\n"); $body = $item['body']; diff --git a/mod/tagger.php b/mod/tagger.php index bc8b71297..22359c64e 100644 --- a/mod/tagger.php +++ b/mod/tagger.php @@ -11,6 +11,7 @@ use Friendica\Core\Session; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\Model\Item; +use Friendica\Protocol\Activity; use Friendica\Util\Strings; use Friendica\Util\XML; use Friendica\Worker\Delivery; @@ -68,7 +69,7 @@ function tagger_content(App $a) { $uri = Item::newURI($owner_uid); $xterm = XML::escape($term); $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status')); - $targettype = (($item['resource-id']) ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ); + $targettype = (($item['resource-id']) ? Activity::OBJ_IMAGE : Activity::OBJ_NOTE ); $href = System::baseUrl() . '/display/' . $item['guid']; $link = XML::escape('' . "\n"); @@ -87,7 +88,7 @@ function tagger_content(App $a) { EOT; $tagid = System::baseUrl() . '/search?tag=' . $xterm; - $objtype = ACTIVITY_OBJ_TAGTERM; + $objtype = Activity::OBJ_TAGTERM; $obj = <<< EOT @@ -130,7 +131,7 @@ EOT; $plink = '[url=' . $item['plink'] . ']' . $post_type . '[/url]'; $arr['body'] = sprintf( $bodyverb, $ulink, $alink, $plink, $termlink ); - $arr['verb'] = ACTIVITY_TAG; + $arr['verb'] = Activity::TAG; $arr['target-type'] = $targettype; $arr['target'] = $target; $arr['object-type'] = $objtype; diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php index 75f5d506e..818752158 100644 --- a/src/Content/Text/BBCode.php +++ b/src/Content/Text/BBCode.php @@ -24,6 +24,7 @@ use Friendica\Model\Event; use Friendica\Model\Photo; use Friendica\Network\Probe; use Friendica\Object\Image; +use Friendica\Protocol\Activity; use Friendica\Util\Map; use Friendica\Util\Network; use Friendica\Util\ParseUrl; @@ -276,7 +277,7 @@ class BBCode extends BaseObject if (preg_match_all("(\[url=(.*?)\]\s*\[img\](.*?)\[\/img\]\s*\[\/url\])ism", $body, $pictures, PREG_SET_ORDER)) { if ((count($pictures) == 1) && !$has_title) { - if (!empty($item['object-type']) && ($item['object-type'] == ACTIVITY_OBJ_IMAGE)) { + if (!empty($item['object-type']) && ($item['object-type'] == Activity::OBJ_IMAGE)) { // Replace the preview picture with the real picture $url = str_replace('-1.', '-0.', $pictures[0][2]); $data = ['url' => $url, 'type' => 'photo']; diff --git a/src/Core/NotificationsManager.php b/src/Core/NotificationsManager.php index 3c8367c91..cf2dd9e36 100644 --- a/src/Core/NotificationsManager.php +++ b/src/Core/NotificationsManager.php @@ -12,6 +12,7 @@ use Friendica\Content\Text\HTML; use Friendica\Database\DBA; use Friendica\Model\Contact; use Friendica\Model\Item; +use Friendica\Protocol\Activity; use Friendica\Util\DateTimeFormat; use Friendica\Util\Proxy as ProxyUtils; use Friendica\Util\Temporal; @@ -250,7 +251,7 @@ class NotificationsManager extends BaseObject // Transform the different types of notification in an usable array switch ($it['verb']) { - case ACTIVITY_LIKE: + case Activity::LIKE: $notif = [ 'label' => 'like', 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], @@ -263,7 +264,7 @@ class NotificationsManager extends BaseObject ]; break; - case ACTIVITY_DISLIKE: + case Activity::DISLIKE: $notif = [ 'label' => 'dislike', 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], @@ -276,7 +277,7 @@ class NotificationsManager extends BaseObject ]; break; - case ACTIVITY_ATTEND: + case Activity::ATTEND: $notif = [ 'label' => 'attend', 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], @@ -289,7 +290,7 @@ class NotificationsManager extends BaseObject ]; break; - case ACTIVITY_ATTENDNO: + case Activity::ATTENDNO: $notif = [ 'label' => 'attendno', 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], @@ -302,7 +303,7 @@ class NotificationsManager extends BaseObject ]; break; - case ACTIVITY_ATTENDMAYBE: + case Activity::ATTENDMAYBE: $notif = [ 'label' => 'attendmaybe', 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], @@ -315,7 +316,7 @@ class NotificationsManager extends BaseObject ]; break; - case ACTIVITY_FRIEND: + case Activity::FRIEND: if (!isset($it['object'])) { $notif = [ 'label' => 'friend', diff --git a/src/Model/Contact.php b/src/Model/Contact.php index 3033bb90b..5dbe90ba9 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -18,6 +18,7 @@ use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\Network\Probe; use Friendica\Object\Image; +use Friendica\Protocol\Activity; use Friendica\Protocol\ActivityPub; use Friendica\Protocol\DFRN; use Friendica\Protocol\Diaspora; @@ -828,7 +829,7 @@ class Contact extends BaseObject } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) { // create an unfollow slap $item = []; - $item['verb'] = NAMESPACE_OSTATUS . "/unfollow"; + $item['verb'] = Activity\Namespaces::OSTATUS . "/unfollow"; $item['follow'] = $contact["url"]; $item['body'] = ''; $item['title'] = ''; @@ -2366,7 +2367,7 @@ class Contact extends BaseObject if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) { // create a follow slap $item = []; - $item['verb'] = ACTIVITY_FOLLOW; + $item['verb'] = Activity::FOLLOW; $item['follow'] = $contact["url"]; $item['body'] = ''; $item['title'] = ''; @@ -2568,7 +2569,7 @@ class Contact extends BaseObject 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')), 'source_link' => $contact_record['url'], 'source_photo' => $contact_record['photo'], - 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW), + 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW), 'otype' => 'intro' ]); } diff --git a/src/Model/Event.php b/src/Model/Event.php index cbd245a23..ef1096c8e 100644 --- a/src/Model/Event.php +++ b/src/Model/Event.php @@ -14,6 +14,7 @@ use Friendica\Core\PConfig; use Friendica\Core\Renderer; use Friendica\Core\System; use Friendica\Database\DBA; +use Friendica\Protocol\Activity; use Friendica\Util\DateTimeFormat; use Friendica\Util\Map; use Friendica\Util\Strings; @@ -303,7 +304,7 @@ class Event extends BaseObject $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]); if (DBA::isResult($item)) { - $object = '' . XML::escape(ACTIVITY_OBJ_EVENT) . '' . XML::escape($event['uri']) . ''; + $object = '' . XML::escape(Activity::OBJ_EVENT) . '' . XML::escape($event['uri']) . ''; $object .= '' . XML::escape(self::getBBCode($event)) . ''; $object .= '' . "\n"; @@ -350,13 +351,13 @@ class Event extends BaseObject $item_arr['deny_gid'] = $event['deny_gid']; $item_arr['private'] = $private; $item_arr['visible'] = 1; - $item_arr['verb'] = ACTIVITY_POST; - $item_arr['object-type'] = ACTIVITY_OBJ_EVENT; + $item_arr['verb'] = Activity::POST; + $item_arr['object-type'] = Activity::OBJ_EVENT; $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0; $item_arr['body'] = self::getBBCode($event); $item_arr['event-id'] = $event['id']; - $item_arr['object'] = '' . XML::escape(ACTIVITY_OBJ_EVENT) . '' . XML::escape($event['uri']) . ''; + $item_arr['object'] = '' . XML::escape(Activity::OBJ_EVENT) . '' . XML::escape($event['uri']) . ''; $item_arr['object'] .= '' . XML::escape(self::getBBCode($event)) . ''; $item_arr['object'] .= '' . "\n"; diff --git a/src/Model/Item.php b/src/Model/Item.php index 2c544a263..6a37a1cf8 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -97,7 +97,11 @@ class Item extends BaseObject // Never reorder or remove entries from this list. Just add new ones at the end, if needed. // The item-activity table only stores the index and needs this array to know the matching activity. - const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE, ACTIVITY_FOLLOW, ACTIVITY2_ANNOUNCE]; + const ACTIVITIES = [ + Activity::LIKE, Activity::DISLIKE, + Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE, + Activity::FOLLOW, + Activity::ANNOUNCE]; private static $legacy_mode = null; @@ -210,9 +214,9 @@ class Item extends BaseObject $row['object'] = ''; } if (array_key_exists('object-type', $row)) { - $row['object-type'] = ACTIVITY_OBJ_NOTE; + $row['object-type'] = Activity::OBJ_NOTE; } - } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) { + } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) { // Posts don't have an object or target - but having tags or files. // We safe some performance by building tag and file strings only here. // We remove object and target since they aren't used for this type. @@ -224,7 +228,7 @@ class Item extends BaseObject } } - if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) { + if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) { // Build the tag string out of the term entries if (array_key_exists('tag', $row) && empty($row['tag'])) { $row['tag'] = Term::tagTextFromItemId($row['internal-iid']); @@ -1153,14 +1157,14 @@ class Item extends BaseObject private static function deleteTagsFromItem($item) { - if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) { + if (($item["verb"] != Activity::TAG) || ($item["object-type"] != Activity::OBJ_TAGTERM)) { return; } $xo = XML::parseString($item["object"], false); $xt = XML::parseString($item["target"], false); - if ($xt->type != ACTIVITY_OBJ_NOTE) { + if ($xt->type != Activity::OBJ_NOTE) { return; } @@ -1366,9 +1370,9 @@ class Item extends BaseObject $item['gravity'] = intval($item['gravity']); } elseif ($item['parent-uri'] === $item['uri']) { $item['gravity'] = GRAVITY_PARENT; - } elseif ($activity->match($item['verb'], ACTIVITY_POST)) { + } elseif ($activity->match($item['verb'], Activity::POST)) { $item['gravity'] = GRAVITY_COMMENT; - } elseif ($activity->match($item['verb'], ACTIVITY_FOLLOW)) { + } elseif ($activity->match($item['verb'], Activity::FOLLOW)) { $item['gravity'] = GRAVITY_ACTIVITY; } else { $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen @@ -1564,14 +1568,14 @@ class Item extends BaseObject return 0; } - if ($item['verb'] == ACTIVITY_FOLLOW) { + if ($item['verb'] == Activity::FOLLOW) { if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) { // Our own follow request can be relayed to us. We don't store it to avoid notification chaos. Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG); return 0; } - $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => $item['uid'], + $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'], 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']]; if (self::exists($condition)) { // It happens that we receive multiple follow requests by the same author - we only store one. @@ -1678,7 +1682,7 @@ class Item extends BaseObject } } - if (stristr($item['verb'], ACTIVITY_POKE)) { + if (stristr($item['verb'], Activity::POKE)) { $notify_type = Delivery::POKE; } @@ -2691,7 +2695,7 @@ class Item extends BaseObject } // Only forward posts - if ($datarray["verb"] != ACTIVITY_POST) { + if ($datarray["verb"] != Activity::POST) { Logger::log('No post', Logger::DEBUG); return false; } @@ -3044,23 +3048,23 @@ class Item extends BaseObject switch ($verb) { case 'like': case 'unlike': - $activity = ACTIVITY_LIKE; + $activity = Activity::LIKE; break; case 'dislike': case 'undislike': - $activity = ACTIVITY_DISLIKE; + $activity = Activity::DISLIKE; break; case 'attendyes': case 'unattendyes': - $activity = ACTIVITY_ATTEND; + $activity = Activity::ATTEND; break; case 'attendno': case 'unattendno': - $activity = ACTIVITY_ATTENDNO; + $activity = Activity::ATTENDNO; break; case 'attendmaybe': case 'unattendmaybe': - $activity = ACTIVITY_ATTENDMAYBE; + $activity = Activity::ATTENDMAYBE; break; default: Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id); @@ -3068,7 +3072,7 @@ class Item extends BaseObject } // Enable activity toggling instead of on/off - $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE; + $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE; Logger::log('like: verb ' . $verb . ' item ' . $item_id); @@ -3122,7 +3126,7 @@ class Item extends BaseObject // event participation are essentially radio toggles. If you make a subsequent choice, // we need to eradicate your first choice. if ($event_verb_flag) { - $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE]; + $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE]; // Translate to the index based activity index $activities = []; @@ -3152,7 +3156,7 @@ class Item extends BaseObject return true; } - $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE; + $objtype = $item['resource-id'] ? Activity::OBJ_IMAGE : Activity::OBJ_NOTE; $new_item = [ 'guid' => System::createUUID(), @@ -3318,7 +3322,7 @@ class Item extends BaseObject return L10n::t('event'); } elseif (!empty($item['resource-id'])) { return L10n::t('photo'); - } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) { + } elseif (!empty($item['verb']) && $item['verb'] !== Activity::POST) { return L10n::t('activity'); } elseif ($item['id'] != $item['parent']) { return L10n::t('comment'); @@ -3432,7 +3436,7 @@ class Item extends BaseObject // In order to provide theme developers more possibilities, event items // are treated differently. - if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) { + if ($item['object-type'] === Activity::OBJ_EVENT && isset($item['event-id'])) { $ev = Event::getItemHTML($item); return $ev; } diff --git a/src/Model/Mail.php b/src/Model/Mail.php index 96a549375..e77d147ca 100644 --- a/src/Model/Mail.php +++ b/src/Model/Mail.php @@ -13,6 +13,7 @@ use Friendica\Model\Item; use Friendica\Model\Photo; use Friendica\Database\DBA; use Friendica\Network\Probe; +use Friendica\Protocol\Activity; use Friendica\Util\DateTimeFormat; use Friendica\Worker\Delivery; @@ -80,7 +81,7 @@ class Mail 'source_name' => $msg['from-name'], 'source_link' => $msg['from-url'], 'source_photo' => $msg['from-photo'], - 'verb' => ACTIVITY_POST, + 'verb' => Activity::POST, 'otype' => 'mail' ]; diff --git a/src/Model/Profile.php b/src/Model/Profile.php index de3290389..eb274a640 100644 --- a/src/Model/Profile.php +++ b/src/Model/Profile.php @@ -23,6 +23,7 @@ use Friendica\Core\System; use Friendica\Core\Theme; use Friendica\Core\Worker; use Friendica\Database\DBA; +use Friendica\Protocol\Activity; use Friendica\Protocol\Diaspora; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; @@ -692,7 +693,7 @@ class Profile while ($rr = DBA::fetch($s)) { $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(), - 'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)], + 'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)], 'visible' => true, 'deleted' => false]; if (!Item::exists($condition)) { continue; diff --git a/src/Module/Xrd.php b/src/Module/Xrd.php index 5e108c3b5..0ff592bfe 100644 --- a/src/Module/Xrd.php +++ b/src/Module/Xrd.php @@ -9,6 +9,7 @@ use Friendica\Core\Renderer; use Friendica\Core\System; use Friendica\Model\User; use Friendica\Model\Photo; +use Friendica\Protocol\Activity\Namespaces; use Friendica\Protocol\Salmon; use Friendica\Util\Strings; @@ -95,11 +96,11 @@ class Xrd extends BaseModule ], 'links' => [ [ - 'rel' => NAMESPACE_DFRN, + 'rel' => Namespaces::DFRN , 'href' => $owner['url'], ], [ - 'rel' => NAMESPACE_FEED, + 'rel' => Namespaces::FEED, 'type' => 'application/atom+xml', 'href' => $owner['poll'], ], @@ -119,7 +120,7 @@ class Xrd extends BaseModule 'href' => $baseURL . '/hcard/' . $owner['nickname'], ], [ - 'rel' => NAMESPACE_POCO, + 'rel' => Namespaces::POCO, 'href' => $owner['poco'], ], [ diff --git a/src/Network/Probe.php b/src/Network/Probe.php index 946a822da..587b8a4d4 100644 --- a/src/Network/Probe.php +++ b/src/Network/Probe.php @@ -18,6 +18,7 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Profile; +use Friendica\Protocol\Activity\Namespaces; use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Email; use Friendica\Protocol\Feed; @@ -200,10 +201,10 @@ class Probe Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA); if (!empty($links) && is_array($links)) { foreach ($links as $link) { - if ($link['@attributes']['rel'] === NAMESPACE_DFRN) { + if ($link['@attributes']['rel'] === Namespaces::DFRN) { $profile_link = $link['@attributes']['href']; } - if (($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB) && ($profile_link == "")) { + if (($link['@attributes']['rel'] === Namespaces::OSTATUSSUB) && ($profile_link == "")) { $profile_link = 'stat:'.$link['@attributes']['template']; } if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') { @@ -492,7 +493,7 @@ class Probe $has_key = false; foreach ($webfinger['links'] as $link) { - if ($link['rel'] == NAMESPACE_OSTATUSSUB) { + if ($link['rel'] == Namespaces::OSTATUSSUB) { $is_ostatus = true; } if ($link['rel'] == 'magic-public-key') { @@ -955,15 +956,15 @@ class Probe // The array is reversed to take into account the order of preference for same-rel links // See: https://tools.ietf.org/html/rfc7033#section-4.4.4 foreach (array_reverse($webfinger["links"]) as $link) { - if (($link["rel"] == NAMESPACE_DFRN) && !empty($link["href"])) { + if (($link["rel"] == Namespaces::DFRN) && !empty($link["href"])) { $data["network"] = Protocol::DFRN; - } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == Namespaces::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) { $data["url"] = $link["href"]; } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) { $hcard_url = $link["href"]; - } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) { + } elseif (($link["rel"] == Namespaces::POCO) && !empty($link["href"])) { $data["poco"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) { $data["photo"] = $link["href"]; @@ -1171,9 +1172,9 @@ class Probe $data["guid"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) { $data["url"] = $link["href"]; - } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == Namespaces::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; - } elseif (($link["rel"] == NAMESPACE_POCO) && !empty($link["href"])) { + } elseif (($link["rel"] == Namespaces::POCO) && !empty($link["href"])) { $data["poco"] = $link["href"]; } elseif (($link["rel"] == "salmon") && !empty($link["href"])) { $data["notify"] = $link["href"]; @@ -1273,7 +1274,7 @@ class Probe $data["url"] = $link["href"]; } elseif (($link["rel"] == "salmon") && !empty($link["href"])) { $data["notify"] = $link["href"]; - } elseif (($link["rel"] == NAMESPACE_FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == Namespaces::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) { $pubkey = $link["href"]; diff --git a/src/Object/Post.php b/src/Object/Post.php index 7dd530801..9f392cb82 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -240,7 +240,7 @@ class Post extends BaseObject $isevent = false; $attend = []; - if ($item['object-type'] === ACTIVITY_OBJ_EVENT) { + if ($item['object-type'] === Activity::OBJ_EVENT) { $response_verbs[] = 'attendyes'; $response_verbs[] = 'attendno'; $response_verbs[] = 'attendmaybe'; @@ -531,8 +531,8 @@ class Post extends BaseObject */ if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) { return false; - } elseif ($activity->match($item->getDataValue('verb'), ACTIVITY_LIKE) || - $activity->match($item->getDataValue('verb'), ACTIVITY_DISLIKE)) { + } elseif ($activity->match($item->getDataValue('verb'), Activity::LIKE) || + $activity->match($item->getDataValue('verb'), Activity::DISLIKE)) { return false; } diff --git a/src/Object/Thread.php b/src/Object/Thread.php index 89ed5a940..4eda1f8f7 100644 --- a/src/Object/Thread.php +++ b/src/Object/Thread.php @@ -7,6 +7,7 @@ namespace Friendica\Object; use Friendica\BaseObject; use Friendica\Core\Logger; use Friendica\Core\Protocol; +use Friendica\Protocol\Activity; use Friendica\Util\Security; /** @@ -154,7 +155,7 @@ class Thread extends BaseObject return false; } - if ($item->getDataValue('verb') === ACTIVITY_LIKE || $item->getDataValue('verb') === ACTIVITY_DISLIKE) { + if ($item->getDataValue('verb') === Activity::LIKE || $item->getDataValue('verb') === Activity::DISLIKE) { Logger::log('[WARN] Conversation::addThread : Thread is a (dis)like ('. $item->getId() .').', Logger::DEBUG); return false; } diff --git a/src/Protocol/Activity.php b/src/Protocol/Activity.php index 64253b065..ddbfce1b7 100644 --- a/src/Protocol/Activity.php +++ b/src/Protocol/Activity.php @@ -2,11 +2,85 @@ namespace Friendica\Protocol; +use Friendica\Protocol\Activity\Namespaces; + /** - * Base class for the Activity namespace + * Base class for the Activity constants and match method */ final class Activity { + const LIKE = Namespaces::ACTIVITY_SCHEMA . 'like'; + + const DISLIKE = Namespaces::DFRN . '/dislike'; + const ATTEND = Namespaces::ZOT . '/activity/attendyes'; + const ATTENDNO = Namespaces::ZOT . '/activity/attendno'; + const ATTENDMAYBE = Namespaces::ZOT . '/activity/attendmaybe'; + const OBJ_HEART = Namespaces::DFRN . '/heart'; + + const FRIEND = Namespaces::ACTIVITY_SCHEMA . 'make-friend'; + const REQ_FRIEND = Namespaces::ACTIVITY_SCHEMA . 'request-friend'; + const UNFRIEND = Namespaces::ACTIVITY_SCHEMA . 'remove-friend'; + const FOLLOW = Namespaces::ACTIVITY_SCHEMA . 'follow'; + const UNFOLLOW = Namespaces::ACTIVITY_SCHEMA . 'stop-following'; + const JOIN = Namespaces::ACTIVITY_SCHEMA . 'join'; + const POST = Namespaces::ACTIVITY_SCHEMA . 'post'; + const UPDATE = Namespaces::ACTIVITY_SCHEMA . 'update'; + const TAG = Namespaces::ACTIVITY_SCHEMA . 'tag'; + const FAVORITE = Namespaces::ACTIVITY_SCHEMA . 'favorite'; + const UNFAVORITE = Namespaces::ACTIVITY_SCHEMA . 'unfavorite'; + const SHARE = Namespaces::ACTIVITY_SCHEMA . 'share'; + const DELETE = Namespaces::ACTIVITY_SCHEMA . 'delete'; + const ANNOUNCE = Namespaces::ACTIVITY2 . 'Announce'; + + const POKE = Namespaces::ZOT . '/activity/poke'; + + const OBJ_BOOKMARK = Namespaces::ACTIVITY_SCHEMA . 'bookmark'; + const OBJ_COMMENT = Namespaces::ACTIVITY_SCHEMA . 'comment'; + const OBJ_NOTE = Namespaces::ACTIVITY_SCHEMA . 'note'; + const OBJ_PERSON = Namespaces::ACTIVITY_SCHEMA . 'person'; + const OBJ_IMAGE = Namespaces::ACTIVITY_SCHEMA . 'image'; + const OBJ_PHOTO = Namespaces::ACTIVITY_SCHEMA . 'photo'; + const OBJ_VIDEO = Namespaces::ACTIVITY_SCHEMA . 'video'; + const OBJ_P_PHOTO = Namespaces::ACTIVITY_SCHEMA . 'profile-photo'; + const OBJ_ALBUM = Namespaces::ACTIVITY_SCHEMA . 'photo-album'; + const OBJ_EVENT = Namespaces::ACTIVITY_SCHEMA . 'event'; + const OBJ_GROUP = Namespaces::ACTIVITY_SCHEMA . 'group'; + const OBJ_TAGTERM = Namespaces::DFRN . '/tagterm'; + const OBJ_PROFILE = Namespaces::DFRN . '/profile'; + + const OBJ_QUESTION = 'http://activityschema.org/object/question'; + + /** + * likes (etc.) can apply to other things besides posts. Check if they are post children, + * in which case we handle them specially + * + * Hidden activities, which doesn't need to be shown + */ + const HIDDEN_ACTIVITIES = [ + Activity::LIKE, Activity::DISLIKE, + Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE, + Activity::FOLLOW, + Activity::ANNOUNCE, + ]; + + /** + * Checks if the given activity is a hidden activity + * + * @param string $activity The current activity + * + * @return bool True, if the activity is hidden + */ + public function isHidden(string $activity) + { + foreach (self::HIDDEN_ACTIVITIES as $hiddenActivity) { + if ($this->match($activity, $hiddenActivity)) { + return true; + } + } + + return false; + } + /** * Compare activity uri. Knows about activity namespace. * @@ -15,9 +89,10 @@ final class Activity * * @return boolean */ - public function match(string $haystack, string $needle) { + public function match(string $haystack, string $needle) + { return (($haystack === $needle) || ((basename($needle) === $haystack) && - strstr($needle, NAMESPACE_ACTIVITY_SCHEMA))); + strstr($needle, Namespaces::ACTIVITY_SCHEMA))); } } diff --git a/src/Protocol/Activity/Namespaces.php b/src/Protocol/Activity/Namespaces.php new file mode 100644 index 000000000..92955c3ad --- /dev/null +++ b/src/Protocol/Activity/Namespaces.php @@ -0,0 +1,27 @@ + $activity['reply-to-id']])) { @@ -254,7 +255,7 @@ class Processor $item['verb'] = $verb; $item['thr-parent'] = $activity['object_id']; $item['gravity'] = GRAVITY_ACTIVITY; - $item['object-type'] = ACTIVITY_OBJ_NOTE; + $item['object-type'] = Activity::OBJ_NOTE; $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? ''; diff --git a/src/Protocol/ActivityPub/Receiver.php b/src/Protocol/ActivityPub/Receiver.php index f23269615..1bc6f9041 100644 --- a/src/Protocol/ActivityPub/Receiver.php +++ b/src/Protocol/ActivityPub/Receiver.php @@ -12,6 +12,7 @@ use Friendica\Model\APContact; use Friendica\Model\Conversation; use Friendica\Model\Item; use Friendica\Model\User; +use Friendica\Protocol\Activity; use Friendica\Protocol\ActivityPub; use Friendica\Util\DateTimeFormat; use Friendica\Util\HTTPSignature; @@ -400,26 +401,26 @@ class Receiver $announce_object_data['object_id'] = $object_data['object_id']; $announce_object_data['object_type'] = $object_data['object_type']; - ActivityPub\Processor::createActivity($announce_object_data, ACTIVITY2_ANNOUNCE); + ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE); } } break; case 'as:Like': if (in_array($object_data['object_type'], self::CONTENT_TYPES)) { - ActivityPub\Processor::createActivity($object_data, ACTIVITY_LIKE); + ActivityPub\Processor::createActivity($object_data, Activity::LIKE); } break; case 'as:Dislike': if (in_array($object_data['object_type'], self::CONTENT_TYPES)) { - ActivityPub\Processor::createActivity($object_data, ACTIVITY_DISLIKE); + ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE); } break; case 'as:TentativeAccept': if (in_array($object_data['object_type'], self::CONTENT_TYPES)) { - ActivityPub\Processor::createActivity($object_data, ACTIVITY_ATTENDMAYBE); + ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE); } break; @@ -444,7 +445,7 @@ class Receiver ActivityPub\Processor::followUser($object_data); } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) { $object_data['reply-to-id'] = $object_data['object_id']; - ActivityPub\Processor::createActivity($object_data, ACTIVITY_FOLLOW); + ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW); } break; @@ -452,7 +453,7 @@ class Receiver if ($object_data['object_type'] == 'as:Follow') { ActivityPub\Processor::acceptFollowUser($object_data); } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) { - ActivityPub\Processor::createActivity($object_data, ACTIVITY_ATTEND); + ActivityPub\Processor::createActivity($object_data, Activity::ATTEND); } break; @@ -460,7 +461,7 @@ class Receiver if ($object_data['object_type'] == 'as:Follow') { ActivityPub\Processor::rejectFollowUser($object_data); } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) { - ActivityPub\Processor::createActivity($object_data, ACTIVITY_ATTENDNO); + ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO); } break; diff --git a/src/Protocol/ActivityPub/Transmitter.php b/src/Protocol/ActivityPub/Transmitter.php index d2581ff3f..531b4c662 100644 --- a/src/Protocol/ActivityPub/Transmitter.php +++ b/src/Protocol/ActivityPub/Transmitter.php @@ -10,6 +10,7 @@ use Friendica\Database\DBA; use Friendica\Core\Config; use Friendica\Core\Logger; use Friendica\Core\System; +use Friendica\Protocol\Activity; use Friendica\Util\HTTPSignature; use Friendica\Core\Protocol; use Friendica\Model\Conversation; @@ -761,25 +762,25 @@ class Transmitter if ($reshared) { $type = 'Announce'; - } elseif ($item['verb'] == ACTIVITY_POST) { + } elseif ($item['verb'] == Activity::POST) { if ($item['created'] == $item['edited']) { $type = 'Create'; } else { $type = 'Update'; } - } elseif ($item['verb'] == ACTIVITY_LIKE) { + } elseif ($item['verb'] == Activity::LIKE) { $type = 'Like'; - } elseif ($item['verb'] == ACTIVITY_DISLIKE) { + } elseif ($item['verb'] == Activity::DISLIKE) { $type = 'Dislike'; - } elseif ($item['verb'] == ACTIVITY_ATTEND) { + } elseif ($item['verb'] == Activity::ATTEND) { $type = 'Accept'; - } elseif ($item['verb'] == ACTIVITY_ATTENDNO) { + } elseif ($item['verb'] == Activity::ATTENDNO) { $type = 'Reject'; - } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) { + } elseif ($item['verb'] == Activity::ATTENDMAYBE) { $type = 'TentativeAccept'; - } elseif ($item['verb'] == ACTIVITY_FOLLOW) { + } elseif ($item['verb'] == Activity::FOLLOW) { $type = 'Follow'; - } elseif ($item['verb'] == ACTIVITY_TAG) { + } elseif ($item['verb'] == Activity::TAG) { $type = 'Add'; } else { $type = ''; @@ -1571,7 +1572,7 @@ class Transmitter $uid = $first_user['uid']; } - $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object, + $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object, 'author-id' => Contact::getPublicIdByUserId($uid)]; if (Item::exists($condition)) { Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG); diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index e1901011e..98f28a56a 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -34,6 +34,7 @@ use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; +use Friendica\Protocol\Activity\Namespaces; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; @@ -382,18 +383,18 @@ class DFRN $type = 'html'; if ($conversation) { - $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed'); + $root = $doc->createElementNS(Namespaces::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", NAMESPACE_THREAD); - $root->setAttribute("xmlns:at", NAMESPACE_TOMB); - $root->setAttribute("xmlns:media", NAMESPACE_MEDIA); - $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN); - $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY); - $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS); - $root->setAttribute("xmlns:poco", NAMESPACE_POCO); - $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS); - $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET); + $root->setAttribute("xmlns:thr", Namespaces::THREAD); + $root->setAttribute("xmlns:at", Namespaces::TOMB); + $root->setAttribute("xmlns:media", Namespaces::MEDIA); + $root->setAttribute("xmlns:dfrn", Namespaces::DFRN); + $root->setAttribute("xmlns:activity", Namespaces::ACTIVITY); + $root->setAttribute("xmlns:georss", Namespaces::GEORSS); + $root->setAttribute("xmlns:poco", Namespaces::POCO); + $root->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); + $root->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false); @@ -557,18 +558,18 @@ class DFRN $alternatelink = $owner['url']; } - $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed'); + $root = $doc->createElementNS(Namespaces::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", NAMESPACE_THREAD); - $root->setAttribute("xmlns:at", NAMESPACE_TOMB); - $root->setAttribute("xmlns:media", NAMESPACE_MEDIA); - $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN); - $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY); - $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS); - $root->setAttribute("xmlns:poco", NAMESPACE_POCO); - $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS); - $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET); + $root->setAttribute("xmlns:thr", Namespaces::THREAD); + $root->setAttribute("xmlns:at", Namespaces::TOMB); + $root->setAttribute("xmlns:media", Namespaces::MEDIA); + $root->setAttribute("xmlns:dfrn", Namespaces::DFRN); + $root->setAttribute("xmlns:activity", Namespaces::ACTIVITY); + $root->setAttribute("xmlns:georss", Namespaces::GEORSS); + $root->setAttribute("xmlns:poco", Namespaces::POCO); + $root->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); + $root->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]); XML::addElement($doc, $root, "title", $owner["name"]); @@ -941,18 +942,18 @@ class DFRN if (!$single) { $entry = $doc->createElement("entry"); } else { - $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry'); + $entry = $doc->createElementNS(Namespaces::ATOM1, 'entry'); $doc->appendChild($entry); - $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD); - $entry->setAttribute("xmlns:at", NAMESPACE_TOMB); - $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA); - $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN); - $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY); - $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS); - $entry->setAttribute("xmlns:poco", NAMESPACE_POCO); - $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS); - $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET); + $entry->setAttribute("xmlns:thr", Namespaces::THREAD); + $entry->setAttribute("xmlns:at", Namespaces::TOMB); + $entry->setAttribute("xmlns:media", Namespaces::MEDIA); + $entry->setAttribute("xmlns:dfrn", Namespaces::DFRN); + $entry->setAttribute("xmlns:activity", Namespaces::ACTIVITY); + $entry->setAttribute("xmlns:georss", Namespaces::GEORSS); + $entry->setAttribute("xmlns:poco", Namespaces::POCO); + $entry->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); + $entry->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); } if ($item['private']) { @@ -1079,9 +1080,9 @@ class DFRN if ($item['object-type'] != "") { XML::addElement($doc, $entry, "activity:object-type", $item['object-type']); } elseif ($item['id'] == $item['parent']) { - XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE); + XML::addElement($doc, $entry, "activity:object-type", Activity::OBJ_NOTE); } else { - XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT); + XML::addElement($doc, $entry, "activity:object-type", Activity::OBJ_COMMENT); } $actobj = self::createActivity($doc, "activity:object", $item['object']); @@ -1124,7 +1125,7 @@ class DFRN "link", "", ["rel" => "mentioned", - "ostatus:object-type" => ACTIVITY_OBJ_GROUP, + "ostatus:object-type" => Activity::OBJ_GROUP, "href" => $mention] ); } else { @@ -1134,7 +1135,7 @@ class DFRN "link", "", ["rel" => "mentioned", - "ostatus:object-type" => ACTIVITY_OBJ_PERSON, + "ostatus:object-type" => Activity::OBJ_PERSON, "href" => $mention] ); } @@ -1750,7 +1751,7 @@ class DFRN $obj_doc = new DOMDocument("1.0", "utf-8"); $obj_doc->formatOutput = true; - $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element); + $obj_element = $obj_doc->createElementNS( Namespaces::ATOM1, $element); $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue; XML::addElement($obj_doc, $obj_element, "type", $activity_type); @@ -1907,7 +1908,7 @@ class DFRN 'source_name' => $importer['name'], 'source_link' => $importer['url'], 'source_photo' => $importer['photo'], - 'verb' => ACTIVITY_REQ_FRIEND, + 'verb' => Activity::REQ_FRIEND, 'otype' => 'intro'] ); @@ -2117,7 +2118,7 @@ class DFRN } $xo = XML::parseString($item["object"], false); - if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) { + if (($xo->type == Activity::OBJ_PERSON) && ($xo->id)) { // somebody was poked/prodded. Was it me? $Blink = ''; foreach ($xo->link as $l) { @@ -2186,32 +2187,32 @@ class DFRN // Big question: Do we need these functions? They were part of the "consume_feed" function. // This function once was responsible for DFRN and OStatus. - if ($activity->match($item["verb"], ACTIVITY_FOLLOW)) { + if ($activity->match($item["verb"], Activity::FOLLOW)) { Logger::log("New follower"); Contact::addRelationship($importer, $contact, $item); return false; } - if ($activity->match($item["verb"], ACTIVITY_UNFOLLOW)) { + if ($activity->match($item["verb"], Activity::UNFOLLOW)) { Logger::log("Lost follower"); Contact::removeFollower($importer, $contact, $item); return false; } - if ($activity->match($item["verb"], ACTIVITY_REQ_FRIEND)) { + if ($activity->match($item["verb"], Activity::REQ_FRIEND)) { Logger::log("New friend request"); Contact::addRelationship($importer, $contact, $item, true); return false; } - if ($activity->match($item["verb"], ACTIVITY_UNFRIEND)) { + if ($activity->match($item["verb"], Activity::UNFRIEND)) { Logger::log("Lost sharer"); Contact::removeSharer($importer, $contact, $item); return false; } } else { - if (($item["verb"] == ACTIVITY_LIKE) - || ($item["verb"] == ACTIVITY_DISLIKE) - || ($item["verb"] == ACTIVITY_ATTEND) - || ($item["verb"] == ACTIVITY_ATTENDNO) - || ($item["verb"] == ACTIVITY_ATTENDMAYBE) + if (($item["verb"] == Activity::LIKE) + || ($item["verb"] == Activity::DISLIKE) + || ($item["verb"] == Activity::ATTEND) + || ($item["verb"] == Activity::ATTENDNO) + || ($item["verb"] == Activity::ATTENDMAYBE) ) { $is_like = true; $item["gravity"] = GRAVITY_ACTIVITY; @@ -2238,11 +2239,11 @@ class DFRN $is_like = false; } - if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) { + if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity::OBJ_TAGTERM)) { $xo = XML::parseString($item["object"], false); $xt = XML::parseString($item["target"], false); - if ($xt->type == ACTIVITY_OBJ_NOTE) { + if ($xt->type == Activity::OBJ_NOTE) { $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]); if (!DBA::isResult($item_tag)) { @@ -2517,7 +2518,7 @@ class DFRN // Now assign the rest of the values that depend on the type of the message if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) { if (!isset($item["object-type"])) { - $item["object-type"] = ACTIVITY_OBJ_COMMENT; + $item["object-type"] = Activity::OBJ_COMMENT; } if ($item["contact-id"] != $owner["contact-id"]) { @@ -2541,11 +2542,11 @@ class DFRN $item["wall"] = 1; } elseif ($entrytype == DFRN::TOP_LEVEL) { if (!isset($item["object-type"])) { - $item["object-type"] = ACTIVITY_OBJ_NOTE; + $item["object-type"] = Activity::OBJ_NOTE; } // Is it an event? - if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) { + if (($item["object-type"] == Activity::OBJ_EVENT) && !$owner_unknown) { Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG); $ev = Event::fromBBCode($item["body"]); if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) { @@ -2642,7 +2643,7 @@ class DFRN Item::distribute($posted_id); } - if (stristr($item["verb"], ACTIVITY_POKE)) { + if (stristr($item["verb"], Activity::POKE)) { $item['id'] = $posted_id; self::doPoke($item, $importer); } @@ -2731,16 +2732,16 @@ class DFRN @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace("atom", NAMESPACE_ATOM1); - $xpath->registerNamespace("thr", NAMESPACE_THREAD); - $xpath->registerNamespace("at", NAMESPACE_TOMB); - $xpath->registerNamespace("media", NAMESPACE_MEDIA); - $xpath->registerNamespace("dfrn", NAMESPACE_DFRN); - $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY); - $xpath->registerNamespace("georss", NAMESPACE_GEORSS); - $xpath->registerNamespace("poco", NAMESPACE_POCO); - $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS); - $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET); + $xpath->registerNamespace("atom", Namespaces::ATOM1); + $xpath->registerNamespace("thr", Namespaces::THREAD); + $xpath->registerNamespace("at", Namespaces::TOMB); + $xpath->registerNamespace("media", Namespaces::MEDIA); + $xpath->registerNamespace("dfrn", Namespaces::DFRN); + $xpath->registerNamespace("activity", Namespaces::ACTIVITY); + $xpath->registerNamespace("georss", Namespaces::GEORSS); + $xpath->registerNamespace("poco", Namespaces::POCO); + $xpath->registerNamespace("ostatus", Namespaces::OSTATUS); + $xpath->registerNamespace("statusnet", Namespaces::STATUSNET); $header = []; $header["uid"] = $importer["importer_uid"]; @@ -2865,7 +2866,7 @@ class DFRN if ($item['verb']) { return $item['verb']; } - return ACTIVITY_POST; + return Activity::POST; } private static function tgroupCheck($uid, $item) diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index aec3a283f..1e61a9ed7 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -32,6 +32,7 @@ use Friendica\Model\Mail; use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; +use Friendica\Protocol\Activity\Namespaces; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Map; @@ -465,7 +466,7 @@ class Diaspora } } - $base = $basedom->children(NAMESPACE_SALMON_ME); + $base = $basedom->children(Namespaces::SALMON_ME); // Not sure if this cleaning is needed $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data); @@ -577,7 +578,7 @@ class Diaspora $author_link = str_replace('acct:', '', $idom->author_id); } - $dom = $basedom->children(NAMESPACE_SALMON_ME); + $dom = $basedom->children(Namespaces::SALMON_ME); // figure out where in the DOM tree our data is hiding @@ -1845,7 +1846,7 @@ class Diaspora $datarray["guid"] = $guid; $datarray["uri"] = self::getUriFromGuid($author, $guid); - $datarray["verb"] = ACTIVITY_POST; + $datarray["verb"] = Activity::POST; $datarray["gravity"] = GRAVITY_COMMENT; if ($thr_uri != "") { @@ -1854,7 +1855,7 @@ class Diaspora $datarray["parent-uri"] = $parent_item["uri"]; } - $datarray["object-type"] = ACTIVITY_OBJ_COMMENT; + $datarray["object-type"] = Activity::OBJ_COMMENT; $datarray["protocol"] = Conversation::PARCEL_DIASPORA; $datarray["source"] = $xml; @@ -2062,9 +2063,9 @@ class Diaspora // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora // We would accept this anyhow. if ($positive == "true") { - $verb = ACTIVITY_LIKE; + $verb = Activity::LIKE; } else { - $verb = ACTIVITY_DISLIKE; + $verb = Activity::DISLIKE; } $datarray = []; @@ -2085,7 +2086,7 @@ class Diaspora $datarray["gravity"] = GRAVITY_ACTIVITY; $datarray["parent-uri"] = $parent_item["uri"]; - $datarray["object-type"] = ACTIVITY_OBJ_NOTE; + $datarray["object-type"] = Activity::OBJ_NOTE; $datarray["body"] = $verb; @@ -2684,9 +2685,9 @@ class Diaspora $datarray['uri'] = self::getUriFromGuid($author, $datarray['guid']); $datarray['parent-uri'] = $parent['uri']; - $datarray['verb'] = $datarray['body'] = ACTIVITY2_ANNOUNCE; + $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE; $datarray['gravity'] = GRAVITY_ACTIVITY; - $datarray['object-type'] = ACTIVITY_OBJ_NOTE; + $datarray['object-type'] = Activity::OBJ_NOTE; $datarray['protocol'] = $item['protocol']; @@ -2757,7 +2758,7 @@ class Diaspora $datarray["guid"] = $guid; $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid); - $datarray["verb"] = ACTIVITY_POST; + $datarray["verb"] = Activity::POST; $datarray["gravity"] = GRAVITY_PARENT; $datarray["protocol"] = Conversation::PARCEL_DIASPORA; @@ -2962,9 +2963,9 @@ class Diaspora XML::unescape($photo->remote_photo_name)."[/img]\n".$body; } - $datarray["object-type"] = ACTIVITY_OBJ_IMAGE; + $datarray["object-type"] = Activity::OBJ_IMAGE; } else { - $datarray["object-type"] = ACTIVITY_OBJ_NOTE; + $datarray["object-type"] = Activity::OBJ_NOTE; // Add OEmbed and other information to the body if (!self::isRedmatrix($contact["url"])) { @@ -2994,7 +2995,7 @@ class Diaspora $datarray["guid"] = $guid; $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid); - $datarray["verb"] = ACTIVITY_POST; + $datarray["verb"] = Activity::POST; $datarray["gravity"] = GRAVITY_PARENT; $datarray["protocol"] = Conversation::PARCEL_DIASPORA; @@ -3780,9 +3781,9 @@ class Diaspora $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment"); $positive = null; - if ($item['verb'] === ACTIVITY_LIKE) { + if ($item['verb'] === Activity::LIKE) { $positive = "true"; - } elseif ($item['verb'] === ACTIVITY_DISLIKE) { + } elseif ($item['verb'] === Activity::DISLIKE) { $positive = "false"; } @@ -3811,13 +3812,13 @@ class Diaspora } switch ($item['verb']) { - case ACTIVITY_ATTEND: + case Activity::ATTEND: $attend_answer = 'accepted'; break; - case ACTIVITY_ATTENDNO: + case Activity::ATTENDNO: $attend_answer = 'declined'; break; - case ACTIVITY_ATTENDMAYBE: + case Activity::ATTENDMAYBE: $attend_answer = 'tentative'; break; default: @@ -3913,13 +3914,13 @@ class Diaspora */ public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false) { - if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) { + if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) { $message = self::constructAttend($item, $owner); $type = "event_participation"; - } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) { + } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { $message = self::constructLike($item, $owner); $type = "like"; - } elseif (!in_array($item["verb"], [ACTIVITY_FOLLOW, ACTIVITY_TAG])) { + } elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) { $message = self::constructComment($item, $owner); $type = "comment"; } @@ -3948,7 +3949,7 @@ class Diaspora $message = ["author" => $item['signer'], "target_guid" => $signed_parts[0], "target_type" => $signed_parts[1]]; - } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) { + } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { $message = ["author" => $signed_parts[4], "guid" => $signed_parts[1], "parent_guid" => $signed_parts[3], @@ -3993,7 +3994,7 @@ class Diaspora { if ($item["deleted"]) { return self::sendRetraction($item, $owner, $contact, $public_batch, true); - } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) { + } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { $type = "like"; } else { $type = "comment"; @@ -4054,7 +4055,7 @@ class Diaspora if ($item['id'] == $item['parent']) { $target_type = "Post"; - } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) { + } elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { $target_type = "Like"; } else { $target_type = "Comment"; @@ -4320,7 +4321,7 @@ class Diaspora return false; } - if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) { + if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { return false; } diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index c678cf0ae..340c93c9e 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -14,6 +14,7 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Item; +use Friendica\Protocol\Activity\Namespaces; use Friendica\Util\Network; use Friendica\Util\XML; @@ -59,13 +60,13 @@ class Feed { $doc = new DOMDocument(); @$doc->loadXML(trim($xml)); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', NAMESPACE_ATOM1); + $xpath->registerNamespace('atom', Namespaces::ATOM1); $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/"); $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/"); $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/"); $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/"); - $xpath->registerNamespace('poco', NAMESPACE_POCO); + $xpath->registerNamespace('poco', Namespaces::POCO); $author = []; $entries = null; @@ -198,8 +199,8 @@ class Feed { $header["origin"] = 0; $header["gravity"] = GRAVITY_PARENT; $header["private"] = 2; - $header["verb"] = ACTIVITY_POST; - $header["object-type"] = ACTIVITY_OBJ_NOTE; + $header["verb"] = Activity::POST; + $header["object-type"] = Activity::OBJ_NOTE; $header["contact-id"] = $contact["id"]; @@ -420,7 +421,7 @@ class Feed { $item["title"] = ""; $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]); $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]); - $item["object-type"] = ACTIVITY_OBJ_BOOKMARK; + $item["object-type"] = Activity::OBJ_BOOKMARK; unset($item["attach"]); } else { if (!empty($summary)) { diff --git a/src/Protocol/OStatus.php b/src/Protocol/OStatus.php index afd406f97..1e287b2ce 100644 --- a/src/Protocol/OStatus.php +++ b/src/Protocol/OStatus.php @@ -25,6 +25,7 @@ use Friendica\Model\Item; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; +use Friendica\Protocol\Activity\Namespaces; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\Proxy as ProxyUtils; @@ -261,14 +262,14 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', NAMESPACE_ATOM1); - $xpath->registerNamespace('thr', NAMESPACE_THREAD); - $xpath->registerNamespace('georss', NAMESPACE_GEORSS); - $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY); - $xpath->registerNamespace('media', NAMESPACE_MEDIA); - $xpath->registerNamespace('poco', NAMESPACE_POCO); - $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS); - $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET); + $xpath->registerNamespace('atom', Namespaces::ATOM1); + $xpath->registerNamespace('thr', Namespaces::THREAD); + $xpath->registerNamespace('georss', Namespaces::GEORSS); + $xpath->registerNamespace('activity', Namespaces::ACTIVITY); + $xpath->registerNamespace('media', Namespaces::MEDIA); + $xpath->registerNamespace('poco', Namespaces::POCO); + $xpath->registerNamespace('ostatus', Namespaces::OSTATUS); + $xpath->registerNamespace('statusnet', Namespaces::STATUSNET); $contact = ["id" => 0]; @@ -342,14 +343,14 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', NAMESPACE_ATOM1); - $xpath->registerNamespace('thr', NAMESPACE_THREAD); - $xpath->registerNamespace('georss', NAMESPACE_GEORSS); - $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY); - $xpath->registerNamespace('media', NAMESPACE_MEDIA); - $xpath->registerNamespace('poco', NAMESPACE_POCO); - $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS); - $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET); + $xpath->registerNamespace('atom', Namespaces::ATOM1); + $xpath->registerNamespace('thr', Namespaces::THREAD); + $xpath->registerNamespace('georss', Namespaces::GEORSS); + $xpath->registerNamespace('activity', Namespaces::ACTIVITY); + $xpath->registerNamespace('media', Namespaces::MEDIA); + $xpath->registerNamespace('poco', Namespaces::POCO); + $xpath->registerNamespace('ostatus', Namespaces::OSTATUS); + $xpath->registerNamespace('statusnet', Namespaces::STATUSNET); $hub = ""; $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0); @@ -428,12 +429,12 @@ class OStatus $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry); // Delete a message - if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) { + if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) { self::deleteNotice($item); continue; } - if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) { + if (in_array($item["verb"], [Namespaces::OSTATUS . "/unfavorite", Activity::UNFAVORITE])) { // Ignore "Unfavorite" message Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG); continue; @@ -447,7 +448,7 @@ class OStatus Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG); } - if ($item["verb"] == ACTIVITY_JOIN) { + if ($item["verb"] == Activity::JOIN) { // ignore "Join" messages Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG); continue; @@ -459,29 +460,29 @@ class OStatus continue; } - if ($item["verb"] == ACTIVITY_FOLLOW) { + if ($item["verb"] == Activity::FOLLOW) { Contact::addRelationship($importer, $contact, $item); continue; } - if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") { + if ($item["verb"] == Namespaces::OSTATUS."/unfollow") { $dummy = null; Contact::removeFollower($importer, $contact, $item, $dummy); continue; } - if ($item["verb"] == ACTIVITY_FAVORITE) { + if ($item["verb"] == Activity::FAVORITE) { $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue; Logger::log("Favorite ".$orig_uri." ".print_r($item, true)); - $item["verb"] = ACTIVITY_LIKE; + $item["verb"] = Activity::LIKE; $item["parent-uri"] = $orig_uri; $item["gravity"] = GRAVITY_ACTIVITY; - $item["object-type"] = ACTIVITY_OBJ_NOTE; + $item["object-type"] = Activity::OBJ_NOTE; } // http://activitystrea.ms/schema/1.0/rsvp-yes - if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) { + if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) { Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG); } @@ -504,7 +505,7 @@ class OStatus if ($valid) { // Never post a thread when the only interaction by our contact was a like $valid = false; - $verbs = [ACTIVITY_POST, ACTIVITY_SHARE]; + $verbs = [Activity::POST, Activity::SHARE]; foreach (self::$itemlist as $item) { if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) { $valid = true; @@ -592,10 +593,10 @@ class OStatus { $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry)); $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry); - if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) { + if (($item["object-type"] == Activity::OBJ_BOOKMARK) || ($item["object-type"] == Activity::OBJ_EVENT)) { $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry); $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry); - } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) { + } elseif ($item["object-type"] == Activity::OBJ_QUESTION) { $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry); } @@ -676,7 +677,7 @@ class OStatus } } // Is it a repeated post? - if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) { + if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) { $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer); if (!empty($link_data['add_body'])) { $add_body .= $link_data['add_body']; @@ -691,7 +692,7 @@ class OStatus } // Mastodon Content Warning - if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) { + if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) { $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry); if (!empty($clear_text)) { $item['content-warning'] = HTML::toBBCode($clear_text); @@ -803,9 +804,9 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', NAMESPACE_ATOM1); - $xpath->registerNamespace('thr', NAMESPACE_THREAD); - $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS); + $xpath->registerNamespace('atom', Namespaces::ATOM1); + $xpath->registerNamespace('thr', Namespaces::THREAD); + $xpath->registerNamespace('ostatus', Namespaces::OSTATUS); $entries = $xpath->query('/atom:feed/atom:entry'); @@ -1067,7 +1068,7 @@ class OStatus $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject); // Mastodon Content Warning - if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) { + if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) { $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject); if (!empty($clear_text)) { $item['content-warning'] = HTML::toBBCode($clear_text); @@ -1105,8 +1106,8 @@ class OStatus switch ($attribute['rel']) { case "alternate": $item["plink"] = $attribute['href']; - if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) - || ($item["object-type"] == ACTIVITY_OBJ_EVENT) + if (($item["object-type"] == Activity::OBJ_QUESTION) + || ($item["object-type"] == Activity::OBJ_EVENT) ) { $item["body"] .= add_page_info($attribute['href']); } @@ -1135,7 +1136,7 @@ class OStatus } break; case "related": - if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) { + if ($item["object-type"] != Activity::OBJ_BOOKMARK) { if (!isset($item["parent-uri"])) { $item["parent-uri"] = $attribute['href']; } @@ -1281,17 +1282,17 @@ class OStatus */ private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false) { - $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed'); + $root = $doc->createElementNS(Namespaces::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", NAMESPACE_THREAD); - $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS); - $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY); - $root->setAttribute("xmlns:media", NAMESPACE_MEDIA); - $root->setAttribute("xmlns:poco", NAMESPACE_POCO); - $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS); - $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET); - $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON); + $root->setAttribute("xmlns:thr", Namespaces::THREAD); + $root->setAttribute("xmlns:georss", Namespaces::GEORSS); + $root->setAttribute("xmlns:activity", Namespaces::ACTIVITY); + $root->setAttribute("xmlns:media", Namespaces::MEDIA); + $root->setAttribute("xmlns:poco", Namespaces::POCO); + $root->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); + $root->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); + $root->setAttribute("xmlns:mastodon", Namespaces::MASTODON); $title = ''; $selfUri = '/feed/' . $owner["nick"] . '/'; @@ -1461,9 +1462,9 @@ class OStatus $author = $doc->createElement("author"); XML::addElement($doc, $author, "id", $owner["url"]); if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) { - XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP); + XML::addElement($doc, $author, "activity:object-type", Activity::OBJ_GROUP); } else { - XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON); + XML::addElement($doc, $author, "activity:object-type", Activity::OBJ_PERSON); } XML::addElement($doc, $author, "uri", $owner["url"]); XML::addElement($doc, $author, "name", $owner["nick"]); @@ -1544,7 +1545,7 @@ class OStatus return $item['verb']; } - return ACTIVITY_POST; + return Activity::POST; } /** @@ -1556,11 +1557,11 @@ class OStatus */ private static function constructObjecttype(array $item) { - if (!empty($item['object-type']) && in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT])) { + if (!empty($item['object-type']) && in_array($item['object-type'], [Activity::OBJ_NOTE, Activity::OBJ_COMMENT])) { return $item['object-type']; } - return ACTIVITY_OBJ_NOTE; + return Activity::OBJ_NOTE; } /** @@ -1589,9 +1590,9 @@ class OStatus return $xml; } - if ($item["verb"] == ACTIVITY_LIKE) { + if ($item["verb"] == Activity::LIKE) { return self::likeEntry($doc, $item, $owner, $toplevel); - } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) { + } elseif (in_array($item["verb"], [Activity::FOLLOW, Namespaces::OSTATUS . "/unfollow"])) { return self::followEntry($doc, $item, $owner, $toplevel); } else { return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode); @@ -1705,11 +1706,11 @@ class OStatus $title = $owner["nick"]." repeated a notice by ".$contact["nick"]; - self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false); + self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false); $as_object = $doc->createElement("activity:object"); - XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity"); + XML::addElement($doc, $as_object, "activity:object-type", Namespaces::ACTIVITY_SCHEMA . "activity"); self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false); @@ -1759,7 +1760,7 @@ class OStatus $entry = self::entryHeader($doc, $owner, $item, $toplevel); - $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite"; + $verb = Activity\Namespaces::ACTIVITY_SCHEMA."favorite"; self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false); $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]); @@ -1790,7 +1791,7 @@ class OStatus private static function addPersonObject(DOMDocument $doc, array $owner, array $contact) { $object = $doc->createElement("activity:object"); - XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON); + XML::addElement($doc, $object, "activity:object-type", Activity::OBJ_PERSON); if ($contact['network'] == Protocol::PHANTOM) { XML::addElement($doc, $object, "id", $contact['url']); @@ -1858,7 +1859,7 @@ class OStatus $connect_id = 0; } - if ($item['verb'] == ACTIVITY_FOLLOW) { + if ($item['verb'] == Activity::FOLLOW) { $message = L10n::t('%s is now following %s.'); $title = L10n::t('following'); $action = "subscription"; @@ -1918,7 +1919,7 @@ class OStatus $entry = self::entryHeader($doc, $owner, $item, $toplevel); - XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE); + XML::addElement($doc, $entry, "activity:object-type", Activity::OBJ_NOTE); self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode); @@ -1950,16 +1951,16 @@ class OStatus $entry->appendChild($author); } } else { - $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry"); + $entry = $doc->createElementNS(Namespaces::ATOM1, "entry"); - $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD); - $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS); - $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY); - $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA); - $entry->setAttribute("xmlns:poco", NAMESPACE_POCO); - $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS); - $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET); - $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON); + $entry->setAttribute("xmlns:thr", Namespaces::THREAD); + $entry->setAttribute("xmlns:georss", Namespaces::GEORSS); + $entry->setAttribute("xmlns:activity", Namespaces::ACTIVITY); + $entry->setAttribute("xmlns:media", Namespaces::MEDIA); + $entry->setAttribute("xmlns:poco", Namespaces::POCO); + $entry->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); + $entry->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); + $entry->setAttribute("xmlns:mastodon", Namespaces::MASTODON); $author = self::addAuthor($doc, $owner); $entry->appendChild($author); @@ -2111,14 +2112,14 @@ class OStatus XML::addElement($doc, $entry, "link", "", [ "rel" => "mentioned", - "ostatus:object-type" => ACTIVITY_OBJ_GROUP, + "ostatus:object-type" => Activity::OBJ_GROUP, "href" => $mention] ); } else { XML::addElement($doc, $entry, "link", "", [ "rel" => "mentioned", - "ostatus:object-type" => ACTIVITY_OBJ_PERSON, + "ostatus:object-type" => Activity::OBJ_PERSON, "href" => $mention] ); } @@ -2231,7 +2232,7 @@ class OStatus if ($filter === 'comments') { $condition[0] .= " AND `object-type` = ? "; - $condition[] = ACTIVITY_OBJ_COMMENT; + $condition[] = Activity::OBJ_COMMENT; } if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) { diff --git a/src/Worker/OnePoll.php b/src/Worker/OnePoll.php index d9bdd66fb..03ae57231 100644 --- a/src/Worker/OnePoll.php +++ b/src/Worker/OnePoll.php @@ -14,6 +14,7 @@ use Friendica\Database\DBA; use Friendica\Model\Contact; use Friendica\Model\Item; use Friendica\Model\User; +use Friendica\Protocol\Activity; use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Email; use Friendica\Protocol\PortableContact; @@ -493,8 +494,8 @@ class OnePoll Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA); $datarray = []; - $datarray['verb'] = ACTIVITY_POST; - $datarray['object-type'] = ACTIVITY_OBJ_NOTE; + $datarray['verb'] = Activity::POST; + $datarray['object-type'] = Activity::OBJ_NOTE; $datarray['network'] = Protocol::MAIL; // $meta = Email::messageMeta($mbox, $msg_uid); diff --git a/tests/src/Protocol/ActivityTest.php b/tests/src/Protocol/ActivityTest.php index b6fcbf395..f580f17f5 100644 --- a/tests/src/Protocol/ActivityTest.php +++ b/tests/src/Protocol/ActivityTest.php @@ -16,13 +16,13 @@ class ActivityTest extends MockedTest 'assert' => true, ], 'simple' => [ - 'haystack' => ACTIVITY_OBJ_TAGTERM, - 'needle' => ACTIVITY_OBJ_TAGTERM, + 'haystack' => Activity::OBJ_TAGTERM, + 'needle' => Activity::OBJ_TAGTERM, 'assert' => true, ], 'withNamespace' => [ 'haystack' => 'tagterm', - 'needle' => NAMESPACE_ACTIVITY_SCHEMA . ACTIVITY_OBJ_TAGTERM, + 'needle' => Activity\Namespaces::ACTIVITY_SCHEMA . Activity::OBJ_TAGTERM, 'assert' => true, ], 'invalidSimple' => [ @@ -32,12 +32,12 @@ class ActivityTest extends MockedTest ], 'invalidWithOutNamespace' => [ 'haystack' => 'tagterm', - 'needle' => ACTIVITY_OBJ_TAGTERM, + 'needle' => Activity::OBJ_TAGTERM, 'assert' => false, ], 'withSubPath' => [ 'haystack' => 'tagterm', - 'needle' => NAMESPACE_ACTIVITY_SCHEMA . '/bla/' . ACTIVITY_OBJ_TAGTERM, + 'needle' => Activity\Namespaces::ACTIVITY_SCHEMA . '/bla/' . Activity::OBJ_TAGTERM, 'assert' => true, ], ]; @@ -54,4 +54,12 @@ class ActivityTest extends MockedTest $this->assertEquals($assert, $activity->match($haystack, $needle)); } + + public function testIsHidden() + { + $activity = new Activity(); + + $this->assertTrue($activity->isHidden(Activity::LIKE)); + $this->assertFalse($activity->isHidden(Activity::OBJ_BOOKMARK)); + } } From 2fba7ed477b25b81c886d713bfb8d44b0c1425a8 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 24 Oct 2019 09:06:22 +0200 Subject: [PATCH 31/46] Rename namespace --- mod/salmon.php | 8 +- src/Model/Contact.php | 5 +- src/Module/Xrd.php | 13 ++- src/Network/Probe.php | 21 ++--- src/Protocol/Activity.php | 74 +++++++-------- .../{Namespaces.php => ANamespace.php} | 2 +- src/Protocol/DFRN.php | 86 +++++++++-------- src/Protocol/Diaspora.php | 6 +- src/Protocol/Feed.php | 6 +- src/Protocol/OStatus.php | 92 +++++++++---------- tests/src/Protocol/ActivityTest.php | 4 +- 11 files changed, 156 insertions(+), 161 deletions(-) rename src/Protocol/Activity/{Namespaces.php => ANamespace.php} (98%) diff --git a/mod/salmon.php b/mod/salmon.php index e59931539..9a6d0864a 100644 --- a/mod/salmon.php +++ b/mod/salmon.php @@ -2,19 +2,19 @@ /** * @file mod/salmon.php */ + use Friendica\App; use Friendica\Core\Logger; use Friendica\Core\PConfig; use Friendica\Core\Protocol; -use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Contact; -use Friendica\Protocol\Activity\Namespaces; +use Friendica\Protocol\Activity\ANamespace; use Friendica\Protocol\OStatus; use Friendica\Protocol\Salmon; use Friendica\Util\Crypto; -use Friendica\Util\Strings; use Friendica\Util\Network; +use Friendica\Util\Strings; function salmon_post(App $a, $xml = '') { @@ -37,7 +37,7 @@ function salmon_post(App $a, $xml = '') { // parse the xml - $dom = simplexml_load_string($xml,'SimpleXMLElement',0, Namespaces::SALMON_ME); + $dom = simplexml_load_string($xml,'SimpleXMLElement',0, ANamespace::SALMON_ME); $base = null; diff --git a/src/Model/Contact.php b/src/Model/Contact.php index 5dbe90ba9..08cad6cd8 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -12,8 +12,8 @@ use Friendica\Core\Hook; use Friendica\Core\L10n; use Friendica\Core\Logger; use Friendica\Core\Protocol; -use Friendica\Core\System; use Friendica\Core\Session; +use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\Network\Probe; @@ -23,7 +23,6 @@ use Friendica\Protocol\ActivityPub; use Friendica\Protocol\DFRN; use Friendica\Protocol\Diaspora; use Friendica\Protocol\OStatus; -use Friendica\Protocol\PortableContact; use Friendica\Protocol\Salmon; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; @@ -829,7 +828,7 @@ class Contact extends BaseObject } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) { // create an unfollow slap $item = []; - $item['verb'] = Activity\Namespaces::OSTATUS . "/unfollow"; + $item['verb'] = Activity\ANamespace::OSTATUS . "/unfollow"; $item['follow'] = $contact["url"]; $item['body'] = ''; $item['title'] = ''; diff --git a/src/Module/Xrd.php b/src/Module/Xrd.php index 0ff592bfe..a28d1eed2 100644 --- a/src/Module/Xrd.php +++ b/src/Module/Xrd.php @@ -4,12 +4,11 @@ namespace Friendica\Module; use Friendica\BaseModule; use Friendica\Core\Hook; -use Friendica\Database\DBA; use Friendica\Core\Renderer; -use Friendica\Core\System; -use Friendica\Model\User; +use Friendica\Database\DBA; use Friendica\Model\Photo; -use Friendica\Protocol\Activity\Namespaces; +use Friendica\Model\User; +use Friendica\Protocol\Activity\ANamespace; use Friendica\Protocol\Salmon; use Friendica\Util\Strings; @@ -96,11 +95,11 @@ class Xrd extends BaseModule ], 'links' => [ [ - 'rel' => Namespaces::DFRN , + 'rel' => ANamespace::DFRN , 'href' => $owner['url'], ], [ - 'rel' => Namespaces::FEED, + 'rel' => ANamespace::FEED, 'type' => 'application/atom+xml', 'href' => $owner['poll'], ], @@ -120,7 +119,7 @@ class Xrd extends BaseModule 'href' => $baseURL . '/hcard/' . $owner['nickname'], ], [ - 'rel' => Namespaces::POCO, + 'rel' => ANamespace::POCO, 'href' => $owner['poco'], ], [ diff --git a/src/Network/Probe.php b/src/Network/Probe.php index 587b8a4d4..0014fa05d 100644 --- a/src/Network/Probe.php +++ b/src/Network/Probe.php @@ -18,12 +18,11 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Profile; -use Friendica\Protocol\Activity\Namespaces; +use Friendica\Protocol\Activity\ANamespace; use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Email; use Friendica\Protocol\Feed; use Friendica\Util\Crypto; -use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\Strings; use Friendica\Util\XML; @@ -201,10 +200,10 @@ class Probe Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA); if (!empty($links) && is_array($links)) { foreach ($links as $link) { - if ($link['@attributes']['rel'] === Namespaces::DFRN) { + if ($link['@attributes']['rel'] === ANamespace::DFRN) { $profile_link = $link['@attributes']['href']; } - if (($link['@attributes']['rel'] === Namespaces::OSTATUSSUB) && ($profile_link == "")) { + if (($link['@attributes']['rel'] === ANamespace::OSTATUSSUB) && ($profile_link == "")) { $profile_link = 'stat:'.$link['@attributes']['template']; } if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') { @@ -493,7 +492,7 @@ class Probe $has_key = false; foreach ($webfinger['links'] as $link) { - if ($link['rel'] == Namespaces::OSTATUSSUB) { + if ($link['rel'] == ANamespace::OSTATUSSUB) { $is_ostatus = true; } if ($link['rel'] == 'magic-public-key') { @@ -956,15 +955,15 @@ class Probe // The array is reversed to take into account the order of preference for same-rel links // See: https://tools.ietf.org/html/rfc7033#section-4.4.4 foreach (array_reverse($webfinger["links"]) as $link) { - if (($link["rel"] == Namespaces::DFRN) && !empty($link["href"])) { + if (($link["rel"] == ANamespace::DFRN) && !empty($link["href"])) { $data["network"] = Protocol::DFRN; - } elseif (($link["rel"] == Namespaces::FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == ANamespace::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) { $data["url"] = $link["href"]; } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) { $hcard_url = $link["href"]; - } elseif (($link["rel"] == Namespaces::POCO) && !empty($link["href"])) { + } elseif (($link["rel"] == ANamespace::POCO) && !empty($link["href"])) { $data["poco"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) { $data["photo"] = $link["href"]; @@ -1172,9 +1171,9 @@ class Probe $data["guid"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) { $data["url"] = $link["href"]; - } elseif (($link["rel"] == Namespaces::FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == ANamespace::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; - } elseif (($link["rel"] == Namespaces::POCO) && !empty($link["href"])) { + } elseif (($link["rel"] == ANamespace::POCO) && !empty($link["href"])) { $data["poco"] = $link["href"]; } elseif (($link["rel"] == "salmon") && !empty($link["href"])) { $data["notify"] = $link["href"]; @@ -1274,7 +1273,7 @@ class Probe $data["url"] = $link["href"]; } elseif (($link["rel"] == "salmon") && !empty($link["href"])) { $data["notify"] = $link["href"]; - } elseif (($link["rel"] == Namespaces::FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == ANamespace::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) { $pubkey = $link["href"]; diff --git a/src/Protocol/Activity.php b/src/Protocol/Activity.php index ddbfce1b7..b1cae7f35 100644 --- a/src/Protocol/Activity.php +++ b/src/Protocol/Activity.php @@ -2,51 +2,51 @@ namespace Friendica\Protocol; -use Friendica\Protocol\Activity\Namespaces; +use Friendica\Protocol\Activity\ANamespace; /** - * Base class for the Activity constants and match method + * Base class for the Activity constants and particular method */ final class Activity { - const LIKE = Namespaces::ACTIVITY_SCHEMA . 'like'; + const LIKE = ANamespace::ACTIVITY_SCHEMA . 'like'; - const DISLIKE = Namespaces::DFRN . '/dislike'; - const ATTEND = Namespaces::ZOT . '/activity/attendyes'; - const ATTENDNO = Namespaces::ZOT . '/activity/attendno'; - const ATTENDMAYBE = Namespaces::ZOT . '/activity/attendmaybe'; - const OBJ_HEART = Namespaces::DFRN . '/heart'; + const DISLIKE = ANamespace::DFRN . '/dislike'; + const ATTEND = ANamespace::ZOT . '/activity/attendyes'; + const ATTENDNO = ANamespace::ZOT . '/activity/attendno'; + const ATTENDMAYBE = ANamespace::ZOT . '/activity/attendmaybe'; + const OBJ_HEART = ANamespace::DFRN . '/heart'; - const FRIEND = Namespaces::ACTIVITY_SCHEMA . 'make-friend'; - const REQ_FRIEND = Namespaces::ACTIVITY_SCHEMA . 'request-friend'; - const UNFRIEND = Namespaces::ACTIVITY_SCHEMA . 'remove-friend'; - const FOLLOW = Namespaces::ACTIVITY_SCHEMA . 'follow'; - const UNFOLLOW = Namespaces::ACTIVITY_SCHEMA . 'stop-following'; - const JOIN = Namespaces::ACTIVITY_SCHEMA . 'join'; - const POST = Namespaces::ACTIVITY_SCHEMA . 'post'; - const UPDATE = Namespaces::ACTIVITY_SCHEMA . 'update'; - const TAG = Namespaces::ACTIVITY_SCHEMA . 'tag'; - const FAVORITE = Namespaces::ACTIVITY_SCHEMA . 'favorite'; - const UNFAVORITE = Namespaces::ACTIVITY_SCHEMA . 'unfavorite'; - const SHARE = Namespaces::ACTIVITY_SCHEMA . 'share'; - const DELETE = Namespaces::ACTIVITY_SCHEMA . 'delete'; - const ANNOUNCE = Namespaces::ACTIVITY2 . 'Announce'; + const FRIEND = ANamespace::ACTIVITY_SCHEMA . 'make-friend'; + const REQ_FRIEND = ANamespace::ACTIVITY_SCHEMA . 'request-friend'; + const UNFRIEND = ANamespace::ACTIVITY_SCHEMA . 'remove-friend'; + const FOLLOW = ANamespace::ACTIVITY_SCHEMA . 'follow'; + const UNFOLLOW = ANamespace::ACTIVITY_SCHEMA . 'stop-following'; + const JOIN = ANamespace::ACTIVITY_SCHEMA . 'join'; + const POST = ANamespace::ACTIVITY_SCHEMA . 'post'; + const UPDATE = ANamespace::ACTIVITY_SCHEMA . 'update'; + const TAG = ANamespace::ACTIVITY_SCHEMA . 'tag'; + const FAVORITE = ANamespace::ACTIVITY_SCHEMA . 'favorite'; + const UNFAVORITE = ANamespace::ACTIVITY_SCHEMA . 'unfavorite'; + const SHARE = ANamespace::ACTIVITY_SCHEMA . 'share'; + const DELETE = ANamespace::ACTIVITY_SCHEMA . 'delete'; + const ANNOUNCE = ANamespace::ACTIVITY2 . 'Announce'; - const POKE = Namespaces::ZOT . '/activity/poke'; + const POKE = ANamespace::ZOT . '/activity/poke'; - const OBJ_BOOKMARK = Namespaces::ACTIVITY_SCHEMA . 'bookmark'; - const OBJ_COMMENT = Namespaces::ACTIVITY_SCHEMA . 'comment'; - const OBJ_NOTE = Namespaces::ACTIVITY_SCHEMA . 'note'; - const OBJ_PERSON = Namespaces::ACTIVITY_SCHEMA . 'person'; - const OBJ_IMAGE = Namespaces::ACTIVITY_SCHEMA . 'image'; - const OBJ_PHOTO = Namespaces::ACTIVITY_SCHEMA . 'photo'; - const OBJ_VIDEO = Namespaces::ACTIVITY_SCHEMA . 'video'; - const OBJ_P_PHOTO = Namespaces::ACTIVITY_SCHEMA . 'profile-photo'; - const OBJ_ALBUM = Namespaces::ACTIVITY_SCHEMA . 'photo-album'; - const OBJ_EVENT = Namespaces::ACTIVITY_SCHEMA . 'event'; - const OBJ_GROUP = Namespaces::ACTIVITY_SCHEMA . 'group'; - const OBJ_TAGTERM = Namespaces::DFRN . '/tagterm'; - const OBJ_PROFILE = Namespaces::DFRN . '/profile'; + const OBJ_BOOKMARK = ANamespace::ACTIVITY_SCHEMA . 'bookmark'; + const OBJ_COMMENT = ANamespace::ACTIVITY_SCHEMA . 'comment'; + const OBJ_NOTE = ANamespace::ACTIVITY_SCHEMA . 'note'; + const OBJ_PERSON = ANamespace::ACTIVITY_SCHEMA . 'person'; + const OBJ_IMAGE = ANamespace::ACTIVITY_SCHEMA . 'image'; + const OBJ_PHOTO = ANamespace::ACTIVITY_SCHEMA . 'photo'; + const OBJ_VIDEO = ANamespace::ACTIVITY_SCHEMA . 'video'; + const OBJ_P_PHOTO = ANamespace::ACTIVITY_SCHEMA . 'profile-photo'; + const OBJ_ALBUM = ANamespace::ACTIVITY_SCHEMA . 'photo-album'; + const OBJ_EVENT = ANamespace::ACTIVITY_SCHEMA . 'event'; + const OBJ_GROUP = ANamespace::ACTIVITY_SCHEMA . 'group'; + const OBJ_TAGTERM = ANamespace::DFRN . '/tagterm'; + const OBJ_PROFILE = ANamespace::DFRN . '/profile'; const OBJ_QUESTION = 'http://activityschema.org/object/question'; @@ -93,6 +93,6 @@ final class Activity { return (($haystack === $needle) || ((basename($needle) === $haystack) && - strstr($needle, Namespaces::ACTIVITY_SCHEMA))); + strstr($needle, ANamespace::ACTIVITY_SCHEMA))); } } diff --git a/src/Protocol/Activity/Namespaces.php b/src/Protocol/Activity/ANamespace.php similarity index 98% rename from src/Protocol/Activity/Namespaces.php rename to src/Protocol/Activity/ANamespace.php index 92955c3ad..9cdf970f4 100644 --- a/src/Protocol/Activity/Namespaces.php +++ b/src/Protocol/Activity/ANamespace.php @@ -5,7 +5,7 @@ namespace Friendica\Protocol\Activity; /** * Activity namespaces constants */ -final class Namespaces +final class ANamespace { const ZOT = 'http://purl.org/zot'; const DFRN = 'http://purl.org/macgirvin/dfrn/1.0'; diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index 98f28a56a..1e841f304 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -10,7 +10,6 @@ namespace Friendica\Protocol; use DOMDocument; use DOMXPath; -use Friendica\App; use Friendica\App\BaseURL; use Friendica\BaseObject; use Friendica\Content\OEmbed; @@ -21,7 +20,6 @@ use Friendica\Core\Hook; use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; -use Friendica\Core\Session; use Friendica\Database\DBA; use Friendica\Model\Contact; use Friendica\Model\Conversation; @@ -34,7 +32,7 @@ use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; -use Friendica\Protocol\Activity\Namespaces; +use Friendica\Protocol\Activity\ANamespace; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; @@ -383,18 +381,18 @@ class DFRN $type = 'html'; if ($conversation) { - $root = $doc->createElementNS(Namespaces::ATOM1, 'feed'); + $root = $doc->createElementNS(ANamespace::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", Namespaces::THREAD); - $root->setAttribute("xmlns:at", Namespaces::TOMB); - $root->setAttribute("xmlns:media", Namespaces::MEDIA); - $root->setAttribute("xmlns:dfrn", Namespaces::DFRN); - $root->setAttribute("xmlns:activity", Namespaces::ACTIVITY); - $root->setAttribute("xmlns:georss", Namespaces::GEORSS); - $root->setAttribute("xmlns:poco", Namespaces::POCO); - $root->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); - $root->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); + $root->setAttribute("xmlns:thr", ANamespace::THREAD); + $root->setAttribute("xmlns:at", ANamespace::TOMB); + $root->setAttribute("xmlns:media", ANamespace::MEDIA); + $root->setAttribute("xmlns:dfrn", ANamespace::DFRN); + $root->setAttribute("xmlns:activity", ANamespace::ACTIVITY); + $root->setAttribute("xmlns:georss", ANamespace::GEORSS); + $root->setAttribute("xmlns:poco", ANamespace::POCO); + $root->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); + $root->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false); @@ -558,18 +556,18 @@ class DFRN $alternatelink = $owner['url']; } - $root = $doc->createElementNS(Namespaces::ATOM1, 'feed'); + $root = $doc->createElementNS(ANamespace::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", Namespaces::THREAD); - $root->setAttribute("xmlns:at", Namespaces::TOMB); - $root->setAttribute("xmlns:media", Namespaces::MEDIA); - $root->setAttribute("xmlns:dfrn", Namespaces::DFRN); - $root->setAttribute("xmlns:activity", Namespaces::ACTIVITY); - $root->setAttribute("xmlns:georss", Namespaces::GEORSS); - $root->setAttribute("xmlns:poco", Namespaces::POCO); - $root->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); - $root->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); + $root->setAttribute("xmlns:thr", ANamespace::THREAD); + $root->setAttribute("xmlns:at", ANamespace::TOMB); + $root->setAttribute("xmlns:media", ANamespace::MEDIA); + $root->setAttribute("xmlns:dfrn", ANamespace::DFRN); + $root->setAttribute("xmlns:activity", ANamespace::ACTIVITY); + $root->setAttribute("xmlns:georss", ANamespace::GEORSS); + $root->setAttribute("xmlns:poco", ANamespace::POCO); + $root->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); + $root->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]); XML::addElement($doc, $root, "title", $owner["name"]); @@ -942,18 +940,18 @@ class DFRN if (!$single) { $entry = $doc->createElement("entry"); } else { - $entry = $doc->createElementNS(Namespaces::ATOM1, 'entry'); + $entry = $doc->createElementNS(ANamespace::ATOM1, 'entry'); $doc->appendChild($entry); - $entry->setAttribute("xmlns:thr", Namespaces::THREAD); - $entry->setAttribute("xmlns:at", Namespaces::TOMB); - $entry->setAttribute("xmlns:media", Namespaces::MEDIA); - $entry->setAttribute("xmlns:dfrn", Namespaces::DFRN); - $entry->setAttribute("xmlns:activity", Namespaces::ACTIVITY); - $entry->setAttribute("xmlns:georss", Namespaces::GEORSS); - $entry->setAttribute("xmlns:poco", Namespaces::POCO); - $entry->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); - $entry->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); + $entry->setAttribute("xmlns:thr", ANamespace::THREAD); + $entry->setAttribute("xmlns:at", ANamespace::TOMB); + $entry->setAttribute("xmlns:media", ANamespace::MEDIA); + $entry->setAttribute("xmlns:dfrn", ANamespace::DFRN); + $entry->setAttribute("xmlns:activity", ANamespace::ACTIVITY); + $entry->setAttribute("xmlns:georss", ANamespace::GEORSS); + $entry->setAttribute("xmlns:poco", ANamespace::POCO); + $entry->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); + $entry->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); } if ($item['private']) { @@ -1751,7 +1749,7 @@ class DFRN $obj_doc = new DOMDocument("1.0", "utf-8"); $obj_doc->formatOutput = true; - $obj_element = $obj_doc->createElementNS( Namespaces::ATOM1, $element); + $obj_element = $obj_doc->createElementNS( ANamespace::ATOM1, $element); $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue; XML::addElement($obj_doc, $obj_element, "type", $activity_type); @@ -2732,16 +2730,16 @@ class DFRN @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace("atom", Namespaces::ATOM1); - $xpath->registerNamespace("thr", Namespaces::THREAD); - $xpath->registerNamespace("at", Namespaces::TOMB); - $xpath->registerNamespace("media", Namespaces::MEDIA); - $xpath->registerNamespace("dfrn", Namespaces::DFRN); - $xpath->registerNamespace("activity", Namespaces::ACTIVITY); - $xpath->registerNamespace("georss", Namespaces::GEORSS); - $xpath->registerNamespace("poco", Namespaces::POCO); - $xpath->registerNamespace("ostatus", Namespaces::OSTATUS); - $xpath->registerNamespace("statusnet", Namespaces::STATUSNET); + $xpath->registerNamespace("atom", ANamespace::ATOM1); + $xpath->registerNamespace("thr", ANamespace::THREAD); + $xpath->registerNamespace("at", ANamespace::TOMB); + $xpath->registerNamespace("media", ANamespace::MEDIA); + $xpath->registerNamespace("dfrn", ANamespace::DFRN); + $xpath->registerNamespace("activity", ANamespace::ACTIVITY); + $xpath->registerNamespace("georss", ANamespace::GEORSS); + $xpath->registerNamespace("poco", ANamespace::POCO); + $xpath->registerNamespace("ostatus", ANamespace::OSTATUS); + $xpath->registerNamespace("statusnet", ANamespace::STATUSNET); $header = []; $header["uid"] = $importer["importer_uid"]; diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index 1e61a9ed7..0bc3ed39e 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -32,7 +32,7 @@ use Friendica\Model\Mail; use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; -use Friendica\Protocol\Activity\Namespaces; +use Friendica\Protocol\Activity\ANamespace; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Map; @@ -466,7 +466,7 @@ class Diaspora } } - $base = $basedom->children(Namespaces::SALMON_ME); + $base = $basedom->children(ANamespace::SALMON_ME); // Not sure if this cleaning is needed $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data); @@ -578,7 +578,7 @@ class Diaspora $author_link = str_replace('acct:', '', $idom->author_id); } - $dom = $basedom->children(Namespaces::SALMON_ME); + $dom = $basedom->children(ANamespace::SALMON_ME); // figure out where in the DOM tree our data is hiding diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index 340c93c9e..f13716e4b 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -14,7 +14,7 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Item; -use Friendica\Protocol\Activity\Namespaces; +use Friendica\Protocol\Activity\ANamespace; use Friendica\Util\Network; use Friendica\Util\XML; @@ -60,13 +60,13 @@ class Feed { $doc = new DOMDocument(); @$doc->loadXML(trim($xml)); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', Namespaces::ATOM1); + $xpath->registerNamespace('atom', ANamespace::ATOM1); $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/"); $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/"); $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/"); $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/"); - $xpath->registerNamespace('poco', Namespaces::POCO); + $xpath->registerNamespace('poco', ANamespace::POCO); $author = []; $entries = null; diff --git a/src/Protocol/OStatus.php b/src/Protocol/OStatus.php index 1e287b2ce..391353274 100644 --- a/src/Protocol/OStatus.php +++ b/src/Protocol/OStatus.php @@ -10,22 +10,22 @@ use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; use Friendica\Core\Cache; use Friendica\Core\Config; -use Friendica\Core\PConfig; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Lock; +use Friendica\Core\Logger; +use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; +use Friendica\Model\APContact; use Friendica\Model\Contact; use Friendica\Model\Conversation; use Friendica\Model\GContact; -use Friendica\Model\APContact; use Friendica\Model\Item; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; -use Friendica\Protocol\Activity\Namespaces; +use Friendica\Protocol\Activity\ANamespace; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\Proxy as ProxyUtils; @@ -262,14 +262,14 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', Namespaces::ATOM1); - $xpath->registerNamespace('thr', Namespaces::THREAD); - $xpath->registerNamespace('georss', Namespaces::GEORSS); - $xpath->registerNamespace('activity', Namespaces::ACTIVITY); - $xpath->registerNamespace('media', Namespaces::MEDIA); - $xpath->registerNamespace('poco', Namespaces::POCO); - $xpath->registerNamespace('ostatus', Namespaces::OSTATUS); - $xpath->registerNamespace('statusnet', Namespaces::STATUSNET); + $xpath->registerNamespace('atom', ANamespace::ATOM1); + $xpath->registerNamespace('thr', ANamespace::THREAD); + $xpath->registerNamespace('georss', ANamespace::GEORSS); + $xpath->registerNamespace('activity', ANamespace::ACTIVITY); + $xpath->registerNamespace('media', ANamespace::MEDIA); + $xpath->registerNamespace('poco', ANamespace::POCO); + $xpath->registerNamespace('ostatus', ANamespace::OSTATUS); + $xpath->registerNamespace('statusnet', ANamespace::STATUSNET); $contact = ["id" => 0]; @@ -343,14 +343,14 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', Namespaces::ATOM1); - $xpath->registerNamespace('thr', Namespaces::THREAD); - $xpath->registerNamespace('georss', Namespaces::GEORSS); - $xpath->registerNamespace('activity', Namespaces::ACTIVITY); - $xpath->registerNamespace('media', Namespaces::MEDIA); - $xpath->registerNamespace('poco', Namespaces::POCO); - $xpath->registerNamespace('ostatus', Namespaces::OSTATUS); - $xpath->registerNamespace('statusnet', Namespaces::STATUSNET); + $xpath->registerNamespace('atom', ANamespace::ATOM1); + $xpath->registerNamespace('thr', ANamespace::THREAD); + $xpath->registerNamespace('georss', ANamespace::GEORSS); + $xpath->registerNamespace('activity', ANamespace::ACTIVITY); + $xpath->registerNamespace('media', ANamespace::MEDIA); + $xpath->registerNamespace('poco', ANamespace::POCO); + $xpath->registerNamespace('ostatus', ANamespace::OSTATUS); + $xpath->registerNamespace('statusnet', ANamespace::STATUSNET); $hub = ""; $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0); @@ -434,7 +434,7 @@ class OStatus continue; } - if (in_array($item["verb"], [Namespaces::OSTATUS . "/unfavorite", Activity::UNFAVORITE])) { + if (in_array($item["verb"], [ANamespace::OSTATUS . "/unfavorite", Activity::UNFAVORITE])) { // Ignore "Unfavorite" message Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG); continue; @@ -465,7 +465,7 @@ class OStatus continue; } - if ($item["verb"] == Namespaces::OSTATUS."/unfollow") { + if ($item["verb"] == ANamespace::OSTATUS . "/unfollow") { $dummy = null; Contact::removeFollower($importer, $contact, $item, $dummy); continue; @@ -804,9 +804,9 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', Namespaces::ATOM1); - $xpath->registerNamespace('thr', Namespaces::THREAD); - $xpath->registerNamespace('ostatus', Namespaces::OSTATUS); + $xpath->registerNamespace('atom', ANamespace::ATOM1); + $xpath->registerNamespace('thr', ANamespace::THREAD); + $xpath->registerNamespace('ostatus', ANamespace::OSTATUS); $entries = $xpath->query('/atom:feed/atom:entry'); @@ -1282,17 +1282,17 @@ class OStatus */ private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false) { - $root = $doc->createElementNS(Namespaces::ATOM1, 'feed'); + $root = $doc->createElementNS(ANamespace::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", Namespaces::THREAD); - $root->setAttribute("xmlns:georss", Namespaces::GEORSS); - $root->setAttribute("xmlns:activity", Namespaces::ACTIVITY); - $root->setAttribute("xmlns:media", Namespaces::MEDIA); - $root->setAttribute("xmlns:poco", Namespaces::POCO); - $root->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); - $root->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); - $root->setAttribute("xmlns:mastodon", Namespaces::MASTODON); + $root->setAttribute("xmlns:thr", ANamespace::THREAD); + $root->setAttribute("xmlns:georss", ANamespace::GEORSS); + $root->setAttribute("xmlns:activity", ANamespace::ACTIVITY); + $root->setAttribute("xmlns:media", ANamespace::MEDIA); + $root->setAttribute("xmlns:poco", ANamespace::POCO); + $root->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); + $root->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); + $root->setAttribute("xmlns:mastodon", ANamespace::MASTODON); $title = ''; $selfUri = '/feed/' . $owner["nick"] . '/'; @@ -1592,7 +1592,7 @@ class OStatus if ($item["verb"] == Activity::LIKE) { return self::likeEntry($doc, $item, $owner, $toplevel); - } elseif (in_array($item["verb"], [Activity::FOLLOW, Namespaces::OSTATUS . "/unfollow"])) { + } elseif (in_array($item["verb"], [Activity::FOLLOW, ANamespace::OSTATUS . "/unfollow"])) { return self::followEntry($doc, $item, $owner, $toplevel); } else { return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode); @@ -1710,7 +1710,7 @@ class OStatus $as_object = $doc->createElement("activity:object"); - XML::addElement($doc, $as_object, "activity:object-type", Namespaces::ACTIVITY_SCHEMA . "activity"); + XML::addElement($doc, $as_object, "activity:object-type", ANamespace::ACTIVITY_SCHEMA . "activity"); self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false); @@ -1760,7 +1760,7 @@ class OStatus $entry = self::entryHeader($doc, $owner, $item, $toplevel); - $verb = Activity\Namespaces::ACTIVITY_SCHEMA."favorite"; + $verb = Activity\ANamespace::ACTIVITY_SCHEMA . "favorite"; self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false); $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]); @@ -1951,16 +1951,16 @@ class OStatus $entry->appendChild($author); } } else { - $entry = $doc->createElementNS(Namespaces::ATOM1, "entry"); + $entry = $doc->createElementNS(ANamespace::ATOM1, "entry"); - $entry->setAttribute("xmlns:thr", Namespaces::THREAD); - $entry->setAttribute("xmlns:georss", Namespaces::GEORSS); - $entry->setAttribute("xmlns:activity", Namespaces::ACTIVITY); - $entry->setAttribute("xmlns:media", Namespaces::MEDIA); - $entry->setAttribute("xmlns:poco", Namespaces::POCO); - $entry->setAttribute("xmlns:ostatus", Namespaces::OSTATUS); - $entry->setAttribute("xmlns:statusnet", Namespaces::STATUSNET); - $entry->setAttribute("xmlns:mastodon", Namespaces::MASTODON); + $entry->setAttribute("xmlns:thr", ANamespace::THREAD); + $entry->setAttribute("xmlns:georss", ANamespace::GEORSS); + $entry->setAttribute("xmlns:activity", ANamespace::ACTIVITY); + $entry->setAttribute("xmlns:media", ANamespace::MEDIA); + $entry->setAttribute("xmlns:poco", ANamespace::POCO); + $entry->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); + $entry->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); + $entry->setAttribute("xmlns:mastodon", ANamespace::MASTODON); $author = self::addAuthor($doc, $owner); $entry->appendChild($author); diff --git a/tests/src/Protocol/ActivityTest.php b/tests/src/Protocol/ActivityTest.php index f580f17f5..fe34eac1d 100644 --- a/tests/src/Protocol/ActivityTest.php +++ b/tests/src/Protocol/ActivityTest.php @@ -22,7 +22,7 @@ class ActivityTest extends MockedTest ], 'withNamespace' => [ 'haystack' => 'tagterm', - 'needle' => Activity\Namespaces::ACTIVITY_SCHEMA . Activity::OBJ_TAGTERM, + 'needle' => Activity\ANamespace::ACTIVITY_SCHEMA . Activity::OBJ_TAGTERM, 'assert' => true, ], 'invalidSimple' => [ @@ -37,7 +37,7 @@ class ActivityTest extends MockedTest ], 'withSubPath' => [ 'haystack' => 'tagterm', - 'needle' => Activity\Namespaces::ACTIVITY_SCHEMA . '/bla/' . Activity::OBJ_TAGTERM, + 'needle' => Activity\ANamespace::ACTIVITY_SCHEMA . '/bla/' . Activity::OBJ_TAGTERM, 'assert' => true, ], ]; From a83dfc11a0f12d1381acb016c5c5cf404152b7ed Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Thu, 24 Oct 2019 21:43:20 +0200 Subject: [PATCH 32/46] Fixing https://github.com/friendica/friendica/pull/7759#discussion_r337102107 --- src/Module/Diaspora/Receive.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Module/Diaspora/Receive.php b/src/Module/Diaspora/Receive.php index 978bccd83..c787b5f97 100644 --- a/src/Module/Diaspora/Receive.php +++ b/src/Module/Diaspora/Receive.php @@ -5,6 +5,7 @@ namespace Friendica\Module\Diaspora; use Friendica\App; use Friendica\BaseModule; use Friendica\Core\Config\Configuration; +use Friendica\Core\L10n\L10n; use Friendica\Model\User; use Friendica\Network\HTTPException; use Friendica\Protocol\Diaspora; @@ -34,7 +35,8 @@ class Receive extends BaseModule $enabled = $config->get('system', 'diaspora_enabled', false); if (!$enabled) { self::$logger->info('Diaspora disabled.'); - throw new HTTPException\InternalServerErrorException('Diaspora disabled.'); + $l10n = self::getClass(L10n::class); + throw new HTTPException\ForbiddenException($l10n->t('Access denied.')); } /** @var App\Arguments $args */ From 3897c74debb303c45c3678d379edea4d3b480fbc Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Fri, 25 Oct 2019 00:10:20 +0200 Subject: [PATCH 33/46] Add docs --- include/conversation.php | 14 +- mod/item.php | 14 +- mod/photos.php | 8 +- mod/poke.php | 4 +- mod/subthread.php | 3 +- mod/tagger.php | 7 +- src/Content/Text/BBCode.php | 2 +- src/Model/Contact.php | 2 +- src/Model/Event.php | 6 +- src/Model/Item.php | 10 +- src/Object/Post.php | 4 +- src/Protocol/Activity.php | 179 ++++++++++++++++++++----- src/Protocol/Activity/ANamespace.php | 105 +++++++++++++++ src/Protocol/Activity/ObjectType.php | 103 ++++++++++++++ src/Protocol/ActivityPub/Processor.php | 16 +-- src/Protocol/DFRN.php | 20 +-- src/Protocol/Diaspora.php | 10 +- src/Protocol/Feed.php | 4 +- src/Protocol/OStatus.php | 36 ++--- src/Worker/OnePoll.php | 2 +- tests/src/Protocol/ActivityTest.php | 12 +- 21 files changed, 439 insertions(+), 122 deletions(-) create mode 100644 src/Protocol/Activity/ObjectType.php diff --git a/include/conversation.php b/include/conversation.php index 75a8f020b..84e47d34e 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -27,12 +27,12 @@ use Friendica\Model\Term; use Friendica\Object\Post; use Friendica\Object\Thread; use Friendica\Protocol\Activity; +use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Proxy as ProxyUtils; -use Friendica\Util\Temporal; use Friendica\Util\Strings; +use Friendica\Util\Temporal; use Friendica\Util\XML; -use Friendica\Util\Crypto; function item_extract_images($body) { @@ -163,7 +163,7 @@ function localize_item(&$item) switch ($obj['verb']) { case Activity::POST: switch ($obj['object-type']) { - case Activity::OBJ_EVENT: + case Activity\ObjectType::EVENT: $post_type = L10n::t('event'); break; default: @@ -201,7 +201,7 @@ function localize_item(&$item) if ($activity->match($item['verb'], Activity::FRIEND)) { - if ($item['object-type']=="" || $item['object-type']!== Activity::OBJ_PERSON) return; + if ($item['object-type']=="" || $item['object-type']!== Activity\ObjectType::PERSON) return; $Aname = $item['author-name']; $Alink = $item['author-link']; @@ -236,7 +236,7 @@ function localize_item(&$item) if (!$verb) { return; } - if ($item['object-type']=="" || $item['object-type']!== Activity::OBJ_PERSON) { + if ($item['object-type']=="" || $item['object-type']!== Activity\ObjectType::PERSON) { return; } @@ -300,7 +300,7 @@ function localize_item(&$item) switch ($obj['verb']) { case Activity::POST: switch ($obj['object-type']) { - case Activity::OBJ_EVENT: + case Activity\ObjectType::EVENT: $post_type = L10n::t('event'); break; default: @@ -408,7 +408,7 @@ function visible_activity($item) { // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere; if ($activity->match($item['verb'], Activity::FOLLOW) && - $item['object-type'] === Activity::OBJ_NOTE && + $item['object-type'] === Activity\ObjectType::NOTE && empty($item['self']) && $item['uid'] == local_user()) { return false; diff --git a/mod/item.php b/mod/item.php index bc69ff7c3..a96d28819 100644 --- a/mod/item.php +++ b/mod/item.php @@ -134,7 +134,7 @@ function item_post(App $a) { $toplevel_item_id = $toplevel_item['id']; $parent_user = $toplevel_item['uid']; - $objecttype = Activity::OBJ_COMMENT; + $objecttype = Activity\ObjectType::COMMENT; } if ($toplevel_item_id) { @@ -467,7 +467,7 @@ function item_post(App $a) { $match = null; if (!$preview && Photo::setPermissionFromBody($body, $profile_uid, $original_contact_id, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)) { - $objecttype = Activity::OBJ_IMAGE; + $objecttype = Activity\ObjectType::IMAGE; } /* @@ -503,7 +503,7 @@ function item_post(App $a) { if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $body, $match, PREG_SET_ORDER) || isset($data["type"])) && ($posttype != Item::PT_PERSONAL_NOTE)) { $posttype = Item::PT_PAGE; - $objecttype = Activity::OBJ_BOOKMARK; + $objecttype = Activity\ObjectType::BOOKMARK; } /** @var BBCode\Video $bbCodeVideo */ @@ -517,15 +517,15 @@ function item_post(App $a) { // Setting the object type if not defined before if (!$objecttype) { - $objecttype = Activity::OBJ_NOTE; // Default value + $objecttype = Activity\ObjectType::NOTE; // Default value $objectdata = BBCode::getAttachedData($body); if ($objectdata["type"] == "link") { - $objecttype = Activity::OBJ_BOOKMARK; + $objecttype = Activity\ObjectType::BOOKMARK; } elseif ($objectdata["type"] == "video") { - $objecttype = Activity::OBJ_VIDEO; + $objecttype = Activity\ObjectType::VIDEO; } elseif ($objectdata["type"] == "photo") { - $objecttype = Activity::OBJ_IMAGE; + $objecttype = Activity\ObjectType::IMAGE; } } diff --git a/mod/photos.php b/mod/photos.php index c1195284c..037da64b1 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -569,22 +569,22 @@ function photos_post(App $a) $arr['visible'] = 1; $arr['verb'] = Activity::TAG; $arr['gravity'] = GRAVITY_PARENT; - $arr['object-type'] = Activity::OBJ_PERSON; - $arr['target-type'] = Activity::OBJ_IMAGE; + $arr['object-type'] = Activity\ObjectType::PERSON; + $arr['target-type'] = Activity\ObjectType::IMAGE; $arr['tag'] = $tagged[4]; $arr['inform'] = $tagged[2]; $arr['origin'] = 1; $arr['body'] = L10n::t('%1$s was tagged in %2$s by %3$s', '[url=' . $tagged[1] . ']' . $tagged[0] . '[/url]', '[url=' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ']' . L10n::t('a photo') . '[/url]', '[url=' . $owner_record['url'] . ']' . $owner_record['name'] . '[/url]') ; $arr['body'] .= "\n\n" . '[url=' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ']' . '[img]' . System::baseUrl() . "/photo/" . $photo['resource-id'] . '-' . $best . '.' . $ext . '[/img][/url]' . "\n" ; - $arr['object'] = '' . Activity::OBJ_PERSON . '' . $tagged[0] . '' . $tagged[1] . '/' . $tagged[0] . ''; + $arr['object'] = '' . Activity\ObjectType::PERSON . '' . $tagged[0] . '' . $tagged[1] . '/' . $tagged[0] . ''; $arr['object'] .= '' . XML::escape('' . "\n"); if ($tagged[3]) { $arr['object'] .= XML::escape('' . "\n"); } $arr['object'] .= '' . "\n"; - $arr['target'] = '' . Activity::OBJ_IMAGE . '' . $photo['desc'] . '' + $arr['target'] = '' . Activity\ObjectType::IMAGE . '' . $photo['desc'] . '' . System::baseUrl() . '/photos/' . $owner_record['nickname'] . '/image/' . $photo['resource-id'] . ''; $arr['target'] .= '' . XML::escape('' . "\n" . '') . ''; diff --git a/mod/poke.php b/mod/poke.php index d667d1448..69fd42c72 100644 --- a/mod/poke.php +++ b/mod/poke.php @@ -118,12 +118,12 @@ function poke_init(App $a) $arr['visible'] = 1; $arr['verb'] = $activity; $arr['private'] = $private; - $arr['object-type'] = Activity::OBJ_PERSON; + $arr['object-type'] = Activity\ObjectType::PERSON; $arr['origin'] = 1; $arr['body'] = '[url=' . $poster['url'] . ']' . $poster['name'] . '[/url]' . ' ' . L10n::t($verbs[$verb][0]) . ' ' . '[url=' . $target['url'] . ']' . $target['name'] . '[/url]'; - $arr['object'] = '' . Activity::OBJ_PERSON . '' . $target['name'] . '' . $target['url'] . ''; + $arr['object'] = '' . Activity\ObjectType::PERSON . '' . $target['name'] . '' . $target['url'] . ''; $arr['object'] .= '' . XML::escape('' . "\n"); $arr['object'] .= XML::escape('' . "\n"); diff --git a/mod/subthread.php b/mod/subthread.php index 58bf26534..aa65b8621 100644 --- a/mod/subthread.php +++ b/mod/subthread.php @@ -2,6 +2,7 @@ /** * @file mod/subthread.php */ + use Friendica\App; use Friendica\Core\Hook; use Friendica\Core\L10n; @@ -88,7 +89,7 @@ function subthread_content(App $a) { $uri = Item::newURI($owner_uid); $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status')); - $objtype = (($item['resource-id']) ? Activity::OBJ_IMAGE : Activity::OBJ_NOTE ); + $objtype = (($item['resource-id']) ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE ); $link = XML::escape('' . "\n"); $body = $item['body']; diff --git a/mod/tagger.php b/mod/tagger.php index 22359c64e..7532adb3f 100644 --- a/mod/tagger.php +++ b/mod/tagger.php @@ -2,12 +2,13 @@ /** * @file mod/tagger.php */ + use Friendica\App; use Friendica\Core\Hook; use Friendica\Core\L10n; use Friendica\Core\Logger; -use Friendica\Core\System; use Friendica\Core\Session; +use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\Model\Item; @@ -69,7 +70,7 @@ function tagger_content(App $a) { $uri = Item::newURI($owner_uid); $xterm = XML::escape($term); $post_type = (($item['resource-id']) ? L10n::t('photo') : L10n::t('status')); - $targettype = (($item['resource-id']) ? Activity::OBJ_IMAGE : Activity::OBJ_NOTE ); + $targettype = (($item['resource-id']) ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE ); $href = System::baseUrl() . '/display/' . $item['guid']; $link = XML::escape('' . "\n"); @@ -88,7 +89,7 @@ function tagger_content(App $a) { EOT; $tagid = System::baseUrl() . '/search?tag=' . $xterm; - $objtype = Activity::OBJ_TAGTERM; + $objtype = Activity\ObjectType::TAGTERM; $obj = <<< EOT diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php index 818752158..11e7840b0 100644 --- a/src/Content/Text/BBCode.php +++ b/src/Content/Text/BBCode.php @@ -277,7 +277,7 @@ class BBCode extends BaseObject if (preg_match_all("(\[url=(.*?)\]\s*\[img\](.*?)\[\/img\]\s*\[\/url\])ism", $body, $pictures, PREG_SET_ORDER)) { if ((count($pictures) == 1) && !$has_title) { - if (!empty($item['object-type']) && ($item['object-type'] == Activity::OBJ_IMAGE)) { + if (!empty($item['object-type']) && ($item['object-type'] == Activity\ObjectType::IMAGE)) { // Replace the preview picture with the real picture $url = str_replace('-1.', '-0.', $pictures[0][2]); $data = ['url' => $url, 'type' => 'photo']; diff --git a/src/Model/Contact.php b/src/Model/Contact.php index 08cad6cd8..c7cfddbb8 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -828,7 +828,7 @@ class Contact extends BaseObject } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) { // create an unfollow slap $item = []; - $item['verb'] = Activity\ANamespace::OSTATUS . "/unfollow"; + $item['verb'] = Activity::O_UNFOLLOW; $item['follow'] = $contact["url"]; $item['body'] = ''; $item['title'] = ''; diff --git a/src/Model/Event.php b/src/Model/Event.php index ef1096c8e..fe81a5e95 100644 --- a/src/Model/Event.php +++ b/src/Model/Event.php @@ -304,7 +304,7 @@ class Event extends BaseObject $item = Item::selectFirst(['id'], ['event-id' => $event['id'], 'uid' => $event['uid']]); if (DBA::isResult($item)) { - $object = '' . XML::escape(Activity::OBJ_EVENT) . '' . XML::escape($event['uri']) . ''; + $object = '' . XML::escape(Activity\ObjectType::EVENT) . '' . XML::escape($event['uri']) . ''; $object .= '' . XML::escape(self::getBBCode($event)) . ''; $object .= '' . "\n"; @@ -352,12 +352,12 @@ class Event extends BaseObject $item_arr['private'] = $private; $item_arr['visible'] = 1; $item_arr['verb'] = Activity::POST; - $item_arr['object-type'] = Activity::OBJ_EVENT; + $item_arr['object-type'] = Activity\ObjectType::EVENT; $item_arr['origin'] = $event['cid'] === 0 ? 1 : 0; $item_arr['body'] = self::getBBCode($event); $item_arr['event-id'] = $event['id']; - $item_arr['object'] = '' . XML::escape(Activity::OBJ_EVENT) . '' . XML::escape($event['uri']) . ''; + $item_arr['object'] = '' . XML::escape(Activity\ObjectType::EVENT) . '' . XML::escape($event['uri']) . ''; $item_arr['object'] .= '' . XML::escape(self::getBBCode($event)) . ''; $item_arr['object'] .= '' . "\n"; diff --git a/src/Model/Item.php b/src/Model/Item.php index 6a37a1cf8..9501c8e5d 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -214,7 +214,7 @@ class Item extends BaseObject $row['object'] = ''; } if (array_key_exists('object-type', $row)) { - $row['object-type'] = Activity::OBJ_NOTE; + $row['object-type'] = Activity\ObjectType::NOTE; } } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) { // Posts don't have an object or target - but having tags or files. @@ -1157,14 +1157,14 @@ class Item extends BaseObject private static function deleteTagsFromItem($item) { - if (($item["verb"] != Activity::TAG) || ($item["object-type"] != Activity::OBJ_TAGTERM)) { + if (($item["verb"] != Activity::TAG) || ($item["object-type"] != Activity\ObjectType::TAGTERM)) { return; } $xo = XML::parseString($item["object"], false); $xt = XML::parseString($item["target"], false); - if ($xt->type != Activity::OBJ_NOTE) { + if ($xt->type != Activity\ObjectType::NOTE) { return; } @@ -3156,7 +3156,7 @@ class Item extends BaseObject return true; } - $objtype = $item['resource-id'] ? Activity::OBJ_IMAGE : Activity::OBJ_NOTE; + $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE; $new_item = [ 'guid' => System::createUUID(), @@ -3436,7 +3436,7 @@ class Item extends BaseObject // In order to provide theme developers more possibilities, event items // are treated differently. - if ($item['object-type'] === Activity::OBJ_EVENT && isset($item['event-id'])) { + if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) { $ev = Event::getItemHTML($item); return $ev; } diff --git a/src/Object/Post.php b/src/Object/Post.php index 9f392cb82..babf24e0d 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -15,8 +15,8 @@ use Friendica\Core\L10n; use Friendica\Core\Logger; use Friendica\Core\PConfig; use Friendica\Core\Protocol; -use Friendica\Core\Session; use Friendica\Core\Renderer; +use Friendica\Core\Session; use Friendica\Database\DBA; use Friendica\Model\Contact; use Friendica\Model\Item; @@ -240,7 +240,7 @@ class Post extends BaseObject $isevent = false; $attend = []; - if ($item['object-type'] === Activity::OBJ_EVENT) { + if ($item['object-type'] === Activity\ObjectType::EVENT) { $response_verbs[] = 'attendyes'; $response_verbs[] = 'attendno'; $response_verbs[] = 'attendmaybe'; diff --git a/src/Protocol/Activity.php b/src/Protocol/Activity.php index b1cae7f35..83e032752 100644 --- a/src/Protocol/Activity.php +++ b/src/Protocol/Activity.php @@ -5,50 +5,157 @@ namespace Friendica\Protocol; use Friendica\Protocol\Activity\ANamespace; /** - * Base class for the Activity constants and particular method + * Base class for the Activity Verbs */ final class Activity { - const LIKE = ANamespace::ACTIVITY_SCHEMA . 'like'; + /** + * Indicates that the actor marked the object as an item of special interest. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const LIKE = ANamespace::ACTIVITY_SCHEMA . 'like'; + /** + * Dislike a message ("I don't like the post") + * + * @see http://purl.org/macgirvin/dfrn/1.0/dislike + * @var string + */ + const DISLIKE = ANamespace::DFRN . '/dislike'; - const DISLIKE = ANamespace::DFRN . '/dislike'; - const ATTEND = ANamespace::ZOT . '/activity/attendyes'; - const ATTENDNO = ANamespace::ZOT . '/activity/attendno'; - const ATTENDMAYBE = ANamespace::ZOT . '/activity/attendmaybe'; - const OBJ_HEART = ANamespace::DFRN . '/heart'; + /** + * Attend an event + * + * @see https://github.com/friendica/friendica/wiki/ActivityStreams#activity_attend + * @var string + */ + const ATTEND = ANamespace::ZOT . '/activity/attendyes'; + /** + * Don't attend an event + * + * @see https://github.com/friendica/friendica/wiki/ActivityStreams#activity_attendno + * @var string + */ + const ATTENDNO = ANamespace::ZOT . '/activity/attendno'; + /** + * Attend maybe an event + * + * @see https://github.com/friendica/friendica/wiki/ActivityStreams#activity_attendmaybe + * @var string + */ + const ATTENDMAYBE = ANamespace::ZOT . '/activity/attendmaybe'; - const FRIEND = ANamespace::ACTIVITY_SCHEMA . 'make-friend'; - const REQ_FRIEND = ANamespace::ACTIVITY_SCHEMA . 'request-friend'; - const UNFRIEND = ANamespace::ACTIVITY_SCHEMA . 'remove-friend'; - const FOLLOW = ANamespace::ACTIVITY_SCHEMA . 'follow'; - const UNFOLLOW = ANamespace::ACTIVITY_SCHEMA . 'stop-following'; - const JOIN = ANamespace::ACTIVITY_SCHEMA . 'join'; - const POST = ANamespace::ACTIVITY_SCHEMA . 'post'; - const UPDATE = ANamespace::ACTIVITY_SCHEMA . 'update'; - const TAG = ANamespace::ACTIVITY_SCHEMA . 'tag'; - const FAVORITE = ANamespace::ACTIVITY_SCHEMA . 'favorite'; - const UNFAVORITE = ANamespace::ACTIVITY_SCHEMA . 'unfavorite'; - const SHARE = ANamespace::ACTIVITY_SCHEMA . 'share'; - const DELETE = ANamespace::ACTIVITY_SCHEMA . 'delete'; - const ANNOUNCE = ANamespace::ACTIVITY2 . 'Announce'; + /** + * Indicates the creation of a friendship that is reciprocated by the object. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const FRIEND = ANamespace::ACTIVITY_SCHEMA . 'make-friend'; + /** + * Indicates the creation of a friendship that has not yet been reciprocated by the object. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const REQ_FRIEND = ANamespace::ACTIVITY_SCHEMA . 'request-friend'; + /** + * Indicates that the actor has removed the object from the collection of friends. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const UNFRIEND = ANamespace::ACTIVITY_SCHEMA . 'remove-friend'; + /** + * Indicates that the actor began following the activity of the object. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const FOLLOW = ANamespace::ACTIVITY_SCHEMA . 'follow'; + /** + * Indicates that the actor has stopped following the object. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const UNFOLLOW = ANamespace::ACTIVITY_SCHEMA . 'stop-following'; + /** + * Indicates that the actor has become a member of the object. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const JOIN = ANamespace::ACTIVITY_SCHEMA . 'join'; + /** + * Implementors SHOULD use verbs such as post where the actor is adding new items to a collection or similar. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const POST = ANamespace::ACTIVITY_SCHEMA . 'post'; + /** + * The "update" verb indicates that the actor has modified the object. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const UPDATE = ANamespace::ACTIVITY_SCHEMA . 'update'; + /** + * Indicates that the actor has identified the presence of a target inside another object. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const TAG = ANamespace::ACTIVITY_SCHEMA . 'tag'; + /** + * Indicates that the actor marked the object as an item of special interest. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const FAVORITE = ANamespace::ACTIVITY_SCHEMA . 'favorite'; + /** + * Indicates that the actor has removed the object from the collection of favorited items. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const UNFAVORITE = ANamespace::ACTIVITY_SCHEMA . 'unfavorite'; + /** + * Indicates that the actor has called out the object to readers. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const SHARE = ANamespace::ACTIVITY_SCHEMA . 'share'; + /** + * Indicates that the actor has deleted the object. + * + * @see http://activitystrea.ms/head/activity-schema.html#verbs + * @var string + */ + const DELETE = ANamespace::ACTIVITY_SCHEMA . 'delete'; + /** + * Indicates that the actor is calling the target's attention the object. + * + * @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-announce + * @var string + */ + const ANNOUNCE = ANamespace::ACTIVITY2 . 'Announce'; - const POKE = ANamespace::ZOT . '/activity/poke'; + /** + * Pokes an user. + * + * @see https://github.com/friendica/friendica/wiki/ActivityStreams#activity_poke + * @var string + */ + const POKE = ANamespace::ZOT . '/activity/poke'; - const OBJ_BOOKMARK = ANamespace::ACTIVITY_SCHEMA . 'bookmark'; - const OBJ_COMMENT = ANamespace::ACTIVITY_SCHEMA . 'comment'; - const OBJ_NOTE = ANamespace::ACTIVITY_SCHEMA . 'note'; - const OBJ_PERSON = ANamespace::ACTIVITY_SCHEMA . 'person'; - const OBJ_IMAGE = ANamespace::ACTIVITY_SCHEMA . 'image'; - const OBJ_PHOTO = ANamespace::ACTIVITY_SCHEMA . 'photo'; - const OBJ_VIDEO = ANamespace::ACTIVITY_SCHEMA . 'video'; - const OBJ_P_PHOTO = ANamespace::ACTIVITY_SCHEMA . 'profile-photo'; - const OBJ_ALBUM = ANamespace::ACTIVITY_SCHEMA . 'photo-album'; - const OBJ_EVENT = ANamespace::ACTIVITY_SCHEMA . 'event'; - const OBJ_GROUP = ANamespace::ACTIVITY_SCHEMA . 'group'; - const OBJ_TAGTERM = ANamespace::DFRN . '/tagterm'; - const OBJ_PROFILE = ANamespace::DFRN . '/profile'; - const OBJ_QUESTION = 'http://activityschema.org/object/question'; + const O_UNFOLLOW = ANamespace::OSTATUS . '/unfollow'; + const O_UNFAVOURITE = ANamespace::OSTATUS . '/unfavorite'; /** * likes (etc.) can apply to other things besides posts. Check if they are post children, diff --git a/src/Protocol/Activity/ANamespace.php b/src/Protocol/Activity/ANamespace.php index 9cdf970f4..55fcc8374 100644 --- a/src/Protocol/Activity/ANamespace.php +++ b/src/Protocol/Activity/ANamespace.php @@ -7,21 +7,126 @@ namespace Friendica\Protocol\Activity; */ final class ANamespace { + /** + * Zot is a WebMTA which provides a decentralised identity and communications protocol using HTTPS/JSON. + * + * @var string + * @see https://zotlabs.org/page/zotlabs/specs+zot6+home + */ const ZOT = 'http://purl.org/zot'; + /** + * Friendica is using ActivityStreams in version 1.0 for its activities and object types. + * Additional types are used for non standard activities. + * + * @var string + * @see https://github.com/friendica/friendica/wiki/ActivityStreams + */ const DFRN = 'http://purl.org/macgirvin/dfrn/1.0'; + /** + * This namespace defines an extension for expressing threaded + * discussions within the Atom Syndication Format [RFC4287] + * + * @see https://tools.ietf.org/rfc/rfc4685.txt + * @var string + */ const THREAD = 'http://purl.org/syndication/thread/1.0'; + /** + * This namespace adds mechanisms to the Atom Syndication Format + * that publishers of Atom Feed and Entry documents can use to + * explicitly identify Atom entries that have been removed. + * + * @see https://tools.ietf.org/html/rfc6721 + * @var string + */ const TOMB = 'http://purl.org/atompub/tombstones/1.0'; + /** + * This specification details a model for representing potential and completed activities + * using the JSON format. + * + * @see https://www.w3.org/ns/activitystreams + * @var string + */ const ACTIVITY2 = 'https://www.w3.org/ns/activitystreams#'; + /** + * Atom Activities 1.0 + * + * This namespace presents an XML format that allows activities on social objects + * to be expressed within the Atom Syndication Format. + * + * @see http://activitystrea.ms/spec/1.0 + * @var string + */ const ACTIVITY = 'http://activitystrea.ms/spec/1.0/'; + /** + * This namespace presents a base set of Object types and Verbs for use with Activity Streams. + * + * @see http://activitystrea.ms/head/activity-schema.html + * @var string + */ const ACTIVITY_SCHEMA = 'http://activitystrea.ms/schema/1.0/'; + /** + * Atom Media Extensions + * + * @var string + */ const MEDIA = 'http://purl.org/syndication/atommedia'; + /** + * The Salmon Protocol is an open, simple, standards-based solution that lets + * aggregators and sources unify the conversations. + * + * @see http://www.salmon-protocol.org/salmon-protocol-summary + * @var string + */ const SALMON_ME = 'http://salmon-protocol.org/ns/magic-env'; + /** + * OStatus is a minimal specification for distributed status updates or microblogging. + * + * @see https://ostatus.github.io/spec/OStatus%201.0%20Draft%202.html + * @var string + */ const OSTATUSSUB = 'http://ostatus.org/schema/1.0/subscribe'; + /** + * GeoRSS was designed as a lightweight, community driven way to extend existing feeds with geographic information. + * + * @see http://www.georss.org/ + * @var string + */ const GEORSS = 'http://www.georss.org/georss'; + /** + * The Portable Contacts specification is designed to make it easier for developers + * to give their users a secure way to access the address books and friends lists + * they have built up all over the web. + * + * @see http://portablecontacts.net/draft-spec/ + * @var string + */ const POCO = 'http://portablecontacts.net/spec/1.0'; + /** + * @var string + */ const FEED = 'http://schemas.google.com/g/2010#updates-from'; + /** + * OStatus is a minimal specification for distributed status updates or microblogging. + * + * @see https://ostatus.github.io/spec/OStatus%201.0%20Draft%202.html + * @var string + */ const OSTATUS = 'http://ostatus.org/schema/1.0'; + /** + * @var string + */ const STATUSNET = 'http://status.net/schema/api/1/'; + /** + * This namespace describes the Atom Activity Streams in RDF Vocabulary (AAIR), + * defined as a dictionary of named properties and classes using W3C's RDF technology, + * and specifically a mapping of the Atom Activity Streams work to RDF. + * + * @see http://xmlns.notu.be/aair/#RFC4287 + * @var string + */ const ATOM1 = 'http://www.w3.org/2005/Atom'; + /** + * @var string + */ const MASTODON = 'http://mastodon.social/schema/1.0'; } diff --git a/src/Protocol/Activity/ObjectType.php b/src/Protocol/Activity/ObjectType.php new file mode 100644 index 000000000..71c7a2157 --- /dev/null +++ b/src/Protocol/Activity/ObjectType.php @@ -0,0 +1,103 @@ + $activity['reply-to-id']])) { @@ -255,7 +255,7 @@ class Processor $item['verb'] = $verb; $item['thr-parent'] = $activity['object_id']; $item['gravity'] = GRAVITY_ACTIVITY; - $item['object-type'] = Activity::OBJ_NOTE; + $item['object-type'] = Activity\ObjectType::NOTE; $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? ''; diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index 1e841f304..6bf3e6e4f 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -1078,9 +1078,9 @@ class DFRN if ($item['object-type'] != "") { XML::addElement($doc, $entry, "activity:object-type", $item['object-type']); } elseif ($item['id'] == $item['parent']) { - XML::addElement($doc, $entry, "activity:object-type", Activity::OBJ_NOTE); + XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE); } else { - XML::addElement($doc, $entry, "activity:object-type", Activity::OBJ_COMMENT); + XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::COMMENT); } $actobj = self::createActivity($doc, "activity:object", $item['object']); @@ -1123,7 +1123,7 @@ class DFRN "link", "", ["rel" => "mentioned", - "ostatus:object-type" => Activity::OBJ_GROUP, + "ostatus:object-type" => Activity\ObjectType::GROUP, "href" => $mention] ); } else { @@ -1133,7 +1133,7 @@ class DFRN "link", "", ["rel" => "mentioned", - "ostatus:object-type" => Activity::OBJ_PERSON, + "ostatus:object-type" => Activity\ObjectType::PERSON, "href" => $mention] ); } @@ -2116,7 +2116,7 @@ class DFRN } $xo = XML::parseString($item["object"], false); - if (($xo->type == Activity::OBJ_PERSON) && ($xo->id)) { + if (($xo->type == Activity\ObjectType::PERSON) && ($xo->id)) { // somebody was poked/prodded. Was it me? $Blink = ''; foreach ($xo->link as $l) { @@ -2237,11 +2237,11 @@ class DFRN $is_like = false; } - if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity::OBJ_TAGTERM)) { + if (($item["verb"] == Activity::TAG) && ($item["object-type"] == Activity\ObjectType::TAGTERM)) { $xo = XML::parseString($item["object"], false); $xt = XML::parseString($item["target"], false); - if ($xt->type == Activity::OBJ_NOTE) { + if ($xt->type == Activity\ObjectType::NOTE) { $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]); if (!DBA::isResult($item_tag)) { @@ -2516,7 +2516,7 @@ class DFRN // Now assign the rest of the values that depend on the type of the message if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) { if (!isset($item["object-type"])) { - $item["object-type"] = Activity::OBJ_COMMENT; + $item["object-type"] = Activity\ObjectType::COMMENT; } if ($item["contact-id"] != $owner["contact-id"]) { @@ -2540,11 +2540,11 @@ class DFRN $item["wall"] = 1; } elseif ($entrytype == DFRN::TOP_LEVEL) { if (!isset($item["object-type"])) { - $item["object-type"] = Activity::OBJ_NOTE; + $item["object-type"] = Activity\ObjectType::NOTE; } // Is it an event? - if (($item["object-type"] == Activity::OBJ_EVENT) && !$owner_unknown) { + if (($item["object-type"] == Activity\ObjectType::EVENT) && !$owner_unknown) { Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG); $ev = Event::fromBBCode($item["body"]); if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) { diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index 0bc3ed39e..709dfa02f 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -1855,7 +1855,7 @@ class Diaspora $datarray["parent-uri"] = $parent_item["uri"]; } - $datarray["object-type"] = Activity::OBJ_COMMENT; + $datarray["object-type"] = Activity\ObjectType::COMMENT; $datarray["protocol"] = Conversation::PARCEL_DIASPORA; $datarray["source"] = $xml; @@ -2086,7 +2086,7 @@ class Diaspora $datarray["gravity"] = GRAVITY_ACTIVITY; $datarray["parent-uri"] = $parent_item["uri"]; - $datarray["object-type"] = Activity::OBJ_NOTE; + $datarray["object-type"] = Activity\ObjectType::NOTE; $datarray["body"] = $verb; @@ -2687,7 +2687,7 @@ class Diaspora $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE; $datarray['gravity'] = GRAVITY_ACTIVITY; - $datarray['object-type'] = Activity::OBJ_NOTE; + $datarray['object-type'] = Activity\ObjectType::NOTE; $datarray['protocol'] = $item['protocol']; @@ -2963,9 +2963,9 @@ class Diaspora XML::unescape($photo->remote_photo_name)."[/img]\n".$body; } - $datarray["object-type"] = Activity::OBJ_IMAGE; + $datarray["object-type"] = Activity\ObjectType::IMAGE; } else { - $datarray["object-type"] = Activity::OBJ_NOTE; + $datarray["object-type"] = Activity\ObjectType::NOTE; // Add OEmbed and other information to the body if (!self::isRedmatrix($contact["url"])) { diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index f13716e4b..816820bc4 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -200,7 +200,7 @@ class Feed { $header["gravity"] = GRAVITY_PARENT; $header["private"] = 2; $header["verb"] = Activity::POST; - $header["object-type"] = Activity::OBJ_NOTE; + $header["object-type"] = Activity\ObjectType::NOTE; $header["contact-id"] = $contact["id"]; @@ -421,7 +421,7 @@ class Feed { $item["title"] = ""; $item["body"] = $item["body"].add_page_info($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]); $item["tag"] = add_page_keywords($item["plink"], $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_blacklist"]); - $item["object-type"] = Activity::OBJ_BOOKMARK; + $item["object-type"] = Activity\ObjectType::BOOKMARK; unset($item["attach"]); } else { if (!empty($summary)) { diff --git a/src/Protocol/OStatus.php b/src/Protocol/OStatus.php index 391353274..d0f7d7edf 100644 --- a/src/Protocol/OStatus.php +++ b/src/Protocol/OStatus.php @@ -434,7 +434,7 @@ class OStatus continue; } - if (in_array($item["verb"], [ANamespace::OSTATUS . "/unfavorite", Activity::UNFAVORITE])) { + if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) { // Ignore "Unfavorite" message Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG); continue; @@ -465,7 +465,7 @@ class OStatus continue; } - if ($item["verb"] == ANamespace::OSTATUS . "/unfollow") { + if ($item["verb"] == Activity::O_UNFOLLOW) { $dummy = null; Contact::removeFollower($importer, $contact, $item, $dummy); continue; @@ -478,7 +478,7 @@ class OStatus $item["verb"] = Activity::LIKE; $item["parent-uri"] = $orig_uri; $item["gravity"] = GRAVITY_ACTIVITY; - $item["object-type"] = Activity::OBJ_NOTE; + $item["object-type"] = Activity\ObjectType::NOTE; } // http://activitystrea.ms/schema/1.0/rsvp-yes @@ -593,10 +593,10 @@ class OStatus { $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry)); $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry); - if (($item["object-type"] == Activity::OBJ_BOOKMARK) || ($item["object-type"] == Activity::OBJ_EVENT)) { + if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) { $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry); $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry); - } elseif ($item["object-type"] == Activity::OBJ_QUESTION) { + } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) { $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry); } @@ -1106,8 +1106,8 @@ class OStatus switch ($attribute['rel']) { case "alternate": $item["plink"] = $attribute['href']; - if (($item["object-type"] == Activity::OBJ_QUESTION) - || ($item["object-type"] == Activity::OBJ_EVENT) + if (($item["object-type"] == Activity\ObjectType::QUESTION) + || ($item["object-type"] == Activity\ObjectType::EVENT) ) { $item["body"] .= add_page_info($attribute['href']); } @@ -1136,7 +1136,7 @@ class OStatus } break; case "related": - if ($item["object-type"] != Activity::OBJ_BOOKMARK) { + if ($item["object-type"] != Activity\ObjectType::BOOKMARK) { if (!isset($item["parent-uri"])) { $item["parent-uri"] = $attribute['href']; } @@ -1462,9 +1462,9 @@ class OStatus $author = $doc->createElement("author"); XML::addElement($doc, $author, "id", $owner["url"]); if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) { - XML::addElement($doc, $author, "activity:object-type", Activity::OBJ_GROUP); + XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP); } else { - XML::addElement($doc, $author, "activity:object-type", Activity::OBJ_PERSON); + XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON); } XML::addElement($doc, $author, "uri", $owner["url"]); XML::addElement($doc, $author, "name", $owner["nick"]); @@ -1557,11 +1557,11 @@ class OStatus */ private static function constructObjecttype(array $item) { - if (!empty($item['object-type']) && in_array($item['object-type'], [Activity::OBJ_NOTE, Activity::OBJ_COMMENT])) { + if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) { return $item['object-type']; } - return Activity::OBJ_NOTE; + return Activity\ObjectType::NOTE; } /** @@ -1592,7 +1592,7 @@ class OStatus if ($item["verb"] == Activity::LIKE) { return self::likeEntry($doc, $item, $owner, $toplevel); - } elseif (in_array($item["verb"], [Activity::FOLLOW, ANamespace::OSTATUS . "/unfollow"])) { + } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) { return self::followEntry($doc, $item, $owner, $toplevel); } else { return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode); @@ -1791,7 +1791,7 @@ class OStatus private static function addPersonObject(DOMDocument $doc, array $owner, array $contact) { $object = $doc->createElement("activity:object"); - XML::addElement($doc, $object, "activity:object-type", Activity::OBJ_PERSON); + XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON); if ($contact['network'] == Protocol::PHANTOM) { XML::addElement($doc, $object, "id", $contact['url']); @@ -1919,7 +1919,7 @@ class OStatus $entry = self::entryHeader($doc, $owner, $item, $toplevel); - XML::addElement($doc, $entry, "activity:object-type", Activity::OBJ_NOTE); + XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE); self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode); @@ -2112,14 +2112,14 @@ class OStatus XML::addElement($doc, $entry, "link", "", [ "rel" => "mentioned", - "ostatus:object-type" => Activity::OBJ_GROUP, + "ostatus:object-type" => Activity\ObjectType::GROUP, "href" => $mention] ); } else { XML::addElement($doc, $entry, "link", "", [ "rel" => "mentioned", - "ostatus:object-type" => Activity::OBJ_PERSON, + "ostatus:object-type" => Activity\ObjectType::PERSON, "href" => $mention] ); } @@ -2232,7 +2232,7 @@ class OStatus if ($filter === 'comments') { $condition[0] .= " AND `object-type` = ? "; - $condition[] = Activity::OBJ_COMMENT; + $condition[] = Activity\ObjectType::COMMENT; } if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) { diff --git a/src/Worker/OnePoll.php b/src/Worker/OnePoll.php index 03ae57231..3f8b98ead 100644 --- a/src/Worker/OnePoll.php +++ b/src/Worker/OnePoll.php @@ -495,7 +495,7 @@ class OnePoll $datarray = []; $datarray['verb'] = Activity::POST; - $datarray['object-type'] = Activity::OBJ_NOTE; + $datarray['object-type'] = Activity\ObjectType::NOTE; $datarray['network'] = Protocol::MAIL; // $meta = Email::messageMeta($mbox, $msg_uid); diff --git a/tests/src/Protocol/ActivityTest.php b/tests/src/Protocol/ActivityTest.php index fe34eac1d..ac332a7f7 100644 --- a/tests/src/Protocol/ActivityTest.php +++ b/tests/src/Protocol/ActivityTest.php @@ -16,13 +16,13 @@ class ActivityTest extends MockedTest 'assert' => true, ], 'simple' => [ - 'haystack' => Activity::OBJ_TAGTERM, - 'needle' => Activity::OBJ_TAGTERM, + 'haystack' => Activity\ObjectType::TAGTERM, + 'needle' => Activity\ObjectType::TAGTERM, 'assert' => true, ], 'withNamespace' => [ 'haystack' => 'tagterm', - 'needle' => Activity\ANamespace::ACTIVITY_SCHEMA . Activity::OBJ_TAGTERM, + 'needle' => Activity\ANamespace::ACTIVITY_SCHEMA . Activity\ObjectType::TAGTERM, 'assert' => true, ], 'invalidSimple' => [ @@ -32,12 +32,12 @@ class ActivityTest extends MockedTest ], 'invalidWithOutNamespace' => [ 'haystack' => 'tagterm', - 'needle' => Activity::OBJ_TAGTERM, + 'needle' => Activity\ObjectType::TAGTERM, 'assert' => false, ], 'withSubPath' => [ 'haystack' => 'tagterm', - 'needle' => Activity\ANamespace::ACTIVITY_SCHEMA . '/bla/' . Activity::OBJ_TAGTERM, + 'needle' => Activity\ANamespace::ACTIVITY_SCHEMA . '/bla/' . Activity\ObjectType::TAGTERM, 'assert' => true, ], ]; @@ -60,6 +60,6 @@ class ActivityTest extends MockedTest $activity = new Activity(); $this->assertTrue($activity->isHidden(Activity::LIKE)); - $this->assertFalse($activity->isHidden(Activity::OBJ_BOOKMARK)); + $this->assertFalse($activity->isHidden(Activity\ObjectType::BOOKMARK)); } } From dc2858938d37e033ee4a0761c2f1e5c2082848cd Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Fri, 25 Oct 2019 00:32:35 +0200 Subject: [PATCH 34/46] Renamed to ActivityNamespace --- mod/salmon.php | 4 +- src/Module/Xrd.php | 8 +- src/Network/Probe.php | 20 ++--- src/Protocol/Activity.php | 48 +++++------ .../{ANamespace.php => ActivityNamespace.php} | 2 +- src/Protocol/Activity/ObjectType.php | 28 +++---- src/Protocol/DFRN.php | 84 +++++++++---------- src/Protocol/Diaspora.php | 6 +- src/Protocol/Feed.php | 6 +- src/Protocol/OStatus.php | 80 +++++++++--------- tests/src/Protocol/ActivityTest.php | 4 +- 11 files changed, 145 insertions(+), 145 deletions(-) rename src/Protocol/Activity/{ANamespace.php => ActivityNamespace.php} (99%) diff --git a/mod/salmon.php b/mod/salmon.php index 9a6d0864a..2a7c4a4b3 100644 --- a/mod/salmon.php +++ b/mod/salmon.php @@ -9,7 +9,7 @@ use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\Model\Contact; -use Friendica\Protocol\Activity\ANamespace; +use Friendica\Protocol\Activity\ActivityNamespace; use Friendica\Protocol\OStatus; use Friendica\Protocol\Salmon; use Friendica\Util\Crypto; @@ -37,7 +37,7 @@ function salmon_post(App $a, $xml = '') { // parse the xml - $dom = simplexml_load_string($xml,'SimpleXMLElement',0, ANamespace::SALMON_ME); + $dom = simplexml_load_string($xml,'SimpleXMLElement',0, ActivityNamespace::SALMON_ME); $base = null; diff --git a/src/Module/Xrd.php b/src/Module/Xrd.php index a28d1eed2..77fa3959a 100644 --- a/src/Module/Xrd.php +++ b/src/Module/Xrd.php @@ -8,7 +8,7 @@ use Friendica\Core\Renderer; use Friendica\Database\DBA; use Friendica\Model\Photo; use Friendica\Model\User; -use Friendica\Protocol\Activity\ANamespace; +use Friendica\Protocol\Activity\ActivityNamespace; use Friendica\Protocol\Salmon; use Friendica\Util\Strings; @@ -95,11 +95,11 @@ class Xrd extends BaseModule ], 'links' => [ [ - 'rel' => ANamespace::DFRN , + 'rel' => ActivityNamespace::DFRN , 'href' => $owner['url'], ], [ - 'rel' => ANamespace::FEED, + 'rel' => ActivityNamespace::FEED, 'type' => 'application/atom+xml', 'href' => $owner['poll'], ], @@ -119,7 +119,7 @@ class Xrd extends BaseModule 'href' => $baseURL . '/hcard/' . $owner['nickname'], ], [ - 'rel' => ANamespace::POCO, + 'rel' => ActivityNamespace::POCO, 'href' => $owner['poco'], ], [ diff --git a/src/Network/Probe.php b/src/Network/Probe.php index 0014fa05d..e63224411 100644 --- a/src/Network/Probe.php +++ b/src/Network/Probe.php @@ -18,7 +18,7 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Profile; -use Friendica\Protocol\Activity\ANamespace; +use Friendica\Protocol\Activity\ActivityNamespace; use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Email; use Friendica\Protocol\Feed; @@ -200,10 +200,10 @@ class Probe Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA); if (!empty($links) && is_array($links)) { foreach ($links as $link) { - if ($link['@attributes']['rel'] === ANamespace::DFRN) { + if ($link['@attributes']['rel'] === ActivityNamespace::DFRN) { $profile_link = $link['@attributes']['href']; } - if (($link['@attributes']['rel'] === ANamespace::OSTATUSSUB) && ($profile_link == "")) { + if (($link['@attributes']['rel'] === ActivityNamespace::OSTATUSSUB) && ($profile_link == "")) { $profile_link = 'stat:'.$link['@attributes']['template']; } if ($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard') { @@ -492,7 +492,7 @@ class Probe $has_key = false; foreach ($webfinger['links'] as $link) { - if ($link['rel'] == ANamespace::OSTATUSSUB) { + if ($link['rel'] == ActivityNamespace::OSTATUSSUB) { $is_ostatus = true; } if ($link['rel'] == 'magic-public-key') { @@ -955,15 +955,15 @@ class Probe // The array is reversed to take into account the order of preference for same-rel links // See: https://tools.ietf.org/html/rfc7033#section-4.4.4 foreach (array_reverse($webfinger["links"]) as $link) { - if (($link["rel"] == ANamespace::DFRN) && !empty($link["href"])) { + if (($link["rel"] == ActivityNamespace::DFRN) && !empty($link["href"])) { $data["network"] = Protocol::DFRN; - } elseif (($link["rel"] == ANamespace::FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) { $data["url"] = $link["href"]; } elseif (($link["rel"] == "http://microformats.org/profile/hcard") && !empty($link["href"])) { $hcard_url = $link["href"]; - } elseif (($link["rel"] == ANamespace::POCO) && !empty($link["href"])) { + } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) { $data["poco"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/avatar") && !empty($link["href"])) { $data["photo"] = $link["href"]; @@ -1171,9 +1171,9 @@ class Probe $data["guid"] = $link["href"]; } elseif (($link["rel"] == "http://webfinger.net/rel/profile-page") && (($link["type"] ?? "") == "text/html") && !empty($link["href"])) { $data["url"] = $link["href"]; - } elseif (($link["rel"] == ANamespace::FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; - } elseif (($link["rel"] == ANamespace::POCO) && !empty($link["href"])) { + } elseif (($link["rel"] == ActivityNamespace::POCO) && !empty($link["href"])) { $data["poco"] = $link["href"]; } elseif (($link["rel"] == "salmon") && !empty($link["href"])) { $data["notify"] = $link["href"]; @@ -1273,7 +1273,7 @@ class Probe $data["url"] = $link["href"]; } elseif (($link["rel"] == "salmon") && !empty($link["href"])) { $data["notify"] = $link["href"]; - } elseif (($link["rel"] == ANamespace::FEED) && !empty($link["href"])) { + } elseif (($link["rel"] == ActivityNamespace::FEED) && !empty($link["href"])) { $data["poll"] = $link["href"]; } elseif (($link["rel"] == "magic-public-key") && !empty($link["href"])) { $pubkey = $link["href"]; diff --git a/src/Protocol/Activity.php b/src/Protocol/Activity.php index 83e032752..d2c5eec4b 100644 --- a/src/Protocol/Activity.php +++ b/src/Protocol/Activity.php @@ -2,7 +2,7 @@ namespace Friendica\Protocol; -use Friendica\Protocol\Activity\ANamespace; +use Friendica\Protocol\Activity\ActivityNamespace; /** * Base class for the Activity Verbs @@ -15,14 +15,14 @@ final class Activity * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const LIKE = ANamespace::ACTIVITY_SCHEMA . 'like'; + const LIKE = ActivityNamespace::ACTIVITY_SCHEMA . 'like'; /** * Dislike a message ("I don't like the post") * * @see http://purl.org/macgirvin/dfrn/1.0/dislike * @var string */ - const DISLIKE = ANamespace::DFRN . '/dislike'; + const DISLIKE = ActivityNamespace::DFRN . '/dislike'; /** * Attend an event @@ -30,21 +30,21 @@ final class Activity * @see https://github.com/friendica/friendica/wiki/ActivityStreams#activity_attend * @var string */ - const ATTEND = ANamespace::ZOT . '/activity/attendyes'; + const ATTEND = ActivityNamespace::ZOT . '/activity/attendyes'; /** * Don't attend an event * * @see https://github.com/friendica/friendica/wiki/ActivityStreams#activity_attendno * @var string */ - const ATTENDNO = ANamespace::ZOT . '/activity/attendno'; + const ATTENDNO = ActivityNamespace::ZOT . '/activity/attendno'; /** * Attend maybe an event * * @see https://github.com/friendica/friendica/wiki/ActivityStreams#activity_attendmaybe * @var string */ - const ATTENDMAYBE = ANamespace::ZOT . '/activity/attendmaybe'; + const ATTENDMAYBE = ActivityNamespace::ZOT . '/activity/attendmaybe'; /** * Indicates the creation of a friendship that is reciprocated by the object. @@ -52,98 +52,98 @@ final class Activity * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const FRIEND = ANamespace::ACTIVITY_SCHEMA . 'make-friend'; + const FRIEND = ActivityNamespace::ACTIVITY_SCHEMA . 'make-friend'; /** * Indicates the creation of a friendship that has not yet been reciprocated by the object. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const REQ_FRIEND = ANamespace::ACTIVITY_SCHEMA . 'request-friend'; + const REQ_FRIEND = ActivityNamespace::ACTIVITY_SCHEMA . 'request-friend'; /** * Indicates that the actor has removed the object from the collection of friends. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const UNFRIEND = ANamespace::ACTIVITY_SCHEMA . 'remove-friend'; + const UNFRIEND = ActivityNamespace::ACTIVITY_SCHEMA . 'remove-friend'; /** * Indicates that the actor began following the activity of the object. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const FOLLOW = ANamespace::ACTIVITY_SCHEMA . 'follow'; + const FOLLOW = ActivityNamespace::ACTIVITY_SCHEMA . 'follow'; /** * Indicates that the actor has stopped following the object. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const UNFOLLOW = ANamespace::ACTIVITY_SCHEMA . 'stop-following'; + const UNFOLLOW = ActivityNamespace::ACTIVITY_SCHEMA . 'stop-following'; /** * Indicates that the actor has become a member of the object. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const JOIN = ANamespace::ACTIVITY_SCHEMA . 'join'; + const JOIN = ActivityNamespace::ACTIVITY_SCHEMA . 'join'; /** * Implementors SHOULD use verbs such as post where the actor is adding new items to a collection or similar. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const POST = ANamespace::ACTIVITY_SCHEMA . 'post'; + const POST = ActivityNamespace::ACTIVITY_SCHEMA . 'post'; /** * The "update" verb indicates that the actor has modified the object. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const UPDATE = ANamespace::ACTIVITY_SCHEMA . 'update'; + const UPDATE = ActivityNamespace::ACTIVITY_SCHEMA . 'update'; /** * Indicates that the actor has identified the presence of a target inside another object. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const TAG = ANamespace::ACTIVITY_SCHEMA . 'tag'; + const TAG = ActivityNamespace::ACTIVITY_SCHEMA . 'tag'; /** * Indicates that the actor marked the object as an item of special interest. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const FAVORITE = ANamespace::ACTIVITY_SCHEMA . 'favorite'; + const FAVORITE = ActivityNamespace::ACTIVITY_SCHEMA . 'favorite'; /** * Indicates that the actor has removed the object from the collection of favorited items. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const UNFAVORITE = ANamespace::ACTIVITY_SCHEMA . 'unfavorite'; + const UNFAVORITE = ActivityNamespace::ACTIVITY_SCHEMA . 'unfavorite'; /** * Indicates that the actor has called out the object to readers. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const SHARE = ANamespace::ACTIVITY_SCHEMA . 'share'; + const SHARE = ActivityNamespace::ACTIVITY_SCHEMA . 'share'; /** * Indicates that the actor has deleted the object. * * @see http://activitystrea.ms/head/activity-schema.html#verbs * @var string */ - const DELETE = ANamespace::ACTIVITY_SCHEMA . 'delete'; + const DELETE = ActivityNamespace::ACTIVITY_SCHEMA . 'delete'; /** * Indicates that the actor is calling the target's attention the object. * * @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-announce * @var string */ - const ANNOUNCE = ANamespace::ACTIVITY2 . 'Announce'; + const ANNOUNCE = ActivityNamespace::ACTIVITY2 . 'Announce'; /** * Pokes an user. @@ -151,11 +151,11 @@ final class Activity * @see https://github.com/friendica/friendica/wiki/ActivityStreams#activity_poke * @var string */ - const POKE = ANamespace::ZOT . '/activity/poke'; + const POKE = ActivityNamespace::ZOT . '/activity/poke'; - const O_UNFOLLOW = ANamespace::OSTATUS . '/unfollow'; - const O_UNFAVOURITE = ANamespace::OSTATUS . '/unfavorite'; + const O_UNFOLLOW = ActivityNamespace::OSTATUS . '/unfollow'; + const O_UNFAVOURITE = ActivityNamespace::OSTATUS . '/unfavorite'; /** * likes (etc.) can apply to other things besides posts. Check if they are post children, @@ -200,6 +200,6 @@ final class Activity { return (($haystack === $needle) || ((basename($needle) === $haystack) && - strstr($needle, ANamespace::ACTIVITY_SCHEMA))); + strstr($needle, ActivityNamespace::ACTIVITY_SCHEMA))); } } diff --git a/src/Protocol/Activity/ANamespace.php b/src/Protocol/Activity/ActivityNamespace.php similarity index 99% rename from src/Protocol/Activity/ANamespace.php rename to src/Protocol/Activity/ActivityNamespace.php index 55fcc8374..a821f069e 100644 --- a/src/Protocol/Activity/ANamespace.php +++ b/src/Protocol/Activity/ActivityNamespace.php @@ -5,7 +5,7 @@ namespace Friendica\Protocol\Activity; /** * Activity namespaces constants */ -final class ANamespace +final class ActivityNamespace { /** * Zot is a WebMTA which provides a decentralised identity and communications protocol using HTTPS/JSON. diff --git a/src/Protocol/Activity/ObjectType.php b/src/Protocol/Activity/ObjectType.php index 71c7a2157..7bed40d87 100644 --- a/src/Protocol/Activity/ObjectType.php +++ b/src/Protocol/Activity/ObjectType.php @@ -13,14 +13,14 @@ final class ObjectType * @see http://activitystrea.ms/head/activity-schema.html#bookmark * @var string */ - const BOOKMARK = ANamespace::ACTIVITY_SCHEMA . 'bookmark'; + const BOOKMARK = ActivityNamespace::ACTIVITY_SCHEMA . 'bookmark'; /** * The "comment" object type represents a textual response to another object. * * @see http://activitystrea.ms/head/activity-schema.html#comment * @var string */ - const COMMENT = ANamespace::ACTIVITY_SCHEMA . 'comment'; + const COMMENT = ActivityNamespace::ACTIVITY_SCHEMA . 'comment'; /** * The "comment" object type represents a textual response to another object. * (Default type for items) @@ -28,25 +28,25 @@ final class ObjectType * @see http://activitystrea.ms/head/activity-schema.html#note * @var string */ - const NOTE = ANamespace::ACTIVITY_SCHEMA . 'note'; + const NOTE = ActivityNamespace::ACTIVITY_SCHEMA . 'note'; /** * The "person" object type represents a user account. * * @see http://activitystrea.ms/head/activity-schema.html#person * @var string */ - const PERSON = ANamespace::ACTIVITY_SCHEMA . 'person'; + const PERSON = ActivityNamespace::ACTIVITY_SCHEMA . 'person'; /** * The "image" object type represents a graphical image. * * @see http://activitystrea.ms/head/activity-schema.html#image * @var string */ - const IMAGE = ANamespace::ACTIVITY_SCHEMA . 'image'; + const IMAGE = ActivityNamespace::ACTIVITY_SCHEMA . 'image'; /** * @var string */ - const PHOTO = ANamespace::ACTIVITY_SCHEMA . 'photo'; + const PHOTO = ActivityNamespace::ACTIVITY_SCHEMA . 'photo'; /** * The "video" object type represents video content, * which usually consists of a motion picture track and an audio track. @@ -54,43 +54,43 @@ final class ObjectType * @see http://activitystrea.ms/head/activity-schema.html#video * @var string */ - const VIDEO = ANamespace::ACTIVITY_SCHEMA . 'video'; + const VIDEO = ActivityNamespace::ACTIVITY_SCHEMA . 'video'; /** * @var string */ - const PROFILE_PHOTO = ANamespace::ACTIVITY_SCHEMA . 'profile-photo'; + const PROFILE_PHOTO = ActivityNamespace::ACTIVITY_SCHEMA . 'profile-photo'; /** * @var string */ - const ALBUM = ANamespace::ACTIVITY_SCHEMA . 'photo-album'; + const ALBUM = ActivityNamespace::ACTIVITY_SCHEMA . 'photo-album'; /** * The "event" object type represents an event that occurs in a certain place during a particular interval of time. * * @see http://activitystrea.ms/head/activity-schema.html#event * @var string */ - const EVENT = ANamespace::ACTIVITY_SCHEMA . 'event'; + const EVENT = ActivityNamespace::ACTIVITY_SCHEMA . 'event'; /** * The "group" object type represents a grouping of objects in which member objects can join or leave. * * @see http://activitystrea.ms/head/activity-schema.html#group * @var string */ - const GROUP = ANamespace::ACTIVITY_SCHEMA . 'group'; + const GROUP = ActivityNamespace::ACTIVITY_SCHEMA . 'group'; /** * @var string */ - const HEART = ANamespace::DFRN . '/heart'; + const HEART = ActivityNamespace::DFRN . '/heart'; /** * @var string */ - const TAGTERM = ANamespace::DFRN . '/tagterm'; + const TAGTERM = ActivityNamespace::DFRN . '/tagterm'; /** * @var string */ - const PROFILE = ANamespace::DFRN . '/profile'; + const PROFILE = ActivityNamespace::DFRN . '/profile'; /** diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index 6bf3e6e4f..6e84fdbb3 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -32,7 +32,7 @@ use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; -use Friendica\Protocol\Activity\ANamespace; +use Friendica\Protocol\Activity\ActivityNamespace; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; @@ -381,18 +381,18 @@ class DFRN $type = 'html'; if ($conversation) { - $root = $doc->createElementNS(ANamespace::ATOM1, 'feed'); + $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", ANamespace::THREAD); - $root->setAttribute("xmlns:at", ANamespace::TOMB); - $root->setAttribute("xmlns:media", ANamespace::MEDIA); - $root->setAttribute("xmlns:dfrn", ANamespace::DFRN); - $root->setAttribute("xmlns:activity", ANamespace::ACTIVITY); - $root->setAttribute("xmlns:georss", ANamespace::GEORSS); - $root->setAttribute("xmlns:poco", ANamespace::POCO); - $root->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); - $root->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); + $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD); + $root->setAttribute("xmlns:at", ActivityNamespace::TOMB); + $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA); + $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN); + $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY); + $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS); + $root->setAttribute("xmlns:poco", ActivityNamespace::POCO); + $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS); + $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET); //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false); @@ -556,18 +556,18 @@ class DFRN $alternatelink = $owner['url']; } - $root = $doc->createElementNS(ANamespace::ATOM1, 'feed'); + $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", ANamespace::THREAD); - $root->setAttribute("xmlns:at", ANamespace::TOMB); - $root->setAttribute("xmlns:media", ANamespace::MEDIA); - $root->setAttribute("xmlns:dfrn", ANamespace::DFRN); - $root->setAttribute("xmlns:activity", ANamespace::ACTIVITY); - $root->setAttribute("xmlns:georss", ANamespace::GEORSS); - $root->setAttribute("xmlns:poco", ANamespace::POCO); - $root->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); - $root->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); + $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD); + $root->setAttribute("xmlns:at", ActivityNamespace::TOMB); + $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA); + $root->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN); + $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY); + $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS); + $root->setAttribute("xmlns:poco", ActivityNamespace::POCO); + $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS); + $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET); XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]); XML::addElement($doc, $root, "title", $owner["name"]); @@ -940,18 +940,18 @@ class DFRN if (!$single) { $entry = $doc->createElement("entry"); } else { - $entry = $doc->createElementNS(ANamespace::ATOM1, 'entry'); + $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry'); $doc->appendChild($entry); - $entry->setAttribute("xmlns:thr", ANamespace::THREAD); - $entry->setAttribute("xmlns:at", ANamespace::TOMB); - $entry->setAttribute("xmlns:media", ANamespace::MEDIA); - $entry->setAttribute("xmlns:dfrn", ANamespace::DFRN); - $entry->setAttribute("xmlns:activity", ANamespace::ACTIVITY); - $entry->setAttribute("xmlns:georss", ANamespace::GEORSS); - $entry->setAttribute("xmlns:poco", ANamespace::POCO); - $entry->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); - $entry->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); + $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD); + $entry->setAttribute("xmlns:at", ActivityNamespace::TOMB); + $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA); + $entry->setAttribute("xmlns:dfrn", ActivityNamespace::DFRN); + $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY); + $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS); + $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO); + $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS); + $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET); } if ($item['private']) { @@ -1749,7 +1749,7 @@ class DFRN $obj_doc = new DOMDocument("1.0", "utf-8"); $obj_doc->formatOutput = true; - $obj_element = $obj_doc->createElementNS( ANamespace::ATOM1, $element); + $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element); $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue; XML::addElement($obj_doc, $obj_element, "type", $activity_type); @@ -2730,16 +2730,16 @@ class DFRN @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace("atom", ANamespace::ATOM1); - $xpath->registerNamespace("thr", ANamespace::THREAD); - $xpath->registerNamespace("at", ANamespace::TOMB); - $xpath->registerNamespace("media", ANamespace::MEDIA); - $xpath->registerNamespace("dfrn", ANamespace::DFRN); - $xpath->registerNamespace("activity", ANamespace::ACTIVITY); - $xpath->registerNamespace("georss", ANamespace::GEORSS); - $xpath->registerNamespace("poco", ANamespace::POCO); - $xpath->registerNamespace("ostatus", ANamespace::OSTATUS); - $xpath->registerNamespace("statusnet", ANamespace::STATUSNET); + $xpath->registerNamespace("atom", ActivityNamespace::ATOM1); + $xpath->registerNamespace("thr", ActivityNamespace::THREAD); + $xpath->registerNamespace("at", ActivityNamespace::TOMB); + $xpath->registerNamespace("media", ActivityNamespace::MEDIA); + $xpath->registerNamespace("dfrn", ActivityNamespace::DFRN); + $xpath->registerNamespace("activity", ActivityNamespace::ACTIVITY); + $xpath->registerNamespace("georss", ActivityNamespace::GEORSS); + $xpath->registerNamespace("poco", ActivityNamespace::POCO); + $xpath->registerNamespace("ostatus", ActivityNamespace::OSTATUS); + $xpath->registerNamespace("statusnet", ActivityNamespace::STATUSNET); $header = []; $header["uid"] = $importer["importer_uid"]; diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index 709dfa02f..6fcfa36bd 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -32,7 +32,7 @@ use Friendica\Model\Mail; use Friendica\Model\Profile; use Friendica\Model\User; use Friendica\Network\Probe; -use Friendica\Protocol\Activity\ANamespace; +use Friendica\Protocol\Activity\ActivityNamespace; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Map; @@ -466,7 +466,7 @@ class Diaspora } } - $base = $basedom->children(ANamespace::SALMON_ME); + $base = $basedom->children(ActivityNamespace::SALMON_ME); // Not sure if this cleaning is needed $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data); @@ -578,7 +578,7 @@ class Diaspora $author_link = str_replace('acct:', '', $idom->author_id); } - $dom = $basedom->children(ANamespace::SALMON_ME); + $dom = $basedom->children(ActivityNamespace::SALMON_ME); // figure out where in the DOM tree our data is hiding diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index 816820bc4..31f54e50c 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -14,7 +14,7 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Item; -use Friendica\Protocol\Activity\ANamespace; +use Friendica\Protocol\Activity\ActivityNamespace; use Friendica\Util\Network; use Friendica\Util\XML; @@ -60,13 +60,13 @@ class Feed { $doc = new DOMDocument(); @$doc->loadXML(trim($xml)); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', ANamespace::ATOM1); + $xpath->registerNamespace('atom', ActivityNamespace::ATOM1); $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/"); $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/"); $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/"); $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/"); - $xpath->registerNamespace('poco', ANamespace::POCO); + $xpath->registerNamespace('poco', ActivityNamespace::POCO); $author = []; $entries = null; diff --git a/src/Protocol/OStatus.php b/src/Protocol/OStatus.php index d0f7d7edf..9a41920ae 100644 --- a/src/Protocol/OStatus.php +++ b/src/Protocol/OStatus.php @@ -25,7 +25,7 @@ use Friendica\Model\Item; use Friendica\Model\User; use Friendica\Network\Probe; use Friendica\Object\Image; -use Friendica\Protocol\Activity\ANamespace; +use Friendica\Protocol\Activity\ActivityNamespace; use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; use Friendica\Util\Proxy as ProxyUtils; @@ -262,14 +262,14 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', ANamespace::ATOM1); - $xpath->registerNamespace('thr', ANamespace::THREAD); - $xpath->registerNamespace('georss', ANamespace::GEORSS); - $xpath->registerNamespace('activity', ANamespace::ACTIVITY); - $xpath->registerNamespace('media', ANamespace::MEDIA); - $xpath->registerNamespace('poco', ANamespace::POCO); - $xpath->registerNamespace('ostatus', ANamespace::OSTATUS); - $xpath->registerNamespace('statusnet', ANamespace::STATUSNET); + $xpath->registerNamespace('atom', ActivityNamespace::ATOM1); + $xpath->registerNamespace('thr', ActivityNamespace::THREAD); + $xpath->registerNamespace('georss', ActivityNamespace::GEORSS); + $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY); + $xpath->registerNamespace('media', ActivityNamespace::MEDIA); + $xpath->registerNamespace('poco', ActivityNamespace::POCO); + $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS); + $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET); $contact = ["id" => 0]; @@ -343,14 +343,14 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', ANamespace::ATOM1); - $xpath->registerNamespace('thr', ANamespace::THREAD); - $xpath->registerNamespace('georss', ANamespace::GEORSS); - $xpath->registerNamespace('activity', ANamespace::ACTIVITY); - $xpath->registerNamespace('media', ANamespace::MEDIA); - $xpath->registerNamespace('poco', ANamespace::POCO); - $xpath->registerNamespace('ostatus', ANamespace::OSTATUS); - $xpath->registerNamespace('statusnet', ANamespace::STATUSNET); + $xpath->registerNamespace('atom', ActivityNamespace::ATOM1); + $xpath->registerNamespace('thr', ActivityNamespace::THREAD); + $xpath->registerNamespace('georss', ActivityNamespace::GEORSS); + $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY); + $xpath->registerNamespace('media', ActivityNamespace::MEDIA); + $xpath->registerNamespace('poco', ActivityNamespace::POCO); + $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS); + $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET); $hub = ""; $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0); @@ -804,9 +804,9 @@ class OStatus @$doc->loadXML($xml); $xpath = new DOMXPath($doc); - $xpath->registerNamespace('atom', ANamespace::ATOM1); - $xpath->registerNamespace('thr', ANamespace::THREAD); - $xpath->registerNamespace('ostatus', ANamespace::OSTATUS); + $xpath->registerNamespace('atom', ActivityNamespace::ATOM1); + $xpath->registerNamespace('thr', ActivityNamespace::THREAD); + $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS); $entries = $xpath->query('/atom:feed/atom:entry'); @@ -1282,17 +1282,17 @@ class OStatus */ private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false) { - $root = $doc->createElementNS(ANamespace::ATOM1, 'feed'); + $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed'); $doc->appendChild($root); - $root->setAttribute("xmlns:thr", ANamespace::THREAD); - $root->setAttribute("xmlns:georss", ANamespace::GEORSS); - $root->setAttribute("xmlns:activity", ANamespace::ACTIVITY); - $root->setAttribute("xmlns:media", ANamespace::MEDIA); - $root->setAttribute("xmlns:poco", ANamespace::POCO); - $root->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); - $root->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); - $root->setAttribute("xmlns:mastodon", ANamespace::MASTODON); + $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD); + $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS); + $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY); + $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA); + $root->setAttribute("xmlns:poco", ActivityNamespace::POCO); + $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS); + $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET); + $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON); $title = ''; $selfUri = '/feed/' . $owner["nick"] . '/'; @@ -1710,7 +1710,7 @@ class OStatus $as_object = $doc->createElement("activity:object"); - XML::addElement($doc, $as_object, "activity:object-type", ANamespace::ACTIVITY_SCHEMA . "activity"); + XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity"); self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false); @@ -1760,7 +1760,7 @@ class OStatus $entry = self::entryHeader($doc, $owner, $item, $toplevel); - $verb = Activity\ANamespace::ACTIVITY_SCHEMA . "favorite"; + $verb = Activity\ActivityNamespace::ACTIVITY_SCHEMA . "favorite"; self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false); $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]); @@ -1951,16 +1951,16 @@ class OStatus $entry->appendChild($author); } } else { - $entry = $doc->createElementNS(ANamespace::ATOM1, "entry"); + $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry"); - $entry->setAttribute("xmlns:thr", ANamespace::THREAD); - $entry->setAttribute("xmlns:georss", ANamespace::GEORSS); - $entry->setAttribute("xmlns:activity", ANamespace::ACTIVITY); - $entry->setAttribute("xmlns:media", ANamespace::MEDIA); - $entry->setAttribute("xmlns:poco", ANamespace::POCO); - $entry->setAttribute("xmlns:ostatus", ANamespace::OSTATUS); - $entry->setAttribute("xmlns:statusnet", ANamespace::STATUSNET); - $entry->setAttribute("xmlns:mastodon", ANamespace::MASTODON); + $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD); + $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS); + $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY); + $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA); + $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO); + $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS); + $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET); + $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON); $author = self::addAuthor($doc, $owner); $entry->appendChild($author); diff --git a/tests/src/Protocol/ActivityTest.php b/tests/src/Protocol/ActivityTest.php index ac332a7f7..5249ebefa 100644 --- a/tests/src/Protocol/ActivityTest.php +++ b/tests/src/Protocol/ActivityTest.php @@ -22,7 +22,7 @@ class ActivityTest extends MockedTest ], 'withNamespace' => [ 'haystack' => 'tagterm', - 'needle' => Activity\ANamespace::ACTIVITY_SCHEMA . Activity\ObjectType::TAGTERM, + 'needle' => Activity\ActivityNamespace::ACTIVITY_SCHEMA . Activity\ObjectType::TAGTERM, 'assert' => true, ], 'invalidSimple' => [ @@ -37,7 +37,7 @@ class ActivityTest extends MockedTest ], 'withSubPath' => [ 'haystack' => 'tagterm', - 'needle' => Activity\ANamespace::ACTIVITY_SCHEMA . '/bla/' . Activity\ObjectType::TAGTERM, + 'needle' => Activity\ActivityNamespace::ACTIVITY_SCHEMA . '/bla/' . Activity\ObjectType::TAGTERM, 'assert' => true, ], ]; From 7343ee510826e981a80c8db1da86d2aa524a488d Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Fri, 25 Oct 2019 00:34:46 +0200 Subject: [PATCH 35/46] Move Namespace of ActivityNamespace --- mod/salmon.php | 2 +- src/Module/Xrd.php | 2 +- src/Network/Probe.php | 2 +- src/Protocol/Activity.php | 2 +- src/Protocol/Activity/ObjectType.php | 2 ++ src/Protocol/{Activity => }/ActivityNamespace.php | 2 +- src/Protocol/DFRN.php | 2 +- src/Protocol/Diaspora.php | 2 +- src/Protocol/Feed.php | 2 +- src/Protocol/OStatus.php | 4 ++-- tests/src/Protocol/ActivityTest.php | 5 +++-- 11 files changed, 15 insertions(+), 12 deletions(-) rename src/Protocol/{Activity => }/ActivityNamespace.php (99%) diff --git a/mod/salmon.php b/mod/salmon.php index 2a7c4a4b3..313c2cb0b 100644 --- a/mod/salmon.php +++ b/mod/salmon.php @@ -9,7 +9,7 @@ use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\Model\Contact; -use Friendica\Protocol\Activity\ActivityNamespace; +use Friendica\Protocol\ActivityNamespace; use Friendica\Protocol\OStatus; use Friendica\Protocol\Salmon; use Friendica\Util\Crypto; diff --git a/src/Module/Xrd.php b/src/Module/Xrd.php index 77fa3959a..1028bfd53 100644 --- a/src/Module/Xrd.php +++ b/src/Module/Xrd.php @@ -8,7 +8,7 @@ use Friendica\Core\Renderer; use Friendica\Database\DBA; use Friendica\Model\Photo; use Friendica\Model\User; -use Friendica\Protocol\Activity\ActivityNamespace; +use Friendica\Protocol\ActivityNamespace; use Friendica\Protocol\Salmon; use Friendica\Util\Strings; diff --git a/src/Network/Probe.php b/src/Network/Probe.php index e63224411..80fa641ed 100644 --- a/src/Network/Probe.php +++ b/src/Network/Probe.php @@ -18,7 +18,7 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Model\Profile; -use Friendica\Protocol\Activity\ActivityNamespace; +use Friendica\Protocol\ActivityNamespace; use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Email; use Friendica\Protocol\Feed; diff --git a/src/Protocol/Activity.php b/src/Protocol/Activity.php index d2c5eec4b..bea2dedb0 100644 --- a/src/Protocol/Activity.php +++ b/src/Protocol/Activity.php @@ -2,7 +2,7 @@ namespace Friendica\Protocol; -use Friendica\Protocol\Activity\ActivityNamespace; +use Friendica\Protocol\ActivityNamespace; /** * Base class for the Activity Verbs diff --git a/src/Protocol/Activity/ObjectType.php b/src/Protocol/Activity/ObjectType.php index 7bed40d87..313378b3e 100644 --- a/src/Protocol/Activity/ObjectType.php +++ b/src/Protocol/Activity/ObjectType.php @@ -2,6 +2,8 @@ namespace Friendica\Protocol\Activity; +use Friendica\Protocol\ActivityNamespace; + /** * This class contains the different object types in activities */ diff --git a/src/Protocol/Activity/ActivityNamespace.php b/src/Protocol/ActivityNamespace.php similarity index 99% rename from src/Protocol/Activity/ActivityNamespace.php rename to src/Protocol/ActivityNamespace.php index a821f069e..c504f2833 100644 --- a/src/Protocol/Activity/ActivityNamespace.php +++ b/src/Protocol/ActivityNamespace.php @@ -1,6 +1,6 @@ $item["thr-parent"], 'uid' => $item["uid"]]); diff --git a/tests/src/Protocol/ActivityTest.php b/tests/src/Protocol/ActivityTest.php index 5249ebefa..a3e9c1148 100644 --- a/tests/src/Protocol/ActivityTest.php +++ b/tests/src/Protocol/ActivityTest.php @@ -3,6 +3,7 @@ namespace Friendica\Test\Protocol; use Friendica\Protocol\Activity; +use Friendica\Protocol\ActivityNamespace; use Friendica\Test\MockedTest; class ActivityTest extends MockedTest @@ -22,7 +23,7 @@ class ActivityTest extends MockedTest ], 'withNamespace' => [ 'haystack' => 'tagterm', - 'needle' => Activity\ActivityNamespace::ACTIVITY_SCHEMA . Activity\ObjectType::TAGTERM, + 'needle' => ActivityNamespace::ACTIVITY_SCHEMA . Activity\ObjectType::TAGTERM, 'assert' => true, ], 'invalidSimple' => [ @@ -37,7 +38,7 @@ class ActivityTest extends MockedTest ], 'withSubPath' => [ 'haystack' => 'tagterm', - 'needle' => Activity\ActivityNamespace::ACTIVITY_SCHEMA . '/bla/' . Activity\ObjectType::TAGTERM, + 'needle' => ActivityNamespace::ACTIVITY_SCHEMA . '/bla/' . Activity\ObjectType::TAGTERM, 'assert' => true, ], ]; From 9f86465fb97effb601dc2ae36ee1301a654b1dce Mon Sep 17 00:00:00 2001 From: Michael Date: Fri, 25 Oct 2019 23:23:38 +0000 Subject: [PATCH 36/46] Images: Show the description as title --- src/Content/Text/BBCode.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php index 75f5d506e..0dbac8b77 100644 --- a/src/Content/Text/BBCode.php +++ b/src/Content/Text/BBCode.php @@ -1552,7 +1552,7 @@ class BBCode extends BaseObject function ($matches) use ($simple_html) { $matches[1] = self::proxyUrl($matches[1], $simple_html); $matches[2] = htmlspecialchars($matches[2], ENT_COMPAT); - return '' . $matches[2] . ''; + return '' . $matches[2] . ''; }, $text); From 1f368d469f4916d7424c2ecdaeeaa0a9fde0e6a0 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sat, 26 Oct 2019 02:01:46 +0200 Subject: [PATCH 37/46] Move Friendica\Core\NotificationsManager to Friendica\Model\Notify --- include/api.php | 6 +++--- mod/notifications.php | 5 ++--- src/{Core/NotificationsManager.php => Model/Notify.php} | 6 ++---- src/Module/Notifications/Notify.php | 6 +++--- 4 files changed, 10 insertions(+), 13 deletions(-) rename src/{Core/NotificationsManager.php => Model/Notify.php} (99%) diff --git a/include/api.php b/include/api.php index 91e31ac94..711c4fea1 100644 --- a/include/api.php +++ b/include/api.php @@ -15,7 +15,6 @@ use Friendica\Core\Config; use Friendica\Core\Hook; use Friendica\Core\L10n; use Friendica\Core\Logger; -use Friendica\Core\NotificationsManager; use Friendica\Core\PConfig; use Friendica\Core\Protocol; use Friendica\Core\Session; @@ -26,6 +25,7 @@ use Friendica\Model\Contact; use Friendica\Model\Group; use Friendica\Model\Item; use Friendica\Model\Mail; +use Friendica\Model\Notify; use Friendica\Model\Photo; use Friendica\Model\Profile; use Friendica\Model\User; @@ -6040,7 +6040,7 @@ function api_friendica_notification($type) if ($a->argc!==3) { throw new BadRequestException("Invalid argument count"); } - $nm = new NotificationsManager(); + $nm = new Notify(); $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50); @@ -6084,7 +6084,7 @@ function api_friendica_notification_seen($type) $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0); - $nm = new NotificationsManager(); + $nm = new Notify(); $note = $nm->getByID($id); if (is_null($note)) { throw new BadRequestException("Invalid argument"); diff --git a/mod/notifications.php b/mod/notifications.php index 8fbc5dac4..a288a0358 100644 --- a/mod/notifications.php +++ b/mod/notifications.php @@ -9,14 +9,13 @@ use Friendica\Content\ContactSelector; use Friendica\Content\Nav; use Friendica\Content\Pager; use Friendica\Core\L10n; -use Friendica\Core\NotificationsManager; use Friendica\Core\Protocol; use Friendica\Core\Renderer; -use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\Module\Login; use Friendica\Model\Contact; +use Friendica\Model\Notify; function notifications_post(App $a) { @@ -85,7 +84,7 @@ function notifications_content(App $a) $json = (($a->argc > 1 && $a->argv[$a->argc - 1] === 'json') ? true : false); - $nm = new NotificationsManager(); + $nm = new Notify(); $o = ''; // Get the nav tabs for the notification pages diff --git a/src/Core/NotificationsManager.php b/src/Model/Notify.php similarity index 99% rename from src/Core/NotificationsManager.php rename to src/Model/Notify.php index cf2dd9e36..9efedc031 100644 --- a/src/Core/NotificationsManager.php +++ b/src/Model/Notify.php @@ -4,14 +4,12 @@ * @brief Methods for read and write notifications from/to database * or for formatting notifications */ -namespace Friendica\Core; +namespace Friendica\Model; use Friendica\BaseObject; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; use Friendica\Database\DBA; -use Friendica\Model\Contact; -use Friendica\Model\Item; use Friendica\Protocol\Activity; use Friendica\Util\DateTimeFormat; use Friendica\Util\Proxy as ProxyUtils; @@ -22,7 +20,7 @@ use Friendica\Util\XML; * @brief Methods for read and write notifications from/to database * or for formatting notifications */ -class NotificationsManager extends BaseObject +final class Notify extends BaseObject { /** * @brief set some extra note properties diff --git a/src/Module/Notifications/Notify.php b/src/Module/Notifications/Notify.php index d31de2cdd..4998a0adb 100644 --- a/src/Module/Notifications/Notify.php +++ b/src/Module/Notifications/Notify.php @@ -4,8 +4,8 @@ namespace Friendica\Module\Notifications; use Friendica\BaseModule; use Friendica\Core\L10n; -use Friendica\Core\NotificationsManager; use Friendica\Core\System; +use Friendica\Model\Notify as ModelNotify; use Friendica\Network\HTTPException; /** @@ -26,7 +26,7 @@ class Notify extends BaseModule // @TODO: Replace with parameter from router if ($a->argc > 2 && $a->argv[1] === 'mark' && $a->argv[2] === 'all') { - $notificationsManager = new NotificationsManager(); + $notificationsManager = new ModelNotify(); $success = $notificationsManager->setAllSeen(); header('Content-type: application/json; charset=utf-8'); @@ -49,7 +49,7 @@ class Notify extends BaseModule // @TODO: Replace with parameter from router if ($a->argc > 2 && $a->argv[1] === 'view' && intval($a->argv[2])) { - $notificationsManager = new NotificationsManager(); + $notificationsManager = new ModelNotify(); // @TODO: Replace with parameter from router $note = $notificationsManager->getByID($a->argv[2]); if (!empty($note)) { From a72e65a7603bc901d1f36faad4b88ddf19ef552f Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sat, 26 Oct 2019 04:03:27 +0200 Subject: [PATCH 38/46] Adapt class structure - Introduce constants - Add constructor parameters - Add typehints - Renamed fields more meaningful - Renamed method names to match identifier - Adjust PHP doc - Add GetClass call at used places --- include/api.php | 13 +- mod/notifications.php | 13 +- src/Model/Notify.php | 647 +++++++++++++++------------- src/Module/Notifications/Notify.php | 7 +- 4 files changed, 368 insertions(+), 312 deletions(-) diff --git a/include/api.php b/include/api.php index 711c4fea1..24a0585ee 100644 --- a/include/api.php +++ b/include/api.php @@ -7,6 +7,7 @@ */ use Friendica\App; +use Friendica\BaseObject; use Friendica\Content\ContactSelector; use Friendica\Content\Feature; use Friendica\Content\Text\BBCode; @@ -1375,7 +1376,7 @@ function api_get_item(array $condition) */ function api_users_show($type) { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); $user_info = api_get_user($a); @@ -2948,7 +2949,7 @@ function api_format_items_profiles($profile_row) */ function api_format_items($items, $user_info, $filter_user = false, $type = "json") { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); $ret = []; @@ -2982,7 +2983,7 @@ function api_format_items($items, $user_info, $filter_user = false, $type = "jso */ function api_format_item($item, $type = "json", $status_user = null, $author_user = null, $owner_user = null) { - $a = \Friendica\BaseObject::getApp(); + $a = BaseObject::getApp(); if (empty($status_user) || empty($author_user) || empty($owner_user)) { list($status_user, $author_user, $owner_user) = api_item_get_user($a, $item); @@ -6040,7 +6041,8 @@ function api_friendica_notification($type) if ($a->argc!==3) { throw new BadRequestException("Invalid argument count"); } - $nm = new Notify(); + /** @var Notify $nm */ + $nm = BaseObject::getClass(Notify::class); $notes = $nm->getAll([], ['seen' => 'ASC', 'date' => 'DESC'], 50); @@ -6084,7 +6086,8 @@ function api_friendica_notification_seen($type) $id = (!empty($_REQUEST['id']) ? intval($_REQUEST['id']) : 0); - $nm = new Notify(); + /** @var Notify $nm */ + $nm = BaseObject::getClass(Notify::class); $note = $nm->getByID($id); if (is_null($note)) { throw new BadRequestException("Invalid argument"); diff --git a/mod/notifications.php b/mod/notifications.php index a288a0358..b60c604fc 100644 --- a/mod/notifications.php +++ b/mod/notifications.php @@ -84,7 +84,8 @@ function notifications_content(App $a) $json = (($a->argc > 1 && $a->argv[$a->argc - 1] === 'json') ? true : false); - $nm = new Notify(); + /** @var Notify $nm */ + $nm = \Friendica\BaseObject::getClass(Notify::class); $o = ''; // Get the nav tabs for the notification pages @@ -111,27 +112,27 @@ function notifications_content(App $a) $all = (($a->argc > 2) && ($a->argv[2] == 'all')); - $notifs = $nm->introNotifs($all, $startrec, $perpage, $id); + $notifs = $nm->getIntroNotifies($all, $startrec, $perpage, $id); // Get the network notifications } elseif (($a->argc > 1) && ($a->argv[1] == 'network')) { $notif_header = L10n::t('Network Notifications'); - $notifs = $nm->networkNotifs($show, $startrec, $perpage); + $notifs = $nm->getNetworkNotifies($show, $startrec, $perpage); // Get the system notifications } elseif (($a->argc > 1) && ($a->argv[1] == 'system')) { $notif_header = L10n::t('System Notifications'); - $notifs = $nm->systemNotifs($show, $startrec, $perpage); + $notifs = $nm->getSystemNotifies($show, $startrec, $perpage); // Get the personal notifications } elseif (($a->argc > 1) && ($a->argv[1] == 'personal')) { $notif_header = L10n::t('Personal Notifications'); - $notifs = $nm->personalNotifs($show, $startrec, $perpage); + $notifs = $nm->getPersonalNotifies($show, $startrec, $perpage); // Get the home notifications } elseif (($a->argc > 1) && ($a->argv[1] == 'home')) { $notif_header = L10n::t('Home Notifications'); - $notifs = $nm->homeNotifs($show, $startrec, $perpage); + $notifs = $nm->getHomeNotifies($show, $startrec, $perpage); // fallback - redirect to main page } else { $a->internalRedirect('notifications'); diff --git a/src/Model/Notify.php b/src/Model/Notify.php index 9efedc031..2d9ad9142 100644 --- a/src/Model/Notify.php +++ b/src/Model/Notify.php @@ -1,20 +1,25 @@ 'network', + self::SYSTEM => 'system', + self::HOME => 'home', + self::PERSONAL => 'personal', + self::INTRO => 'intros', + ]; + + /** @var array Array of the allowed notifies and their printable name */ + const PRINT_TYPES = [ + self::NETWORK => 'Network', + self::SYSTEM => 'System', + self::HOME => 'Home', + self::PERSONAL => 'Personal', + self::INTRO => 'Introductions', + ]; + + /** @var array The array of access keys for notify pages */ + const ACCESS_KEYS = [ + self::NETWORK => 'w', + self::SYSTEM => 'y', + self::HOME => 'h', + self::PERSONAL => 'r', + self::INTRO => 'i', + ]; + + /** @var Database */ + private $dba; + /** @var L10n */ + private $l10n; + /** @var App\Arguments */ + private $args; + /** @var App\BaseURL */ + private $baseUrl; + /** @var PConfiguration */ + private $pConfig; + /** @var LoggerInterface */ + private $logger; + + public function __construct(Database $dba, L10n $l10n, App\Arguments $args, App\BaseURL $baseUrl, + PConfiguration $pConfig, LoggerInterface $logger) + { + $this->dba = $dba; + $this->l10n = $l10n; + $this->args = $args; + $this->baseUrl = $baseUrl; + $this->pConfig = $pConfig; + $this->logger = $logger; + } + /** - * @brief set some extra note properties - * - * @param array $notes array of note arrays from db - * @return array Copy of input array with added properties - * * Set some extra properties to note array from db: * - timestamp as int in default TZ * - date_rel : relative date string * - msg_html: message as html string * - msg_plain: message as plain text string - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * + * @param array $notes array of note arrays from db + * + * @return array Copy of input array with added properties + * + * @throws Exception */ - private function _set_extra(array $notes) + private function setExtra(array $notes) { - $rets = []; - foreach ($notes as $n) { - $local_time = DateTimeFormat::local($n['date']); - $n['timestamp'] = strtotime($local_time); - $n['date_rel'] = Temporal::getRelativeDate($n['date']); - $n['msg_html'] = BBCode::convert($n['msg'], false); - $n['msg_plain'] = explode("\n", trim(HTML::toPlaintext($n['msg_html'], 0)))[0]; + $retNotes = []; + foreach ($notes as $note) { + $local_time = DateTimeFormat::local($note['date']); + $note['timestamp'] = strtotime($local_time); + $note['date_rel'] = Temporal::getRelativeDate($note['date']); + $note['msg_html'] = BBCode::convert($note['msg'], false); + $note['msg_plain'] = explode("\n", trim(HTML::toPlaintext($note['msg_html'], 0)))[0]; - $rets[] = $n; + $retNotes[] = $note; } - return $rets; + return $retNotes; } /** @@ -58,9 +120,9 @@ final class Notify extends BaseObject * @param string $limit optional Query limits * * @return array|bool of results or false on errors - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws Exception */ - public function getAll($filter = [], $order = ['date' => 'DESC'], $limit = "") + public function getAll(array $filter = [], array $order = ['date' => 'DESC'], string $limit = "") { $params = []; @@ -72,10 +134,10 @@ final class Notify extends BaseObject $dbFilter = array_merge($filter, ['uid' => local_user()]); - $stmtNotifies = DBA::select('notify', [], $dbFilter, $params); + $stmtNotifies = $this->dba->select('notify', [], $dbFilter, $params); - if (DBA::isResult($stmtNotifies)) { - return $this->_set_extra(DBA::toArray($stmtNotifies)); + if ($this->dba->isResult($stmtNotifies)) { + return $this->setExtra($this->dba->toArray($stmtNotifies)); } return false; @@ -85,14 +147,15 @@ final class Notify extends BaseObject * @brief Get one note for local_user() by $id value * * @param int $id identity + * * @return array note values or null if not found - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws Exception */ - public function getByID($id) + public function getByID(int $id) { - $stmtNotify = DBA::selectFirst('notify', [], ['id' => $id, 'uid' => local_user()]); - if (DBA::isResult($stmtNotify)) { - return $this->_set_extra([$stmtNotify])[0]; + $stmtNotify = $this->dba->selectFirst('notify', [], ['id' => $id, 'uid' => local_user()]); + if ($this->dba->isResult($stmtNotify)) { + return $this->setExtra([$stmtNotify])[0]; } return null; } @@ -102,12 +165,13 @@ final class Notify extends BaseObject * * @param array $note note array * @param bool $seen optional true or false, default true + * * @return bool true on success, false on errors - * @throws \Exception + * @throws Exception */ - public function setSeen($note, $seen = true) + public function setSeen(array $note, bool $seen = true) { - return DBA::update('notify', ['seen' => $seen], [ + return $this->dba->update('notify', ['seen' => $seen], [ '(`link` = ? OR (`parent` != 0 AND `parent` = ? AND `otype` = ?)) AND `uid` = ?', $note['link'], $note['parent'], @@ -120,61 +184,36 @@ final class Notify extends BaseObject * @brief set seen state of all notifications of local_user() * * @param bool $seen optional true or false. default true + * * @return bool true on success, false on error - * @throws \Exception + * @throws Exception */ - public function setAllSeen($seen = true) + public function setAllSeen(bool $seen = true) { - return DBA::update('notify', ['seen' => $seen], ['uid' => local_user()]); + return $this->dba->update('notify', ['seen' => $seen], ['uid' => local_user()]); } /** * @brief List of pages for the Notifications TabBar * * @return array with with notifications TabBar data - * @throws \Exception + * @throws Exception */ public function getTabs() { - $selected = self::getApp()->argv[1] ?? ''; + $selected = $this->args->get(1, ''); - $tabs = [ - [ - 'label' => L10n::t('System'), - 'url' => 'notifications/system', - 'sel' => (($selected == 'system') ? 'active' : ''), - 'id' => 'system-tab', - 'accesskey' => 'y', - ], - [ - 'label' => L10n::t('Network'), - 'url' => 'notifications/network', - 'sel' => (($selected == 'network') ? 'active' : ''), - 'id' => 'network-tab', - 'accesskey' => 'w', - ], - [ - 'label' => L10n::t('Personal'), - 'url' => 'notifications/personal', - 'sel' => (($selected == 'personal') ? 'active' : ''), - 'id' => 'personal-tab', - 'accesskey' => 'r', - ], - [ - 'label' => L10n::t('Home'), - 'url' => 'notifications/home', - 'sel' => (($selected == 'home') ? 'active' : ''), - 'id' => 'home-tab', - 'accesskey' => 'h', - ], - [ - 'label' => L10n::t('Introductions'), - 'url' => 'notifications/intros', - 'sel' => (($selected == 'intros') ? 'active' : ''), - 'id' => 'intro-tab', - 'accesskey' => 'i', - ], - ]; + $tabs = []; + + foreach (self::URL_TYPES as $type => $url) { + $tabs[] = [ + 'label' => $this->l10n->t(self::PRINT_TYPES[$type]), + 'url' => 'notifications/' . $url, + 'sel' => (($selected == $url) ? 'active' : ''), + 'id' => $type . '-tab', + 'accesskey' => self::ACCESS_KEYS[$type], + ]; + } return $tabs; } @@ -182,8 +221,9 @@ final class Notify extends BaseObject /** * @brief Format the notification query in an usable array * - * @param array $notifs The array from the db query - * @param string $ident The notifications identifier (e.g. network) + * @param array $notifies The array from the db query + * @param string $ident The notifications identifier (e.g. network) + * * @return array * string 'label' => The type of the notification * string 'link' => URL to the source @@ -193,174 +233,174 @@ final class Notify extends BaseObject * string 'when' => The date of the notification * string 'ago' => T relative date of the notification * bool 'seen' => Is the notification marked as "seen" - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws Exception */ - private function formatNotifs(array $notifs, $ident = "") + private function formatNotifies(array $notifies, string $ident = "") { $arr = []; - if (DBA::isResult($notifs)) { - foreach ($notifs as $it) { + if ($this->dba->isResult($notifies)) { + foreach ($notifies as $notify) { // Because we use different db tables for the notification query - // we have sometimes $it['unseen'] and sometimes $it['seen]. - // So we will have to transform $it['unseen'] - if (array_key_exists('unseen', $it)) { - $it['seen'] = ($it['unseen'] > 0 ? false : true); + // we have sometimes $notify['unseen'] and sometimes $notify['seen]. + // So we will have to transform $notify['unseen'] + if (array_key_exists('unseen', $notify)) { + $notify['seen'] = ($notify['unseen'] > 0 ? false : true); } // For feed items we use the user's contact, since the avatar is mostly self choosen. - if (!empty($it['network']) && $it['network'] == Protocol::FEED) { - $it['author-avatar'] = $it['contact-avatar']; + if (!empty($notify['network']) && $notify['network'] == Protocol::FEED) { + $notify['author-avatar'] = $notify['contact-avatar']; } // Depending on the identifier of the notification we need to use different defaults switch ($ident) { - case 'system': + case self::SYSTEM: $default_item_label = 'notify'; - $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id']; - $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO); - $default_item_url = $it['url']; - $default_item_text = strip_tags(BBCode::convert($it['msg'])); - $default_item_when = DateTimeFormat::local($it['date'], 'r'); - $default_item_ago = Temporal::getRelativeDate($it['date']); + $default_item_link = $this->baseUrl->get(true) . '/notify/view/' . $notify['id']; + $default_item_image = ProxyUtils::proxifyUrl($notify['photo'], false, ProxyUtils::SIZE_MICRO); + $default_item_url = $notify['url']; + $default_item_text = strip_tags(BBCode::convert($notify['msg'])); + $default_item_when = DateTimeFormat::local($notify['date'], 'r'); + $default_item_ago = Temporal::getRelativeDate($notify['date']); break; - case 'home': + case self::HOME: $default_item_label = 'comment'; - $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid']; - $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO); - $default_item_url = $it['author-link']; - $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']); - $default_item_when = DateTimeFormat::local($it['created'], 'r'); - $default_item_ago = Temporal::getRelativeDate($it['created']); + $default_item_link = $this->baseUrl->get(true) . '/display/' . $notify['parent-guid']; + $default_item_image = ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO); + $default_item_url = $notify['author-link']; + $default_item_text = $this->l10n->t("%s commented on %s's post", $notify['author-name'], $notify['parent-author-name']); + $default_item_when = DateTimeFormat::local($notify['created'], 'r'); + $default_item_ago = Temporal::getRelativeDate($notify['created']); break; default: - $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment'); - $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid']; - $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO); - $default_item_url = $it['author-link']; - $default_item_text = (($it['id'] == $it['parent']) - ? L10n::t("%s created a new post", $it['author-name']) - : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name'])); - $default_item_when = DateTimeFormat::local($it['created'], 'r'); - $default_item_ago = Temporal::getRelativeDate($it['created']); + $default_item_label = (($notify['id'] == $notify['parent']) ? 'post' : 'comment'); + $default_item_link = $this->baseUrl->get(true) . '/display/' . $notify['parent-guid']; + $default_item_image = ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO); + $default_item_url = $notify['author-link']; + $default_item_text = (($notify['id'] == $notify['parent']) + ? $this->l10n->t("%s created a new post", $notify['author-name']) + : $this->l10n->t("%s commented on %s's post", $notify['author-name'], $notify['parent-author-name'])); + $default_item_when = DateTimeFormat::local($notify['created'], 'r'); + $default_item_ago = Temporal::getRelativeDate($notify['created']); } // Transform the different types of notification in an usable array - switch ($it['verb']) { + switch ($notify['verb']) { case Activity::LIKE: - $notif = [ + $notify = [ 'label' => 'like', - 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $it['author-link'], - 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $it['seen'] + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s liked %s's post", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] ]; break; case Activity::DISLIKE: - $notif = [ + $notify = [ 'label' => 'dislike', - 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $it['author-link'], - 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $it['seen'] + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s disliked %s's post", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] ]; break; case Activity::ATTEND: - $notif = [ + $notify = [ 'label' => 'attend', - 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $it['author-link'], - 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $it['seen'] + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s is attending %s's event", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] ]; break; case Activity::ATTENDNO: - $notif = [ + $notify = [ 'label' => 'attendno', - 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $it['author-link'], - 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $it['seen'] + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s is not attending %s's event", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] ]; break; case Activity::ATTENDMAYBE: - $notif = [ + $notify = [ 'label' => 'attendmaybe', - 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $it['author-link'], - 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $it['seen'] + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s may attend %s's event", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] ]; break; case Activity::FRIEND: - if (!isset($it['object'])) { - $notif = [ + if (!isset($notify['object'])) { + $notify = [ 'label' => 'friend', - 'link' => $default_item_link, + 'link' => $default_item_link, 'image' => $default_item_image, - 'url' => $default_item_url, - 'text' => $default_item_text, - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $it['seen'] + 'url' => $default_item_url, + 'text' => $default_item_text, + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] ]; break; } /// @todo Check if this part here is used at all - Logger::log('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), Logger::DEBUG); + $this->logger->info('Complete data.', ['notify' => $notify, 'callStack' => System::callstack(20)]); - $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">"; - $obj = XML::parseString($xmlhead . $it['object']); - $it['fname'] = $obj->title; + $xmlHead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">"; + $obj = XML::parseString($xmlHead . $notify['object']); + $notify['fname'] = $obj->title; - $notif = [ + $notify = [ 'label' => 'friend', - 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $it['author-link'], - 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $it['seen'] + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s is now friends with %s", $notify['author-name'], $notify['fname']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] ]; break; default: - $notif = [ + $notify = [ 'label' => $default_item_label, - 'link' => $default_item_link, + 'link' => $default_item_link, 'image' => $default_item_image, - 'url' => $default_item_url, - 'text' => $default_item_text, - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $it['seen'] + 'url' => $default_item_url, + 'text' => $default_item_text, + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] ]; } - $arr[] = $notif; + $arr[] = $notify; } } @@ -375,15 +415,16 @@ final class Notify extends BaseObject * @param int $start Start the query at this point * @param int $limit Maximum number of query results * - * @return array with + * @return array [string, array] * string 'ident' => Notification identifier * array 'notifications' => Network notifications - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * + * @throws Exception */ - public function networkNotifs($seen = 0, $start = 0, $limit = 80) + public function getNetworkNotifies(int $seen = 0, int $start = 0, int $limit = 80) { - $ident = 'network'; - $notifs = []; + $ident = self::NETWORK; + $notifies = []; $condition = ['wall' => false, 'uid' => local_user()]; @@ -397,13 +438,13 @@ final class Notify extends BaseObject $items = Item::selectForUser(local_user(), $fields, $condition, $params); - if (DBA::isResult($items)) { - $notifs = $this->formatNotifs(Item::inArray($items), $ident); + if ($this->dba->isResult($items)) { + $notifies = $this->formatNotifies(Item::inArray($items), $ident); } $arr = [ - 'notifications' => $notifs, - 'ident' => $ident, + 'notifications' => $notifies, + 'ident' => $ident, ]; return $arr; @@ -417,38 +458,38 @@ final class Notify extends BaseObject * @param int $start Start the query at this point * @param int $limit Maximum number of query results * - * @return array with + * @return array [string, array] * string 'ident' => Notification identifier * array 'notifications' => System notifications - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * + * @throws Exception */ - public function systemNotifs($seen = 0, $start = 0, $limit = 80) + public function getSystemNotifies(int $seen = 0, int $start = 0, int $limit = 80) { - $ident = 'system'; - $notifs = []; - $sql_seen = ""; + $ident = self::SYSTEM; + $notifies = []; $filter = ['uid' => local_user()]; if ($seen === 0) { $filter['seen'] = false; } - $params = []; + $params = []; $params['order'] = ['date' => 'DESC']; $params['limit'] = [$start, $limit]; - $stmtNotifies = DBA::select('notify', + $stmtNotifies = $this->dba->select('notify', ['id', 'url', 'photo', 'msg', 'date', 'seen', 'verb'], $filter, $params); - if (DBA::isResult($stmtNotifies)) { - $notifs = $this->formatNotifs(DBA::toArray($stmtNotifies), $ident); + if ($this->dba->isResult($stmtNotifies)) { + $notifies = $this->formatNotifies($this->dba->toArray($stmtNotifies), $ident); } $arr = [ - 'notifications' => $notifs, - 'ident' => $ident, + 'notifications' => $notifies, + 'ident' => $ident, ]; return $arr; @@ -462,17 +503,18 @@ final class Notify extends BaseObject * @param int $start Start the query at this point * @param int $limit Maximum number of query results * - * @return array with + * @return array [string, array] * string 'ident' => Notification identifier * array 'notifications' => Personal notifications - * @throws \Exception + * + * @throws Exception */ - public function personalNotifs($seen = 0, $start = 0, $limit = 80) + public function getPersonalNotifies(int $seen = 0, int $start = 0, int $limit = 80) { - $ident = 'personal'; - $notifs = []; + $ident = self::PERSONAL; + $notifies = []; - $myurl = str_replace('http://', '', self::getApp()->contact['nurl']); + $myurl = str_replace('http://', '', self::getApp()->contact['nurl']); $diasp_url = str_replace('/profile/', '/u/', $myurl); $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)", @@ -488,13 +530,13 @@ final class Notify extends BaseObject $items = Item::selectForUser(local_user(), $fields, $condition, $params); - if (DBA::isResult($items)) { - $notifs = $this->formatNotifs(Item::inArray($items), $ident); + if ($this->dba->isResult($items)) { + $notifies = $this->formatNotifies(Item::inArray($items), $ident); } $arr = [ - 'notifications' => $notifs, - 'ident' => $ident, + 'notifications' => $notifies, + 'ident' => $ident, ]; return $arr; @@ -508,17 +550,18 @@ final class Notify extends BaseObject * @param int $start Start the query at this point * @param int $limit Maximum number of query results * - * @return array with + * @return array [string, array] * string 'ident' => Notification identifier * array 'notifications' => Home notifications - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * + * @throws Exception */ - public function homeNotifs($seen = 0, $start = 0, $limit = 80) + public function getHomeNotifies($seen = 0, int $start = 0, int $limit = 80) { - $ident = 'home'; - $notifs = []; + $ident = self::HOME; + $notifies = []; - $condition = ['wall' => true, 'uid' => local_user()]; + $condition = ['wall' => false, 'uid' => local_user()]; if ($seen === 0) { $condition['unseen'] = true; @@ -527,15 +570,16 @@ final class Notify extends BaseObject $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar', 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid']; $params = ['order' => ['received' => true], 'limit' => [$start, $limit]]; + $items = Item::selectForUser(local_user(), $fields, $condition, $params); - if (DBA::isResult($items)) { - $notifs = $this->formatNotifs(Item::inArray($items), $ident); + if ($this->dba->isResult($items)) { + $notifies = $this->formatNotifies(Item::inArray($items), $ident); } $arr = [ - 'notifications' => $notifs, - 'ident' => $ident, + 'notifications' => $notifies, + 'ident' => $ident, ]; return $arr; @@ -550,16 +594,18 @@ final class Notify extends BaseObject * @param int $limit Maximum number of query results * @param int $id When set, only the introduction with this id is displayed * - * @return array with + * @return array [string, array] * string 'ident' => Notification identifier * array 'notifications' => Introductions - * @throws \Friendica\Network\HTTPException\InternalServerErrorException - * @throws \ImagickException + * + * @throws ImagickException + * @throws Exception */ - public function introNotifs($all = false, $start = 0, $limit = 80, $id = 0) + public function getIntroNotifies($all = false, int $start = 0, int $limit = 80, int $id = 0) { - $ident = 'introductions'; - $notifs = []; + /// @todo sanitize wording according to SELF::INTRO + $ident = 'introductions'; + $notifies = []; $sql_extra = ""; if (empty($id)) { @@ -573,7 +619,7 @@ final class Notify extends BaseObject } /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact - $stmtNotifies = DBA::p( + $stmtNotifies = $this->dba->p( "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*, `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`, `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`, @@ -590,13 +636,13 @@ final class Notify extends BaseObject $start, $limit ); - if (DBA::isResult($stmtNotifies)) { - $notifs = $this->formatIntros(DBA::toArray($stmtNotifies)); + if ($this->dba->isResult($stmtNotifies)) { + $notifies = $this->formatIntros($this->dba->toArray($stmtNotifies)); } $arr = [ - 'ident' => $ident, - 'notifications' => $notifs, + 'ident' => $ident, + 'notifications' => $notifies, ]; return $arr; @@ -606,120 +652,123 @@ final class Notify extends BaseObject * @brief Format the notification query in an usable array * * @param array $intros The array from the db query + * * @return array with the introductions - * @throws \Friendica\Network\HTTPException\InternalServerErrorException - * @throws \ImagickException + * @throws HTTPException\InternalServerErrorException + * @throws ImagickException */ - private function formatIntros($intros) + private function formatIntros(array $intros) { $knowyou = ''; - $arr = []; + $formattedIntros = []; - foreach ($intros as $it) { + foreach ($intros as $intro) { // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests. // We have to distinguish between these two because they use different data. // Contact suggestions - if ($it['fid']) { - $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->getHostName() . ((self::getApp()->getURLPath()) ? '/' . self::getApp()->getURLPath() : '')); + if ($intro['fid']) { + $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . + $this->baseUrl->getHostName() . + (($this->baseUrl->getURLPath()) ? '/' . $this->baseUrl->getURLPath() : '')); $intro = [ - 'label' => 'friend_suggestion', - 'notify_type' => L10n::t('Friend Suggestion'), - 'intro_id' => $it['intro_id'], - 'madeby' => $it['name'], - 'madeby_url' => $it['url'], - 'madeby_zrl' => Contact::magicLink($it['url']), - 'madeby_addr' => $it['addr'], - 'contact_id' => $it['contact-id'], - 'photo' => (!empty($it['fphoto']) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"), - 'name' => $it['fname'], - 'url' => $it['furl'], - 'zrl' => Contact::magicLink($it['furl']), - 'hidden' => $it['hidden'] == 1, - 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0), - 'knowyou' => $knowyou, - 'note' => $it['note'], - 'request' => $it['frequest'] . '?addr=' . $return_addr, + 'label' => 'friend_suggestion', + 'notify_type' => $this->l10n->t('Friend Suggestion'), + 'intro_id' => $intro['intro_id'], + 'madeby' => $intro['name'], + 'madeby_url' => $intro['url'], + 'madeby_zrl' => Contact::magicLink($intro['url']), + 'madeby_addr' => $intro['addr'], + 'contact_id' => $intro['contact-id'], + 'photo' => (!empty($intro['fphoto']) ? ProxyUtils::proxifyUrl($intro['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"), + 'name' => $intro['fname'], + 'url' => $intro['furl'], + 'zrl' => Contact::magicLink($intro['furl']), + 'hidden' => $intro['hidden'] == 1, + 'post_newfriend' => (intval($this->pConfig->get(local_user(), 'system', 'post_newfriend')) ? '1' : 0), + 'knowyou' => $knowyou, + 'note' => $intro['note'], + 'request' => $intro['frequest'] . '?addr=' . $return_addr, ]; // Normal connection requests } else { - $it = $this->getMissingIntroData($it); + $intro = $this->getMissingIntroData($intro); - if (empty($it['url'])) { + if (empty($intro['url'])) { continue; } // Don't show these data until you are connected. Diaspora is doing the same. - if ($it['gnetwork'] === Protocol::DIASPORA) { - $it['glocation'] = ""; - $it['gabout'] = ""; - $it['ggender'] = ""; + if ($intro['gnetwork'] === Protocol::DIASPORA) { + $intro['glocation'] = ""; + $intro['gabout'] = ""; + $intro['ggender'] = ""; } $intro = [ - 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'), - 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')), - 'dfrn_id' => $it['issued-id'], - 'uid' => $_SESSION['uid'], - 'intro_id' => $it['intro_id'], - 'contact_id' => $it['contact-id'], - 'photo' => (!empty($it['photo']) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"), - 'name' => $it['name'], - 'location' => BBCode::convert($it['glocation'], false), - 'about' => BBCode::convert($it['gabout'], false), - 'keywords' => $it['gkeywords'], - 'gender' => $it['ggender'], - 'hidden' => $it['hidden'] == 1, - 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0), - 'url' => $it['url'], - 'zrl' => Contact::magicLink($it['url']), - 'addr' => $it['gaddr'], - 'network' => $it['gnetwork'], - 'knowyou' => $it['knowyou'], - 'note' => $it['note'], + 'label' => (($intro['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'), + 'notify_type' => (($intro['network'] !== Protocol::OSTATUS) ? $this->l10n->t('Friend/Connect Request') : $this->l10n->t('New Follower')), + 'dfrn_id' => $intro['issued-id'], + 'uid' => $_SESSION['uid'], + 'intro_id' => $intro['intro_id'], + 'contact_id' => $intro['contact-id'], + 'photo' => (!empty($intro['photo']) ? ProxyUtils::proxifyUrl($intro['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"), + 'name' => $intro['name'], + 'location' => BBCode::convert($intro['glocation'], false), + 'about' => BBCode::convert($intro['gabout'], false), + 'keywords' => $intro['gkeywords'], + 'gender' => $intro['ggender'], + 'hidden' => $intro['hidden'] == 1, + 'post_newfriend' => (intval($this->pConfig->get(local_user(), 'system', 'post_newfriend')) ? '1' : 0), + 'url' => $intro['url'], + 'zrl' => Contact::magicLink($intro['url']), + 'addr' => $intro['gaddr'], + 'network' => $intro['gnetwork'], + 'knowyou' => $intro['knowyou'], + 'note' => $intro['note'], ]; } - $arr[] = $intro; + $formattedIntros[] = $intro; } - return $arr; + return $formattedIntros; } /** * @brief Check for missing contact data and try to fetch the data from * from other sources * - * @param array $arr The input array with the intro data + * @param array $intro The input array with the intro data * * @return array The array with the intro data - * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws HTTPException\InternalServerErrorException */ - private function getMissingIntroData($arr) + private function getMissingIntroData(array $intro) { // If the network and the addr isn't available from the gcontact // table entry, take the one of the contact table entry - if (empty($arr['gnetwork']) && !empty($arr['network'])) { - $arr['gnetwork'] = $arr['network']; + if (empty($intro['gnetwork']) && !empty($intro['network'])) { + $intro['gnetwork'] = $intro['network']; } - if (empty($arr['gaddr']) && !empty($arr['addr'])) { - $arr['gaddr'] = $arr['addr']; + if (empty($intro['gaddr']) && !empty($intro['addr'])) { + $intro['gaddr'] = $intro['addr']; } // If the network and addr is still not available // get the missing data data from other sources - if (empty($arr['gnetwork']) || empty($arr['gaddr'])) { - $ret = Contact::getDetailsByURL($arr['url']); + if (empty($intro['gnetwork']) || empty($intro['gaddr'])) { + $ret = Contact::getDetailsByURL($intro['url']); - if (empty($arr['gnetwork']) && !empty($ret['network'])) { - $arr['gnetwork'] = $ret['network']; + if (empty($intro['gnetwork']) && !empty($ret['network'])) { + $intro['gnetwork'] = $ret['network']; } - if (empty($arr['gaddr']) && !empty($ret['addr'])) { - $arr['gaddr'] = $ret['addr']; + if (empty($intro['gaddr']) && !empty($ret['addr'])) { + $intro['gaddr'] = $ret['addr']; } } - return $arr; + return $intro; } } diff --git a/src/Module/Notifications/Notify.php b/src/Module/Notifications/Notify.php index 4998a0adb..bad0900ea 100644 --- a/src/Module/Notifications/Notify.php +++ b/src/Module/Notifications/Notify.php @@ -3,6 +3,7 @@ namespace Friendica\Module\Notifications; use Friendica\BaseModule; +use Friendica\BaseObject; use Friendica\Core\L10n; use Friendica\Core\System; use Friendica\Model\Notify as ModelNotify; @@ -26,7 +27,8 @@ class Notify extends BaseModule // @TODO: Replace with parameter from router if ($a->argc > 2 && $a->argv[1] === 'mark' && $a->argv[2] === 'all') { - $notificationsManager = new ModelNotify(); + /** @var ModelNotify $notificationsManager */ + $notificationsManager = self::getClass(ModelNotify::class); $success = $notificationsManager->setAllSeen(); header('Content-type: application/json; charset=utf-8'); @@ -49,7 +51,8 @@ class Notify extends BaseModule // @TODO: Replace with parameter from router if ($a->argc > 2 && $a->argv[1] === 'view' && intval($a->argv[2])) { - $notificationsManager = new ModelNotify(); + /** @var ModelNotify $notificationsManager */ + $notificationsManager = BaseObject::getClass(ModelNotify::class); // @TODO: Replace with parameter from router $note = $notificationsManager->getByID($a->argv[2]); if (!empty($note)) { From fdc0236aa18958e4dc44e447c62783df1110fe45 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sat, 26 Oct 2019 04:33:59 +0200 Subject: [PATCH 39/46] Fix arguments --- mod/notifications.php | 2 +- src/Model/Notify.php | 329 +++++++++++++++++++++--------------------- 2 files changed, 166 insertions(+), 165 deletions(-) diff --git a/mod/notifications.php b/mod/notifications.php index b60c604fc..2c8e39bfb 100644 --- a/mod/notifications.php +++ b/mod/notifications.php @@ -78,7 +78,7 @@ function notifications_content(App $a) } $page = ($_REQUEST['page'] ?? 0) ?: 1; - $show = $_REQUEST['show'] ?? 0; + $show = ($_REQUEST['show'] ?? '' === 'all'); Nav::setSelected('notifications'); diff --git a/src/Model/Notify.php b/src/Model/Notify.php index 2d9ad9142..2ee1a03a4 100644 --- a/src/Model/Notify.php +++ b/src/Model/Notify.php @@ -27,6 +27,9 @@ use Friendica\Network\HTTPException; */ final class Notify extends BaseObject { + /** @var int The default limit of notifies per page */ + const DEFAULT_PAGE_LIMIT = 80; + const NETWORK = 'network'; const SYSTEM = 'system'; const PERSONAL = 'personal'; @@ -113,7 +116,7 @@ final class Notify extends BaseObject } /** - * @brief Get all notifications for local_user() + * Get all notifications for local_user() * * @param array $filter optional Array "column name"=>value: filter query by columns values * @param array $order optional Array to order by @@ -144,7 +147,7 @@ final class Notify extends BaseObject } /** - * @brief Get one note for local_user() by $id value + * Get one note for local_user() by $id value * * @param int $id identity * @@ -181,7 +184,7 @@ final class Notify extends BaseObject } /** - * @brief set seen state of all notifications of local_user() + * Set seen state of all notifications of local_user() * * @param bool $seen optional true or false. default true * @@ -219,7 +222,7 @@ final class Notify extends BaseObject } /** - * @brief Format the notification query in an usable array + * Format the notification query in an usable array * * @param array $notifies The array from the db query * @param string $ident The notifications identifier (e.g. network) @@ -237,159 +240,126 @@ final class Notify extends BaseObject */ private function formatNotifies(array $notifies, string $ident = "") { - $arr = []; + $formattedNotifies = []; - if ($this->dba->isResult($notifies)) { - foreach ($notifies as $notify) { - // Because we use different db tables for the notification query - // we have sometimes $notify['unseen'] and sometimes $notify['seen]. - // So we will have to transform $notify['unseen'] - if (array_key_exists('unseen', $notify)) { - $notify['seen'] = ($notify['unseen'] > 0 ? false : true); - } + foreach ($notifies as $notify) { + // Because we use different db tables for the notification query + // we have sometimes $notify['unseen'] and sometimes $notify['seen]. + // So we will have to transform $notify['unseen'] + if (array_key_exists('unseen', $notify)) { + $notify['seen'] = ($notify['unseen'] > 0 ? false : true); + } - // For feed items we use the user's contact, since the avatar is mostly self choosen. - if (!empty($notify['network']) && $notify['network'] == Protocol::FEED) { - $notify['author-avatar'] = $notify['contact-avatar']; - } + // For feed items we use the user's contact, since the avatar is mostly self choosen. + if (!empty($notify['network']) && $notify['network'] == Protocol::FEED) { + $notify['author-avatar'] = $notify['contact-avatar']; + } - // Depending on the identifier of the notification we need to use different defaults - switch ($ident) { - case self::SYSTEM: - $default_item_label = 'notify'; - $default_item_link = $this->baseUrl->get(true) . '/notify/view/' . $notify['id']; - $default_item_image = ProxyUtils::proxifyUrl($notify['photo'], false, ProxyUtils::SIZE_MICRO); - $default_item_url = $notify['url']; - $default_item_text = strip_tags(BBCode::convert($notify['msg'])); - $default_item_when = DateTimeFormat::local($notify['date'], 'r'); - $default_item_ago = Temporal::getRelativeDate($notify['date']); - break; + // Depending on the identifier of the notification we need to use different defaults + switch ($ident) { + case self::SYSTEM: + $default_item_label = 'notify'; + $default_item_link = $this->baseUrl->get(true) . '/notify/view/' . $notify['id']; + $default_item_image = ProxyUtils::proxifyUrl($notify['photo'], false, ProxyUtils::SIZE_MICRO); + $default_item_url = $notify['url']; + $default_item_text = strip_tags(BBCode::convert($notify['msg'])); + $default_item_when = DateTimeFormat::local($notify['date'], 'r'); + $default_item_ago = Temporal::getRelativeDate($notify['date']); + break; - case self::HOME: - $default_item_label = 'comment'; - $default_item_link = $this->baseUrl->get(true) . '/display/' . $notify['parent-guid']; - $default_item_image = ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO); - $default_item_url = $notify['author-link']; - $default_item_text = $this->l10n->t("%s commented on %s's post", $notify['author-name'], $notify['parent-author-name']); - $default_item_when = DateTimeFormat::local($notify['created'], 'r'); - $default_item_ago = Temporal::getRelativeDate($notify['created']); - break; + case self::HOME: + $default_item_label = 'comment'; + $default_item_link = $this->baseUrl->get(true) . '/display/' . $notify['parent-guid']; + $default_item_image = ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO); + $default_item_url = $notify['author-link']; + $default_item_text = $this->l10n->t("%s commented on %s's post", $notify['author-name'], $notify['parent-author-name']); + $default_item_when = DateTimeFormat::local($notify['created'], 'r'); + $default_item_ago = Temporal::getRelativeDate($notify['created']); + break; - default: - $default_item_label = (($notify['id'] == $notify['parent']) ? 'post' : 'comment'); - $default_item_link = $this->baseUrl->get(true) . '/display/' . $notify['parent-guid']; - $default_item_image = ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO); - $default_item_url = $notify['author-link']; - $default_item_text = (($notify['id'] == $notify['parent']) - ? $this->l10n->t("%s created a new post", $notify['author-name']) - : $this->l10n->t("%s commented on %s's post", $notify['author-name'], $notify['parent-author-name'])); - $default_item_when = DateTimeFormat::local($notify['created'], 'r'); - $default_item_ago = Temporal::getRelativeDate($notify['created']); - } + default: + $default_item_label = (($notify['id'] == $notify['parent']) ? 'post' : 'comment'); + $default_item_link = $this->baseUrl->get(true) . '/display/' . $notify['parent-guid']; + $default_item_image = ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO); + $default_item_url = $notify['author-link']; + $default_item_text = (($notify['id'] == $notify['parent']) + ? $this->l10n->t("%s created a new post", $notify['author-name']) + : $this->l10n->t("%s commented on %s's post", $notify['author-name'], $notify['parent-author-name'])); + $default_item_when = DateTimeFormat::local($notify['created'], 'r'); + $default_item_ago = Temporal::getRelativeDate($notify['created']); + } - // Transform the different types of notification in an usable array - switch ($notify['verb']) { - case Activity::LIKE: - $notify = [ - 'label' => 'like', - 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $notify['author-link'], - 'text' => $this->l10n->t("%s liked %s's post", $notify['author-name'], $notify['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $notify['seen'] - ]; - break; + // Transform the different types of notification in an usable array + switch ($notify['verb']) { + case Activity::LIKE: + $formattedNotify = [ + 'label' => 'like', + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s liked %s's post", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] + ]; + break; - case Activity::DISLIKE: - $notify = [ - 'label' => 'dislike', - 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $notify['author-link'], - 'text' => $this->l10n->t("%s disliked %s's post", $notify['author-name'], $notify['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $notify['seen'] - ]; - break; + case Activity::DISLIKE: + $formattedNotify = [ + 'label' => 'dislike', + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s disliked %s's post", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] + ]; + break; - case Activity::ATTEND: - $notify = [ - 'label' => 'attend', - 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $notify['author-link'], - 'text' => $this->l10n->t("%s is attending %s's event", $notify['author-name'], $notify['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $notify['seen'] - ]; - break; + case Activity::ATTEND: + $formattedNotify = [ + 'label' => 'attend', + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s is attending %s's event", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] + ]; + break; - case Activity::ATTENDNO: - $notify = [ - 'label' => 'attendno', - 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $notify['author-link'], - 'text' => $this->l10n->t("%s is not attending %s's event", $notify['author-name'], $notify['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $notify['seen'] - ]; - break; + case Activity::ATTENDNO: + $formattedNotify = [ + 'label' => 'attendno', + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s is not attending %s's event", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] + ]; + break; - case Activity::ATTENDMAYBE: - $notify = [ - 'label' => 'attendmaybe', - 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $notify['author-link'], - 'text' => $this->l10n->t("%s may attend %s's event", $notify['author-name'], $notify['parent-author-name']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $notify['seen'] - ]; - break; + case Activity::ATTENDMAYBE: + $formattedNotify = [ + 'label' => 'attendmaybe', + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s may attend %s's event", $notify['author-name'], $notify['parent-author-name']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] + ]; + break; - case Activity::FRIEND: - if (!isset($notify['object'])) { - $notify = [ - 'label' => 'friend', - 'link' => $default_item_link, - 'image' => $default_item_image, - 'url' => $default_item_url, - 'text' => $default_item_text, - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $notify['seen'] - ]; - break; - } - /// @todo Check if this part here is used at all - $this->logger->info('Complete data.', ['notify' => $notify, 'callStack' => System::callstack(20)]); - - $xmlHead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">"; - $obj = XML::parseString($xmlHead . $notify['object']); - $notify['fname'] = $obj->title; - - $notify = [ + case Activity::FRIEND: + if (!isset($notify['object'])) { + $formattedNotify = [ 'label' => 'friend', - 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], - 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), - 'url' => $notify['author-link'], - 'text' => $this->l10n->t("%s is now friends with %s", $notify['author-name'], $notify['fname']), - 'when' => $default_item_when, - 'ago' => $default_item_ago, - 'seen' => $notify['seen'] - ]; - break; - - default: - $notify = [ - 'label' => $default_item_label, 'link' => $default_item_link, 'image' => $default_item_image, 'url' => $default_item_url, @@ -398,19 +368,50 @@ final class Notify extends BaseObject 'ago' => $default_item_ago, 'seen' => $notify['seen'] ]; - } + break; + } + /// @todo Check if this part here is used at all + $this->logger->info('Complete data.', ['notify' => $notify, 'callStack' => System::callstack(20)]); - $arr[] = $notify; + $xmlHead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">"; + $obj = XML::parseString($xmlHead . $notify['object']); + $notify['fname'] = $obj->title; + + $formattedNotify = [ + 'label' => 'friend', + 'link' => $this->baseUrl->get(true) . '/display/' . $notify['parent-guid'], + 'image' => ProxyUtils::proxifyUrl($notify['author-avatar'], false, ProxyUtils::SIZE_MICRO), + 'url' => $notify['author-link'], + 'text' => $this->l10n->t("%s is now friends with %s", $notify['author-name'], $notify['fname']), + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] + ]; + break; + + default: + $formattedNotify = [ + 'label' => $default_item_label, + 'link' => $default_item_link, + 'image' => $default_item_image, + 'url' => $default_item_url, + 'text' => $default_item_text, + 'when' => $default_item_when, + 'ago' => $default_item_ago, + 'seen' => $notify['seen'] + ]; } + + $formattedNotifies[] = $formattedNotify; } - return $arr; + return $formattedNotifies; } /** - * @brief Get network notifications + * Get network notifications * - * @param int|string $seen If 0 only include notifications into the query + * @param bool $seen False => only include notifications into the query * which aren't marked as "seen" * @param int $start Start the query at this point * @param int $limit Maximum number of query results @@ -421,14 +422,14 @@ final class Notify extends BaseObject * * @throws Exception */ - public function getNetworkNotifies(int $seen = 0, int $start = 0, int $limit = 80) + public function getNetworkNotifies(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) { $ident = self::NETWORK; $notifies = []; $condition = ['wall' => false, 'uid' => local_user()]; - if ($seen === 0) { + if (!$seen) { $condition['unseen'] = true; } @@ -451,9 +452,9 @@ final class Notify extends BaseObject } /** - * @brief Get system notifications + * Get system notifications * - * @param int|string $seen If 0 only include notifications into the query + * @param bool $seen False => only include notifications into the query * which aren't marked as "seen" * @param int $start Start the query at this point * @param int $limit Maximum number of query results @@ -464,13 +465,13 @@ final class Notify extends BaseObject * * @throws Exception */ - public function getSystemNotifies(int $seen = 0, int $start = 0, int $limit = 80) + public function getSystemNotifies(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) { $ident = self::SYSTEM; $notifies = []; $filter = ['uid' => local_user()]; - if ($seen === 0) { + if (!$seen) { $filter['seen'] = false; } @@ -496,9 +497,9 @@ final class Notify extends BaseObject } /** - * @brief Get personal notifications + * Get personal notifications * - * @param int|string $seen If 0 only include notifications into the query + * @param bool $seen False => only include notifications into the query * which aren't marked as "seen" * @param int $start Start the query at this point * @param int $limit Maximum number of query results @@ -509,7 +510,7 @@ final class Notify extends BaseObject * * @throws Exception */ - public function getPersonalNotifies(int $seen = 0, int $start = 0, int $limit = 80) + public function getPersonalNotifies(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) { $ident = self::PERSONAL; $notifies = []; @@ -520,7 +521,7 @@ final class Notify extends BaseObject $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)", local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]']; - if ($seen === 0) { + if (!$seen) { $condition[0] .= " AND `unseen`"; } @@ -545,7 +546,7 @@ final class Notify extends BaseObject /** * @brief Get home notifications * - * @param int|string $seen If 0 only include notifications into the query + * @param bool $seen False => only include notifications into the query * which aren't marked as "seen" * @param int $start Start the query at this point * @param int $limit Maximum number of query results @@ -556,14 +557,14 @@ final class Notify extends BaseObject * * @throws Exception */ - public function getHomeNotifies($seen = 0, int $start = 0, int $limit = 80) + public function getHomeNotifies(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) { $ident = self::HOME; $notifies = []; $condition = ['wall' => false, 'uid' => local_user()]; - if ($seen === 0) { + if (!$seen) { $condition['unseen'] = true; } @@ -601,7 +602,7 @@ final class Notify extends BaseObject * @throws ImagickException * @throws Exception */ - public function getIntroNotifies($all = false, int $start = 0, int $limit = 80, int $id = 0) + public function getIntroNotifies(bool $all = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT, int $id = 0) { /// @todo sanitize wording according to SELF::INTRO $ident = 'introductions'; From 3465bd9f1102203b12e5d3439ecbe080b54d81bd Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sat, 26 Oct 2019 05:02:14 +0200 Subject: [PATCH 40/46] rename methods --- mod/notifications.php | 10 +++++----- src/Model/Notify.php | 24 ++++++++++++------------ 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/mod/notifications.php b/mod/notifications.php index 2c8e39bfb..da508a33c 100644 --- a/mod/notifications.php +++ b/mod/notifications.php @@ -112,27 +112,27 @@ function notifications_content(App $a) $all = (($a->argc > 2) && ($a->argv[2] == 'all')); - $notifs = $nm->getIntroNotifies($all, $startrec, $perpage, $id); + $notifs = $nm->getIntroList($all, $startrec, $perpage, $id); // Get the network notifications } elseif (($a->argc > 1) && ($a->argv[1] == 'network')) { $notif_header = L10n::t('Network Notifications'); - $notifs = $nm->getNetworkNotifies($show, $startrec, $perpage); + $notifs = $nm->getNetworkList($show, $startrec, $perpage); // Get the system notifications } elseif (($a->argc > 1) && ($a->argv[1] == 'system')) { $notif_header = L10n::t('System Notifications'); - $notifs = $nm->getSystemNotifies($show, $startrec, $perpage); + $notifs = $nm->getSystemList($show, $startrec, $perpage); // Get the personal notifications } elseif (($a->argc > 1) && ($a->argv[1] == 'personal')) { $notif_header = L10n::t('Personal Notifications'); - $notifs = $nm->getPersonalNotifies($show, $startrec, $perpage); + $notifs = $nm->getPersonalList($show, $startrec, $perpage); // Get the home notifications } elseif (($a->argc > 1) && ($a->argv[1] == 'home')) { $notif_header = L10n::t('Home Notifications'); - $notifs = $nm->getHomeNotifies($show, $startrec, $perpage); + $notifs = $nm->getHomeList($show, $startrec, $perpage); // fallback - redirect to main page } else { $a->internalRedirect('notifications'); diff --git a/src/Model/Notify.php b/src/Model/Notify.php index 2ee1a03a4..8a60ee6c0 100644 --- a/src/Model/Notify.php +++ b/src/Model/Notify.php @@ -238,7 +238,7 @@ final class Notify extends BaseObject * bool 'seen' => Is the notification marked as "seen" * @throws Exception */ - private function formatNotifies(array $notifies, string $ident = "") + private function formatList(array $notifies, string $ident = "") { $formattedNotifies = []; @@ -422,7 +422,7 @@ final class Notify extends BaseObject * * @throws Exception */ - public function getNetworkNotifies(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) + public function getNetworkList(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) { $ident = self::NETWORK; $notifies = []; @@ -440,7 +440,7 @@ final class Notify extends BaseObject $items = Item::selectForUser(local_user(), $fields, $condition, $params); if ($this->dba->isResult($items)) { - $notifies = $this->formatNotifies(Item::inArray($items), $ident); + $notifies = $this->formatList(Item::inArray($items), $ident); } $arr = [ @@ -465,7 +465,7 @@ final class Notify extends BaseObject * * @throws Exception */ - public function getSystemNotifies(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) + public function getSystemList(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) { $ident = self::SYSTEM; $notifies = []; @@ -485,7 +485,7 @@ final class Notify extends BaseObject $params); if ($this->dba->isResult($stmtNotifies)) { - $notifies = $this->formatNotifies($this->dba->toArray($stmtNotifies), $ident); + $notifies = $this->formatList($this->dba->toArray($stmtNotifies), $ident); } $arr = [ @@ -510,7 +510,7 @@ final class Notify extends BaseObject * * @throws Exception */ - public function getPersonalNotifies(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) + public function getPersonalList(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) { $ident = self::PERSONAL; $notifies = []; @@ -532,7 +532,7 @@ final class Notify extends BaseObject $items = Item::selectForUser(local_user(), $fields, $condition, $params); if ($this->dba->isResult($items)) { - $notifies = $this->formatNotifies(Item::inArray($items), $ident); + $notifies = $this->formatList(Item::inArray($items), $ident); } $arr = [ @@ -557,7 +557,7 @@ final class Notify extends BaseObject * * @throws Exception */ - public function getHomeNotifies(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) + public function getHomeList(bool $seen = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT) { $ident = self::HOME; $notifies = []; @@ -575,7 +575,7 @@ final class Notify extends BaseObject $items = Item::selectForUser(local_user(), $fields, $condition, $params); if ($this->dba->isResult($items)) { - $notifies = $this->formatNotifies(Item::inArray($items), $ident); + $notifies = $this->formatList(Item::inArray($items), $ident); } $arr = [ @@ -602,7 +602,7 @@ final class Notify extends BaseObject * @throws ImagickException * @throws Exception */ - public function getIntroNotifies(bool $all = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT, int $id = 0) + public function getIntroList(bool $all = false, int $start = 0, int $limit = self::DEFAULT_PAGE_LIMIT, int $id = 0) { /// @todo sanitize wording according to SELF::INTRO $ident = 'introductions'; @@ -638,7 +638,7 @@ final class Notify extends BaseObject $limit ); if ($this->dba->isResult($stmtNotifies)) { - $notifies = $this->formatIntros($this->dba->toArray($stmtNotifies)); + $notifies = $this->formatIntroList($this->dba->toArray($stmtNotifies)); } $arr = [ @@ -658,7 +658,7 @@ final class Notify extends BaseObject * @throws HTTPException\InternalServerErrorException * @throws ImagickException */ - private function formatIntros(array $intros) + private function formatIntroList(array $intros) { $knowyou = ''; From 28d5f393307e8ec7d08172db9e88428984e71315 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sat, 26 Oct 2019 05:03:58 +0200 Subject: [PATCH 41/46] simplify show determination --- mod/notifications.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mod/notifications.php b/mod/notifications.php index da508a33c..a215f9d7a 100644 --- a/mod/notifications.php +++ b/mod/notifications.php @@ -78,7 +78,7 @@ function notifications_content(App $a) } $page = ($_REQUEST['page'] ?? 0) ?: 1; - $show = ($_REQUEST['show'] ?? '' === 'all'); + $show = isset($_REQUEST['show']) ? $_REQUEST['show'] : false; Nav::setSelected('notifications'); From 5d995b854a77e7d8a3279e09d6d158db7eb9644d Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Sat, 26 Oct 2019 05:24:05 +0200 Subject: [PATCH 42/46] just remove parenthess --- mod/notifications.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mod/notifications.php b/mod/notifications.php index a215f9d7a..88972728c 100644 --- a/mod/notifications.php +++ b/mod/notifications.php @@ -78,7 +78,7 @@ function notifications_content(App $a) } $page = ($_REQUEST['page'] ?? 0) ?: 1; - $show = isset($_REQUEST['show']) ? $_REQUEST['show'] : false; + $show = ($_REQUEST['show'] ?? '') === 'all'; Nav::setSelected('notifications'); From 60eb6603bf5701f33cf81dbb492508002c751a80 Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 27 Oct 2019 17:41:47 +0000 Subject: [PATCH 43/46] (hopefully) fix preview issue with tags on Mastodon --- src/Content/Text/BBCode.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php index 8a029fe53..fc5c772d5 100644 --- a/src/Content/Text/BBCode.php +++ b/src/Content/Text/BBCode.php @@ -1746,9 +1746,9 @@ class BBCode extends BaseObject * - [url=]#[/url] */ $text = preg_replace_callback("/(?:#\[url\=.*?\]|\[url\=.*?\]#)(.*?)\[\/url\]/ism", function($matches) { - return '#' + . '" class="tag" rel="tag" title="' . XML::escape($matches[1]) . '">' . XML::escape($matches[1]) . ''; }, $text); From 30a6231f118fc1385131ae0e5ab69b83d7e6ec8c Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 27 Oct 2019 17:45:43 +0000 Subject: [PATCH 44/46] Fix indentation --- src/Content/Text/BBCode.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php index fc5c772d5..9169c91d0 100644 --- a/src/Content/Text/BBCode.php +++ b/src/Content/Text/BBCode.php @@ -1746,7 +1746,7 @@ class BBCode extends BaseObject * - [url=]#[/url] */ $text = preg_replace_callback("/(?:#\[url\=.*?\]|\[url\=.*?\]#)(.*?)\[\/url\]/ism", function($matches) { - return '#%s
', $data['url'], $data['title']); } else { From d9d71ea1e687a683f881b6d5f1ffc04f5f7ab048 Mon Sep 17 00:00:00 2001 From: Philipp Holzer Date: Mon, 28 Oct 2019 00:01:35 +0100 Subject: [PATCH 46/46] Wrong condition for home notifications --- src/Model/Notify.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Model/Notify.php b/src/Model/Notify.php index 8a60ee6c0..eef481ad8 100644 --- a/src/Model/Notify.php +++ b/src/Model/Notify.php @@ -562,7 +562,7 @@ final class Notify extends BaseObject $ident = self::HOME; $notifies = []; - $condition = ['wall' => false, 'uid' => local_user()]; + $condition = ['wall' => true, 'uid' => local_user()]; if (!$seen) { $condition['unseen'] = true;