Merge pull request #5042 from Quix0r/rewrites/curly-braces-is-result-usage-002

Rewrites/curly braces is result usage 002
This commit is contained in:
Hypolite Petovan 2018-05-14 22:51:07 -04:00 committed by GitHub
commit abbe213fef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 311 additions and 197 deletions

14
.gitignore vendored
View file

@ -9,7 +9,6 @@ include/jquery-1.4.2.min.js
favicon.* favicon.*
home.html home.html
addon addon
*.orig
*~ *~
robots.txt robots.txt
@ -24,9 +23,11 @@ report/
.buildpath .buildpath
.externalToolBuilders .externalToolBuilders
.settings .settings
#ignore OSX .DS_Store files #ignore OSX .DS_Store files
.DS_Store .DS_Store
#ignore NetBeans IDE's private files (at least)
/nbproject/private/ /nbproject/private/
#ignore smarty cache #ignore smarty cache
@ -53,9 +54,14 @@ nbproject
#ignore things from transifex-client #ignore things from transifex-client
venv/ venv/
#ignore Composer dependencies #ignore all in 'vendor' as `utils/composer.phar install` will bring it back
/vendor vendor/*
/view/asset
#ignore config files from JetBrains #ignore config files from JetBrains
/.idea /.idea
#ignore addons/ directory
addons/
#Ignore .htaccess as it may contain local changes
.htaccess

View file

@ -38,4 +38,3 @@ AddType audio/ogg .oga
RewriteRule ^(.*)$ index.php?pagename=$1 [E=REMOTE_USER:%{HTTP:Authorization},L,QSA] RewriteRule ^(.*)$ index.php?pagename=$1 [E=REMOTE_USER:%{HTTP:Authorization},L,QSA]
</IfModule> </IfModule>

View file

@ -38,7 +38,7 @@ if (substr($directory, 0, 1) != "/") {
} }
$directory = realpath($directory."/.."); $directory = realpath($directory."/..");
@include($directory."/.htconfig.php"); include $directory."/.htconfig.php";
if (!isset($pidfile)) { if (!isset($pidfile)) {
die('Please specify a pid file in the variable $pidfile in the .htconfig.php. For example:'."\n". die('Please specify a pid file in the variable $pidfile in the .htconfig.php. For example:'."\n".

View file

@ -1076,6 +1076,7 @@ function is_site_admin()
$adminlist = explode(",", str_replace(" ", "", $a->config['admin_email'])); $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
//if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email'])) //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
/// @TODO This if() + 2 returns can be shrinked into one return
if (local_user() && x($a->user, 'email') && x($a->config, 'admin_email') && in_array($a->user['email'], $adminlist)) { if (local_user() && x($a->user, 'email') && x($a->config, 'admin_email') && in_array($a->user['email'], $adminlist)) {
return true; return true;
} }
@ -1173,7 +1174,7 @@ function random_digits($digits)
{ {
$rn = ''; $rn = '';
for ($i = 0; $i < $digits; $i++) { for ($i = 0; $i < $digits; $i++) {
/// @TODO rand() is different to mt_rand() and maybe lesser "random" /// @TODO Avoid rand/mt_rand, when it comes to cryptography, they are generating predictable (seedable) numbers.
$rn .= rand(0, 9); $rn .= rand(0, 9);
} }
return $rn; return $rn;
@ -1187,7 +1188,7 @@ function get_server()
$server = "https://dir.friendica.social"; $server = "https://dir.friendica.social";
} }
return($server); return $server;
} }
function get_temppath() function get_temppath()
@ -1236,7 +1237,7 @@ function get_cachefile($file, $writemode = true)
$cache = get_itemcachepath(); $cache = get_itemcachepath();
if ((!$cache) || (!is_dir($cache))) { if ((!$cache) || (!is_dir($cache))) {
return(""); return "";
} }
$subfolder = $cache . "/" . substr($file, 0, 2); $subfolder = $cache . "/" . substr($file, 0, 2);
@ -1250,7 +1251,6 @@ function get_cachefile($file, $writemode = true)
} }
} }
/// @TODO no need to put braces here
return $cachepath; return $cachepath;
} }
@ -1357,7 +1357,6 @@ function get_spoolpath()
return ""; return "";
} }
if (!function_exists('exif_imagetype')) { if (!function_exists('exif_imagetype')) {
function exif_imagetype($file) function exif_imagetype($file)
{ {
@ -1395,7 +1394,7 @@ function validate_include(&$file)
} }
// Simply return flag // Simply return flag
return ($valid); return $valid;
} }
function current_load() function current_load()

View file

@ -935,7 +935,7 @@ function api_reformat_xml(&$item, &$key)
* *
* @return string The XML data * @return string The XML data
*/ */
function api_create_xml($data, $root_element) function api_create_xml(array $data, $root_element)
{ {
$childname = key($data); $childname = key($data);
$data2 = array_pop($data); $data2 = array_pop($data);
@ -4379,7 +4379,6 @@ function api_fr_photo_create_update($type)
throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen"); throw new InternalServerErrorException("unknown error - this error on uploading or updating a photo should never happen");
} }
/** /**
* @brief delete a single photo from the database through api * @brief delete a single photo from the database through api
* *
@ -4518,6 +4517,7 @@ function api_account_update_profile_image($type)
} else { } else {
throw new InternalServerErrorException('Unsupported filetype'); throw new InternalServerErrorException('Unsupported filetype');
} }
// change specified profile or all profiles to the new resource-id // change specified profile or all profiles to the new resource-id
if ($is_default_profile) { if ($is_default_profile) {
$condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()]; $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $data['photo']['id'], api_user()];
@ -4531,7 +4531,6 @@ function api_account_update_profile_image($type)
Contact::updateSelfFromUserID(api_user(), true); Contact::updateSelfFromUserID(api_user(), true);
// Update global directory in background // Update global directory in background
//$user = api_get_user(get_app());
$url = System::baseUrl() . '/profile/' . get_app()->user['nickname']; $url = System::baseUrl() . '/profile/' . get_app()->user['nickname'];
if ($url && strlen(Config::get('system', 'directory'))) { if ($url && strlen(Config::get('system', 'directory'))) {
Worker::add(PRIORITY_LOW, "Directory", $url); Worker::add(PRIORITY_LOW, "Directory", $url);
@ -5273,27 +5272,27 @@ function api_in_reply_to($item)
/** /**
* *
* @param string $Text * @param string $text
* *
* @return string * @return string
*/ */
function api_clean_plain_items($Text) function api_clean_plain_items($text)
{ {
$include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false"); $include_entities = strtolower(x($_REQUEST, 'include_entities') ? $_REQUEST['include_entities'] : "false");
$Text = BBCode::cleanPictureLinks($Text); $text = BBCode::cleanPictureLinks($text);
$URLSearchString = "^\[\]"; $URLSearchString = "^\[\]";
$Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $Text); $text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $text);
if ($include_entities == "true") { if ($include_entities == "true") {
$Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $Text); $text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '[url=$1]$1[/url]', $text);
} }
// Simplify "attachment" element // Simplify "attachment" element
$Text = api_clean_attachments($Text); $text = api_clean_attachments($text);
return($Text); return $text;
} }
/** /**

View file

@ -116,7 +116,7 @@ function localize_item(&$item) {
$item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']); $item['body'] = item_redir_and_replace_images($extracted['body'], $extracted['images'], $item['contact-id']);
} }
/// @Separted ??? /// @TODO Separted ???
$xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">"; $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
if (activity_match($item['verb'], ACTIVITY_LIKE) if (activity_match($item['verb'], ACTIVITY_LIKE)
|| activity_match($item['verb'], ACTIVITY_DISLIKE) || activity_match($item['verb'], ACTIVITY_DISLIKE)
@ -162,22 +162,19 @@ function localize_item(&$item) {
if (activity_match($item['verb'], ACTIVITY_LIKE)) { if (activity_match($item['verb'], ACTIVITY_LIKE)) {
$bodyverb = L10n::t('%1$s likes %2$s\'s %3$s'); $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
} } elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
elseif (activity_match($item['verb'], ACTIVITY_DISLIKE)) {
$bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s'); $bodyverb = L10n::t('%1$s doesn\'t like %2$s\'s %3$s');
} } elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
elseif (activity_match($item['verb'], ACTIVITY_ATTEND)) {
$bodyverb = L10n::t('%1$s attends %2$s\'s %3$s'); $bodyverb = L10n::t('%1$s attends %2$s\'s %3$s');
} } elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
elseif (activity_match($item['verb'], ACTIVITY_ATTENDNO)) {
$bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s'); $bodyverb = L10n::t('%1$s doesn\'t attend %2$s\'s %3$s');
} } elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
elseif (activity_match($item['verb'], ACTIVITY_ATTENDMAYBE)) {
$bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s'); $bodyverb = L10n::t('%1$s attends maybe %2$s\'s %3$s');
} }
$item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
$item['body'] = sprintf($bodyverb, $author, $objauthor, $plink);
} }
if (activity_match($item['verb'], ACTIVITY_FRIEND)) { if (activity_match($item['verb'], ACTIVITY_FRIEND)) {
if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return; if ($item['object-type']=="" || $item['object-type']!== ACTIVITY_OBJ_PERSON) return;
@ -304,8 +301,8 @@ function localize_item(&$item) {
$item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag ); $item['body'] = L10n::t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag );
} }
if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
if (activity_match($item['verb'], ACTIVITY_FAVORITE)) {
if ($item['object-type'] == "") { if ($item['object-type'] == "") {
return; return;
} }
@ -394,11 +391,10 @@ function visible_activity($item) {
} }
} }
if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE) { // @TODO below if() block can be rewritten to a single line: $isVisible = allConditionsHere;
if (!($item['self'] && ($item['uid'] == local_user()))) { if (activity_match($item['verb'], ACTIVITY_FOLLOW) && $item['object-type'] === ACTIVITY_OBJ_NOTE && empty($item['self']) && $item['uid'] == local_user()) {
return false; return false;
} }
}
return true; return true;
} }
@ -1123,7 +1119,7 @@ function builtin_activity_puller($item, &$conv_responses) {
$url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>'; $url = '<a href="'. $url . '"'. $sparkle .'>' . htmlentities($item['author-name']) . '</a>';
if (!$item['thr-parent']) { if (!x($item, 'thr-parent')) {
$item['thr-parent'] = $item['parent-uri']; $item['thr-parent'] = $item['parent-uri'];
} }
@ -1611,19 +1607,17 @@ function sort_thr_commented(array $a, array $b)
return strcmp($b['commented'], $a['commented']); return strcmp($b['commented'], $a['commented']);
} }
/// @TODO Add type-hint function render_location_dummy(array $item) {
function render_location_dummy($item) { if (x($item, 'location') && !empty($item['location'])) {
if ($item['location'] != "") {
return $item['location']; return $item['location'];
} }
if ($item['coord'] != "") { if (x($item, 'coord') && !empty($item['coord'])) {
return $item['coord']; return $item['coord'];
} }
} }
/// @TODO Add type-hint function get_responses(array $conv_responses, array $response_verbs, $ob, array $item) {
function get_responses($conv_responses, $response_verbs, $ob, $item) {
$ret = []; $ret = [];
foreach ($response_verbs as $v) { foreach ($response_verbs as $v) {
$ret[$v] = []; $ret[$v] = [];

View file

@ -274,6 +274,7 @@ function consume_feed($xml, $importer, $contact, &$hub, $datedir = 0, $pass = 0)
function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') { function subscribe_to_hub($url, $importer, $contact, $hubmode = 'subscribe') {
$a = get_app(); $a = get_app();
$r = null;
if (is_array($importer)) { if (is_array($importer)) {
$r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1", $r = q("SELECT `nickname` FROM `user` WHERE `uid` = %d LIMIT 1",

View file

@ -254,6 +254,7 @@ function can_write_wall($owner)
return false; return false;
} }
/// @TODO $groups should be array
function permissions_sql($owner_id, $remote_verified = false, $groups = null) function permissions_sql($owner_id, $remote_verified = false, $groups = null)
{ {
$local_user = local_user(); $local_user = local_user();
@ -275,6 +276,13 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null)
*/ */
if ($local_user && $local_user == $owner_id) { if ($local_user && $local_user == $owner_id) {
$sql = ''; $sql = '';
/**
* Authenticated visitor. Unless pre-verified,
* check that the contact belongs to this $owner_id
* and load the groups the visitor belongs to.
* If pre-verified, the caller is expected to have already
* done this and passed the groups into this function.
*/
} elseif ($remote_user) { } elseif ($remote_user) {
/* /*
* Authenticated visitor. Unless pre-verified, * Authenticated visitor. Unless pre-verified,
@ -298,10 +306,11 @@ function permissions_sql($owner_id, $remote_verified = false, $groups = null)
if ($remote_verified) { if ($remote_verified) {
$gs = '<<>>'; // should be impossible to match $gs = '<<>>'; // should be impossible to match
if (is_array($groups) && count($groups)) { if (is_array($groups)) {
foreach ($groups as $g) foreach ($groups as $g) {
$gs .= '|<' . intval($g) . '>'; $gs .= '|<' . intval($g) . '>';
} }
}
$sql = sprintf( $sql = sprintf(
" AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s') " AND ( NOT (deny_cid REGEXP '<%d>' OR deny_gid REGEXP '%s')

View file

@ -182,6 +182,7 @@ function autoname($len) {
break; break;
} }
} }
if (substr($word, -1) == 'q') { if (substr($word, -1) == 'q') {
$word = substr($word, 0, -1); $word = substr($word, 0, -1);
} }
@ -1660,12 +1661,13 @@ function bb_translate_video($s) {
$r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER); $r = preg_match_all("/\[video\](.*?)\[\/video\]/ism",$s,$matches,PREG_SET_ORDER);
if ($r) { if ($r) {
foreach ($matches as $mtch) { foreach ($matches as $mtch) {
if ((stristr($mtch[1],'youtube')) || (stristr($mtch[1],'youtu.be'))) if ((stristr($mtch[1], 'youtube')) || (stristr($mtch[1], 'youtu.be'))) {
$s = str_replace($mtch[0], '[youtube]' . $mtch[1] . '[/youtube]', $s); $s = str_replace($mtch[0], '[youtube]' . $mtch[1] . '[/youtube]', $s);
elseif (stristr($mtch[1],'vimeo')) } elseif (stristr($mtch[1], 'vimeo')) {
$s = str_replace($mtch[0], '[vimeo]' . $mtch[1] . '[/vimeo]', $s); $s = str_replace($mtch[0], '[vimeo]' . $mtch[1] . '[/vimeo]', $s);
} }
} }
}
return $s; return $s;
} }
@ -1829,8 +1831,7 @@ function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
if (!intval($uid)) { if (!intval($uid)) {
return false; return false;
} } elseif ($file_old == $file_new) {
if ($file_old == $file_new) {
return true; return true;
} }
@ -1853,9 +1854,10 @@ function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
$check_new_tags = explode(",",file_tag_file_to_list($file_new,$type)); $check_new_tags = explode(",",file_tag_file_to_list($file_new,$type));
foreach ($check_new_tags as $tag) { foreach ($check_new_tags as $tag) {
if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket)) if (! stristr($saved,$lbracket . file_tag_encode($tag) . $rbracket)) {
$new_tags[] = $tag; $new_tags[] = $tag;
} }
}
$filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type); $filetags_updated .= file_tag_list_to_file(implode(",",$new_tags),$type);
@ -1864,9 +1866,10 @@ function file_tag_update_pconfig($uid, $file_old, $file_new, $type = 'file') {
$check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type)); $check_deleted_tags = explode(",",file_tag_file_to_list($file_old,$type));
foreach ($check_deleted_tags as $tag) { foreach ($check_deleted_tags as $tag) {
if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket)) if (! stristr($file_new,$lbracket . file_tag_encode($tag) . $rbracket)) {
$deleted_tags[] = $tag; $deleted_tags[] = $tag;
} }
}
foreach ($deleted_tags as $key => $tag) { foreach ($deleted_tags as $key => $tag) {
$r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d", $r = q("SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d",
@ -1975,17 +1978,22 @@ function protect_sprintf($s) {
return str_replace('%', '%%', $s); return str_replace('%', '%%', $s);
} }
/// @TODO Rewrite this
function is_a_date_arg($s) { function is_a_date_arg($s) {
$i = intval($s); $i = intval($s);
if ($i > 1900) { if ($i > 1900) {
$y = date('Y'); $y = date('Y');
if ($i <= $y + 1 && strpos($s, '-') == 4) { if ($i <= $y + 1 && strpos($s, '-') == 4) {
$m = intval(substr($s, 5)); $m = intval(substr($s, 5));
if ($m > 0 && $m <= 12)
if ($m > 0 && $m <= 12) {
return true; return true;
} }
} }
}
return false; return false;
} }
@ -2003,6 +2011,7 @@ function deindent($text, $chr = "[\t ]", $count = NULL) {
preg_match("|^" . $chr . "*|", $lines[$k], $m); preg_match("|^" . $chr . "*|", $lines[$k], $m);
$count = strlen($m[0]); $count = strlen($m[0]);
} }
for ($k = 0; $k < count($lines); $k++) { for ($k = 0; $k < count($lines); $k++) {
$lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]); $lines[$k] = preg_replace("|^" . $chr . "{" . $count . "}|", "", $lines[$k]);
} }

View file

@ -64,7 +64,7 @@ function admin_post(App $a)
case 'addons': case 'addons':
if ($a->argc > 2 && if ($a->argc > 2 &&
is_file("addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php")) { is_file("addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php")) {
@include_once("addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php"); include_once "addon/" . $a->argv[2] . "/" . $a->argv[2] . ".php";
if (function_exists($a->argv[2] . '_addon_admin_post')) { if (function_exists($a->argv[2] . '_addon_admin_post')) {
$func = $a->argv[2] . '_addon_admin_post'; $func = $a->argv[2] . '_addon_admin_post';
$func($a); $func($a);
@ -917,6 +917,7 @@ function admin_page_site_post(App $a)
$upds = implode(", ", $upd); $upds = implode(", ", $upd);
$r = q("UPDATE %s SET %s;", $table_name, $upds); $r = q("UPDATE %s SET %s;", $table_name, $upds);
if (!DBM::is_result($r)) { if (!DBM::is_result($r)) {
notice("Failed updating '$table_name': " . dba::errorMessage()); notice("Failed updating '$table_name': " . dba::errorMessage());
goaway('admin/site'); goaway('admin/site');
@ -1298,15 +1299,18 @@ function admin_page_site(App $a)
$user_names = []; $user_names = [];
$user_names['---'] = L10n::t('Multi user instance'); $user_names['---'] = L10n::t('Multi user instance');
$users = q("SELECT `username`, `nickname` FROM `user`"); $users = q("SELECT `username`, `nickname` FROM `user`");
foreach ($users as $user) { foreach ($users as $user) {
$user_names[$user['nickname']] = $user['username']; $user_names[$user['nickname']] = $user['username'];
} }
/* Banner */ /* Banner */
$banner = Config::get('system', 'banner'); $banner = Config::get('system', 'banner');
if ($banner == false) { if ($banner == false) {
$banner = '<a href="https://friendi.ca"><img id="logo-img" src="images/friendica-32.png" alt="logo" /></a><span id="logo-text"><a href="https://friendi.ca">Friendica</a></span>'; $banner = '<a href="https://friendi.ca"><img id="logo-img" src="images/friendica-32.png" alt="logo" /></a><span id="logo-text"><a href="https://friendi.ca">Friendica</a></span>';
} }
$banner = htmlspecialchars($banner); $banner = htmlspecialchars($banner);
$info = Config::get('config', 'info'); $info = Config::get('config', 'info');
$info = htmlspecialchars($info); $info = htmlspecialchars($info);
@ -1506,9 +1510,12 @@ function admin_page_dbsync(App $a)
if ($a->argc > 2 && intval($a->argv[2])) { if ($a->argc > 2 && intval($a->argv[2])) {
require_once 'update.php'; require_once 'update.php';
$func = 'update_' . intval($a->argv[2]); $func = 'update_' . intval($a->argv[2]);
if (function_exists($func)) { if (function_exists($func)) {
$retval = $func(); $retval = $func();
if ($retval === UPDATE_FAILED) { if ($retval === UPDATE_FAILED) {
$o .= L10n::t("Executing %s failed with error: %s", $func, $retval); $o .= L10n::t("Executing %s failed with error: %s", $func, $retval);
} elseif ($retval === UPDATE_SUCCESS) { } elseif ($retval === UPDATE_SUCCESS) {
@ -1521,11 +1528,13 @@ function admin_page_dbsync(App $a)
$o .= L10n::t('There was no additional update function %s that needed to be called.', $func) . "<br />"; $o .= L10n::t('There was no additional update function %s that needed to be called.', $func) . "<br />";
Config::set('database', $func, 'success'); Config::set('database', $func, 'success');
} }
return $o; return $o;
} }
$failed = []; $failed = [];
$r = q("SELECT `k`, `v` FROM `config` WHERE `cat` = 'database' "); $r = q("SELECT `k`, `v` FROM `config` WHERE `cat` = 'database' ");
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
$upd = intval(substr($rr['k'], 7)); $upd = intval(substr($rr['k'], 7));
@ -1535,6 +1544,7 @@ function admin_page_dbsync(App $a)
$failed[] = $upd; $failed[] = $upd;
} }
} }
if (!count($failed)) { if (!count($failed)) {
$o = replace_macros(get_markup_template('structure_check.tpl'), [ $o = replace_macros(get_markup_template('structure_check.tpl'), [
'$base' => System::baseUrl(true), '$base' => System::baseUrl(true),
@ -1921,7 +1931,7 @@ function admin_page_addons(App $a)
$admin_form = ""; $admin_form = "";
if (in_array($addon, $a->addons_admin)) { if (in_array($addon, $a->addons_admin)) {
@require_once("addon/$addon/$addon.php"); require_once "addon/$addon/$addon.php";
$func = $addon . '_addon_admin'; $func = $addon . '_addon_admin';
$func($a, $admin_form); $func($a, $admin_form);
} }

View file

@ -433,6 +433,7 @@ function events_content(App $a) {
if (x($_REQUEST, 'location')) {$orig_event['location'] = $_REQUEST['location'];} if (x($_REQUEST, 'location')) {$orig_event['location'] = $_REQUEST['location'];}
if (x($_REQUEST, 'start')) {$orig_event['start'] = $_REQUEST['start'];} if (x($_REQUEST, 'start')) {$orig_event['start'] = $_REQUEST['start'];}
if (x($_REQUEST, 'finish')) {$orig_event['finish'] = $_REQUEST['finish'];} if (x($_REQUEST, 'finish')) {$orig_event['finish'] = $_REQUEST['finish'];}
if (x($_REQUEST,'finish')) $orig_event['finish'] = $_REQUEST['finish'];
$n_checked = ((x($orig_event) && $orig_event['nofinish']) ? ' checked="checked" ' : ''); $n_checked = ((x($orig_event) && $orig_event['nofinish']) ? ' checked="checked" ' : '');
$a_checked = ((x($orig_event) && $orig_event['adjust']) ? ' checked="checked" ' : ''); $a_checked = ((x($orig_event) && $orig_event['adjust']) ? ' checked="checked" ' : '');

View file

@ -1243,9 +1243,11 @@ function photos_content(App $a)
$prevlink = ''; $prevlink = '';
$nextlink = ''; $nextlink = '';
/// @todo This query is totally bad, the whole functionality has to be changed /*
// The query leads to a really intense used index. * @todo This query is totally bad, the whole functionality has to be changed
// By now we hide it if someone wants to. * The query leads to a really intense used index.
* By now we hide it if someone wants to.
*/
if (!Config::get('system', 'no_count', false)) { if (!Config::get('system', 'no_count', false)) {
$order_field = defaults($_GET, 'order', ''); $order_field = defaults($_GET, 'order', '');
if ($order_field === 'posted') { if ($order_field === 'posted') {
@ -1280,8 +1282,10 @@ function photos_content(App $a)
} }
} }
if (count($ph) == 1) if (count($ph) == 1) {
$hires = $lores = $ph[0]; $hires = $lores = $ph[0];
}
if (count($ph) > 1) { if (count($ph) > 1) {
if ($ph[1]['scale'] == 2) { if ($ph[1]['scale'] == 2) {
// original is 640 or less, we can display it directly // original is 640 or less, we can display it directly
@ -1293,6 +1297,7 @@ function photos_content(App $a)
} }
$album_link = 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']); $album_link = 'photos/' . $a->data['user']['nickname'] . '/album/' . bin2hex($ph[0]['album']);
$tools = null; $tools = null;
$lock = null; $lock = null;
@ -1319,8 +1324,9 @@ function photos_content(App $a)
]); ]);
} }
if ($prevlink) if ($prevlink) {
$prevlink = [$prevlink, '<div class="icon prev"></div>'] ; $prevlink = [$prevlink, '<div class="icon prev"></div>'] ;
}
$photo = [ $photo = [
'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']], 'href' => 'photo/' . $hires['resource-id'] . '-' . $hires['scale'] . '.' . $phototypes[$hires['type']],
@ -1681,8 +1687,9 @@ function photos_content(App $a)
$twist = false; $twist = false;
foreach ($r as $rr) { foreach ($r as $rr) {
//hide profile photos to others //hide profile photos to others
if (!$is_owner && !remote_user() && ($rr['album'] == L10n::t('Profile Photos'))) if (!$is_owner && !remote_user() && ($rr['album'] == L10n::t('Profile Photos'))) {
continue; continue;
}
$twist = !$twist; $twist = !$twist;

View file

@ -63,17 +63,19 @@ function subthread_content(App $a) {
WHERE `contact`.`self` = 1 AND `contact`.`uid` = %d LIMIT 1", WHERE `contact`.`self` = 1 AND `contact`.`uid` = %d LIMIT 1",
intval($owner_uid) intval($owner_uid)
); );
if (DBM::is_result($r))
if (DBM::is_result($r)) {
$owner = $r[0]; $owner = $r[0];
}
if (! $owner) { if (! $owner) {
logger('like: no owner'); logger('like: no owner');
return; return;
} }
if (! $remote_owner) if (! $remote_owner) {
$remote_owner = $owner; $remote_owner = $owner;
}
$contact = null; $contact = null;
// This represents the person posting // This represents the person posting
@ -85,9 +87,11 @@ function subthread_content(App $a) {
intval($_SESSION['visitor_id']), intval($_SESSION['visitor_id']),
intval($owner_uid) intval($owner_uid)
); );
if (DBM::is_result($r))
if (DBM::is_result($r)) {
$contact = $r[0]; $contact = $r[0];
} }
}
if (! $contact) { if (! $contact) {
return; return;
} }

View file

@ -159,10 +159,12 @@ EOT;
} }
$term_objtype = ($item['resource-id'] ? TERM_OBJ_PHOTO : TERM_OBJ_POST); $term_objtype = ($item['resource-id'] ? TERM_OBJ_PHOTO : TERM_OBJ_POST);
$t = q("SELECT count(tid) as tcount FROM term WHERE oid=%d AND term='%s'", $t = q("SELECT count(tid) as tcount FROM term WHERE oid=%d AND term='%s'",
intval($item['id']), intval($item['id']),
dbesc($term) dbesc($term)
); );
if ((!$blocktags) && $t[0]['tcount'] == 0 ) { if ((!$blocktags) && $t[0]['tcount'] == 0 ) {
q("INSERT INTO term (oid, otype, type, term, url, uid) VALUE (%d, %d, %d, '%s', '%s', %d)", q("INSERT INTO term (oid, otype, type, term, url, uid) VALUE (%d, %d, %d, '%s', '%s', %d)",
intval($item['id']), intval($item['id']),
@ -176,19 +178,21 @@ EOT;
// if the original post is on this site, update it. // if the original post is on this site, update it.
$r = q("select `tag`,`id`,`uid` from item where `origin` = 1 AND `uri` = '%s' LIMIT 1", $r = q("SELECT `tag`,`id`,`uid` FROM `item` WHERE `origin`=1 AND `uri`='%s' LIMIT 1",
dbesc($item['uri']) dbesc($item['uri'])
); );
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
$x = q("SELECT `blocktags` FROM `user` WHERE `uid` = %d limit 1", $x = q("SELECT `blocktags` FROM `user` WHERE `uid`=%d LIMIT 1",
intval($r[0]['uid']) intval($r[0]['uid'])
); );
$t = q("SELECT count(tid) as tcount FROM term WHERE oid=%d AND term='%s'", $t = q("SELECT COUNT(`tid`) AS `tcount` FROM `term` WHERE `oid`=%d AND `term`='%s'",
intval($r[0]['id']), intval($r[0]['id']),
dbesc($term) dbesc($term)
); );
if(count($x) && !$x[0]['blocktags'] && $t[0]['tcount']==0){
q("INSERT INTO term (oid, otype, type, term, url, uid) VALUE (%d, %d, %d, '%s', '%s', %d)", if (DBM::is_result($x) && !$x[0]['blocktags'] && $t[0]['tcount'] == 0){
q("INSERT INTO term (`oid`, `otype`, `type`, `term`, `url`, `uid`) VALUE (%d, %d, %d, '%s', '%s', %d)",
intval($r[0]['id']), intval($r[0]['id']),
$term_objtype, $term_objtype,
TERM_HASHTAG, TERM_HASHTAG,

View file

@ -40,6 +40,12 @@ class Cache extends \Friendica\BaseObject
self::$driver = new Cache\MemcachedCacheDriver($memcached_hosts); self::$driver = new Cache\MemcachedCacheDriver($memcached_hosts);
break; break;
case 'redis':
$redis_host = Config::get('system', 'redis_host', '127.0.0.1');
$redis_port = Config::get('system', 'redis_port', 6379);
self::$driver = new Cache\RedisCacheDriver($redis_host, $redis_port);
break;
default: default:
self::$driver = new Cache\DatabaseCacheDriver(); self::$driver = new Cache\DatabaseCacheDriver();
} }

View file

@ -0,0 +1,77 @@
<?php
namespace Friendica\Core\Cache;
use Friendica\BaseObject;
use Friendica\Core\Cache;
/**
* Redis Cache Driver. This driver is based on Memcache driver
*
* @author Hypolite Petovan <mrpetovan@gmail.com>
* @author Roland Haeder <roland@mxchange.org>
*/
class RedisCacheDriver extends BaseObject implements ICacheDriver
{
/**
* @var Redis
*/
private $redis;
public function __construct($redis_host, $redis_port)
{
if (!class_exists('Redis', false)) {
throw new \Exception('Redis class isn\'t available');
}
$this->redis = new \Redis();
if (!$this->redis->connect($redis_host, $redis_port)) {
throw new \Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
}
}
public function get($key)
{
$return = null;
// We fetch with the hostname as key to avoid problems with other applications
$cached = $this->redis->get(self::getApp()->get_hostname() . ':' . $key);
// @see http://php.net/manual/en/redis.get.php#84275
if (is_bool($cached) || is_double($cached) || is_long($cached)) {
return $return;
}
$value = @unserialize($cached);
// Only return a value if the serialized value is valid.
// We also check if the db entry is a serialized
// boolean 'false' value (which we want to return).
if ($cached === serialize(false) || $value !== false) {
$return = $value;
}
return $return;
}
public function set($key, $value, $duration = Cache::MONTH)
{
// We store with the hostname as key to avoid problems with other applications
return $this->redis->set(
self::getApp()->get_hostname() . ":" . $key,
serialize($value),
time() + $duration
);
}
public function delete($key)
{
return $this->redis->delete($key);
}
public function clear()
{
return true;
}
}

View file

@ -29,9 +29,7 @@ class PConfig extends BaseObject
public static function init($uid) public static function init($uid)
{ {
$a = self::getApp(); if (Config::get('system', 'config_adapter') == 'preload') {
if (isset($a->config['system']['config_adapter']) && $a->config['system']['config_adapter'] == 'preload') {
self::$adapter = new Config\PreloadPConfigAdapter($uid); self::$adapter = new Config\PreloadPConfigAdapter($uid);
} else { } else {
self::$adapter = new Config\JITPConfigAdapter($uid); self::$adapter = new Config\JITPConfigAdapter($uid);

View file

@ -688,7 +688,7 @@ class Worker
logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG); logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
// Are there fewer workers running as possible? Then fork a new one. // Are there fewer workers running as possible? Then fork a new one.
if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) { if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG); logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
self::spawnWorker(); self::spawnWorker();
} }
@ -1039,7 +1039,7 @@ class Worker
} }
$priority = PRIORITY_MEDIUM; $priority = PRIORITY_MEDIUM;
$dont_fork = Config::get("system", "worker_dont_fork"); $dont_fork = Config::get("system", "worker_dont_fork", false);
$created = DateTimeFormat::utcNow(); $created = DateTimeFormat::utcNow();
$run_parameter = array_shift($args); $run_parameter = array_shift($args);

View file

@ -803,10 +803,10 @@ class Event extends BaseObject
/** /**
* @brief Format an item array with event data to HTML. * @brief Format an item array with event data to HTML.
* *
* @param arr $item Array with item and event data. * @param array $item Array with item and event data.
* @return string HTML output. * @return string HTML output.
*/ */
public static function getItemHTML($item) { public static function getItemHTML(array $item) {
$same_date = false; $same_date = false;
$finish = false; $finish = false;

View file

@ -1032,8 +1032,9 @@ class Item extends BaseObject
} }
// Is this a shadow entry? // Is this a shadow entry?
if ($item['uid'] == 0) if ($item['uid'] == 0) {
return; return;
}
// Is there a shadow parent? // Is there a shadow parent?
if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) { if (!dba::exists('item', ['uri' => $item['parent-uri'], 'uid' => 0])) {
@ -1073,12 +1074,10 @@ class Item extends BaseObject
// If this was a comment to a Diaspora post we don't get our comment back. // If this was a comment to a Diaspora post we don't get our comment back.
// This means that we have to distribute the comment by ourselves. // This means that we have to distribute the comment by ourselves.
if ($origin) { if ($origin && dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
if (dba::exists('item', ['id' => $parent, 'network' => NETWORK_DIASPORA])) {
self::distribute($public_shadow); self::distribute($public_shadow);
} }
} }
}
/** /**
* Adds a "lang" specification in a "postopts" element of given $arr, * Adds a "lang" specification in a "postopts" element of given $arr,
@ -1087,14 +1086,14 @@ class Item extends BaseObject
*/ */
private static function addLanguageInPostopts(&$item) private static function addLanguageInPostopts(&$item)
{ {
$postopts = "";
if (!empty($item['postopts'])) { if (!empty($item['postopts'])) {
if (strstr($item['postopts'], 'lang=')) { if (strstr($item['postopts'], 'lang=')) {
// do not override // do not override
return; return;
} }
$postopts = $item['postopts']; $postopts = $item['postopts'];
} else {
$postopts = "";
} }
$naked_body = Text\BBCode::toPlaintext($item['body'], false); $naked_body = Text\BBCode::toPlaintext($item['body'], false);

View file

@ -81,7 +81,7 @@ class DFRN
$root->appendChild($entry); $root->appendChild($entry);
} }
return(trim($doc->saveXML())); return trim($doc->saveXML());
} }
/** /**
@ -96,7 +96,6 @@ class DFRN
* @param boolean $onlyheader Output only the header without content? (Default is "no") * @param boolean $onlyheader Output only the header without content? (Default is "no")
* *
* @return string DFRN feed entries * @return string DFRN feed entries
* @todo Find proper type-hints
*/ */
public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
{ {
@ -222,11 +221,9 @@ class DFRN
//$sql_extra .= file_tag_file_query('item',$category,'category'); //$sql_extra .= file_tag_file_query('item',$category,'category');
} }
if ($public_feed) { if ($public_feed && ! $converse) {
if (! $converse) {
$sql_extra .= " AND `contact`.`self` = 1 "; $sql_extra .= " AND `contact`.`self` = 1 ";
} }
}
$check_date = DateTimeFormat::utc($last_update); $check_date = DateTimeFormat::utc($last_update);
@ -426,7 +423,7 @@ class DFRN
$root->appendChild($mail); $root->appendChild($mail);
return(trim($doc->saveXML())); return trim($doc->saveXML());
} }
/** /**
@ -455,7 +452,7 @@ class DFRN
$root->appendChild($suggest); $root->appendChild($suggest);
return(trim($doc->saveXML())); return trim($doc->saveXML());
} }
/** /**
@ -490,7 +487,6 @@ class DFRN
$photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']]; $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
} }
unset($rp, $ext);
$doc = new DOMDocument('1.0', 'utf-8'); $doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true; $doc->formatOutput = true;
@ -514,7 +510,7 @@ class DFRN
$root->appendChild($relocate); $root->appendChild($relocate);
return(trim($doc->saveXML())); return trim($doc->saveXML());
} }
/** /**
@ -896,7 +892,7 @@ class DFRN
* @return object XML entry object * @return object XML entry object
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
{ {
$mentioned = []; $mentioned = [];
@ -1067,6 +1063,7 @@ class DFRN
$tags = Item::getFeedTags($item); $tags = Item::getFeedTags($item);
/// @TODO Combine this with similar below if() block?
if (count($tags)) { if (count($tags)) {
foreach ($tags as $t) { foreach ($tags as $t) {
if (($type != 'html') || ($t[0] != "@")) { if (($type != 'html') || ($t[0] != "@")) {
@ -1596,6 +1593,7 @@ class DFRN
$avatarlist[$width] = $href; $avatarlist[$width] = $href;
} }
} }
if (count($avatarlist) > 0) { if (count($avatarlist) > 0) {
krsort($avatarlist); krsort($avatarlist);
$author["avatar"] = current($avatarlist); $author["avatar"] = current($avatarlist);
@ -2098,6 +2096,9 @@ class DFRN
$condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])]; $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
dba::update('contact', $fields, $condition); dba::update('contact', $fields, $condition);
// @TODO No dba:update here?
dba::update('contact', $fields, $condition);
Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true); Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
logger('Contacts are updated.'); logger('Contacts are updated.');

View file

@ -1948,7 +1948,7 @@ class OStatus
* @param bool $complete default true * @param bool $complete default true
* @return void * @return void
*/ */
private static function entryFooter($doc, $entry, $item, $owner, $complete = true) private static function entryFooter($doc, $entry, array $item, array $owner, $complete = true)
{ {
$mentioned = []; $mentioned = [];
@ -1988,6 +1988,7 @@ class OStatus
if (isset($parent_item)) { if (isset($parent_item)) {
$r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item); $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
if (DBM::is_result($r)) { if (DBM::is_result($r)) {
if ($r['conversation-uri'] != '') { if ($r['conversation-uri'] != '') {
$conversation_uri = $r['conversation-uri']; $conversation_uri = $r['conversation-uri'];
@ -2048,9 +2049,11 @@ class OStatus
} }
if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) { if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned", XML::addElement($doc, $entry, "link", "", [
"rel" => "mentioned",
"ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group", "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
"href" => $owner['url']]); "href" => $owner['url']
]);
} }
if (!$item["private"]) { if (!$item["private"]) {

View file

@ -1316,20 +1316,8 @@ class PortableContact
$version = $data->version; $version = $data->version;
$site_name = $data->site_name; $site_name = $data->site_name;
$info = $data->info; $info = $data->info;
$register_policy_str = $data->register_policy; $register_policy = constant($data->register_policy);
$platform = $data->platform; $platform = $data->platform;
switch ($register_policy_str) {
case "REGISTER_CLOSED":
$register_policy = REGISTER_CLOSED;
break;
case "REGISTER_APPROVE":
$register_policy = REGISTER_APPROVE;
break;
case "REGISTER_OPEN":
$register_policy = REGISTER_OPEN;
break;
}
} }
} }
} }