Cleanups: isResult() more used, readability improved (#5608)

* [diaspora]: Maybe SimpleXMLElement is the right type-hint?

* Changes proposed + pre-renaming:
- pre-renamed $db -> $connection
- added TODOs for not allowing bad method invocations (there is a
  BadMethodCallException in SPL)

* If no record is found, below $r[0] will fail with a E_NOTICE and the code
doesn't behave as expected.

* Ops, one more left ...

* Continued:
- added documentation for Contact::updateSslPolicy() method
- added type-hint for $contact of same method
- empty lines added + TODO where the bug origins that $item has no element 'body'

* Added empty lines for better readability

* Cleaned up:
- no more x() (deprecated) usage but empty() instead
- fixed mixing of space/tab indending
- merged else/if block goether in elseif() (lesser nested code blocks)

* Re-fixed DBM -> DBA switch

* Fixes/rewrites:
- use empty()/isset() instead of deprecated x()
- merged 2 nested if() blocks into one
- avoided nested if() block inside else block by rewriting it to elseif()
- $contact_id is an integer, let's test on > 0 here
- added a lot spaces and some empty lines for better readability

* Rewrite:
- moved all CONTACT_* constants from boot.php to Contact class

* CR request:
- renamed Contact::CONTACT_IS_* -> Contact::* ;-)

* Rewrites:
- moved PAGE_* to Friendica\Model\Profile class
- fixed mixure with "Contact::* rewrite"

* Ops, one still there (return is no function)

* Rewrite to Proxy class:
- introduced new Friendica\Network\Proxy class for in exchange of proxy_*()
  functions
- moved also all PROXY_* constants there as Proxy::*
- removed now no longer needed mod/proxy.php loading as composer's auto-load
  will do this for us
- renamed those proxy_*() functions to better names:
  + proxy_init()           -> Proxy::init()         (public)
  + proxy_url()            -> Proxy::proxifyUrl()   (public)
  + proxy_parse_html()     -> Proxy::proxifyHtml()  (public)
  + proxy_is_local_image() -> Proxy::isLocalImage() (private)
  + proxy_parse_query()    -> Proxy::parseQuery()   (private)
  + proxy_img_cb()         -> Proxy::replaceUrl()   (private)

* CR request:
- moved all PAGE_* constants to Friendica\Model\Contact class
- fixed all references of both classes

* Ops, need to set $a here ...

* CR request:
- moved Proxy class to Friendica\Module
- extended BaseModule

* Ops, no need for own instance of $a when self::getApp() is around.

* Proxy-rewrite:
- proxy_url() and proxy_parse_html() are both non-module functions (now
  methods)
- so they must be splitted into a seperate class
- also the SIZE_* and DEFAULT_TIME constants are both not relevant to module

* No instances from utility classes

* Fixed error:
- proxify*() is now located in `Friendica\Util\ProxyUtils`

* Moved back to original place, ops? How did they move here? Well, it was not
intended by me.

* Removed duplicate (left-over from split) constants and static array. Thank to
MrPetovan finding it.

* Renamed ProxyUtils -> Proxy and aliased it back to ProxyUtils.

* Rewrite:
- stopped using deprecated NETWORK_* constants, now Protocol::* should be used
- still left them intact for slow/lazy developers ...

* Ops, was added accidentally ...

* Ops, why these wrong moves?

* Ops, one to much (thanks to MrPetovan)

* Ops, wrong moving ...

* moved back to original place ...

* spaces added

* empty lines add for better readability.

* convertered spaces -> tab for code indenting.

* CR request: Add space between if and brace.

* CR requests fixed + move reverted
- ops, src/Module/*.php has been moved to src/Network/ accidentally
- reverted some parts in src/Database/DBA.php as pointed out by Annando
- removed internal TODO items
- added some spaces for better readability
This commit is contained in:
Roland Häder 2018-08-24 07:05:49 +02:00 committed by Hypolite Petovan
parent 93ba393559
commit 61693419e8
16 changed files with 122 additions and 60 deletions

View file

@ -308,6 +308,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
if ($network === Protocol::DFRN) {
$new_relation = Contact::FOLLOWER;
if (($relation == Contact::SHARING) || ($duplex)) {
$new_relation = Contact::FRIEND;
}
@ -550,6 +551,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
logger('dfrn_confirm: request - photos imported');
$new_relation = Contact::SHARING;
if (($relation == Contact::FOLLOWER) || ($duplex)) {
$new_relation = Contact::FRIEND;
}

View file

@ -79,6 +79,7 @@ function photos_init(App $a) {
if ($albums) {
$a->data['albums'] = $albums;
if ($albums_visible) {
$ret['success'] = true;
}
@ -117,7 +118,6 @@ function photos_init(App $a) {
]);
}
if (empty($a->page['aside'])) {
$a->page['aside'] = '';
}
@ -166,7 +166,7 @@ function photos_post(App $a)
}
}
if ($contact_id) {
if ($contact_id > 0) {
$r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
intval($contact_id),
intval($page_owner_uid)
@ -204,6 +204,7 @@ function photos_post(App $a)
DBA::escape($album),
intval($page_owner_uid)
);
if (!DBA::isResult($r)) {
notice(L10n::t('Album not found.') . EOL);
goaway($_SESSION['photo_return']);
@ -253,6 +254,7 @@ function photos_post(App $a)
'$confirm_name' => 'dropalbum', // Needed so that confirmation will bring us back into this if statement
'$cancel' => L10n::t('Cancel'),
]);
$a->error = 1; // Set $a->error so the other module functions don't execute
return;
}
@ -273,6 +275,7 @@ function photos_post(App $a)
DBA::escape($album)
);
}
if (DBA::isResult($r)) {
foreach ($r as $rr) {
$res[] = "'" . DBA::escape($rr['rid']) . "'" ;
@ -313,6 +316,7 @@ function photos_post(App $a)
// Check if we should do HTML-based delete confirmation
if (!empty($_REQUEST['confirm'])) {
$drop_url = $a->query_string;
$a->page['content'] = replace_macros(get_markup_template('confirm.tpl'), [
'$method' => 'post',
'$message' => L10n::t('Do you really want to delete this photo?'),
@ -322,6 +326,7 @@ function photos_post(App $a)
'$confirm_name' => 'delete', // Needed so that confirmation will bring us back into this if statement
'$cancel' => L10n::t('Cancel'),
]);
$a->error = 1; // Set $a->error so the other module functions don't execute
return;
}
@ -434,6 +439,7 @@ function photos_post(App $a)
DBA::escape($resource_id),
intval($page_owner_uid)
);
if (DBA::isResult($p)) {
$ext = $phototypes[$p[0]['type']];
$r = q("UPDATE `photo` SET `desc` = '%s', `album` = '%s', `allow_cid` = '%s', `allow_gid` = '%s', `deny_cid` = '%s', `deny_gid` = '%s' WHERE `resource-id` = '%s' AND `uid` = %d",
@ -521,28 +527,35 @@ function photos_post(App $a)
if (strpos($tag, '@') === 0) {
$profile = '';
$name = substr($tag,1);
if ((strpos($name, '@')) || (strpos($name, 'http://'))) {
$newname = $name;
$links = @Probe::lrdd($name);
if (count($links)) {
foreach ($links as $link) {
if ($link['@attributes']['rel'] === 'http://webfinger.net/rel/profile-page') {
$profile = $link['@attributes']['href'];
}
if ($link['@attributes']['rel'] === 'salmon') {
$salmon = '$url:' . str_replace(',', '%sc', $link['@attributes']['href']);
if (strlen($inform)) {
$inform .= ',';
}
$inform .= $salmon;
}
}
}
$taginfo[] = [$newname, $profile, $salmon];
} else {
$newname = $name;
$alias = '';
$tagcid = 0;
if (strrpos($newname, '+')) {
$tagcid = intval(substr($newname, strrpos($newname, '+') + 1));
}
@ -574,6 +587,7 @@ function photos_post(App $a)
if (DBA::isResult($r)) {
$newname = $r[0]['name'];
$profile = $r[0]['url'];
$notify = 'cid:' . $r[0]['id'];
if (strlen($inform)) {
$inform .= ',';
@ -581,15 +595,18 @@ function photos_post(App $a)
$inform .= $notify;
}
}
if ($profile) {
if (substr($notify, 0, 4) === 'cid:') {
$taginfo[] = [$newname, $profile, $notify, $r[0], '@[url=' . str_replace(',','%2c',$profile) . ']' . $newname . '[/url]'];
} else {
$taginfo[] = [$newname, $profile, $notify, null, $str_tags .= '@[url=' . $profile . ']' . $newname . '[/url]'];
}
if (strlen($str_tags)) {
$str_tags .= ',';
}
$profile = str_replace(',', '%2c', $profile);
$str_tags .= '@[url='.$profile.']'.$newname.'[/url]';
}
@ -622,6 +639,7 @@ function photos_post(App $a)
$best = 2;
break;
}
if (intval($scales['scale']) == 4) {
$best = 4;
break;

View file

@ -33,8 +33,9 @@ function repair_ostatus_content(App $a) {
intval(Contact::FRIEND),
intval(Contact::SHARING));
if (!$r)
return($o.L10n::t("Error"));
if (!DBA::isResult($r)) {
return ($o . L10n::t("Error"));
}
$total = $r[0]["total"];
@ -47,7 +48,7 @@ function repair_ostatus_content(App $a) {
intval(Contact::FRIEND),
intval(Contact::SHARING), $counter++);
if (!$r) {
if (!DBA::isResult($r)) {
$o .= L10n::t("Done");
return $o;
}

View file

@ -153,11 +153,14 @@ function salmon_post(App $a, $xml = '') {
DBA::escape(normalise_link($author_link)),
intval($importer['uid'])
);
if (! DBA::isResult($r)) {
if (!DBA::isResult($r)) {
logger('Author ' . $author_link . ' unknown to user ' . $importer['uid'] . '.');
if(PConfig::get($importer['uid'],'system','ostatus_autofriend')) {
if (PConfig::get($importer['uid'], 'system', 'ostatus_autofriend')) {
$result = Contact::createFromProbe($importer['uid'], $author_link);
if($result['success']) {
if ($result['success']) {
$r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND ( `url` = '%s' OR `alias` = '%s')
AND `uid` = %d LIMIT 1",
DBA::escape(Protocol::OSTATUS),

View file

@ -13,7 +13,8 @@ use Friendica\Model\Contact;
use Friendica\Model\GContact;
use Friendica\Util\Proxy as ProxyUtils;
function suggest_init(App $a) {
function suggest_init(App $a)
{
if (! local_user()) {
return;
}

View file

@ -274,6 +274,7 @@ function videos_content(App $a)
// perhaps they're visiting - but not a community page, so they wouldn't have write access
if (remote_user() && (!$visitor)) {
$contact_id = 0;
if (!empty($_SESSION['remote'])) {
foreach($_SESSION['remote'] as $v) {
if($v['uid'] == $owner_uid) {

View file

@ -16,24 +16,25 @@ function wall_attach_post(App $a) {
$r_json = (x($_GET,'response') && $_GET['response']=='json');
if($a->argc > 1) {
if ($a->argc > 1) {
$nick = $a->argv[1];
$r = q("SELECT `user`.*, `contact`.`id` FROM `user` LEFT JOIN `contact` on `user`.`uid` = `contact`.`uid` WHERE `user`.`nickname` = '%s' AND `user`.`blocked` = 0 and `contact`.`self` = 1 LIMIT 1",
DBA::escape($nick)
);
if (! DBA::isResult($r)) {
if ($r_json) {
echo json_encode(['error'=>L10n::t('Invalid request.')]);
echo json_encode(['error' => L10n::t('Invalid request.')]);
killme();
}
return;
}
} else {
if ($r_json) {
echo json_encode(['error'=>L10n::t('Invalid request.')]);
echo json_encode(['error' => L10n::t('Invalid request.')]);
killme();
}
return;
}
@ -45,25 +46,27 @@ function wall_attach_post(App $a) {
$page_owner_nick = $r[0]['nickname'];
$community_page = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
if((local_user()) && (local_user() == $page_owner_uid))
if ((local_user()) && (local_user() == $page_owner_uid)) {
$can_post = true;
else {
if($community_page && remote_user()) {
} else {
if ($community_page && remote_user()) {
$contact_id = 0;
if(is_array($_SESSION['remote'])) {
foreach($_SESSION['remote'] as $v) {
if($v['uid'] == $page_owner_uid) {
if (is_array($_SESSION['remote'])) {
foreach ($_SESSION['remote'] as $v) {
if ($v['uid'] == $page_owner_uid) {
$contact_id = $v['cid'];
break;
}
}
}
if($contact_id) {
if ($contact_id > 0) {
$r = q("SELECT `uid` FROM `contact` WHERE `blocked` = 0 AND `pending` = 0 AND `id` = %d AND `uid` = %d LIMIT 1",
intval($contact_id),
intval($page_owner_uid)
);
if (DBA::isResult($r)) {
$can_post = true;
$visitor = $contact_id;
@ -71,18 +74,19 @@ function wall_attach_post(App $a) {
}
}
}
if(! $can_post) {
if (! $can_post) {
if ($r_json) {
echo json_encode(['error'=>L10n::t('Permission denied.')]);
echo json_encode(['error' => L10n::t('Permission denied.')]);
killme();
}
notice(L10n::t('Permission denied.') . EOL );
killme();
}
if(! x($_FILES,'userfile')) {
if (! x($_FILES,'userfile')) {
if ($r_json) {
echo json_encode(['error'=>L10n::t('Invalid request.')]);
echo json_encode(['error' => L10n::t('Invalid request.')]);
}
killme();
}
@ -99,23 +103,23 @@ function wall_attach_post(App $a) {
* Then Filesize gets <= 0.
*/
if($filesize <=0) {
if ($filesize <= 0) {
$msg = L10n::t('Sorry, maybe your upload is bigger than the PHP configuration allows') . EOL .(L10n::t('Or - did you try to upload an empty file?'));
if ($r_json) {
echo json_encode(['error'=>$msg]);
echo json_encode(['error' => $msg]);
} else {
notice( $msg. EOL );
notice($msg . EOL);
}
@unlink($src);
killme();
}
if(($maxfilesize) && ($filesize > $maxfilesize)) {
if ($maxfilesize && $filesize > $maxfilesize) {
$msg = L10n::t('File exceeds size limit of %s', formatBytes($maxfilesize));
if ($r_json) {
echo json_encode(['error'=>$msg]);
echo json_encode(['error' => $msg]);
} else {
echo $msg. EOL ;
echo $msg . EOL ;
}
@unlink($src);
killme();
@ -134,12 +138,12 @@ function wall_attach_post(App $a) {
@unlink($src);
if(! $r) {
if (! $r) {
$msg = L10n::t('File upload failed.');
if ($r_json) {
echo json_encode(['error'=>$msg]);
echo json_encode(['error' => $msg]);
} else {
echo $msg. EOL ;
echo $msg . EOL ;
}
killme();
}
@ -153,15 +157,15 @@ function wall_attach_post(App $a) {
if (! DBA::isResult($r)) {
$msg = L10n::t('File upload failed.');
if ($r_json) {
echo json_encode(['error'=>$msg]);
echo json_encode(['error' => $msg]);
} else {
echo $msg. EOL ;
echo $msg . EOL ;
}
killme();
}
if ($r_json) {
echo json_encode(['ok'=>true]);
echo json_encode(['ok' => true]);
killme();
}

View file

@ -91,6 +91,7 @@ class DBA
self::$connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
self::$connected = true;
} catch (PDOException $e) {
/// @TODO At least log exception, don't ignore it!
}
}
@ -255,6 +256,7 @@ class DBA
switch (self::$driver) {
case 'pdo':
return substr(@self::$connection->quote($str, PDO::PARAM_STR), 1, -1);
case 'mysqli':
return @self::$connection->real_escape_string($str);
}
@ -932,13 +934,11 @@ class DBA
switch (self::$driver) {
case 'pdo':
if (self::$connection->inTransaction()) {
break;
}
if (!self::$connection->beginTransaction()) {
if (!self::$connection->inTransaction() && !self::$connection->beginTransaction()) {
return false;
}
break;
case 'mysqli':
if (!self::$connection->begin_transaction()) {
return false;
@ -957,10 +957,13 @@ class DBA
if (!self::$connection->inTransaction()) {
return true;
}
return self::$connection->commit();
case 'mysqli':
return self::$connection->commit();
}
return true;
}
@ -993,6 +996,7 @@ class DBA
}
$ret = self::$connection->rollBack();
break;
case 'mysqli':
$ret = self::$connection->rollback();
break;

View file

@ -1526,7 +1526,9 @@ class Contact extends BaseObject
$item['guid'] = '';
$item['tag'] = '';
$item['attach'] = '';
$slap = OStatus::salmon($item, $owner);
if (!empty($contact['notify'])) {
Salmon::slapper($owner, $contact['notify'], $slap);
}
@ -1540,7 +1542,15 @@ class Contact extends BaseObject
return $result;
}
public static function updateSslPolicy($contact, $new_policy)
/**
* @brief Updated contact's SSL policy
*
* @param array $contact Contact array
* @param string $new_policy New policy, valid: self,full
*
* @return array Contact array with updated values
*/
public static function updateSslPolicy(array $contact, $new_policy)
{
$ssl_changed = false;
if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {

View file

@ -40,6 +40,7 @@ class Conversation
if (isset($arr['parent-uri']) && ($arr['parent-uri'] != $arr['uri'])) {
$conversation['reply-to-uri'] = $arr['parent-uri'];
}
if (isset($arr['thr-parent']) && ($arr['thr-parent'] != $arr['uri'])) {
$conversation['reply-to-uri'] = $arr['thr-parent'];
}

View file

@ -915,6 +915,11 @@ class GContact
intval($uid)
);
if (!DBA::isResult($r)) {
logger('Cannot find user with uid=' . $uid, LOGGER_INFO);
return false;
}
$location = Profile::formatLocation(
["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
);

View file

@ -71,9 +71,11 @@ class User
public static function getOwnerDataByNick($nick)
{
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
if (!DBA::isResult($user)) {
return false;
}
return self::getOwnerDataById($user['uid']);
}

View file

@ -1330,6 +1330,7 @@ class DFRN
$key = openssl_random_pseudo_bytes(16);
$data = self::aesEncrypt($postvars['data'], $key);
break;
default:
logger("rino: invalid requested version '$rino_remote_version'");
Contact::markForArchival($contact);

View file

@ -2425,10 +2425,11 @@ class Diaspora
Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
// technically they are sharing with us (Contact::SHARING),
// but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
// we are going to change the relationship and make them a follower.
/*
* technically they are sharing with us (Contact::SHARING),
* but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
* we are going to change the relationship and make them a follower.
*/
if (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing && $following) {
$new_relation = Contact::FRIEND;
} elseif (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing) {
@ -2755,7 +2756,7 @@ class Diaspora
*
* @return int The message id of the newly created item
*/
private static function receiveStatusMessage(array $importer, $data, $xml)
private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
{
$author = notags(unxmlify($data->author));
$guid = notags(unxmlify($data->guid));

View file

@ -444,25 +444,30 @@ class Delivery extends BaseObject
if (($target_item["thr-parent"] != "") && ($target_item["thr-parent"] != $target_item["parent-uri"])) {
$headers .= " <".Email::iri2msgid($target_item["thr-parent"]).">";
}
$headers .= "\n";
if (empty($target_item['title'])) {
$condition = ['uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
$title = Item::selectFirst(['title'], $condition);
if (DBA::isResult($title) && ($title['title'] != '')) {
$subject = $title['title'];
} else {
$condition = ['parent-uri' => $target_item['parent-uri'], 'uid' => $owner['uid']];
$title = Item::selectFirst(['title'], $condition);
if (DBA::isResult($title) && ($title['title'] != '')) {
$subject = $title['title'];
}
}
}
if (strncasecmp($subject, 'RE:', 3)) {
$subject = 'Re: ' . $subject;
}
}
Email::send($addr, $subject, $headers, $target_item);
}
}

View file

@ -607,12 +607,15 @@ class OnePoll
if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $contact['network'] == Protocol::FEED)) {
logger('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
$hubs = explode(',', $hub);
if (count($hubs)) {
foreach ($hubs as $h) {
$h = trim($h);
if (!strlen($h)) {
continue;
}
subscribe_to_hub($h, $importer, $contact, $hubmode);
}
}
@ -652,7 +655,7 @@ class OnePoll
* @param array $contact The personal contact entry
* @param array $fields The fields that are updated
*/
private static function updateContact($contact, $fields)
private static function updateContact(array $contact, array $fields)
{
DBA::update('contact', $fields, ['id' => $contact['id']]);
DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);