Merge pull request #11655 from Quix0r/fixes/more-type-hints-002

More type-hints and documentation added
This commit is contained in:
Hypolite Petovan 2022-06-19 09:27:29 -04:00 committed by GitHub
commit 622b978a84
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
31 changed files with 672 additions and 564 deletions

View file

@ -1,6 +1,6 @@
-- ------------------------------------------
-- Friendica 2022.09-dev (Giant Rhubarb)
-- DB_UPDATE_VERSION 1469
-- DB_UPDATE_VERSION 1470
-- ------------------------------------------
@ -1234,7 +1234,7 @@ CREATE TABLE IF NOT EXISTS `post-media` (
`publisher-name` varchar(255) COMMENT 'Name of the publisher of the media',
`publisher-image` varbinary(255) COMMENT 'Image of the publisher of the media',
PRIMARY KEY(`id`),
UNIQUE INDEX `uri-id-url` (`uri-id`,`url`),
UNIQUE INDEX `uri-id-url` (`uri-id`,`url`(512)),
INDEX `uri-id-id` (`uri-id`,`id`),
FOREIGN KEY (`uri-id`) REFERENCES `item-uri` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE
) DEFAULT COLLATE utf8mb4_general_ci COMMENT='Attached media';

View file

@ -31,11 +31,11 @@ Fields
Indexes
------------
| Name | Fields |
| ---------- | ------------------- |
| PRIMARY | id |
| uri-id-url | UNIQUE, uri-id, url |
| uri-id-id | uri-id, id |
| Name | Fields |
| ---------- | ------------------------ |
| PRIMARY | id |
| uri-id-url | UNIQUE, uri-id, url(512) |
| uri-id-id | uri-id, id |
Foreign Keys
------------

View file

@ -157,9 +157,9 @@ function wall_upload_post(App $a, $desktopmode = true)
" - size: " . $filesize . " - type: " . $filetype);
$imagedata = @file_get_contents($src);
$Image = new Image($imagedata, $filetype);
$image = new Image($imagedata, $filetype);
if (!$Image->isValid()) {
if (!$image->isValid()) {
$msg = DI::l10n()->t('Unable to process image.');
@unlink($src);
if ($r_json) {
@ -170,18 +170,18 @@ function wall_upload_post(App $a, $desktopmode = true)
System::exit();
}
$Image->orient($src);
$image->orient($src);
@unlink($src);
$max_length = DI::config()->get('system', 'max_image_length');
if ($max_length > 0) {
$Image->scaleDown($max_length);
$filesize = strlen($Image->asString());
$image->scaleDown($max_length);
$filesize = strlen($image->asString());
Logger::info("File upload: Scaling picture to new size " . $max_length);
}
$width = $Image->getWidth();
$height = $Image->getHeight();
$width = $image->getWidth();
$height = $image->getHeight();
$maximagesize = DI::config()->get('system', 'maximagesize');
@ -190,10 +190,10 @@ function wall_upload_post(App $a, $desktopmode = true)
foreach ([5120, 2560, 1280, 640] as $pixels) {
if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
$Image->scaleDown($pixels);
$filesize = strlen($Image->asString());
$width = $Image->getWidth();
$height = $Image->getHeight();
$image->scaleDown($pixels);
$filesize = strlen($image->asString());
$width = $image->getWidth();
$height = $image->getHeight();
}
}
if ($filesize > $maximagesize) {
@ -220,7 +220,7 @@ function wall_upload_post(App $a, $desktopmode = true)
$defperm = '<' . $default_cid . '>';
$r = Photo::store($Image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $defperm);
$r = Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 0, Photo::DEFAULT, $defperm);
if (!$r) {
$msg = DI::l10n()->t('Image upload failed.');
@ -233,16 +233,16 @@ function wall_upload_post(App $a, $desktopmode = true)
}
if ($width > 640 || $height > 640) {
$Image->scaleDown(640);
$r = Photo::store($Image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $defperm);
$image->scaleDown(640);
$r = Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 1, Photo::DEFAULT, $defperm);
if ($r) {
$smallest = 1;
}
}
if ($width > 320 || $height > 320) {
$Image->scaleDown(320);
$r = Photo::store($Image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $defperm);
$image->scaleDown(320);
$r = Photo::store($image, $page_owner_uid, $visitor, $resource_id, $filename, $album, 2, Photo::DEFAULT, $defperm);
if ($r && ($smallest == 0)) {
$smallest = 2;
}
@ -264,8 +264,8 @@ function wall_upload_post(App $a, $desktopmode = true)
$picture["height"] = $photo["height"];
$picture["type"] = $photo["type"];
$picture["albumpage"] = DI::baseUrl() . '/photos/' . $page_owner_nick . '/image/' . $resource_id;
$picture["picture"] = DI::baseUrl() . "/photo/{$resource_id}-0." . $Image->getExt();
$picture["preview"] = DI::baseUrl() . "/photo/{$resource_id}-{$smallest}." . $Image->getExt();
$picture["picture"] = DI::baseUrl() . "/photo/{$resource_id}-0." . $image->getExt();
$picture["preview"] = DI::baseUrl() . "/photo/{$resource_id}-{$smallest}." . $image->getExt();
if ($r_json) {
System::jsonExit(['picture' => $picture]);
@ -280,7 +280,7 @@ function wall_upload_post(App $a, $desktopmode = true)
System::jsonExit(['ok' => true]);
}
echo "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $page_owner_nick . '/image/' . $resource_id . '][img]' . DI::baseUrl() . "/photo/{$resource_id}-{$smallest}.".$Image->getExt()."[/img][/url]\n\n";
echo "\n\n" . '[url=' . DI::baseUrl() . '/photos/' . $page_owner_nick . '/image/' . $resource_id . '][img]' . DI::baseUrl() . "/photo/{$resource_id}-{$smallest}." . $image->getExt() . "[/img][/url]\n\n";
System::exit();
// NOTREACHED
}

View file

@ -656,7 +656,7 @@ class Installer
* @return bool true if the check was successful, otherwise false
* @throws Exception
*/
public function checkDB(Database $dba)
public function checkDB(Database $dba): bool
{
$dba->reconnect();

View file

@ -150,10 +150,9 @@ class DBStructure
* Print out database error messages
*
* @param string $message Message to be added to the error message
*
* @return string Error message
*/
private static function printUpdateError($message)
private static function printUpdateError(string $message): string
{
echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n",
DBA::errorNo(), DBA::errorMessage());
@ -164,7 +163,7 @@ class DBStructure
public static function writeStructure()
{
$tables = [];
foreach (self::definition(null) as $name => $definition) {
foreach (self::definition('') as $name => $definition) {
$indexes = [[
'name' => 'Name',
'fields' => 'Fields',
@ -225,8 +224,8 @@ class DBStructure
$field['default'] = $value['default'] ?? 'NULL';
$field['extra'] = $value['extra'] ?? '';
foreach ($field as $fieldname => $fieldvalue) {
$lengths[$fieldname] = max($lengths[$fieldname] ?? 0, strlen($fieldvalue));
foreach ($field as $fieldName => $fieldvalue) {
$lengths[$fieldName] = max($lengths[$fieldName] ?? 0, strlen($fieldvalue));
}
$fields[] = $field;
@ -263,7 +262,7 @@ class DBStructure
file_put_contents($filename, $content);
}
public static function printStructure($basePath)
public static function printStructure(string $basePath)
{
$database = self::definition($basePath, false);
@ -288,12 +287,12 @@ class DBStructure
* On first pass, defines DB_UPDATE_VERSION constant.
*
* @see static/dbstructure.config.php
* @param boolean $with_addons_structure Whether to tack on addons additional tables
* @param string $basePath The base path of this application
* @param boolean $with_addons_structure Whether to tack on addons additional tables
* @return array
* @throws Exception
*/
public static function definition($basePath, $with_addons_structure = true)
public static function definition(string $basePath, bool $with_addons_structure = true): array
{
if (!self::$definition) {
if (empty($basePath)) {
@ -303,7 +302,7 @@ class DBStructure
$filename = $basePath . '/static/dbstructure.config.php';
if (!is_readable($filename)) {
throw new Exception('Missing database structure config file static/dbstructure.config.php');
throw new Exception('Missing database structure config file static/dbstructure.config.php at basePath=' . $basePath);
}
$definition = require $filename;
@ -327,23 +326,23 @@ class DBStructure
/**
* Get field data for the given table
*
* @param string $table
* @param string $table Tavle to load field definitions for
* @param array $data data fields
* @return array fields for the given
*/
public static function getFieldsForTable(string $table, array $data = [])
public static function getFieldsForTable(string $table, array $data = []): array
{
$definition = DBStructure::definition('', false);
if (empty($definition[$table])) {
return [];
}
$fieldnames = array_keys($definition[$table]['fields']);
$fieldNames = array_keys($definition[$table]['fields']);
$fields = [];
// Assign all field that are present in the table
foreach ($fieldnames as $field) {
foreach ($fieldNames as $field) {
if (isset($data[$field])) {
// Limit the length of varchar, varbinary, char and binrary fields
if (is_string($data[$field]) && preg_match("/char\((\d*)\)/", $definition[$table]['fields'][$field]['type'], $result)) {
@ -358,45 +357,54 @@ class DBStructure
return $fields;
}
private static function createTable($name, $structure, $verbose, $action)
/**
* Creates given table with structure
*
* @param string $name Name of table
* @param array $structure Structure of table
* @param boolean $verbose Output SQL statements
* @param boolean $action Whether to run the SQL commands
* @return Whether the SQL command ran successful
*/
private static function createTable(string $name, array $structure, bool $verbose, bool $action): bool
{
$r = true;
$engine = "";
$comment = "";
$engine = '';
$comment = '';
$sql_rows = [];
$primary_keys = [];
$foreign_keys = [];
foreach ($structure["fields"] as $fieldname => $field) {
$sql_rows[] = "`" . DBA::escape($fieldname) . "` " . self::FieldCommand($field);
foreach ($structure['fields'] as $fieldName => $field) {
$sql_rows[] = '`' . DBA::escape($fieldName) . '` ' . self::FieldCommand($field);
if (!empty($field['primary'])) {
$primary_keys[] = $fieldname;
$primary_keys[] = $fieldName;
}
if (!empty($field['foreign'])) {
$foreign_keys[$fieldname] = $field;
$foreign_keys[$fieldName] = $field;
}
}
if (!empty($structure["indexes"])) {
foreach ($structure["indexes"] as $indexname => $fieldnames) {
$sql_index = self::createIndex($indexname, $fieldnames, "");
if (!empty($structure['indexes'])) {
foreach ($structure['indexes'] as $indexName => $fieldNames) {
$sql_index = self::createIndex($indexName, $fieldNames, '');
if (!is_null($sql_index)) {
$sql_rows[] = $sql_index;
}
}
}
foreach ($foreign_keys as $fieldname => $parameters) {
$sql_rows[] = self::foreignCommand($name, $fieldname, $parameters);
foreach ($foreign_keys as $fieldName => $parameters) {
$sql_rows[] = self::foreignCommand($name, $fieldName, $parameters);
}
if (isset($structure["engine"])) {
$engine = " ENGINE=" . $structure["engine"];
if (isset($structure['engine'])) {
$engine = ' ENGINE=' . $structure['engine'];
}
if (isset($structure["comment"])) {
$comment = " COMMENT='" . DBA::escape($structure["comment"]) . "'";
if (isset($structure['comment'])) {
$comment = " COMMENT='" . DBA::escape($structure['comment']) . "'";
}
$sql = implode(",\n\t", $sql_rows);
@ -414,71 +422,77 @@ class DBStructure
return $r;
}
private static function FieldCommand($parameters, $create = true)
/**
* Returns SQL statement for field
*
* @param array $parameters Parameters for SQL statement
* @param boolean $create Whether to include PRIMARY KEY statement (unused)
* @return string SQL statement part
*/
private static function FieldCommand(array $parameters, bool $create = true): string
{
$fieldstruct = $parameters["type"];
$fieldstruct = $parameters['type'];
if (isset($parameters["Collation"])) {
$fieldstruct .= " COLLATE " . $parameters["Collation"];
if (isset($parameters['Collation'])) {
$fieldstruct .= ' COLLATE ' . $parameters['Collation'];
}
if (isset($parameters["not null"])) {
$fieldstruct .= " NOT NULL";
if (isset($parameters['not null'])) {
$fieldstruct .= ' NOT NULL';
}
if (isset($parameters["default"])) {
if (strpos(strtolower($parameters["type"]), "int") !== false) {
$fieldstruct .= " DEFAULT " . $parameters["default"];
if (isset($parameters['default'])) {
if (strpos(strtolower($parameters['type']), 'int') !== false) {
$fieldstruct .= ' DEFAULT ' . $parameters['default'];
} else {
$fieldstruct .= " DEFAULT '" . $parameters["default"] . "'";
$fieldstruct .= " DEFAULT '" . $parameters['default'] . "'";
}
}
if (isset($parameters["extra"])) {
$fieldstruct .= " " . $parameters["extra"];
if (isset($parameters['extra'])) {
$fieldstruct .= ' ' . $parameters['extra'];
}
if (isset($parameters["comment"])) {
$fieldstruct .= " COMMENT '" . DBA::escape($parameters["comment"]) . "'";
if (isset($parameters['comment'])) {
$fieldstruct .= " COMMENT '" . DBA::escape($parameters['comment']) . "'";
}
/*if (($parameters["primary"] != "") && $create)
$fieldstruct .= " PRIMARY KEY";*/
/*if (($parameters['primary'] != '') && $create)
$fieldstruct .= ' PRIMARY KEY';*/
return ($fieldstruct);
return $fieldstruct;
}
private static function createIndex($indexname, $fieldnames, $method = "ADD")
private static function createIndex(string $indexName, array $fieldNames, string $method = 'ADD')
{
$method = strtoupper(trim($method));
if ($method != "" && $method != "ADD") {
throw new Exception("Invalid parameter 'method' in self::createIndex(): '$method'");
}
if (in_array($fieldnames[0], ["UNIQUE", "FULLTEXT"])) {
$index_type = array_shift($fieldnames);
if (in_array($fieldNames[0], ["UNIQUE", "FULLTEXT"])) {
$index_type = array_shift($fieldNames);
$method .= " " . $index_type;
}
$names = "";
foreach ($fieldnames as $fieldname) {
foreach ($fieldNames as $fieldName) {
if ($names != "") {
$names .= ",";
}
if (preg_match('|(.+)\((\d+)\)|', $fieldname, $matches)) {
if (preg_match('|(.+)\((\d+)\)|', $fieldName, $matches)) {
$names .= "`" . DBA::escape($matches[1]) . "`(" . intval($matches[2]) . ")";
} else {
$names .= "`" . DBA::escape($fieldname) . "`";
$names .= "`" . DBA::escape($fieldName) . "`";
}
}
if ($indexname == "PRIMARY") {
if ($indexName == "PRIMARY") {
return sprintf("%s PRIMARY KEY(%s)", $method, $names);
}
$sql = sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexname), $names);
return ($sql);
return sprintf("%s INDEX `%s` (%s)", $method, DBA::escape($indexName), $names);
}
/**
@ -500,7 +514,7 @@ class DBStructure
* @return string Empty string if the update is successful, error messages otherwise
* @throws Exception
*/
public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false)
public static function performUpdate(bool $enable_maintenance_mode = true, bool $verbose = false): string
{
if ($enable_maintenance_mode) {
DI::config()->set('system', 'maintenance', 1);
@ -524,7 +538,7 @@ class DBStructure
* @return string Empty string if the update is successful, error messages otherwise
* @throws Exception
*/
public static function install(string $basePath)
public static function install(string $basePath): string
{
return self::update($basePath, false, true, true);
}
@ -541,7 +555,7 @@ class DBStructure
* @return string Empty string if the update is successful, error messages otherwise
* @throws Exception
*/
private static function update($basePath, $verbose, $action, $install = false, array $tables = null, array $definition = null)
private static function update(string $basePath, bool $verbose, bool $action, bool $install = false, array $tables = null, array $definition = null): string
{
$in_maintenance_mode = DI::config()->get('system', 'maintenance');
@ -606,15 +620,15 @@ class DBStructure
* or the definition differ from current status
* and index name doesn't start with "local_"
*/
foreach ($database[$name]["indexes"] as $indexname => $fieldnames) {
$current_index_definition = implode(",", $fieldnames);
if (isset($structure["indexes"][$indexname])) {
$new_index_definition = implode(",", $structure["indexes"][$indexname]);
foreach ($database[$name]["indexes"] as $indexName => $fieldNames) {
$current_index_definition = implode(",", $fieldNames);
if (isset($structure["indexes"][$indexName])) {
$new_index_definition = implode(",", $structure["indexes"][$indexName]);
} else {
$new_index_definition = "__NOT_SET__";
}
if ($current_index_definition != $new_index_definition && substr($indexname, 0, 6) != 'local_') {
$sql2 = self::dropIndex($indexname);
if ($current_index_definition != $new_index_definition && substr($indexName, 0, 6) != 'local_') {
$sql2 = self::dropIndex($indexName);
if ($sql3 == "") {
$sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
} else {
@ -623,9 +637,9 @@ class DBStructure
}
}
// Compare the field structure field by field
foreach ($structure["fields"] as $fieldname => $parameters) {
if (!isset($database[$name]["fields"][$fieldname])) {
$sql2 = self::addTableField($fieldname, $parameters);
foreach ($structure["fields"] as $fieldName => $parameters) {
if (!isset($database[$name]["fields"][$fieldName])) {
$sql2 = self::addTableField($fieldName, $parameters);
if ($sql3 == "") {
$sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
} else {
@ -633,7 +647,7 @@ class DBStructure
}
} else {
// Compare the field definition
$field_definition = $database[$name]["fields"][$fieldname];
$field_definition = $database[$name]["fields"][$fieldName];
// Remove the relation data that is used for the referential integrity
unset($parameters['relation']);
@ -653,7 +667,7 @@ class DBStructure
$current_field_definition = DBA::cleanQuery(implode(",", $field_definition));
$new_field_definition = DBA::cleanQuery(implode(",", $parameters));
if ($current_field_definition != $new_field_definition) {
$sql2 = self::modifyTableField($fieldname, $parameters);
$sql2 = self::modifyTableField($fieldName, $parameters);
if ($sql3 == "") {
$sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
} else {
@ -670,15 +684,15 @@ class DBStructure
* Don't create keys if table is new
*/
if (!$is_new_table) {
foreach ($structure["indexes"] as $indexname => $fieldnames) {
if (isset($database[$name]["indexes"][$indexname])) {
$current_index_definition = implode(",", $database[$name]["indexes"][$indexname]);
foreach ($structure["indexes"] as $indexName => $fieldNames) {
if (isset($database[$name]["indexes"][$indexName])) {
$current_index_definition = implode(",", $database[$name]["indexes"][$indexName]);
} else {
$current_index_definition = "__NOT_SET__";
}
$new_index_definition = implode(",", $fieldnames);
$new_index_definition = implode(",", $fieldNames);
if ($current_index_definition != $new_index_definition) {
$sql2 = self::createIndex($indexname, $fieldnames);
$sql2 = self::createIndex($indexName, $fieldNames);
if ($sql2 != "") {
if ($sql3 == "") {
@ -694,17 +708,17 @@ class DBStructure
// Foreign keys
// Compare the field structure field by field
foreach ($structure["fields"] as $fieldname => $parameters) {
foreach ($structure["fields"] as $fieldName => $parameters) {
if (empty($parameters['foreign'])) {
continue;
}
$constraint = self::getConstraintName($name, $fieldname, $parameters);
$constraint = self::getConstraintName($name, $fieldName, $parameters);
unset($existing_foreign_keys[$constraint]);
if (empty($database[$name]['foreign_keys'][$constraint])) {
$sql2 = self::addForeignKey($name, $fieldname, $parameters);
$sql2 = self::addForeignKey($name, $fieldName, $parameters);
if ($sql3 == "") {
$sql3 = "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
@ -767,9 +781,9 @@ class DBStructure
// Now have a look at the field collations
// Compare the field structure field by field
foreach ($structure["fields"] as $fieldname => $parameters) {
foreach ($structure["fields"] as $fieldName => $parameters) {
// Compare the field definition
$field_definition = ($database[$name]["fields"][$fieldname] ?? '') ?: ['Collation' => ''];
$field_definition = ($database[$name]["fields"][$fieldName] ?? '') ?: ['Collation' => ''];
// Define the default collation if not given
if (!isset($parameters['Collation']) && !empty($field_definition['Collation'])) {
@ -779,7 +793,7 @@ class DBStructure
}
if ($field_definition['Collation'] != $parameters['Collation']) {
$sql2 = self::modifyTableField($fieldname, $parameters);
$sql2 = self::modifyTableField($fieldName, $parameters);
if (($sql3 == "") || (substr($sql3, -2, 2) == "; ")) {
$sql3 .= "ALTER" . $ignore . " TABLE `" . $name . "` " . $sql2;
} else {
@ -826,7 +840,13 @@ class DBStructure
return $errors;
}
private static function tableStructure($table)
/**
* Returns an array with table structure information
*
* @param string $table Name of table
* @return array Table structure information
*/
private static function tableStructure(string $table): array
{
// This query doesn't seem to be executable as a prepared statement
$indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
@ -909,41 +929,42 @@ class DBStructure
}
}
return ["fields" => $fielddata, "indexes" => $indexdata,
"foreign_keys" => $foreigndata, "table_status" => $table_status];
return [
'fields' => $fielddata,
'indexes' => $indexdata,
'foreign_keys' => $foreigndata,
'table_status' => $table_status
];
}
private static function dropIndex($indexname)
private static function dropIndex(string $indexName): string
{
$sql = sprintf("DROP INDEX `%s`", DBA::escape($indexname));
return ($sql);
return sprintf("DROP INDEX `%s`", DBA::escape($indexName));
}
private static function addTableField($fieldname, $parameters)
private static function addTableField(string $fieldName, array $parameters): string
{
$sql = sprintf("ADD `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters));
return ($sql);
return sprintf("ADD `%s` %s", DBA::escape($fieldName), self::FieldCommand($parameters));
}
private static function modifyTableField($fieldname, $parameters)
private static function modifyTableField(string $fieldName, array $parameters): string
{
$sql = sprintf("MODIFY `%s` %s", DBA::escape($fieldname), self::FieldCommand($parameters, false));
return ($sql);
return sprintf("MODIFY `%s` %s", DBA::escape($fieldName), self::FieldCommand($parameters, false));
}
private static function getConstraintName(string $tablename, string $fieldname, array $parameters)
private static function getConstraintName(string $tableName, string $fieldName, array $parameters): string
{
$foreign_table = array_keys($parameters['foreign'])[0];
$foreign_field = array_values($parameters['foreign'])[0];
return $tablename . "-" . $fieldname. "-" . $foreign_table. "-" . $foreign_field;
return $tableName . '-' . $fieldName. '-' . $foreign_table. '-' . $foreign_field;
}
private static function foreignCommand(string $tablename, string $fieldname, array $parameters) {
private static function foreignCommand(string $tableName, string $fieldName, array $parameters) {
$foreign_table = array_keys($parameters['foreign'])[0];
$foreign_field = array_values($parameters['foreign'])[0];
$sql = "FOREIGN KEY (`" . $fieldname . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
$sql = "FOREIGN KEY (`" . $fieldName . "`) REFERENCES `" . $foreign_table . "` (`" . $foreign_field . "`)";
if (!empty($parameters['foreign']['on update'])) {
$sql .= " ON UPDATE " . strtoupper($parameters['foreign']['on update']);
@ -960,12 +981,12 @@ class DBStructure
return $sql;
}
private static function addForeignKey(string $tablename, string $fieldname, array $parameters)
private static function addForeignKey(string $tableName, string $fieldName, array $parameters): string
{
return sprintf("ADD %s", self::foreignCommand($tablename, $fieldname, $parameters));
return sprintf("ADD %s", self::foreignCommand($tableName, $fieldName, $parameters));
}
private static function dropForeignKey(string $constraint)
private static function dropForeignKey(string $constraint): string
{
return sprintf("DROP FOREIGN KEY `%s`", $constraint);
}
@ -983,7 +1004,7 @@ class DBStructure
* @return boolean Was the renaming successful?
* @throws Exception
*/
public static function rename($table, $columns, $type = self::RENAME_COLUMN)
public static function rename(string $table, array $columns, int $type = self::RENAME_COLUMN): bool
{
if (empty($table) || empty($columns)) {
return false;
@ -1019,7 +1040,7 @@ class DBStructure
return false;
}
$sql .= ";";
$sql .= ';';
$stmt = DBA::p($sql);
@ -1079,39 +1100,33 @@ class DBStructure
/**
* Check if a foreign key exists for the given table field
*
* @param string $table
* @param string $field
* @return boolean
* @param string $table Table name
* @param string $field Field name
* @return boolean Wether a foreign key exists
*/
public static function existsForeignKeyForField(string $table, string $field)
public static function existsForeignKeyForField(string $table, string $field): bool
{
return DBA::exists(['INFORMATION_SCHEMA' => 'KEY_COLUMN_USAGE'],
["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
DBA::databaseName(), $table, $field]);
}
/**
* Check if a table exists
*
* @param string|array $table Table name
* Check if a table exists
*
* @param string $table Single table name (please loop yourself)
* @return boolean Does the table exist?
* @throws Exception
*/
public static function existsTable($table)
public static function existsTable(string $table): bool
{
if (empty($table)) {
return false;
}
if (is_array($table)) {
$condition = ['table_schema' => key($table), 'table_name' => current($table)];
} else {
$condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
}
$condition = ['table_schema' => DBA::databaseName(), 'table_name' => $table];
$result = DBA::exists(['information_schema' => 'tables'], $condition);
return $result;
return DBA::exists(['information_schema' => 'tables'], $condition);
}
/**
@ -1122,7 +1137,7 @@ class DBStructure
* @return array An array of the table columns
* @throws Exception
*/
public static function getColumns($table)
public static function getColumns(string $table): array
{
$stmtColumns = DBA::p("SHOW COLUMNS FROM `" . $table . "`");
return DBA::toArray($stmtColumns);
@ -1130,6 +1145,9 @@ class DBStructure
/**
* Check if initial database values do exist - or create them
*
* @param bool $verbose Whether to output messages
* @return void
*/
public static function checkInitialValues(bool $verbose = false)
{
@ -1265,7 +1283,7 @@ class DBStructure
*
* @return boolean
*/
private static function isUpdating()
private static function isUpdating(): bool
{
$isUpdate = false;

View file

@ -526,6 +526,7 @@ class APContact
*
* @param string $url inbox url
* @param boolean $shared Shared Inbox
* @return void
*/
private static function unarchiveInbox(string $url, bool $shared)
{

View file

@ -44,7 +44,7 @@ class Attach
* @return array field list
* @throws \Exception
*/
private static function getFields()
private static function getFields(): array
{
$allfields = DBStructure::definition(DI::app()->getBasePath(), false);
$fields = array_keys($allfields['attach']['fields']);

View file

@ -35,10 +35,9 @@ class FileTag
* URL encode <, >, left and right brackets
*
* @param string $s String to be URL encoded.
*
* @return string The URL encoded string.
*/
private static function encode($s)
private static function encode(string $s): string
{
return str_replace(['<', '>', '[', ']'], ['%3c', '%3e', '%5b', '%5d'], $s);
}
@ -47,10 +46,9 @@ class FileTag
* URL decode <, >, left and right brackets
*
* @param string $s The URL encoded string to be decoded
*
* @return string The decoded string.
*/
private static function decode($s)
private static function decode(string $s): string
{
return str_replace(['%3c', '%3e', '%5b', '%5d'], ['<', '>', '[', ']'], $s);
}
@ -62,10 +60,9 @@ class FileTag
*
* @param array $array A list of tags.
* @param string $type Optional file type.
*
* @return string A list of file tags.
*/
public static function arrayToFile(array $array, string $type = 'file')
public static function arrayToFile(array $array, string $type = 'file'): string
{
$tag_list = '';
if ($type == 'file') {
@ -92,10 +89,9 @@ class FileTag
*
* @param string $file File tags
* @param string $type Optional file type.
*
* @return array List of tag names.
*/
public static function fileToArray(string $file, string $type = 'file')
public static function fileToArray(string $file, string $type = 'file'): array
{
$matches = [];
$return = [];

View file

@ -96,7 +96,7 @@ class GServer
*
* @param string $url
* @param boolean $no_check Don't check if the server hadn't been found
* @return int gserver id
* @return int|null gserver id or NULL on empty URL or failed check
*/
public static function getID(string $url, bool $no_check = false)
{
@ -156,7 +156,7 @@ class GServer
*
* @return boolean 'true' if server seems vital
*/
public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false)
public static function reachable(string $profile, string $server = '', string $network = '', bool $force = false): bool
{
if ($server == '') {
$contact = Contact::getByURL($profile, null, ['baseurl']);
@ -172,7 +172,7 @@ class GServer
return self::check($server, $network, $force);
}
public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = '')
public static function getNextUpdateDate(bool $success, string $created = '', string $last_contact = ''): string
{
// On successful contact process check again next week
if ($success) {
@ -231,7 +231,7 @@ class GServer
*
* @return boolean 'true' if server seems vital
*/
public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false)
public static function check(string $server_url, string $network = '', bool $force = false, bool $only_nodeinfo = false): bool
{
$server_url = self::cleanURL($server_url);
if ($server_url == '') {
@ -286,7 +286,7 @@ class GServer
* @param string $url
* @return string cleaned URL
*/
public static function cleanURL(string $url)
public static function cleanURL(string $url): string
{
$url = trim($url, '/');
$url = str_replace('/index.php', '', $url);
@ -305,7 +305,7 @@ class GServer
* @param string $url
* @return string base URL
*/
private static function getBaseURL(string $url)
private static function getBaseURL(string $url): string
{
$urlparts = parse_url(self::cleanURL($url));
unset($urlparts['path']);
@ -322,7 +322,7 @@ class GServer
*
* @return boolean 'true' if server could be detected
*/
public static function detect(string $url, string $network = '', bool $only_nodeinfo = false)
public static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
{
Logger::info('Detect server type', ['server' => $url]);
$serverdata = ['detection-method' => self::DETECT_MANUAL];
@ -535,7 +535,7 @@ class GServer
$serverdata['last_contact'] = DateTimeFormat::utcNow();
$serverdata['failed'] = false;
$gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
$gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => $serverdata['nurl']]);
if (!DBA::isResult($gserver)) {
$serverdata['created'] = DateTimeFormat::utcNow();
$ret = DBA::insert('gserver', $serverdata);
@ -586,6 +586,7 @@ class GServer
* Fetch relay data from a given server url
*
* @param string $server_url address of the server
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function discoverRelay(string $server_url)
@ -685,7 +686,7 @@ class GServer
*
* @return array server data
*/
private static function fetchStatistics(string $url)
private static function fetchStatistics(string $url): array
{
$curlResult = DI::httpClient()->get($url . '/statistics.json', HttpClientAccept::JSON);
if (!$curlResult->isSuccess()) {
@ -758,7 +759,7 @@ class GServer
* @return array Server data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult)
private static function fetchNodeinfo(string $url, ICanHandleHttpResponses $httpResult): array
{
if (!$httpResult->isSuccess()) {
return [];
@ -811,7 +812,7 @@ class GServer
* @return array Server data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function parseNodeinfo1(string $nodeinfo_url)
private static function parseNodeinfo1(string $nodeinfo_url): array
{
$curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
if (!$curlResult->isSuccess()) {
@ -904,7 +905,7 @@ class GServer
* @return array Server data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function parseNodeinfo2(string $nodeinfo_url)
private static function parseNodeinfo2(string $nodeinfo_url): array
{
$curlResult = DI::httpClient()->get($nodeinfo_url, HttpClientAccept::JSON);
if (!$curlResult->isSuccess()) {
@ -1001,10 +1002,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function fetchSiteinfo(string $url, array $serverdata)
private static function fetchSiteinfo(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/siteinfo.json', HttpClientAccept::JSON);
if (!$curlResult->isSuccess()) {
@ -1085,10 +1085,9 @@ class GServer
* Checks if the server contains a valid host meta file
*
* @param string $url URL of the given server
*
* @return boolean 'true' if the server seems to be vital
*/
private static function validHostMeta(string $url)
private static function validHostMeta(string $url): bool
{
$xrd_timeout = DI::config()->get('system', 'xrd_timeout');
$curlResult = DI::httpClient()->get($url . '/.well-known/host-meta', HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout]);
@ -1131,10 +1130,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectNetworkViaContacts(string $url, array $serverdata)
private static function detectNetworkViaContacts(string $url, array $serverdata): array
{
$contacts = [];
@ -1176,10 +1174,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function checkPoCo(string $url, array $serverdata)
private static function checkPoCo(string $url, array $serverdata): array
{
$serverdata['poco'] = '';
@ -1208,10 +1205,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
public static function checkMastodonDirectory(string $url, array $serverdata)
public static function checkMastodonDirectory(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/api/v1/directory?limit=1', HttpClientAccept::JSON);
if (!$curlResult->isSuccess()) {
@ -1238,7 +1234,7 @@ class GServer
*
* @return array server data
*/
private static function detectPeertube(string $url, array $serverdata)
private static function detectPeertube(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/api/v1/config', HttpClientAccept::JSON);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
@ -1282,10 +1278,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectNextcloud(string $url, array $serverdata)
private static function detectNextcloud(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/status.php', HttpClientAccept::JSON);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
@ -1310,7 +1305,15 @@ class GServer
return $serverdata;
}
private static function fetchWeeklyUsage(string $url, array $serverdata) {
/**
* Fetches weekly usage data
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
* @return array server data
*/
private static function fetchWeeklyUsage(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/api/v1/instance/activity', HttpClientAccept::JSON);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
return $serverdata;
@ -1346,10 +1349,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectFromContacts(string $url, array $serverdata)
private static function detectFromContacts(string $url, array $serverdata): array
{
$gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
if (empty($gserver)) {
@ -1374,10 +1376,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectMastodonAlikes(string $url, array $serverdata)
private static function detectMastodonAlikes(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/api/v1/instance', HttpClientAccept::JSON);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
@ -1439,10 +1440,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectHubzilla(string $url, array $serverdata)
private static function detectHubzilla(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/api/statusnet/config.json', HttpClientAccept::JSON);
if (!$curlResult->isSuccess() || ($curlResult->getBody() == '')) {
@ -1517,10 +1517,9 @@ class GServer
* Converts input value to a boolean value
*
* @param string|integer $val
*
* @return boolean
*/
private static function toBoolean($val)
private static function toBoolean($val): bool
{
if (($val == 'true') || ($val == 1)) {
return true;
@ -1536,10 +1535,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectPumpIO(string $url, array $serverdata)
private static function detectPumpIO(string $url, array $serverdata): array
{
$curlResult = DI::httpClient()->get($url . '/.well-known/host-meta.json', HttpClientAccept::JSON);
if (!$curlResult->isSuccess()) {
@ -1549,7 +1547,6 @@ class GServer
$data = json_decode($curlResult->getBody(), true);
if (empty($data['links'])) {
return $serverdata;
}
// We are looking for some endpoints that are typical for pump.io
@ -1586,10 +1583,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectGNUSocial(string $url, array $serverdata)
private static function detectGNUSocial(string $url, array $serverdata): array
{
// Test for GNU Social
$curlResult = DI::httpClient()->get($url . '/api/gnusocial/version.json', HttpClientAccept::JSON);
@ -1641,10 +1637,9 @@ class GServer
*
* @param string $url URL of the given server
* @param array $serverdata array with server data
*
* @return array server data
*/
private static function detectFriendica(string $url, array $serverdata)
private static function detectFriendica(string $url, array $serverdata): array
{
// There is a bug in some versions of Friendica that will return an ActivityStream actor when the content type "application/json" is requested.
// Because of this me must not use ACCEPT_JSON here.
@ -1717,10 +1712,9 @@ class GServer
* @param object $curlResult result of curl execution
* @param array $serverdata array with server data
* @param string $url Server URL
*
* @return array server data
*/
private static function analyseRootBody($curlResult, array $serverdata, string $url)
private static function analyseRootBody($curlResult, array $serverdata, string $url): array
{
if (empty($curlResult->getBody())) {
return $serverdata;
@ -1859,7 +1853,7 @@ class GServer
*
* @return array server data
*/
private static function analyseRootHeader($curlResult, array $serverdata)
private static function analyseRootHeader($curlResult, array $serverdata): array
{
if ($curlResult->getHeader('server') == 'Mastodon') {
$serverdata['platform'] = 'mastodon';

View file

@ -39,7 +39,14 @@ class Group
const FOLLOWERS = '~';
const MUTUALS = '&';
public static function getByUserId($uid, $includesDeleted = false)
/**
* Fetches group record by user id and maybe includes deleted groups as well
*
* @param int $uid User id to fetch group(s) for
* @param bool $includesDeleted Whether deleted groups should be included
* @return array|bool Array on success, bool on error
*/
public static function getByUserId(int $uid, bool $includesDeleted = false)
{
$conditions = ['uid' => $uid, 'cid' => null];
@ -51,15 +58,18 @@ class Group
}
/**
* @param int $group_id
* Checks whether given group id is found in database
*
* @param int $group_id Groupd it
* @param int $uid Optional user id
* @return bool
* @throws \Exception
*/
public static function exists($group_id, $uid = null)
public static function exists(int $group_id, int $uid = null): bool
{
$condition = ['id' => $group_id, 'deleted' => false];
if (isset($uid)) {
if (!is_null($uid)) {
$condition = [
'uid' => $uid
];
@ -73,12 +83,12 @@ class Group
*
* Note: If we found a deleted group with the same name, we restore it
*
* @param int $uid
* @param string $name
* @return boolean
* @param int $uid User id to create group for
* @param string $name Name of group
* @return int|boolean Id of newly created group or false on error
* @throws \Exception
*/
public static function create($uid, $name)
public static function create(int $uid, string $name)
{
$return = false;
if (!empty($uid) && !empty($name)) {
@ -114,7 +124,7 @@ class Group
* @return bool Was the update successful?
* @throws \Exception
*/
public static function update($id, $name)
public static function update(int $id, string $name): bool
{
return DBA::update('group', ['name' => $name], ['id' => $id]);
}
@ -122,11 +132,11 @@ class Group
/**
* Get a list of group ids a contact belongs to
*
* @param int $cid
* @return array
* @param int $cid Contact id
* @return array Group ids
* @throws \Exception
*/
public static function getIdsByContactId($cid)
public static function getIdsByContactId(int $cid): array
{
$return = [];
@ -185,12 +195,12 @@ class Group
*
* Returns false if no group has been found.
*
* @param int $uid
* @param string $name
* @return int|boolean
* @param int $uid User id
* @param string $name Group name
* @return int|boolean Groups' id number or false on error
* @throws \Exception
*/
public static function getIdByName($uid, $name)
public static function getIdByName(int $uid, string $name)
{
if (!$uid || !strlen($name)) {
return false;
@ -211,7 +221,7 @@ class Group
* @return boolean
* @throws \Exception
*/
public static function remove($gid)
public static function remove(int $gid): bool
{
if (!$gid) {
return false;
@ -314,13 +324,14 @@ class Group
* Adds contacts to a group
*
* @param int $gid
* @param array $contacts
* @param array $contacts Array with contact ids
* @return void
* @throws \Exception
*/
public static function addMembers(int $gid, array $contacts)
{
if (!$gid || !$contacts) {
return false;
return;
}
// @TODO Backward compatibility with user contacts, remove by version 2022.03
@ -342,8 +353,9 @@ class Group
/**
* Removes contacts from a group
*
* @param int $gid
* @param array $contacts
* @param int $gid Group id
* @param array $contacts Contact ids
* @return bool
* @throws \Exception
*/
public static function removeMembers(int $gid, array $contacts)
@ -369,19 +381,20 @@ class Group
$contactIds[] = $cdata['user'];
}
DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $contactIds]);
// Return status of deletion
return DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $contactIds]);
}
/**
* Returns the combined list of contact ids from a group id list
*
* @param int $uid
* @param array $group_ids
* @param boolean $check_dead
* @param int $uid User id
* @param array $group_ids Groups ids
* @param boolean $check_dead Whether check "dead" records (?)
* @return array
* @throws \Exception
*/
public static function expand($uid, array $group_ids, $check_dead = false)
public static function expand(int $uid, array $group_ids, bool $check_dead = false): array
{
if (!is_array($group_ids) || !count($group_ids)) {
return [];
@ -454,13 +467,13 @@ class Group
/**
* Returns a templated group selection list
*
* @param int $uid
* @param int $uid User id
* @param int $gid An optional pre-selected group
* @param string $label An optional label of the list
* @return string
* @throws \Exception
*/
public static function displayGroupSelection($uid, $gid = 0, $label = '')
public static function displayGroupSelection(int $uid, int $gid = 0, string $label = ''): string
{
$display_groups = [
[
@ -502,12 +515,12 @@ class Group
* 'standard' => include link 'Edit groups'
* 'extended' => include link 'Create new group'
* 'full' => include link 'Create new group' and provide for each group a link to edit this group
* @param string $group_id
* @param int $cid
* @return string
* @param string|int $group_id Distinct group id or 'everyone'
* @param int $cid Contact id
* @return string Sidebar widget HTML code
* @throws \Exception
*/
public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
public static function sidebarWidget(string $every = 'contact', string $each = 'group', string $editmode = 'standard', $group_id = '', int $cid = 0)
{
if (!local_user()) {
return '';
@ -589,7 +602,7 @@ class Group
* @param integer $id Contact ID
* @return integer Group IO
*/
public static function getIdForForum(int $id)
public static function getIdForForum(int $id): int
{
Logger::info('Get id for forum id', ['id' => $id]);
$contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']);
@ -617,6 +630,7 @@ class Group
* Fetch the followers of a given contact id and store them as group members
*
* @param integer $id Contact ID
* @return void
*/
public static function updateMembersForForum(int $id)
{

View file

@ -96,8 +96,8 @@ class Item
'event-created', 'event-edited', 'event-start', 'event-finish',
'event-summary', 'event-desc', 'event-location', 'event-type',
'event-nofinish', 'event-ignore', 'event-id',
"question-id", "question-multiple", "question-voters", "question-end-time",
"has-categories", "has-media",
'question-id', 'question-multiple', 'question-voters', 'question-end-time',
'has-categories', 'has-media',
'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
];
@ -226,7 +226,7 @@ class Item
foreach ($notify_items as $notify_item) {
$post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
}
return $rows;
@ -237,9 +237,10 @@ class Item
*
* @param array $condition The condition for finding the item entries
* @param integer $priority Priority for the notification
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
public static function markForDeletion(array $condition, int $priority = PRIORITY_HIGH)
{
$items = Post::select(['id'], $condition);
while ($item = Post::fetch($items)) {
@ -253,6 +254,7 @@ class Item
*
* @param array $condition The condition for finding the item entries
* @param integer $uid User who wants to delete this item
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function deleteForUser(array $condition, int $uid)
@ -282,11 +284,10 @@ class Item
*
* @param integer $item_id
* @param integer $priority Priority for the notification
*
* @return boolean success
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
public static function markForDeletionById(int $item_id, int $priority = PRIORITY_HIGH): bool
{
Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
// locate item to be deleted
@ -331,7 +332,7 @@ class Item
// If item has attachments, drop them
$attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
foreach($attachments as $attachment) {
if (preg_match("|attach/(\d+)|", $attachment['url'], $matches)) {
if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
}
}
@ -360,7 +361,7 @@ class Item
// send the notification upstream/downstream
if ($priority) {
Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
}
} elseif ($item['uid'] != 0) {
Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
@ -372,7 +373,14 @@ class Item
return true;
}
public static function guid($item, $notify)
/**
* Get guid from given item record
*
* @param array $item Item record
* @param bool Whether to notify (?)
* @return string Guid
*/
public static function guid(array $item, bool $notify): string
{
if (!empty($item['guid'])) {
return trim($item['guid']);
@ -425,7 +433,13 @@ class Item
return $guid;
}
private static function contactId($item)
/**
* Returns contact id from given item record
*
* @param array $item Item record
* @return int Contact id
*/
private static function contactId(array $item): int
{
if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
return $item['contact-id'];
@ -451,17 +465,17 @@ class Item
* @param array $item The item fields that are to be inserted
* @throws \Exception
*/
private static function spool($orig_item)
private static function spool(array $item)
{
// Now we store the data in the spool directory
// We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
$file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
$spoolpath = System::getSpoolPath();
if ($spoolpath != "") {
if ($spoolpath != '') {
$spool = $spoolpath . '/' . $file;
file_put_contents($spool, json_encode($orig_item));
file_put_contents($spool, json_encode($item));
Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
}
}
@ -469,10 +483,10 @@ class Item
/**
* Check if the item array is a duplicate
*
* @param array $item
* @param array $item Item record
* @return boolean is it a duplicate?
*/
private static function isDuplicate(array $item)
private static function isDuplicate(array $item): bool
{
// Checking if there is already an item with the same guid
$condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
@ -521,10 +535,10 @@ class Item
/**
* Check if the item array is valid
*
* @param array $item
* @param array $item Item record
* @return boolean item is valid
*/
public static function isValid(array $item)
public static function isValid(array $item): bool
{
// When there is no content then we don't post it
if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
@ -591,10 +605,10 @@ class Item
/**
* Check if the item array is too old
*
* @param array $item
* @param array $item Item record
* @return boolean item is too old
*/
public static function isTooOld(array $item)
public static function isTooOld(array $item): bool
{
// check for create date and expire time
$expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
@ -623,15 +637,20 @@ class Item
/**
* Return the id of the given item array if it has been stored before
*
* @param array $item
* @return integer item id
* @param array $item Item record
* @return integer Item id or zero on error
*/
private static function getDuplicateID(array $item)
private static function getDuplicateID(array $item): int
{
if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
$condition = ["`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
$item['uri-id'], $item['uid'],
Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
$condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
$item['uri-id'],
$item['uid'],
Protocol::ACTIVITYPUB,
Protocol::DIASPORA,
Protocol::DFRN,
Protocol::OSTATUS
];
$existing = Post::selectFirst(['id', 'network'], $condition);
if (DBA::isResult($existing)) {
// We only log the entries with a different user id than 0. Otherwise we would have too many false positives
@ -640,12 +659,12 @@ class Item
'uri-id' => $item['uri-id'],
'uid' => $item['uid'],
'network' => $item['network'],
'existing_id' => $existing["id"],
'existing_network' => $existing["network"]
'existing_id' => $existing['id'],
'existing_network' => $existing['network']
]);
}
return $existing["id"];
return $existing['id'];
}
}
return 0;
@ -658,7 +677,7 @@ class Item
* @return array item array with parent data
* @throws \Exception
*/
private static function getTopLevelParent(array $item)
private static function getTopLevelParent(array $item): array
{
$fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
'uri-id', 'parent-uri-id',
@ -724,11 +743,20 @@ class Item
} elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
return GRAVITY_ACTIVITY;
}
Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
return GRAVITY_UNKNOWN; // Should not happen
}
public static function insert(array $item, int $notify = 0, bool $post_local = true)
/**
* Inserts item record
*
* @param array $item Item array to be inserted
* @param int $notify Notification (type?)
* @param bool $post_local (???)
* @return int Zero means error, otherwise primary key (id) is being returned
*/
public static function insert(array $item, int $notify = 0, bool $post_local = true): int
{
$orig_item = $item;
@ -869,7 +897,7 @@ class Item
Contact::checkAvatarCache($item['owner-id']);
// The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
$item["contact-id"] = self::contactId($item);
$item['contact-id'] = self::contactId($item);
if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
empty($item['origin']) &&self::isTooOld($item)) {
@ -944,8 +972,8 @@ class Item
$item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
// Is this item available in the global items (with uid=0)?
if ($item["uid"] == 0) {
$item["global"] = true;
if ($item['uid'] == 0) {
$item['global'] = true;
// Set the global flag on all items if this was a global item entry
Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
@ -954,8 +982,8 @@ class Item
}
// ACL settings
if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
$item["private"] = self::PRIVATE;
if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
$item['private'] = self::PRIVATE;
}
if ($notify && $post_local) {

View file

@ -30,7 +30,6 @@ class ItemURI
* Insert an item-uri record and return its id
*
* @param array $fields Item-uri fields
*
* @return int|null item-uri id
* @throws \Exception
*/
@ -61,12 +60,15 @@ class ItemURI
* Searched for an id of a given uri. Adds it, if not existing yet.
*
* @param string $uri
*
* @return integer item-uri id
* @throws \Exception
*/
public static function getIdByURI($uri)
public static function getIdByURI(string $uri): int
{
if (empty($uri)) {
return 0;
}
// If the URI gets too long we only take the first parts and hope for best
$uri = substr($uri, 0, 255);
@ -82,11 +84,10 @@ class ItemURI
* Searched for an id of a given guid.
*
* @param string $guid
*
* @return integer item-uri id
* @throws \Exception
*/
public static function getIdByGUID($guid)
public static function getIdByGUID(string $guid): int
{
// If the GUID gets too long we only take the first parts and hope for best
$guid = substr($guid, 0, 255);

View file

@ -45,7 +45,7 @@ class Mail
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function insert($msg, $notification = true)
public static function insert(array $msg, bool $notification = true)
{
if (!isset($msg['reply'])) {
$msg['reply'] = DBA::exists('mail', ['parent-uri' => $msg['parent-uri']]);
@ -125,7 +125,7 @@ class Mail
* @return int
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function send($recipient = 0, $body = '', $subject = '', $replyto = '')
public static function send(int $recipient = 0, string $body = '', string $subject = '', string $replyto = ''): int
{
$a = DI::app();
@ -255,7 +255,7 @@ class Mail
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function sendWall(array $recipient = [], $body = '', $subject = '', $replyto = '')
public static function sendWall(array $recipient = [], string $body = '', string $subject = '', string $replyto = ''): int
{
if (!$recipient) {
return -1;

View file

@ -22,6 +22,7 @@
namespace Friendica\Model;
use Friendica\Core\Addon;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Database\DBA;
use Friendica\DI;
use stdClass;
@ -101,7 +102,7 @@ class Nodeinfo
*
* @return array with supported services
*/
public static function getServices()
public static function getServices(): array
{
$services = [
'inbound' => [],
@ -156,9 +157,19 @@ class Nodeinfo
return $services;
}
public static function getOrganization($config)
/**
* Gathers organization information and returns it as an array
*
* @param IManageConfigValues $config Configuration instance
* @return array Organization information
*/
public static function getOrganization(IManageConfigValues $config): array
{
$organization = ['name' => null, 'contact' => null, 'account' => null];
$organization = [
'name' => null,
'contact' => null,
'account' => null
];
if (!empty($config->get('config', 'admin_email'))) {
$adminList = explode(',', str_replace(' ', '', $config->get('config', 'admin_email')));

View file

@ -40,16 +40,16 @@ class OpenWebAuthToken
* @return boolean
* @throws \Exception
*/
public static function create($type, $uid, $token, $meta)
public static function create(string $type, uid $uid, string $token, string $meta)
{
$fields = [
"type" => $type,
"uid" => $uid,
"token" => $token,
"meta" => $meta,
"created" => DateTimeFormat::utcNow()
'type' => $type,
'uid' => $uid,
'token' => $token,
'meta' => $meta,
'created' => DateTimeFormat::utcNow()
];
return DBA::insert("openwebauth-token", $fields);
return DBA::insert('openwebauth-token', $fields);
}
/**
@ -62,15 +62,15 @@ class OpenWebAuthToken
* @return string|boolean The meta enry or false if not found.
* @throws \Exception
*/
public static function getMeta($type, $uid, $token)
public static function getMeta(string $type, int $uid, string $token)
{
$condition = ["type" => $type, "uid" => $uid, "token" => $token];
$condition = ['type' => $type, 'uid' => $uid, 'token' => $token];
$entry = DBA::selectFirst("openwebauth-token", ["id", "meta"], $condition);
$entry = DBA::selectFirst('openwebauth-token', ['id', 'meta'], $condition);
if (DBA::isResult($entry)) {
DBA::delete("openwebauth-token", ["id" => $entry["id"]]);
DBA::delete('openwebauth-token', ['id' => $entry['id']]);
return $entry["meta"];
return $entry['meta'];
}
return false;
}
@ -82,10 +82,10 @@ class OpenWebAuthToken
* @param string $interval SQL compatible time interval
* @throws \Exception
*/
public static function purge($type, $interval)
public static function purge(string $type, string $interval)
{
$condition = ["`type` = ? AND `created` < ?", $type, DateTimeFormat::utcNow() . " - INTERVAL " . $interval];
DBA::delete("openwebauth-token", $condition);
$condition = ["`type` = ? AND `created` < ?", $type, DateTimeFormat::utcNow() . ' - INTERVAL ' . $interval];
DBA::delete('openwebauth-token', $condition);
}
}

View file

@ -94,7 +94,7 @@ class Photo
$fields = self::getFields();
}
return DBA::selectFirst("photo", $fields, $conditions, $params);
return DBA::selectFirst('photo', $fields, $conditions, $params);
}
/**
@ -112,8 +112,8 @@ class Photo
*/
public static function getPhotosForUser(int $uid, string $resourceid, array $conditions = [], array $params = [])
{
$conditions["resource-id"] = $resourceid;
$conditions["uid"] = $uid;
$conditions['resource-id'] = $resourceid;
$conditions['uid'] = $uid;
return self::selectToArray([], $conditions, $params);
}
@ -132,11 +132,11 @@ class Photo
* @throws \Exception
* @see \Friendica\Database\DBA::select
*/
public static function getPhotoForUser($uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
public static function getPhotoForUser(int $uid, $resourceid, $scale = 0, array $conditions = [], array $params = [])
{
$conditions["resource-id"] = $resourceid;
$conditions["uid"] = $uid;
$conditions["scale"] = $scale;
$conditions['resource-id'] = $resourceid;
$conditions['uid'] = $uid;
$conditions['scale'] = $scale;
return self::selectFirst([], $conditions, $params);
}
@ -156,19 +156,19 @@ class Photo
*/
public static function getPhoto(string $resourceid, int $scale = 0)
{
$r = self::selectFirst(["uid"], ["resource-id" => $resourceid]);
$r = self::selectFirst(['uid'], ['resource-id' => $resourceid]);
if (!DBA::isResult($r)) {
return false;
}
$uid = $r["uid"];
$uid = $r['uid'];
$accessible = $uid ? (bool)DI::pConfig()->get($uid, 'system', 'accessible-photos', false) : false;
$sql_acl = Security::getPermissionsSQLByUserId($uid, $accessible);
$conditions = ["`resource-id` = ? AND `scale` <= ? " . $sql_acl, $resourceid, $scale];
$params = ["order" => ["scale" => true]];
$params = ['order' => ['scale' => true]];
$photo = self::selectFirst([], $conditions, $params);
return $photo;
@ -182,9 +182,9 @@ class Photo
* @return boolean
* @throws \Exception
*/
public static function exists(array $conditions)
public static function exists(array $conditions): bool
{
return DBA::exists("photo", $conditions);
return DBA::exists('photo', $conditions);
}
@ -193,7 +193,7 @@ class Photo
*
* @param array $photo Photo data. Needs at least 'id', 'type', 'backend-class', 'backend-ref'
*
* @return \Friendica\Object\Image
* @return \Friendica\Object\Image|null Image object or null on error
*/
public static function getImageDataForPhoto(array $photo)
{
@ -248,11 +248,11 @@ class Photo
* @return array field list
* @throws \Exception
*/
private static function getFields()
private static function getFields(): array
{
$allfields = DBStructure::definition(DI::app()->getBasePath(), false);
$fields = array_keys($allfields["photo"]["fields"]);
array_splice($fields, array_search("data", $fields), 1);
$fields = array_keys($allfields['photo']['fields']);
array_splice($fields, array_search('data', $fields), 1);
return $fields;
}
@ -265,14 +265,14 @@ class Photo
* @return array
* @throws \Exception
*/
public static function createPhotoForSystemResource($filename, $mimetype = '')
public static function createPhotoForSystemResource(string $filename, string $mimetype = ''): array
{
if (empty($mimetype)) {
$mimetype = Images::guessTypeByExtension($filename);
}
$fields = self::getFields();
$values = array_fill(0, count($fields), "");
$values = array_fill(0, count($fields), '');
$photo = array_combine($fields, $values);
$photo['backend-class'] = SystemResource::NAME;
@ -293,14 +293,14 @@ class Photo
* @return array
* @throws \Exception
*/
public static function createPhotoForExternalResource($url, $uid = 0, $mimetype = '')
public static function createPhotoForExternalResource(string $url, int $uid = 0, string $mimetype = ''): array
{
if (empty($mimetype)) {
$mimetype = Images::guessTypeByExtension($url);
}
$fields = self::getFields();
$values = array_fill(0, count($fields), "");
$values = array_fill(0, count($fields), '');
$photo = array_combine($fields, $values);
$photo['backend-class'] = ExternalResource::NAME;
@ -314,14 +314,14 @@ class Photo
/**
* store photo metadata in db and binary in default backend
*
* @param Image $Image Image object with data
* @param Image $image Image object with data
* @param integer $uid User ID
* @param integer $cid Contact ID
* @param integer $rid Resource ID
* @param string $rid Resource ID
* @param string $filename Filename
* @param string $album Album name
* @param integer $scale Scale
* @param integer $profile Is a profile image? optional, default = 0
* @param integer $type Photo type, optional, default: Photo::DEFAULT
* @param string $allow_cid Permissions, allowed contacts. optional, default = ""
* @param string $allow_gid Permissions, allowed groups. optional, default = ""
* @param string $deny_cid Permissions, denied contacts.optional, default = ""
@ -331,71 +331,71 @@ class Photo
* @return boolean True on success
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $type = self::DEFAULT, $allow_cid = "", $allow_gid = "", $deny_cid = "", $deny_gid = "", $desc = "")
public static function store(Image $image, int $uid, int $cid, string $rid, string $filename, string $album, int $scale, int $type = self::DEFAULT, string $allow_cid = '', string $allow_gid = '', string $deny_cid = '', string $deny_gid = '', string $desc = ''): bool
{
$photo = self::selectFirst(["guid"], ["`resource-id` = ? AND `guid` != ?", $rid, ""]);
$photo = self::selectFirst(['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']);
if (DBA::isResult($photo)) {
$guid = $photo["guid"];
$guid = $photo['guid'];
} else {
$guid = System::createGUID();
}
$existing_photo = self::selectFirst(["id", "created", "backend-class", "backend-ref"], ["resource-id" => $rid, "uid" => $uid, "contact-id" => $cid, "scale" => $scale]);
$existing_photo = self::selectFirst(['id', 'created', 'backend-class', 'backend-ref'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]);
$created = DateTimeFormat::utcNow();
if (DBA::isResult($existing_photo)) {
$created = $existing_photo["created"];
$created = $existing_photo['created'];
}
// Get defined storage backend.
// if no storage backend, we use old "data" column in photo table.
// if is an existing photo, reuse same backend
$data = "";
$backend_ref = "";
$storage = "";
$data = '';
$backend_ref = '';
$storage = '';
try {
if (DBA::isResult($existing_photo)) {
$backend_ref = (string)$existing_photo["backend-ref"];
$storage = DI::storageManager()->getWritableStorageByName($existing_photo["backend-class"] ?? '');
$backend_ref = (string)$existing_photo['backend-ref'];
$storage = DI::storageManager()->getWritableStorageByName($existing_photo['backend-class'] ?? '');
} else {
$storage = DI::storage();
}
$backend_ref = $storage->put($Image->asString(), $backend_ref);
$backend_ref = $storage->put($image->asString(), $backend_ref);
} catch (InvalidClassStorageException $storageException) {
$data = $Image->asString();
$data = $image->asString();
}
$fields = [
"uid" => $uid,
"contact-id" => $cid,
"guid" => $guid,
"resource-id" => $rid,
"hash" => md5($Image->asString()),
"created" => $created,
"edited" => DateTimeFormat::utcNow(),
"filename" => basename($filename),
"type" => $Image->getType(),
"album" => $album,
"height" => $Image->getHeight(),
"width" => $Image->getWidth(),
"datasize" => strlen($Image->asString()),
"data" => $data,
"scale" => $scale,
"photo-type" => $type,
"profile" => false,
"allow_cid" => $allow_cid,
"allow_gid" => $allow_gid,
"deny_cid" => $deny_cid,
"deny_gid" => $deny_gid,
"desc" => $desc,
"backend-class" => (string)$storage,
"backend-ref" => $backend_ref
'uid' => $uid,
'contact-id' => $cid,
'guid' => $guid,
'resource-id' => $rid,
'hash' => md5($image->asString()),
'created' => $created,
'edited' => DateTimeFormat::utcNow(),
'filename' => basename($filename),
'type' => $image->getType(),
'album' => $album,
'height' => $image->getHeight(),
'width' => $image->getWidth(),
'datasize' => strlen($image->asString()),
'data' => $data,
'scale' => $scale,
'photo-type' => $type,
'profile' => false,
'allow_cid' => $allow_cid,
'allow_gid' => $allow_gid,
'deny_cid' => $deny_cid,
'deny_gid' => $deny_gid,
'desc' => $desc,
'backend-class' => (string)$storage,
'backend-ref' => $backend_ref
];
if (DBA::isResult($existing_photo)) {
$r = DBA::update("photo", $fields, ["id" => $existing_photo["id"]]);
$r = DBA::update('photo', $fields, ['id' => $existing_photo['id']]);
} else {
$r = DBA::insert("photo", $fields);
$r = DBA::insert('photo', $fields);
}
return $r;
@ -413,7 +413,7 @@ class Photo
* @throws \Exception
* @see \Friendica\Database\DBA::delete
*/
public static function delete(array $conditions, array $options = [])
public static function delete(array $conditions, array $options = []): bool
{
// get photo to delete data info
$photos = DBA::select('photo', ['id', 'backend-class', 'backend-ref'], $conditions);
@ -423,7 +423,7 @@ class Photo
$backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
$backend_class->delete($photo['backend-ref'] ?? '');
// Delete the photos after they had been deleted successfully
DBA::delete("photo", ['id' => $photo['id']]);
DBA::delete('photo', ['id' => $photo['id']]);
} catch (InvalidClassStorageException $storageException) {
DI::logger()->debug('Storage class not found.', ['conditions' => $conditions, 'exception' => $storageException]);
} catch (ReferenceStorageException $referenceStorageException) {
@ -433,34 +433,34 @@ class Photo
DBA::close($photos);
return DBA::delete("photo", $conditions, $options);
return DBA::delete('photo', $conditions, $options);
}
/**
* Update a photo
*
* @param array $fields Contains the fields that are updated
* @param array $conditions Condition array with the key values
* @param Image $img Image to update. Optional, default null.
* @param array|boolean $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
* @param array $fields Contains the fields that are updated
* @param array $conditions Condition array with the key values
* @param Image $image Image to update. Optional, default null.
* @param array $old_fields Array with the old field values that are about to be replaced (true = update on duplicate)
*
* @return boolean Was the update successfull?
*
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @see \Friendica\Database\DBA::update
*/
public static function update($fields, $conditions, Image $img = null, array $old_fields = [])
public static function update(array $fields, array $conditions, Image $image = null, array $old_fields = []): bool
{
if (!is_null($img)) {
if (!is_null($image)) {
// get photo to update
$photos = self::selectToArray(['backend-class', 'backend-ref'], $conditions);
foreach($photos as $photo) {
try {
$backend_class = DI::storageManager()->getWritableStorageByName($photo['backend-class'] ?? '');
$fields["backend-ref"] = $backend_class->put($img->asString(), $photo['backend-ref']);
$fields['backend-ref'] = $backend_class->put($image->asString(), $photo['backend-ref']);
} catch (InvalidClassStorageException $storageException) {
$fields["data"] = $img->asString();
$fields['data'] = $image->asString();
}
}
$fields['updated'] = DateTimeFormat::utcNow();
@ -468,7 +468,7 @@ class Photo
$fields['edited'] = DateTimeFormat::utcNow();
return DBA::update("photo", $fields, $conditions, $old_fields);
return DBA::update('photo', $fields, $conditions, $old_fields);
}
/**
@ -476,20 +476,20 @@ class Photo
* @param integer $uid user id
* @param integer $cid contact id
* @param boolean $quit_on_error optional, default false
* @return array
* @return array|bool Array on success, false on error
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function importProfilePhoto($image_url, $uid, $cid, $quit_on_error = false)
public static function importProfilePhoto(string $image_url, int $uid, int $cid, bool $quit_on_error = false)
{
$thumb = "";
$micro = "";
$thumb = '';
$micro = '';
$photo = DBA::selectFirst(
"photo", ["resource-id"], ["uid" => $uid, "contact-id" => $cid, "scale" => 4, "photo-type" => self::CONTACT_AVATAR]
'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'photo-type' => self::CONTACT_AVATAR]
);
if (!empty($photo['resource-id'])) {
$resource_id = $photo["resource-id"];
$resource_id = $photo['resource-id'];
} else {
$resource_id = self::newResource();
}
@ -507,66 +507,66 @@ class Photo
$type = '';
}
if ($quit_on_error && ($img_str == "")) {
if ($quit_on_error && ($img_str == '')) {
return false;
}
$type = Images::getMimeTypeByData($img_str, $image_url, $type);
$Image = new Image($img_str, $type);
if ($Image->isValid()) {
$Image->scaleToSquare(300);
$image = new Image($img_str, $type);
if ($image->isValid()) {
$image->scaleToSquare(300);
$filesize = strlen($Image->asString());
$filesize = strlen($image->asString());
$maximagesize = DI::config()->get('system', 'maximagesize');
if (!empty($maximagesize) && ($filesize > $maximagesize)) {
Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $Image->getType()]);
if ($Image->getType() == 'image/gif') {
$Image->toStatic();
$Image = new Image($Image->asString(), 'image/png');
Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
if ($image->getType() == 'image/gif') {
$image->toStatic();
$image = new Image($image->asString(), 'image/png');
$filesize = strlen($Image->asString());
Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
$filesize = strlen($image->asString());
Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
}
if ($filesize > $maximagesize) {
foreach ([160, 80] as $pixels) {
if ($filesize > $maximagesize) {
Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $Image->getType()]);
$Image->scaleDown($pixels);
$filesize = strlen($Image->asString());
Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
$image->scaleDown($pixels);
$filesize = strlen($image->asString());
}
}
}
Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $Image->getType()]);
Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
}
$r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
$r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
if ($r === false) {
$photo_failure = true;
}
$Image->scaleDown(80);
$image->scaleDown(80);
$r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
$r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 5, self::CONTACT_AVATAR);
if ($r === false) {
$photo_failure = true;
}
$Image->scaleDown(48);
$image->scaleDown(48);
$r = self::store($Image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
$r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 6, self::CONTACT_AVATAR);
if ($r === false) {
$photo_failure = true;
}
$suffix = "?ts=" . time();
$suffix = '?ts=' . time();
$image_url = DI::baseUrl() . "/photo/" . $resource_id . "-4." . $Image->getExt() . $suffix;
$thumb = DI::baseUrl() . "/photo/" . $resource_id . "-5." . $Image->getExt() . $suffix;
$micro = DI::baseUrl() . "/photo/" . $resource_id . "-6." . $Image->getExt() . $suffix;
$image_url = DI::baseUrl() . '/photo/' . $resource_id . '-4.' . $image->getExt() . $suffix;
$thumb = DI::baseUrl() . '/photo/' . $resource_id . '-5.' . $image->getExt() . $suffix;
$micro = DI::baseUrl() . '/photo/' . $resource_id . '-6.' . $image->getExt() . $suffix;
} else {
$photo_failure = true;
}
@ -590,31 +590,33 @@ class Photo
* @param string $hemi hemi
* @return float
*/
public static function getGps($exifCoord, $hemi)
public static function getGps(array $exifCoord, string $hemi): float
{
$degrees = count($exifCoord) > 0 ? self::gps2Num($exifCoord[0]) : 0;
$minutes = count($exifCoord) > 1 ? self::gps2Num($exifCoord[1]) : 0;
$seconds = count($exifCoord) > 2 ? self::gps2Num($exifCoord[2]) : 0;
$flip = ($hemi == "W" || $hemi == "S") ? -1 : 1;
$flip = ($hemi == 'W' || $hemi == 'S') ? -1 : 1;
return floatval($flip * ($degrees + ($minutes / 60) + ($seconds / 3600)));
}
/**
* Change GPS to float number
*
* @param string $coordPart coordPart
* @return float
*/
private static function gps2Num($coordPart)
private static function gps2Num(string $coordPart): float
{
$parts = explode("/", $coordPart);
$parts = explode('/', $coordPart);
if (count($parts) <= 0) {
return 0;
}
if (count($parts) == 1) {
return $parts[0];
return (float)$parts[0];
}
return floatval($parts[0]) / floatval($parts[1]);
@ -631,17 +633,18 @@ class Photo
* @return array Returns array of the photo albums
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getAlbums($uid, $update = false)
public static function getAlbums(int $uid, bool $update = false): array
{
$sql_extra = Security::getPermissionsSQLByUserId($uid);
$avatar_type = (local_user() && (local_user() == $uid)) ? self::USER_AVATAR : self::DEFAULT;
$banner_type = (local_user() && (local_user() == $uid)) ? self::USER_BANNER : self::DEFAULT;
$key = "photo_albums:".$uid.":".local_user().":".remote_user();
$key = 'photo_albums:' . $uid . ':' . local_user() . ':' . remote_user();
$albums = DI::cache()->get($key);
if (is_null($albums) || $update) {
if (!DI::config()->get("system", "no_count", false)) {
if (!DI::config()->get('system', 'no_count', false)) {
/// @todo This query needs to be renewed. It is really slow
// At this time we just store the data in the cache
$albums = DBA::toArray(DBA::p("SELECT COUNT(DISTINCT `resource-id`) AS `total`, `album`, ANY_VALUE(`created`) AS `created`
@ -674,19 +677,19 @@ class Photo
* @return void
* @throws \Exception
*/
public static function clearAlbumCache($uid)
public static function clearAlbumCache(int $uid)
{
$key = "photo_albums:".$uid.":".local_user().":".remote_user();
$key = 'photo_albums:' . $uid . ':' . local_user() . ':' . remote_user();
DI::cache()->set($key, null, Duration::DAY);
}
/**
* Generate a unique photo ID.
*
* @return string
* @return string Resource GUID
* @throws \Exception
*/
public static function newResource()
public static function newResource(): string
{
return System::createGUID(32, false);
}
@ -697,7 +700,7 @@ class Photo
* @param string $image_uri The URI of the photo
* @return string The rid of the photo, or an empty string if the URI is not local
*/
public static function ridFromURI(string $image_uri)
public static function ridFromURI(string $image_uri): string
{
if (!stristr($image_uri, DI::baseUrl() . '/photo/')) {
return '';
@ -809,7 +812,7 @@ class Photo
* @param string $name Picture link
* @return array
*/
public static function getResourceData(string $name):array
public static function getResourceData(string $name): array
{
$base = DI::baseUrl()->get();
@ -840,8 +843,9 @@ class Photo
* @return boolean
* @throws \Exception
*/
public static function isLocal($name)
public static function isLocal(string $name): bool
{
// @TODO Maybe a proper check here on true condition?
return (bool)self::getIdForName($name);
}
@ -851,7 +855,7 @@ class Photo
* @param string $name Picture link
* @return int
*/
public static function getIdForName($name)
public static function getIdForName(string $name): int
{
$data = self::getResourceData($name);
if (empty($data)) {
@ -872,7 +876,7 @@ class Photo
* @return boolean
* @throws \Exception
*/
public static function isLocalPage($name)
public static function isLocalPage(string $name): bool
{
$base = DI::baseUrl()->get();
@ -885,17 +889,23 @@ class Photo
return DBA::exists('photo', ['resource-id' => $guid]);
}
private static function fitImageSize($Image)
/**
* Tries to resize image to wanted maximum size
*
* @param Image $image Image instance
* @return Image|null Image instance on success, null on error
*/
private static function fitImageSize(Image $image)
{
$max_length = DI::config()->get('system', 'max_image_length');
if ($max_length > 0) {
$Image->scaleDown($max_length);
$image->scaleDown($max_length);
Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
}
$filesize = strlen($Image->asString());
$width = $Image->getWidth();
$height = $Image->getHeight();
$filesize = strlen($image->asString());
$width = $image->getWidth();
$height = $image->getHeight();
$maximagesize = DI::config()->get('system', 'maximagesize');
@ -904,10 +914,10 @@ class Photo
foreach ([5120, 2560, 1280, 640] as $pixels) {
if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
$Image->scaleDown($pixels);
$filesize = strlen($Image->asString());
$width = $Image->getWidth();
$height = $Image->getHeight();
$image->scaleDown($pixels);
$filesize = strlen($image->asString());
$width = $image->getWidth();
$height = $image->getHeight();
}
}
if ($filesize > $maximagesize) {
@ -916,10 +926,16 @@ class Photo
}
}
return $Image;
return $image;
}
private static function loadImageFromURL(string $image_url)
/**
* Fetches image from URL and returns an array with instance and local file name
*
* @param string $image_url URL to image
* @return array With: 'image' and 'filename' fields or empty array on error
*/
private static function loadImageFromURL(string $image_url): array
{
$filename = basename($image_url);
if (!empty($image_url)) {
@ -939,17 +955,23 @@ class Photo
$type = Images::getMimeTypeByData($img_str, $image_url, $type);
$Image = new Image($img_str, $type);
$image = new Image($img_str, $type);
$Image = self::fitImageSize($Image);
if (empty($Image)) {
$image = self::fitImageSize($image);
if (empty($image)) {
return [];
}
return ['image' => $Image, 'filename' => $filename];
return ['image' => $image, 'filename' => $filename];
}
private static function uploadImage(array $files)
/**
* Inserts uploaded image into database and removes local temporary file
*
* @param array $files File array
* @return array With 'image' for Image instance and 'filename' for local file name or empty array on error
*/
private static function uploadImage(array $files): array
{
Logger::info('starting new upload');
@ -1008,34 +1030,36 @@ class Photo
Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
$imagedata = @file_get_contents($src);
$Image = new Image($imagedata, $filetype);
if (!$Image->isValid()) {
$image = new Image($imagedata, $filetype);
if (!$image->isValid()) {
Logger::notice('Image is unvalid', ['files' => $files]);
return [];
}
$Image->orient($src);
$image->orient($src);
@unlink($src);
$Image = self::fitImageSize($Image);
if (empty($Image)) {
$image = self::fitImageSize($image);
if (empty($image)) {
return [];
}
return ['image' => $Image, 'filename' => $filename];
return ['image' => $image, 'filename' => $filename];
}
/**
* Handles uploaded image and assigns it to given user id
*
* @param int $uid User ID
* @param array $files uploaded file array
* @param string $album
* @param string $album Album name (optional)
* @param string|null $allow_cid
* @param string|null $allow_gid
* @param string $deny_cid
* @param string $deny_gid
* @param string $desc
* @param string $resource_id
* @return array photo record
* @param string $desc Description (optional)
* @param string $resource_id GUID (optional)
* @return array photo record or empty array on error
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function upload(int $uid, array $files, string $album = '', string $allow_cid = null, string $allow_gid = null, string $deny_cid = '', string $deny_gid = '', string $desc = '', string $resource_id = ''): array
@ -1052,10 +1076,10 @@ class Photo
return [];
}
$Image = $data['image'];
$image = $data['image'];
$filename = $data['filename'];
$width = $Image->getWidth();
$height = $Image->getHeight();
$width = $image->getWidth();
$height = $image->getHeight();
$resource_id = $resource_id ?: self::newResource();
$album = $album ?: DI::l10n()->t('Wall Photos');
@ -1067,23 +1091,23 @@ class Photo
$smallest = 0;
$r = self::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) {
Logger::notice('Photo could not be stored');
return [];
}
if ($width > 640 || $height > 640) {
$Image->scaleDown(640);
$r = self::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$image->scaleDown(640);
$r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 1, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if ($r) {
$smallest = 1;
}
}
if ($width > 320 || $height > 320) {
$Image->scaleDown(320);
$r = self::store($Image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
$image->scaleDown(320);
$r = self::store($image, $user['uid'], 0, $resource_id, $filename, $album, 2, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if ($r && ($smallest == 0)) {
$smallest = 2;
}
@ -1105,8 +1129,8 @@ class Photo
$picture['height'] = $photo['height'];
$picture['type'] = $photo['type'];
$picture['albumpage'] = DI::baseUrl() . '/photos/' . $user['nickname'] . '/image/' . $resource_id;
$picture['picture'] = DI::baseUrl() . '/photo/{$resource_id}-0.' . $Image->getExt();
$picture['preview'] = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $Image->getExt();
$picture['picture'] = DI::baseUrl() . '/photo/{$resource_id}-0.' . $image->getExt();
$picture['preview'] = DI::baseUrl() . '/photo/{$resource_id}-{$smallest}.' . $image->getExt();
Logger::info('upload done', ['picture' => $picture]);
return $picture;
@ -1139,10 +1163,10 @@ class Photo
return '';
}
$Image = $data['image'];
$image = $data['image'];
$filename = $data['filename'];
$width = $Image->getWidth();
$height = $Image->getHeight();
$width = $image->getWidth();
$height = $image->getHeight();
$resource_id = self::newResource();
$album = DI::l10n()->t(self::PROFILE_PHOTOS);
@ -1151,28 +1175,28 @@ class Photo
logger::info('starting new profile image upload');
if ($width > 300 || $height > 300) {
$Image->scaleDown(300);
$image->scaleDown(300);
}
$r = self::store($Image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
$r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
if (!$r) {
logger::notice('profile image upload with scale 4 (300) failed');
}
if ($width > 80 || $height > 80) {
$Image->scaleDown(80);
$image->scaleDown(80);
}
$r = self::store($Image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
$r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
if (!$r) {
logger::notice('profile image upload with scale 5 (80) failed');
}
if ($width > 48 || $height > 48) {
$Image->scaleDown(48);
$image->scaleDown(48);
}
$r = self::store($Image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
$r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
if (!$r) {
logger::notice('profile image upload with scale 6 (48) failed');
}
@ -1217,19 +1241,19 @@ class Photo
return '';
}
$Image = $data['image'];
$image = $data['image'];
$filename = $data['filename'];
$width = $Image->getWidth();
$height = $Image->getHeight();
$width = $image->getWidth();
$height = $image->getHeight();
$resource_id = self::newResource();
$album = DI::l10n()->t(self::BANNER_PHOTOS);
if ($width > 960) {
$Image->scaleDown(960);
$image->scaleDown(960);
}
$r = self::store($Image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
$r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
if (!$r) {
logger::notice('profile banner upload with scale 3 (960) failed');
}
@ -1247,3 +1271,4 @@ class Photo
return $resource_id;
}
}

View file

@ -39,7 +39,7 @@ class Post
* @return int ID of inserted post
* @throws \Exception
*/
public static function insert(int $uri_id, array $data = [])
public static function insert(int $uri_id, array $data = []): int
{
if (empty($uri_id)) {
throw new BadMethodCallException('Empty URI_id');
@ -107,8 +107,10 @@ class Post
* @param object $stmt statement object
* @param bool $do_close
* @return array Data array
* @todo Find proper type-hint for $stmt and maybe avoid boolean
*/
public static function toArray($stmt, $do_close = true) {
public static function toArray($stmt, bool $do_close = true)
{
if (is_bool($stmt)) {
return $stmt;
}
@ -131,7 +133,8 @@ class Post
* @return boolean Are there rows for that condition?
* @throws \Exception
*/
public static function exists($condition) {
public static function exists(array $condition): bool
{
return DBA::exists('post-user-view', $condition);
}
@ -151,7 +154,7 @@ class Post
* $count = Post::count($condition);
* @throws \Exception
*/
public static function count(array $condition = [], array $params = [])
public static function count(array $condition = [], array $params = []): int
{
return DBA::count('post-user-view', $condition, $params);
}
@ -172,7 +175,7 @@ class Post
* $count = Post::count($condition);
* @throws \Exception
*/
public static function countThread(array $condition = [], array $params = [])
public static function countThread(array $condition = [], array $params = []): int
{
return DBA::count('post-thread-user-view', $condition, $params);
}
@ -193,7 +196,7 @@ class Post
* $count = Post::count($condition);
* @throws \Exception
*/
public static function countPosts(array $condition = [], array $params = [])
public static function countPosts(array $condition = [], array $params = []): int
{
return DBA::count('post-view', $condition, $params);
}
@ -209,7 +212,7 @@ class Post
* @throws \Exception
* @see DBA::select
*/
public static function selectFirst(array $fields = [], array $condition = [], $params = [])
public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
{
$params['limit'] = 1;
@ -234,7 +237,7 @@ class Post
* @throws \Exception
* @see DBA::select
*/
public static function selectFirstPost(array $fields = [], array $condition = [], $params = [])
public static function selectFirstPost(array $fields = [], array $condition = [], array $params = [])
{
$params['limit'] = 1;
@ -259,7 +262,7 @@ class Post
* @throws \Exception
* @see DBA::select
*/
public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
public static function selectFirstThread(array $fields = [], array $condition = [], array $params = [])
{
$params['limit'] = 1;
@ -284,7 +287,7 @@ class Post
* @return array
* @throws \Exception
*/
public static function selectToArray(array $fields = [], array $condition = [], $params = [])
public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
{
$result = self::select($fields, $condition, $params);
@ -312,7 +315,7 @@ class Post
* @return boolean|object
* @throws \Exception
*/
private static function selectView(string $view, array $selected = [], array $condition = [], $params = [])
private static function selectView(string $view, array $selected = [], array $condition = [], array $params = [])
{
if (empty($selected)) {
$selected = array_merge(Item::DISPLAY_FIELDLIST, Item::ITEM_FIELDLIST);
@ -337,7 +340,7 @@ class Post
* @return boolean|object
* @throws \Exception
*/
public static function select(array $selected = [], array $condition = [], $params = [])
public static function select(array $selected = [], array $condition = [], array $params = [])
{
return self::selectView('post-user-view', $selected, $condition, $params);
}
@ -352,7 +355,7 @@ class Post
* @return boolean|object
* @throws \Exception
*/
public static function selectPosts(array $selected = [], array $condition = [], $params = [])
public static function selectPosts(array $selected = [], array $condition = [], array $params = [])
{
return self::selectView('post-view', $selected, $condition, $params);
}
@ -367,7 +370,7 @@ class Post
* @return boolean|object
* @throws \Exception
*/
public static function selectThread(array $selected = [], array $condition = [], $params = [])
public static function selectThread(array $selected = [], array $condition = [], array $params = [])
{
return self::selectView('post-thread-user-view', $selected, $condition, $params);
}
@ -384,7 +387,7 @@ class Post
* @return boolean|object
* @throws \Exception
*/
private static function selectViewForUser(string $view, $uid, array $selected = [], array $condition = [], $params = [])
private static function selectViewForUser(string $view, int $uid, array $selected = [], array $condition = [], array $params = [])
{
if (empty($selected)) {
$selected = Item::DISPLAY_FIELDLIST;
@ -425,7 +428,7 @@ class Post
* @return boolean|object
* @throws \Exception
*/
public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
public static function selectForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
{
return self::selectViewForUser('post-user-view', $uid, $selected, $condition, $params);
}
@ -441,7 +444,7 @@ class Post
* @return boolean|object
* @throws \Exception
*/
public static function selectPostsForUser($uid, array $selected = [], array $condition = [], $params = [])
public static function selectPostsForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
{
return self::selectViewForUser('post-view', $uid, $selected, $condition, $params);
}
@ -457,7 +460,7 @@ class Post
* @return boolean|object
* @throws \Exception
*/
public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
public static function selectThreadForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
{
return self::selectViewForUser('post-thread-user-view', $uid, $selected, $condition, $params);
}
@ -473,7 +476,7 @@ class Post
* @throws \Exception
* @see DBA::select
*/
public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
public static function selectFirstForUser(int $uid, array $selected = [], array $condition = [], array $params = [])
{
$params['limit'] = 1;
@ -640,7 +643,7 @@ class Post
* @return boolean was the delete successful?
* @throws \Exception
*/
public static function delete(array $conditions, array $options = [])
public static function delete(array $conditions, array $options = []): bool
{
return DBA::delete('post', $conditions, $options);
}

View file

@ -109,7 +109,7 @@ class Media
* @param array $media
* @return array cleaned media array
*/
private static function unsetEmptyFields(array $media)
private static function unsetEmptyFields(array $media): array
{
$fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
foreach ($fields as $field) {
@ -145,7 +145,7 @@ class Media
* @param string $title
* @return string "[attach]" element
*/
public static function getAttachElement(string $href, int $length, string $type, string $title = '')
public static function getAttachElement(string $href, int $length, string $type, string $title = ''): string
{
$media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
'size' => $length, 'mimetype' => $type, 'description' => $title]);
@ -160,7 +160,7 @@ class Media
* @param array $media
* @return array media array with additional data
*/
public static function fetchAdditionalData(array $media)
public static function fetchAdditionalData(array $media): array
{
if (Network::isLocalLink($media['url'])) {
$media = self::fetchLocalData($media);
@ -235,7 +235,7 @@ class Media
* @param array $media
* @return array media with added data
*/
private static function fetchLocalData(array $media)
private static function fetchLocalData(array $media): array
{
if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
return $media;
@ -266,7 +266,7 @@ class Media
* @param array $data
* @return array data array with the detected type
*/
public static function addType(array $data)
public static function addType(array $data): array
{
if (empty($data['mimetype'])) {
Logger::info('No MimeType provided', ['media' => $data]);
@ -318,7 +318,7 @@ class Media
* @param string $preview Preview picture
* @return boolean
*/
private static function isPictureLink(string $page, string $preview)
private static function isPictureLink(string $page, string $preview): bool
{
return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
}
@ -330,7 +330,7 @@ class Media
* @param string $body
* @return string Body without media links
*/
public static function insertFromBody(int $uriid, string $body)
public static function insertFromBody(int $uriid, string $body): string
{
// Simplify image codes
$unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
@ -413,6 +413,7 @@ class Media
*
* @param integer $uriid
* @param string $body
* @return void
*/
public static function insertFromRelevantUrl(int $uriid, string $body)
{
@ -448,6 +449,7 @@ class Media
*
* @param integer $uriid
* @param string $body
* @return void
*/
public static function insertFromAttachmentData(int $uriid, string $body)
{
@ -506,9 +508,9 @@ class Media
/**
* Retrieves the media attachments associated with the provided item ID.
*
* @param int $uri_id
* @param array $types
* @return array
* @param int $uri_id URI id
* @param array $types Media types
* @return array|bool Array on success, false on error
* @throws \Exception
*/
public static function getByURIId(int $uri_id, array $types = [])
@ -525,12 +527,12 @@ class Media
/**
* Checks if media attachments are associated with the provided item ID.
*
* @param int $uri_id
* @param array $types
* @return array
* @param int $uri_id URI id
* @param array $types Media types
* @return bool Whether media attachment exists
* @throws \Exception
*/
public static function existsByURIId(int $uri_id, array $types = [])
public static function existsByURIId(int $uri_id, array $types = []): bool
{
$condition = ['uri-id' => $uri_id];
@ -544,13 +546,13 @@ class Media
/**
* Split the attachment media in the three segments "visual", "link" and "additional"
*
* @param int $uri_id
* @param string $guid
* @param int $uri_id URI id
* @param string $guid GUID
* @param array $links list of links that shouldn't be added
* @param bool $has_media
* @return array attachments
*/
public static function splitAttachments(int $uri_id, string $guid = '', array $links = [], bool $has_media = true)
public static function splitAttachments(int $uri_id, string $guid = '', array $links = [], bool $has_media = true): array
{
$attachments = ['visual' => [], 'link' => [], 'additional' => []];
@ -648,7 +650,7 @@ class Media
* @param string $body
* @return string body
*/
public static function addAttachmentsToBody(int $uriid, string $body = '')
public static function addAttachmentsToBody(int $uriid, string $body = ''): string
{
if (empty($body)) {
$item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
@ -701,7 +703,7 @@ class Media
* @param string $size One of the Proxy::SIZE_* constants
* @return string preview link
*/
public static function getPreviewUrlForId(int $id, string $size = ''):string
public static function getPreviewUrlForId(int $id, string $size = ''): string
{
$url = DI::baseUrl() . '/photo/preview/';
switch ($size) {
@ -731,7 +733,7 @@ class Media
* @param string $size One of the Proxy::SIZE_* constants
* @return string media link
*/
public static function getUrlForId(int $id, string $size = ''):string
public static function getUrlForId(int $id, string $size = ''): string
{
$url = DI::baseUrl() . '/photo/media/';
switch ($size) {

View file

@ -54,10 +54,10 @@ class Profile
*
* @param integer User ID
*
* @return array Profile data
* @return array|bool Profile data or false on error
* @throws \Exception
*/
public static function getByUID($uid)
public static function getByUID(int $uid)
{
return DBA::selectFirst('profile', [], ['uid' => $uid]);
}
@ -69,7 +69,7 @@ class Profile
* @param int $id The contact owner ID
* @param array $fields The selected fields
*
* @return array Profile data for the ID
* @return array|bool Profile data for the ID or false on error
* @throws \Exception
*/
public static function getById(int $uid, int $id, array $fields = [])
@ -81,7 +81,7 @@ class Profile
* Returns profile data for the contact owner
*
* @param int $uid The User ID
* @param array $fields The fields to retrieve
* @param array|bool $fields The fields to retrieve or false on error
*
* @return array Array of profile data
* @throws \Exception
@ -94,9 +94,9 @@ class Profile
/**
* Update a profile entry and distribute the changes if needed
*
* @param array $fields
* @param integer $uid
* @return boolean
* @param array $fields Profile fields to update
* @param integer $uid User id
* @return boolean Whether update was successful
*/
public static function update(array $fields, int $uid): bool
{
@ -136,8 +136,10 @@ class Profile
/**
* Publish a changed profile
* @param int $uid
*
* @param int $uid User id
* @param bool $force Force publishing to the directory
* @return void
*/
public static function publishUpdate(int $uid, bool $force = false)
{
@ -163,7 +165,7 @@ class Profile
*
* @return string Location string
*/
public static function formatLocation(array $profile)
public static function formatLocation(array $profile): string
{
$location = '';

View file

@ -34,9 +34,10 @@ class PushSubscriber
*
* @param integer $uid User ID
* @param int $default_priority
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function publishFeed($uid, $default_priority = PRIORITY_HIGH)
public static function publishFeed(int $uid, int $default_priority = PRIORITY_HIGH)
{
$condition = ['push' => 0, 'uid' => $uid];
DBA::update('push_subscriber', ['push' => 1, 'next_try' => DBA::NULL_DATETIME], $condition);
@ -48,9 +49,10 @@ class PushSubscriber
* start workers to transmit the feed data
*
* @param int $default_priority
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function requeue($default_priority = PRIORITY_HIGH)
public static function requeue(int $default_priority = PRIORITY_HIGH)
{
// We'll push to each subscriber that has push > 0,
// i.e. there has been an update (set in notifier.php).
@ -80,9 +82,10 @@ class PushSubscriber
* @param string $hub_callback Callback address
* @param string $hub_topic Feed topic
* @param string $hub_secret Subscription secret
* @return void
* @throws \Exception
*/
public static function renew($uid, $nick, $subscribe, $hub_callback, $hub_topic, $hub_secret)
public static function renew(int $uid, string $nick, int $subscribe, string $hub_callback, string $hub_topic, string $hub_secret)
{
// fetch the old subscription if it exists
$subscriber = DBA::selectFirst('push_subscriber', ['last_update', 'push'], ['callback_url' => $hub_callback]);
@ -119,9 +122,10 @@ class PushSubscriber
* Delay the push subscriber
*
* @param integer $id Subscriber ID
* @return void
* @throws \Exception
*/
public static function delay($id)
public static function delay(int $id)
{
$subscriber = DBA::selectFirst('push_subscriber', ['push', 'callback_url', 'renewed', 'nickname'], ['id' => $id]);
if (!DBA::isResult($subscriber)) {
@ -158,9 +162,10 @@ class PushSubscriber
*
* @param integer $id Subscriber ID
* @param string $last_update Date of last transmitted item
* @return void
* @throws \Exception
*/
public static function reset($id, $last_update)
public static function reset(int $id, string $last_update)
{
$subscriber = DBA::selectFirst('push_subscriber', ['callback_url', 'nickname'], ['id' => $id]);
if (!DBA::isResult($subscriber)) {

View file

@ -166,7 +166,7 @@ class Directory extends BaseModule
'img_hover' => $contact['name'],
'name' => $contact['name'],
'details' => $details,
'account_type' => Model\Contact::getAccountType($contact['contact-type'] ?? ''),
'account_type' => Model\Contact::getAccountType($contact['contact-type'] ?? 0),
'profile' => $profile,
'location' => $location_e,
'tags' => $contact['pub_keywords'],

View file

@ -128,7 +128,7 @@ class Photo extends BaseModule
throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
}
$photo = self::getPhotoByid($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
$photo = self::getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
} else {
$photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
$scale = 0;
@ -228,10 +228,18 @@ class Photo extends BaseModule
System::exit();
}
private static function getPhotoByid(int $id, $type, $customsize)
/**
* Fetches photo record by given id number, type and custom size
*
* @param int $id Photo id
* @param string $type Photo type
* @param int $customsize Custom size (?)
* @return array|bool Array on success, false on error
*/
private static function getPhotoById(int $id, string $type, int $customsize)
{
switch($type) {
case "preview":
case 'preview':
$media = DBA::selectFirst('post-media', ['preview', 'url', 'mimetype', 'type', 'uri-id'], ['id' => $id]);
if (empty($media)) {
return false;
@ -251,7 +259,7 @@ class Photo extends BaseModule
}
return MPhoto::createPhotoForExternalResource($url, (int)local_user(), $media['mimetype']);
case "media":
case 'media':
$media = DBA::selectFirst('post-media', ['url', 'mimetype', 'uri-id'], ['id' => $id, 'type' => Post\Media::IMAGE]);
if (empty($media)) {
return false;
@ -262,14 +270,14 @@ class Photo extends BaseModule
}
return MPhoto::createPhotoForExternalResource($media['url'], (int)local_user(), $media['mimetype']);
case "link":
case 'link':
$link = DBA::selectFirst('post-link', ['url', 'mimetype'], ['id' => $id]);
if (empty($link)) {
return false;
}
return MPhoto::createPhotoForExternalResource($link['url'], (int)local_user(), $link['mimetype']);
case "contact":
case 'contact':
$fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'xmpp', 'addr', 'network', 'failed', 'updated'];
$contact = Contact::getById($id, $fields);
if (empty($contact)) {
@ -287,7 +295,7 @@ class Photo extends BaseModule
} else {
$scale = 4;
}
$photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $contact['uid'], "profile" => 1]);
$photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $contact['uid'], 'profile' => 1]);
if (!empty($photo)) {
return $photo;
}
@ -330,7 +338,7 @@ class Photo extends BaseModule
}
if ($update) {
Logger::info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
Worker::add(PRIORITY_LOW, "UpdateContact", $id);
Worker::add(PRIORITY_LOW, 'UpdateContact', $id);
} else {
Logger::info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
}
@ -352,7 +360,7 @@ class Photo extends BaseModule
}
}
return MPhoto::createPhotoForExternalResource($url, 0, $mimetext);
case "header":
case 'header':
$fields = ['uid', 'url', 'header', 'network', 'gsid'];
$contact = Contact::getById($id, $fields);
if (empty($contact)) {
@ -367,37 +375,37 @@ class Photo extends BaseModule
$url = Contact::getDefaultHeader($contact);
}
return MPhoto::createPhotoForExternalResource($url);
case "banner":
$photo = MPhoto::selectFirst([], ["scale" => 3, 'uid' => $id, 'photo-type' => MPhoto::USER_BANNER]);
case 'banner':
$photo = MPhoto::selectFirst([], ['scale' => 3, 'uid' => $id, 'photo-type' => MPhoto::USER_BANNER]);
if (!empty($photo)) {
return $photo;
}
return MPhoto::createPhotoForExternalResource(DI::baseUrl() . '/images/friendica-banner.jpg');
case "profile":
case "custom":
case 'profile':
case 'custom':
$scale = 4;
break;
case "micro":
case 'micro':
$scale = 6;
break;
case "avatar":
case 'avatar':
default:
$scale = 5;
}
$photo = MPhoto::selectFirst([], ["scale" => $scale, "uid" => $id, "profile" => 1]);
$photo = MPhoto::selectFirst([], ['scale' => $scale, 'uid' => $id, 'profile' => 1]);
if (empty($photo)) {
$contact = DBA::selectFirst('contact', [], ['uid' => $id, 'self' => true]) ?: [];
switch($type) {
case "profile":
case "custom":
case 'profile':
case 'custom':
$default = Contact::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
break;
case "micro":
case 'micro':
$default = Contact::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
break;
case "avatar":
case 'avatar':
default:
$default = Contact::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
}

View file

@ -33,14 +33,14 @@ interface ICanHandleHttpResponses
*
* @return string The Return Code
*/
public function getReturnCode();
public function getReturnCode(): string;
/**
* Returns the Content Type
*
* @return string the Content Type
*/
public function getContentType();
public function getContentType(): string;
/**
* Returns the headers
@ -55,21 +55,20 @@ interface ICanHandleHttpResponses
/**
* Returns all headers
* @see MessageInterface::getHeaders()
*
* @see MessageInterface::getHeaders()
* @return string[][]
*/
public function getHeaders();
/**
* Check if a specified header exists
*
* @see MessageInterface::hasHeader()
*
* @param string $field header field
*
* @return boolean "true" if header exists
*/
public function inHeader(string $field);
public function inHeader(string $field): bool;
/**
* Returns the headers as an associated array
@ -83,21 +82,22 @@ interface ICanHandleHttpResponses
/**
* @return bool
*/
public function isSuccess();
public function isSuccess(): bool;
/**
* @return string
*/
public function getUrl();
public function getUrl(): string;
/**
* @return string
*/
public function getRedirectUrl();
public function getRedirectUrl(): string;
/**
* @see MessageInterface::getBody()
* Getter for body
*
* @see MessageInterface::getBody()
* @return string
*/
public function getBody();
@ -105,20 +105,20 @@ interface ICanHandleHttpResponses
/**
* @return boolean
*/
public function isRedirectUrl();
public function isRedirectUrl(): bool;
/**
* @return integer
*/
public function getErrorNumber();
public function getErrorNumber(): int;
/**
* @return string
*/
public function getError();
public function getError(): string;
/**
* @return boolean
*/
public function isTimeout();
public function isTimeout(): bool;
}

View file

@ -1008,7 +1008,7 @@ class Post
/**
* @return string
*/
private function getRedirectUrl()
private function getRedirectUrl(): string
{
return $this->redirect_url;
}

View file

@ -110,7 +110,7 @@ class ContactResult implements IResult
/**
* @return string
*/
public function getUrl()
public function getUrl(): string
{
return $this->url;
}

View file

@ -1216,7 +1216,7 @@ class Processor
}
$replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
$uriid = ItemURI::getIdByURI($replyto);
$uriid = ItemURI::getIdByURI($replyto ?? '');
if (Post::exists(['uri-id' => $uriid])) {
Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
return true;

View file

@ -164,7 +164,7 @@ abstract class MailBuilder
*
* @return string[][]
*/
public function getHeaders()
public function getHeaders(): array
{
return $this->headers;
}
@ -182,7 +182,7 @@ abstract class MailBuilder
* @param string[][] $headers
* @return $this
*/
public function withHeaders(array $headers)
public function withHeaders(array $headers): MailBuilder
{
$this->headers = $headers;

View file

@ -29,7 +29,7 @@ class Mimetype
* @param string $filename filename
* @return mixed array or string
*/
public static function getContentType($filename)
public static function getContentType(string $filename)
{
$mime_types = [

View file

@ -59,7 +59,7 @@ class ParseUrl
* @param string $accept content-type to accept
* @return array content type
*/
public static function getContentType(string $url, string $accept = HttpClientAccept::DEFAULT)
public static function getContentType(string $url, string $accept = HttpClientAccept::DEFAULT): array
{
$curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => $accept]);

View file

@ -30,9 +30,9 @@ class MergeContact
/**
* Replace all occurences of the given contact id and replace it
*
* @param integer $new_cid
* @param integer $old_cid
* @param integer $uid
* @param integer $new_cid New contact id
* @param integer $old_cid Old contact id
* @param integer $uid User id
*/
public static function execute(int $new_cid, int $old_cid, int $uid)
{

View file

@ -55,7 +55,7 @@
use Friendica\Database\DBA;
if (!defined('DB_UPDATE_VERSION')) {
define('DB_UPDATE_VERSION', 1469);
define('DB_UPDATE_VERSION', 1470);
}
return [
@ -1272,7 +1272,7 @@ return [
],
"indexes" => [
"PRIMARY" => ["id"],
"uri-id-url" => ["UNIQUE", "uri-id", "url"],
"uri-id-url" => ["UNIQUE", "uri-id", "url(512)"],
"uri-id-id" => ["uri-id", "id"],
]
],