diff --git a/include/api.php b/include/api.php index bc60590a5..36e38a86e 100644 --- a/include/api.php +++ b/include/api.php @@ -222,7 +222,7 @@ function api_login(App $a) } else { $user_id = User::authenticate(trim($user), trim($password)); if ($user_id) { - $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]); + $record = dba::selectFirst('user', [], ['uid' => $user_id]); } } @@ -473,7 +473,7 @@ function api_rss_extra(App $a, $arr, $user_info) */ function api_unique_id_to_nurl($id) { - $r = dba::select('contact', array('nurl'), array('uid' => 0, 'id' => $id), array('limit' => 1)); + $r = dba::selectFirst('contact', array('nurl'), array('uid' => 0, 'id' => $id)); if (DBM::is_result($r)) { return $r["nurl"]; @@ -792,7 +792,7 @@ function api_get_user(App $a, $contact_id = null) // If this is a local user and it uses Frio, we can get its color preferences. if ($ret['self']) { - $theme_info = dba::select('user', ['theme'], ['uid' => $ret['uid']], ['limit' => 1]); + $theme_info = dba::selectFirst('user', ['theme'], ['uid' => $ret['uid']]); if ($theme_info['theme'] === 'frio') { $schema = PConfig::get($ret['uid'], 'frio', 'schema'); if ($schema && ($schema != '---')) { @@ -4870,7 +4870,7 @@ function api_friendica_remoteauth() // traditional DFRN - $r = dba::select('contact', [], ['uid' => api_user(), 'nurl' => $c_url], ['limit' => 1]); + $r = dba::selectFirst('contact', [], ['uid' => api_user(), 'nurl' => $c_url]); if (!DBM::is_result($r) || ($r['network'] !== NETWORK_DFRN)) { throw new BadRequestException("Unknown contact"); diff --git a/include/contact_widgets.php b/include/contact_widgets.php index a1c93f142..cc25c88ed 100644 --- a/include/contact_widgets.php +++ b/include/contact_widgets.php @@ -224,12 +224,12 @@ function common_friends_visitor_widget($profile_uid) if (!$cid) { if (get_my_url()) { - $r = dba::select('contact', array('id'), - array('nurl' => normalise_link(get_my_url()), 'uid' => $profile_uid), array('limit' => 1)); + $r = dba::selectFirst('contact', ['id'], + ['nurl' => normalise_link(get_my_url()), 'uid' => $profile_uid]); if (DBM::is_result($r)) { $cid = $r['id']; } else { - $r = dba::select('gcontact', array('id'), array('nurl' => normalise_link(get_my_url())), array('limit' => 1)); + $r = dba::selectFirst('gcontact', ['id'], ['nurl' => normalise_link(get_my_url())]); if (DBM::is_result($r)) { $zcid = $r['id']; } diff --git a/include/conversation.php b/include/conversation.php index 423d9884e..228e90598 100644 --- a/include/conversation.php +++ b/include/conversation.php @@ -968,9 +968,8 @@ function best_link_url($item, &$sparkle, $url = '') { $clean_url = normalise_link($item['author-link']); if (local_user()) { - $r = dba::select('contact', array('id'), - array('network' => NETWORK_DFRN, 'uid' => local_user(), 'nurl' => normalise_link($clean_url), 'pending' => false), - array('limit' => 1)); + $r = dba::selectFirst('contact', ['id'], + ['network' => NETWORK_DFRN, 'uid' => local_user(), 'nurl' => normalise_link($clean_url), 'pending' => false]); if (DBM::is_result($r)) { $best_url = 'redir/' . $r['id']; $sparkle = true; @@ -1020,7 +1019,7 @@ function item_photo_menu($item) { $cid = 0; $network = ''; $rel = 0; - $r = dba::select('contact', array('id', 'network', 'rel'), array('uid' => local_user(), 'nurl' => normalise_link($item['author-link'])), array('limit' => 1)); + $r = dba::selectFirst('contact', array('id', 'network', 'rel'), array('uid' => local_user(), 'nurl' => normalise_link($item['author-link']))); if (DBM::is_result($r)) { $cid = $r['id']; $network = $r['network']; diff --git a/include/dba.php b/include/dba.php index 391a6fcf7..32fa88d95 100644 --- a/include/dba.php +++ b/include/dba.php @@ -313,7 +313,7 @@ class dba { * For all regular queries please use dba::select or dba::exists * * @param string $sql SQL statement - * @return object statement object + * @return bool|object statement object */ public static function p($sql) { $a = get_app(); @@ -572,7 +572,7 @@ class dba { $fields = array($array_key); } - $stmt = self::select($table, $fields, $condition, array('limit' => 1, 'only_query' => true)); + $stmt = self::select($table, $fields, $condition, ['limit' => 1]); if (is_bool($stmt)) { $retval = $stmt; @@ -586,10 +586,11 @@ class dba { } /** + * Fetches the first row + * + * Please use dba::selectFirst or dba::exists whenever this is possible. + * * @brief Fetches the first row - * - * Please use dba::select or dba::exists whenever this is possible. - * * @param string $sql SQL statement * @return array first row of query */ @@ -639,7 +640,7 @@ class dba { /** * @brief Returns the number of rows of a statement * - * @param object Statement object + * @param PDOStatement|mysqli_result|mysqli_stmt Statement object * @return int Number of rows */ public static function num_rows($stmt) { @@ -658,7 +659,7 @@ class dba { /** * @brief Fetch a single row * - * @param object $stmt statement object + * @param PDOStatement|mysqli_result|mysqli_stmt $stmt statement object * @return array current row */ public static function fetch($stmt) { @@ -1046,7 +1047,7 @@ class dba { if (is_bool($old_fields)) { $do_insert = $old_fields; - $old_fields = self::select($table, array(), $condition, array('limit' => 1)); + $old_fields = self::selectFirst($table, [], $condition); if (is_bool($old_fields)) { if ($do_insert) { @@ -1083,15 +1084,40 @@ class dba { return self::e($sql, $params); } + /** + * Retrieve a single record from a table and returns it in an associative array + * + * @brief Retrieve a single record from a table + * @param string $table + * @param array $fields + * @param array $condition + * @param array $params + * @return bool|array + * @see dba::select + */ + public static function selectFirst($table, array $fields = [], array $condition = [], $params = []) + { + $params['limit'] = 1; + $result = self::select($table, $fields, $condition, $params); + + if (is_bool($result)) { + return $result; + } else { + $row = self::fetch($result); + self::close($result); + return $row; + } + } + /** * @brief Select rows from a table * - * @param string $table Table name - * @param array $fields array of selected fields - * @param array $condition array of fields for condition - * @param array $params array of several parameters + * @param string $table Table name + * @param array $fields Array of selected fields, empty for all + * @param array $condition Array of fields for condition + * @param array $params Array of several parameters * - * @return boolean|object If "limit" is equal "1" only a single row is returned, else a query object is returned + * @return boolean|object * * Example: * $table = "item"; @@ -1101,7 +1127,7 @@ class dba { * or: * $condition = array("`uid` = ? AND `network` IN (?, ?)", 1, 'dfrn', 'dspr'); * - * $params = array("order" => array("id", "received" => true), "limit" => 1); + * $params = array("order" => array("id", "received" => true), "limit" => 10); * * $data = dba::select($table, $fields, $condition, $params); */ @@ -1112,53 +1138,38 @@ class dba { } if (count($fields) > 0) { - $select_fields = "`".implode("`, `", array_values($fields))."`"; + $select_fields = "`" . implode("`, `", array_values($fields)) . "`"; } else { $select_fields = "*"; } $condition_string = self::buildCondition($condition); - $param_string = ''; - $single_row = false; - if (isset($params['order'])) { - $param_string .= " ORDER BY "; + $order_string = " ORDER BY "; foreach ($params['order'] AS $fields => $order) { if (!is_int($fields)) { - $param_string .= "`".$fields."` ".($order ? "DESC" : "ASC").", "; + $order_string .= "`" . $fields . "` " . ($order ? "DESC" : "ASC") . ", "; } else { - $param_string .= "`".$order."`, "; + $order_string .= "`" . $order . "`, "; } } - $param_string = substr($param_string, 0, -2); + $order_string = substr($order_string, 0, -2); } if (isset($params['limit']) && is_int($params['limit'])) { - $param_string .= " LIMIT ".$params['limit']; - $single_row = ($params['limit'] == 1); + $limit_string = " LIMIT " . $params['limit']; } if (isset($params['limit']) && is_array($params['limit'])) { - $param_string .= " LIMIT ".intval($params['limit'][0]).", ".intval($params['limit'][1]); - $single_row = ($params['limit'][1] == 1); + $limit_string = " LIMIT " . intval($params['limit'][0]) . ", " . intval($params['limit'][1]); } - if (isset($params['only_query']) && $params['only_query']) { - $single_row = !$params['only_query']; - } - - $sql = "SELECT ".$select_fields." FROM `".$table."`".$condition_string.$param_string; + $sql = "SELECT " . $select_fields . " FROM `" . $table . "`" . $condition_string . $order_string . $limit_string; $result = self::p($sql, $condition); - if (is_bool($result) || !$single_row) { - return $result; - } else { - $row = self::fetch($result); - self::close($result); - return $row; - } + return $result; } /** @@ -1270,7 +1281,7 @@ class dba { * @brief Closes the current statement * * @param object $stmt statement object - * @return boolean was the close successfull? + * @return boolean was the close successful? */ public static function close($stmt) { if (!is_object($stmt)) { diff --git a/include/enotify.php b/include/enotify.php index 79c5df3f5..286957256 100644 --- a/include/enotify.php +++ b/include/enotify.php @@ -50,8 +50,8 @@ function notification($params) } if ($params['type'] != SYSTEM_EMAIL) { - $user = dba::select('user', array('nickname', 'page-flags'), - array('uid' => $params['uid']), array('limit' => 1)); + $user = dba::selectFirst('user', ['nickname', 'page-flags'], + ['uid' => $params['uid']]); // There is no need to create notifications for forum accounts if (!DBM::is_result($user) || in_array($user["page-flags"], array(PAGE_COMMUNITY, PAGE_PRVGROUP))) { @@ -106,7 +106,7 @@ function notification($params) } if ($params['type'] == NOTIFY_COMMENT) { - $p = dba::select('thread', ['ignored'], ['iid' => $parent_id], ['limit' => 1]); + $p = dba::selectFirst('thread', ['ignored'], ['iid' => $parent_id]); if (DBM::is_result($p) && $p["ignored"]) { logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG); return; @@ -131,7 +131,7 @@ function notification($params) $p = null; if ($params['otype'] === 'item' && $parent_id) { - $p = dba::select('item', [], ['id' => $parent_id], ['limit' => 1]); + $p = dba::selectFirst('item', [], ['id' => $parent_id]); } $item_post_type = item_post_type($p); @@ -672,12 +672,12 @@ function check_item_notification($itemid, $uid, $defaulttype = "") { $profiles = $notification_data["profiles"]; $fields = ['notify-flags', 'language', 'username', 'email', 'nickname']; - $user = dba::select('user', $fields, ['uid' => $uid], ['limit' => 1]); + $user = dba::selectFirst('user', $fields, ['uid' => $uid]); if (!DBM::is_result($user)) { return false; } - $owner = dba::select('contact', ['url'], ['self' => true, 'uid' => $uid], ['limit' => 1]); + $owner = dba::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]); if (!DBM::is_result($owner)) { return false; } diff --git a/include/identity.php b/include/identity.php index 11f2b7f5b..0c6224594 100644 --- a/include/identity.php +++ b/include/identity.php @@ -162,7 +162,7 @@ function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0) if (remote_user() && count($_SESSION['remote'])) { foreach ($_SESSION['remote'] as $visitor) { if ($visitor['uid'] == $uid) { - $r = dba::select('contact', array('profile-id'), array('id' => $visitor['cid']), array('limit' => 1)); + $r = dba::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]); if (DBM::is_result($r)) { $profile = $r['profile-id']; } diff --git a/include/items.php b/include/items.php index 83f7f76a8..f1ce70d46 100644 --- a/include/items.php +++ b/include/items.php @@ -562,9 +562,9 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f // check for create date and expire time $expire_interval = Config::get('system', 'dbclean-expire-days', 0); - $r = dba::select('user', array('expire'), array('uid' => $uid), array("limit" => 1)); - if (DBM::is_result($r) && ($r['expire'] > 0) && (($r['expire'] < $expire_interval) || ($expire_interval == 0))) { - $expire_interval = $r['expire']; + $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]); + if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) { + $expire_interval = $user['expire']; } if (($expire_interval > 0) && !empty($arr['created'])) { @@ -1149,14 +1149,14 @@ function item_store($arr, $force_parent = false, $notify = false, $dontcache = f */ function item_set_last_item($arr) { // Unarchive the author - $contact = dba::select('contact', [], ['id' => $arr["author-link"]], ['limit' => 1]); + $contact = dba::selectFirst('contact', [], ['id' => $arr["author-link"]]); if ($contact['term-date'] > NULL_DATE) { Contact::unmarkForArchival($contact); } // Unarchive the contact if it is a toplevel posting if ($arr["parent-uri"] === $arr["uri"]) { - $contact = dba::select('contact', [], ['id' => $arr["contact-id"]], ['limit' => 1]); + $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"]]); if ($contact['term-date'] > NULL_DATE) { Contact::unmarkForArchival($contact); } diff --git a/include/message.php b/include/message.php index 844a803c0..189de2aef 100644 --- a/include/message.php +++ b/include/message.php @@ -69,7 +69,7 @@ function send_message($recipient = 0, $body = '', $subject = '', $replyto = '') 'subject' => $subject, 'recips' => $handles); dba::insert('conv', $fields); - $r = dba::select('conv', array('id'), array('guid' => $conv_guid, 'uid' => local_user()), array('limit' => 1)); + $r = dba::selectFirst('conv', ['id'], ['guid' => $conv_guid, 'uid' => local_user()]); if (DBM::is_result($r)) { $convid = $r['id']; } @@ -188,7 +188,7 @@ function send_wallmessage($recipient = '', $body = '', $subject = '', $replyto = 'subject' => $subject, 'recips' => $handles); dba::insert('conv', $fields); - $r = dba::select('conv', array('id'), array('guid' => $conv_guid, 'uid' => $recipient['uid']), array('limit' => 1)); + $r = dba::selectFirst('conv', ['id'], ['guid' => $conv_guid, 'uid' => $recipient['uid']]); if (!DBM::is_result($r)) { logger('send message: conversation not found.'); return -4; diff --git a/include/nav.php b/include/nav.php index 1bc9a3ae1..ac76dd5aa 100644 --- a/include/nav.php +++ b/include/nav.php @@ -94,7 +94,7 @@ function nav_info(App $a) $nav['usermenu'][] = array('notes/', t('Personal notes'), '', t('Your personal notes')); // user info - $r = dba::select('contact', array('micro'), array('uid' => $a->user['uid'], 'self' => true), array('limit' => 1)); + $r = dba::selectFirst('contact', ['micro'], ['uid' => $a->user['uid'], 'self' => true]); $userinfo = array( 'icon' => (DBM::is_result($r) ? $a->remove_baseurl($r['micro']) : 'images/person-48.jpg'), 'name' => $a->user['username'], diff --git a/include/session.php b/include/session.php index b1619e90f..cf51518f2 100644 --- a/include/session.php +++ b/include/session.php @@ -33,7 +33,7 @@ function ref_session_read($id) return ''; } - $r = dba::select('session', array('data'), array('sid' => $id), array('limit' => 1)); + $r = dba::selectFirst('session', ['data'], ['sid' => $id]); if (DBM::is_result($r)) { $session_exists = true; return $r['data']; diff --git a/include/tags.php b/include/tags.php index 50fe1e490..02091f169 100644 --- a/include/tags.php +++ b/include/tags.php @@ -226,12 +226,7 @@ function wtagblock($uid, $count = 0, $owner_id = 0, $flags = '', $type = TERM_HA $o = ''; $r = tagadelic($uid, $count, $owner_id, $flags, $type); if (count($r)) { - $contact = dba::select( - 'contact', - array('url'), - array('id' => $uid), - array('limit' => 1) - ); + $contact = dba::selectFirst('contact', ['url'], ['id' => $uid]); $url = System::removedBaseUrl($contact['url']); foreach ($r as $rr) { diff --git a/index.php b/index.php index 711478fe1..f96627994 100644 --- a/index.php +++ b/index.php @@ -108,7 +108,7 @@ if (!$a->is_backend()) { */ if (x($_SESSION, 'authenticated') && !x($_SESSION, 'language')) { // we didn't loaded user data yet, but we need user language - $r = dba::select('user', array('language'), array('uid' => $_SESSION['uid']), array('limit' => 1)); + $r = dba::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]); $_SESSION['language'] = $lang; if (DBM::is_result($r)) { $_SESSION['language'] = $r['language']; diff --git a/mod/admin.php b/mod/admin.php index 75e28e0fb..e7463a360 100644 --- a/mod/admin.php +++ b/mod/admin.php @@ -1551,8 +1551,8 @@ function admin_page_users(App $a) { if ($a->argc > 2) { $uid = $a->argv[3]; - $user = q("SELECT `username`, `blocked` FROM `user` WHERE `uid` = %d", intval($uid)); - if (count($user) == 0) { + $user = dba::selectFirst('user', ['username', 'blocked'], ['uid' => $uid]); + if (DBM::is_result($user)) { notice('User not found' . EOL); goaway('admin/users'); return ''; // NOTREACHED @@ -1563,15 +1563,15 @@ function admin_page_users(App $a) // delete user User::remove($uid); - notice(t("User '%s' deleted", $user[0]['username']) . EOL); + notice(t("User '%s' deleted", $user['username']) . EOL); break; case "block": check_form_security_token_redirectOnErr('/admin/users', 'admin_users', 't'); q("UPDATE `user` SET `blocked` = %d WHERE `uid` = %s", - intval(1 - $user[0]['blocked']), + intval(1 - $user['blocked']), intval($uid) ); - notice(sprintf(($user[0]['blocked'] ? t("User '%s' unblocked") : t("User '%s' blocked")), $user[0]['username']) . EOL); + notice(sprintf(($user['blocked'] ? t("User '%s' unblocked") : t("User '%s' blocked")), $user['username']) . EOL); break; } goaway('admin/users'); @@ -1625,8 +1625,6 @@ function admin_page_users(App $a) ORDER BY $sql_order $sql_order_direction LIMIT %d, %d", intval($a->pager['start']), intval($a->pager['itemspage']) ); - //echo "
$users"; killme();
-
 	$adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
 	$_setup_users = function ($e) use ($adminlist) {
 		$accounts = array(
diff --git a/mod/cal.php b/mod/cal.php
index 4a6e2c992..51a66613e 100644
--- a/mod/cal.php
+++ b/mod/cal.php
@@ -6,10 +6,10 @@
  * 	This calendar is for profile visitors and contains only the events
  * 	of the profile owner
  */
+
 use Friendica\App;
 use Friendica\Content\Feature;
 use Friendica\Core\Config;
-use Friendica\Core\PConfig;
 use Friendica\Core\System;
 use Friendica\Database\DBM;
 use Friendica\Model\Contact;
@@ -32,16 +32,13 @@ function cal_init(App $a)
 
 	if ($a->argc > 1) {
 		$nick = $a->argv[1];
-		$user = q("SELECT * FROM `user` WHERE `nickname` = '%s' AND `blocked` = 0 LIMIT 1",
-			dbesc($nick)
-		);
-
-		if (!count($user)) {
+		$user = dba::selectFirst('user', [], ['nickname' => $nick, 'blocked' => false]);
+		if (!DBM::is_result($user)) {
 			return;
 		}
 
-		$a->data['user'] = $user[0];
-		$a->profile_uid = $user[0]['uid'];
+		$a->data['user'] = $user;
+		$a->profile_uid = $user['uid'];
 
 		// if it's a json request abort here becaus we don't
 		// need the widget data
diff --git a/mod/common.php b/mod/common.php
index 1f1e8c337..11bddf6b5 100644
--- a/mod/common.php
+++ b/mod/common.php
@@ -63,19 +63,13 @@ function common_content(App $a)
 	}
 
 	if (!$cid && get_my_url()) {
-		/// @todo : Initialize $profile_uid
-		$r = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
-			dbesc(normalise_link(get_my_url())),
-			intval($profile_uid)
-		);
-		if (DBM::is_result($r)) {
-			$cid = $r[0]['id'];
+		$contact = dba::selectFirst('contact', ['id'], ['nurl' => normalise_link(get_my_url()), 'uid' => $uid]);
+		if (DBM::is_result($contact)) {
+			$cid = $contact['id'];
 		} else {
-			$r = q("SELECT `id` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
-				dbesc(normalise_link(get_my_url()))
-			);
-			if (DBM::is_result($r)) {
-				$zcid = $r[0]['id'];
+			$gcontact = dba::selectFirst('gcontact', ['id'], ['nurl' => normalise_link(get_my_url())]);
+			if (DBM::is_result($gcontact)) {
+				$zcid = $gcontact['id'];
 			}
 		}
 	}
diff --git a/mod/contacts.php b/mod/contacts.php
index a63591713..90c4af7d1 100644
--- a/mod/contacts.php
+++ b/mod/contacts.php
@@ -33,7 +33,7 @@ function contacts_init(App $a)
 	$contact = [];
 	if ((($a->argc == 2) && intval($a->argv[1])) || (($a->argc == 3) && intval($a->argv[1]) && ($a->argv[2] == "posts"))) {
 		$contact_id = intval($a->argv[1]);
-		$contact = dba::select('contact', [], ['id' => $contact_id, 'uid' => local_user()], ['limit' => 1]);
+		$contact = dba::selectFirst('contact', [], ['id' => $contact_id, 'uid' => local_user()]);
 	}
 
 	if (DBM::is_result($contact)) {
@@ -222,7 +222,7 @@ function contacts_post(App $a)
 		notice(t('Failed to update contact record.') . EOL);
 	}
 
-	$contact = dba::select('contact', [], ['id' => $contact_id, 'uid' => local_user()], ['limit' => 1]);
+	$contact = dba::selectFirst('contact', [], ['id' => $contact_id, 'uid' => local_user()]);
 	if (DBM::is_result($contact)) {
 		$a->data['contact'] = $contact;
 	}
@@ -233,7 +233,7 @@ function contacts_post(App $a)
 
 function _contact_update($contact_id)
 {
-	$contact = dba::select('contact', ['uid', 'url', 'network'], ['id' => $contact_id, 'uid' => local_user()], ['limit' => 1]);
+	$contact = dba::selectFirst('contact', ['uid', 'url', 'network'], ['id' => $contact_id, 'uid' => local_user()]);
 	if (!DBM::is_result($contact)) {
 		return;
 	}
@@ -254,7 +254,7 @@ function _contact_update($contact_id)
 
 function _contact_update_profile($contact_id)
 {
-	$contact = dba::select('contact', ['uid', 'url', 'network'], ['id' => $contact_id, 'uid' => local_user()], ['limit' => 1]);
+	$contact = dba::selectFirst('contact', ['uid', 'url', 'network'], ['id' => $contact_id, 'uid' => local_user()]);
 	if (!DBM::is_result($contact)) {
 		return;
 	}
@@ -389,7 +389,7 @@ function contacts_content(App $a)
 
 		$cmd = $a->argv[2];
 
-		$orig_record = dba::select('contact', [], ['id' => $contact_id, 'uid' => local_user(), 'self' => false], ['limit' => 1]);
+		$orig_record = dba::selectFirst('contact', [], ['id' => $contact_id, 'uid' => local_user(), 'self' => false]);
 		if (!DBM::is_result($orig_record)) {
 			notice(t('Could not access contact record.') . EOL);
 			goaway('contacts');
@@ -904,7 +904,7 @@ function contact_posts($a, $contact_id)
 {
 	$o = contacts_tab($a, $contact_id, 1);
 
-	$contact = dba::select('contact', ['url'], ['id' => $contact_id], ['limit' => 1]);
+	$contact = dba::selectFirst('contact', ['url'], ['id' => $contact_id]);
 	if (DBM::is_result($contact)) {
 		$a->page['aside'] = "";
 		profile_load($a, "", 0, Contact::getDetailsByURL($contact["url"]));
diff --git a/mod/display.php b/mod/display.php
index 755c8b922..25dd9b3af 100644
--- a/mod/display.php
+++ b/mod/display.php
@@ -202,7 +202,7 @@ function display_content(App $a, $update = false, $update_uid = 0) {
 
 	if ($update) {
 		$item_id = $_REQUEST['item_id'];
-		$item = dba::select('item', ['uid', 'parent'], ['id' => $item_id], ['limit' => 1]);
+		$item = dba::selectFirst('item', ['uid', 'parent'], ['id' => $item_id]);
 		$a->profile = array('uid' => intval($item['uid']), 'profile_uid' => intval($item['uid']));
 		$item_parent = $item['parent'];
 	} else {
@@ -345,7 +345,7 @@ function display_content(App $a, $update = false, $update_uid = 0) {
 	$s = dba::inArray($r);
 
 	if (local_user() && (local_user() == $a->profile['uid'])) {
-		$unseen = dba::select('item', array('id'), array('parent' => $s[0]['parent'], 'unseen' => true), array('limit' => 1));
+		$unseen = dba::selectFirst('item', ['id'], ['parent' => $s[0]['parent'], 'unseen' => true]);
 		if (DBM::is_result($unseen)) {
 			dba::update('item', array('unseen' => false), array('parent' => $s[0]['parent'], 'unseen' => true));
 		}
diff --git a/mod/hovercard.php b/mod/hovercard.php
index 29dfd2689..a9cd95f58 100644
--- a/mod/hovercard.php
+++ b/mod/hovercard.php
@@ -44,7 +44,7 @@ function hovercard_content()
 	$cid = 0;
 	if (local_user() && strpos($profileurl, 'redir/') === 0) {
 		$cid = intval(substr($profileurl, 6));
-		$r = dba::select('contact', array('nurl'), array('id' => $cid), array('limit' => 1));
+		$r = dba::selectFirst('contact', ['nurl'], ['id' => $cid]);
 		$profileurl = defaults($r, 'nurl', '');
 	}
 
diff --git a/mod/network.php b/mod/network.php
index 8cebe7317..84dc9255e 100644
--- a/mod/network.php
+++ b/mod/network.php
@@ -580,8 +580,8 @@ function networkThreadedView(App $a, $update = 0) {
 
 		if ($cid) {
 			// If $cid belongs to a communitity forum or a privat goup,.add a mention to the status editor
-			$condition = array("`id` = ? AND (`forum` OR `prv`)", $cid);
-			$contact = dba::select('contact', array('addr', 'nick'), $condition, array('limit' => 1));
+			$condition = ["`id` = ? AND (`forum` OR `prv`)", $cid];
+			$contact = dba::selectFirst('contact', ['addr', 'nick'], $condition);
 			if (DBM::is_result($contact)) {
 				if ($contact["addr"] != '') {
 					$content = "!".$contact["addr"];
@@ -632,7 +632,7 @@ function networkThreadedView(App $a, $update = 0) {
 	$sql_nets = (($nets) ? sprintf(" and $sql_table.`network` = '%s' ", dbesc($nets)) : '');
 
 	if ($group) {
-		$r = dba::select('group', array('name'), array('id' => $group, 'uid' => $_SESSION['uid']), array('limit' => 1));
+		$r = dba::selectFirst('group', ['name'], ['id' => $group, 'uid' => $_SESSION['uid']]);
 		if (!DBM::is_result($r)) {
 			if ($update)
 				killme();
@@ -647,7 +647,7 @@ function networkThreadedView(App $a, $update = 0) {
 			$contact_str_self = "";
 
 			$contact_str = implode(',',$contacts);
-			$self = dba::select('contact', array('id'), array('uid' => $_SESSION['uid'], 'self' => true), array('limit' => 1));
+			$self = dba::selectFirst('contact', ['id'], ['uid' => $_SESSION['uid'], 'self' => true]);
 			if (DBM::is_result($self)) {
 				$contact_str_self = $self["id"];
 			}
@@ -665,10 +665,10 @@ function networkThreadedView(App $a, $update = 0) {
 		)) . $o;
 
 	} elseif ($cid) {
-		$fields = array('id', 'name', 'network', 'writable', 'nurl',
-				'forum', 'prv', 'contact-type', 'addr', 'thumb', 'location');
-		$condition = array("`id` = ? AND (NOT `blocked` OR `pending`)", $cid);
-		$r = dba::select('contact', $fields, $condition, array('limit' => 1));
+		$fields = ['id', 'name', 'network', 'writable', 'nurl',
+				'forum', 'prv', 'contact-type', 'addr', 'thumb', 'location'];
+		$condition = ["`id` = ? AND (NOT `blocked` OR `pending`)", $cid];
+		$r = dba::selectFirst('contact', $fields, $condition);
 		if (DBM::is_result($r)) {
 			$sql_extra = " AND ".$sql_table.".`contact-id` = ".intval($cid);
 
diff --git a/mod/noscrape.php b/mod/noscrape.php
index 0269c3f77..fb5dea872 100644
--- a/mod/noscrape.php
+++ b/mod/noscrape.php
@@ -67,14 +67,14 @@ function noscrape_init(App $a) {
 
 	// We display the last activity (post or login), reduced to year and week number
 	$last_active = 0;
-	$condition = array('uid' => $a->profile['uid'], 'self' => true);
-	$contact = dba::select('contact', array('last-item'), $condition, array('limit' => 1));
+	$condition = ['uid' => $a->profile['uid'], 'self' => true];
+	$contact = dba::selectFirst('contact', ['last-item'], $condition);
 	if (DBM::is_result($contact)) {
 		$last_active = strtotime($contact['last-item']);
 	}
 
-	$condition = array('uid' => $a->profile['uid']);
-	$user = dba::select('user', array('login_date'), $condition, array('limit' => 1));
+	$condition = ['uid' => $a->profile['uid']];
+	$user = dba::selectFirst('user', ['login_date'], $condition);
 	if (DBM::is_result($user)) {
 		if ($last_active < strtotime($user['login_date'])) {
 			$last_active = strtotime($user['login_date']);
diff --git a/mod/proxy.php b/mod/proxy.php
index e134565ce..80a84a165 100644
--- a/mod/proxy.php
+++ b/mod/proxy.php
@@ -148,7 +148,7 @@ function proxy_init(App $a) {
 	$r = array();
 
 	if (!$direct_cache && ($cachefile == '')) {
-		$r = dba::select('photo', array('data', 'desc'), array('resource-id' => $urlhash), array('limit' => 1));
+		$r = dba::selectFirst('photo', ['data', 'desc'], ['resource-id' => $urlhash]);
 		if (DBM::is_result($r)) {
 			$img_str = $r['data'];
 			$mime = $r['desc'];
diff --git a/mod/receive.php b/mod/receive.php
index fcc898a0c..0c7a7e095 100644
--- a/mod/receive.php
+++ b/mod/receive.php
@@ -32,7 +32,7 @@ function receive_post(App $a)
 		}
 		$guid = $a->argv[2];
 
-		$importer = dba::select('user', array(), array('guid' => $guid, 'account_expired' => false, 'account_removed' => false), array('limit' => 1));
+		$importer = dba::selectFirst('user', [], ['guid' => $guid, 'account_expired' => false, 'account_removed' => false]);
 		if (!DBM::is_result($importer)) {
 			http_status_exit(500);
 		}
diff --git a/mod/settings.php b/mod/settings.php
index 10c57ff8b..8fd890804 100644
--- a/mod/settings.php
+++ b/mod/settings.php
@@ -997,7 +997,7 @@ function settings_content(App $a)
 
 	require_once('include/acl_selectors.php');
 
-	$profile = dba::select('profile', [], ['is-default' => true, 'uid' => local_user()], ['limit' => 1]);
+	$profile = dba::selectFirst('profile', [], ['is-default' => true, 'uid' => local_user()]);
 	if (!DBM::is_result($profile)) {
 		notice(t('Unable to find your profile. Please contact your admin.') . EOL);
 		return;
diff --git a/mod/unfollow.php b/mod/unfollow.php
index 046fdfe7d..a68c4de90 100644
--- a/mod/unfollow.php
+++ b/mod/unfollow.php
@@ -23,10 +23,10 @@ function unfollow_post(App $a) {
 	$url = notags(trim($_REQUEST['url']));
 	$return_url = $_SESSION['return_url'];
 
-	$condition = array("`uid` = ? AND `rel` = ? AND (`nurl` = ? OR `alias` = ? OR `alias` = ?) AND `network` != ?",
+	$condition = ["`uid` = ? AND `rel` = ? AND (`nurl` = ? OR `alias` = ? OR `alias` = ?) AND `network` != ?",
 			$uid, CONTACT_IS_FRIEND, normalise_link($url),
-			normalise_link($url), $url, NETWORK_STATUSNET);
-	$contact = dba::select('contact', array(), $condition, array('limit' => 1));
+			normalise_link($url), $url, NETWORK_STATUSNET];
+	$contact = dba::selectFirst('contact', [], $condition);
 
 	if (!DBM::is_result($contact)) {
 		notice(t("Contact wasn't found or can't be unfollowed."));
@@ -62,10 +62,10 @@ function unfollow_content(App $a) {
 
 	$submit = t('Submit Request');
 
-	$condition = array("`uid` = ? AND `rel` = ? AND (`nurl` = ? OR `alias` = ? OR `alias` = ?) AND `network` != ?",
+	$condition = ["`uid` = ? AND `rel` = ? AND (`nurl` = ? OR `alias` = ? OR `alias` = ?) AND `network` != ?",
 			local_user(), CONTACT_IS_FRIEND, normalise_link($url),
-			normalise_link($url), $url, NETWORK_STATUSNET);
-	$contact = dba::select('contact', array('url', 'network', 'addr', 'name'), $condition, array('limit' => 1));
+			normalise_link($url), $url, NETWORK_STATUSNET];
+	$contact = dba::selectFirst('contact', ['url', 'network', 'addr', 'name'], $condition);
 
 	if (!DBM::is_result($contact)) {
 		notice(t("You aren't a friend of this contact.").EOL);
diff --git a/mod/xrd.php b/mod/xrd.php
index 363994a8d..af1167581 100644
--- a/mod/xrd.php
+++ b/mod/xrd.php
@@ -29,13 +29,14 @@ function xrd_init(App $a)
 		$name = ltrim(basename($uri), '~');
 	} else {
 		$local = str_replace('acct:', '', $uri);
-		if (substr($local, 0, 2) == '//')
+		if (substr($local, 0, 2) == '//') {
 			$local = substr($local, 2);
+		}
 
 		$name = substr($local, 0, strpos($local, '@'));
 	}
 
-	$r = dba::select('user', array(), array('nickname' => $name), array('limit' => 1));
+	$r = dba::selectFirst('user', [], ['nickname' => $name]);
 	if (!DBM::is_result($r)) {
 		killme();
 	}
diff --git a/src/Content/OEmbed.php b/src/Content/OEmbed.php
index 07c36685c..5a3f07b53 100644
--- a/src/Content/OEmbed.php
+++ b/src/Content/OEmbed.php
@@ -1,405 +1,404 @@
-
- */
-class OEmbed
-{
-	public static function replaceCallback($matches)
-	{
-		$embedurl = $matches[1];
-		$j = self::fetchURL($embedurl);
-		$s = self::formatObject($j);
-
-		return $s;
-	}
-
-	/**
-	 * @brief Get data from an URL to embed its content.
-	 *
-	 * @param string $embedurl The URL from which the data should be fetched.
-	 * @param bool $no_rich_type If set to true rich type content won't be fetched.
-	 *
-	 * @return bool|object Returns object with embed content or false if no embedable
-	 * 	 content exists
-	 */
-	public static function fetchURL($embedurl, $no_rich_type = false)
-	{
-		$embedurl = trim($embedurl, "'");
-		$embedurl = trim($embedurl, '"');
-
-		$a = get_app();
-
-		$condition = array('url' => normalise_link($embedurl));
-		$r = dba::select('oembed', array('content'), $condition, array('limit' => 1));
-
-		if (DBM::is_result($r)) {
-			$txt = $r["content"];
-		} else {
-			$txt = Cache::get($a->videowidth . $embedurl);
-		}
-		// These media files should now be caught in bbcode.php
-		// left here as a fallback in case this is called from another source
-
-		$noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");
-		$ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
-
-
-		if (is_null($txt)) {
-			$txt = "";
-
-			if (!in_array($ext, $noexts)) {
-				// try oembed autodiscovery
-				$redirects = 0;
-				$html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
-				if ($html_text) {
-					$dom = @DOMDocument::loadHTML($html_text);
-					if ($dom) {
-						$xpath = new DOMXPath($dom);
-						$entries = $xpath->query("//link[@type='application/json+oembed']");
-						foreach ($entries as $e) {
-							$href = $e->getAttributeNode("href")->nodeValue;
-							$txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
-							break;
-						}
-						$entries = $xpath->query("//link[@type='text/json+oembed']");
-						foreach ($entries as $e) {
-							$href = $e->getAttributeNode("href")->nodeValue;
-							$txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
-							break;
-						}
-					}
-				}
-			}
-
-			$txt = trim($txt);
-
-			if (!$txt || $txt[0] != "{") {
-				$txt = '{"type":"error"}';
-			} else { //save in cache
-				$j = json_decode($txt);
-				if ($j->type != "error") {
-					dba::insert('oembed', array('url' => normalise_link($embedurl),
-						'content' => $txt, 'created' => datetime_convert()), true);
-				}
-
-				Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY);
-			}
-		}
-
-		$j = json_decode($txt);
-
-		if (!is_object($j)) {
-			return false;
-		}
-
-		// Always embed the SSL version
-		if (isset($j->html)) {
-			$j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"), array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
-		}
-
-		$j->embedurl = $embedurl;
-
-		// If fetching information doesn't work, then improve via internal functions
-		if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) {
-			$data = ParseUrl::getSiteinfoCached($embedurl, true, false);
-			$j->type = $data["type"];
-
-			if ($j->type == "photo") {
-				$j->url = $data["url"];
-				//$j->width = $data["images"][0]["width"];
-				//$j->height = $data["images"][0]["height"];
-			}
-
-			if (isset($data["title"])) {
-				$j->title = $data["title"];
-			}
-
-			if (isset($data["text"])) {
-				$j->description = $data["text"];
-			}
-
-			if (is_array($data["images"])) {
-				$j->thumbnail_url = $data["images"][0]["src"];
-				$j->thumbnail_width = $data["images"][0]["width"];
-				$j->thumbnail_height = $data["images"][0]["height"];
-			}
-		}
-
-		call_hooks('oembed_fetch_url', $embedurl, $j);
-
-		return $j;
-	}
-
-	public static function formatObject($j)
-	{
-		$embedurl = $j->embedurl;
-		$jhtml = $j->html;
-		$ret = '
'; - switch ($j->type) { - case "video": - if (isset($j->thumbnail_url)) { - $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200; - $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height : 180; - // make sure we don't attempt divide by zero, fallback is a 1:1 ratio - $tr = (($th) ? $tw / $th : 1); - - $th = 120; - $tw = $th * $tr; - $tpl = get_markup_template('oembed_video.tpl'); - $ret .= replace_macros($tpl, array( - '$baseurl' => System::baseUrl(), - '$embedurl' => $embedurl, - '$escapedhtml' => base64_encode($jhtml), - '$tw' => $tw, - '$th' => $th, - '$turl' => $j->thumbnail_url, - )); - } else { - $ret = $jhtml; - } - break; - case "photo": - $ret .= ''; - break; - case "link": - break; - case "rich": - if (self::isAllowedURL($embedurl)) { - $ret .= proxy_parse_html($jhtml); - } - break; - } - - $ret .= '
'; - // add link to source if not present in "rich" type - if ($j->type != 'rich' || !strpos($j->html, $embedurl)) { - $ret .= '

'; - if (isset($j->title)) { - if (isset($j->provider_name)) { - $ret .= $j->provider_name . ": "; - } - - $embedlink = (isset($j->title)) ? $j->title : $embedurl; - $ret .= '' . $embedlink . ''; - if (isset($j->author_name)) { - $ret .= ' (' . $j->author_name . ')'; - } - } elseif (isset($j->provider_name) || isset($j->author_name)) { - $embedlink = ""; - if (isset($j->provider_name)) { - $embedlink .= $j->provider_name; - } - - if (isset($j->author_name)) { - if ($embedlink != "") { - $embedlink .= ": "; - } - - $embedlink .= $j->author_name; - } - if (trim($embedlink) == "") { - $embedlink = $embedurl; - } - - $ret .= '' . $embedlink . ''; - } - $ret .= "

"; - } elseif (!strpos($j->html, $embedurl)) { - // add for html2bbcode conversion - $ret .= '' . $j->title . ''; - } - - $ret = str_replace("\n", "", $ret); - return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret)); - } - - public static function BBCode2HTML($text) - { - $stopoembed = Config::get("system", "no_oembed"); - if ($stopoembed == true) { - return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "" . t('Embedding disabled') . " : $1", $text); - } - return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text); - } - - /** - * Find .... - * and replace it with [embed]url[/embed] - */ - public static function HTML2BBCode($text) - { - // start parser only if 'oembed' is in text - if (strpos($text, "oembed")) { - - // convert non ascii chars to html entities - $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text)); - - // If it doesn't parse at all, just return the text. - $dom = @DOMDocument::loadHTML($html_text); - if (!$dom) { - return $text; - } - $xpath = new DOMXPath($dom); - - $xattr = self::buildXPath("class", "oembed"); - $entries = $xpath->query("//div[$xattr]"); - - $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed"); - foreach ($entries as $e) { - $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue; - if (!is_null($href)) { - $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e); - } - } - return self::getInnerHTML($dom->getElementsByTagName("body")->item(0)); - } else { - return $text; - } - } - - /** - * Determines if rich content OEmbed is allowed for the provided URL - * - * @brief Determines if rich content OEmbed is allowed for the provided URL - * @param string $url - * @return boolean - */ - public static function isAllowedURL($url) - { - if (!Config::get('system', 'no_oembed_rich_content')) { - return true; - } - - $domain = parse_url($url, PHP_URL_HOST); - if (!x($domain)) { - return false; - } - - $str_allowed = Config::get('system', 'allowed_oembed', ''); - if (!x($str_allowed)) { - return false; - } - - $allowed = explode(',', $str_allowed); - - return allowed_domain($domain, $allowed); - } - - public static function getHTML($url, $title = null) - { - // Always embed the SSL version - $url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"), - array("https://www.youtube.com/", "https://player.vimeo.com/"), $url); - - $o = OEmbed::fetchURL($url); - - if (!is_object($o) || $o->type == 'error') { - throw new Exception('OEmbed failed for URL: ' . $url); - } - - if (x($title)) { - $o->title = $title; - } - - $html = OEmbed::formatObject($o); - - return $html; - } - - /** - * @brief Generates the iframe HTML for an oembed attachment. - * - * Width and height are given by the remote, and are regularly too small for - * the generated iframe. - * - * The width is entirely discarded for the actual width of the post, while fixed - * height is used as a starting point before the inevitable resizing. - * - * Since the iframe is automatically resized on load, there are no need for ugly - * and impractical scrollbars. - * - * @todo This function is currently unused until someoneā„¢ adds support for a separate OEmbed domain - * - * @param string $src Original remote URL to embed - * @param string $width - * @param string $height - * @return string formatted HTML - * - * @see oembed_format_object() - */ - private static function iframe($src, $width, $height) - { - $a = get_app(); - - if (!$height || strstr($height, '%')) { - $height = '200'; - } - $width = '100%'; - - $src = System::baseUrl() . '/oembed/' . base64url_encode($src); - return ''; - } - - /** - * Generates an XPath query to select elements whose provided attribute contains - * the provided value in a space-separated list. - * - * @brief Generates attribute search XPath string - * - * @param string $attr Name of the attribute to seach - * @param string $value Value to search in a space-separated list - * @return string - */ - private static function buildXPath($attr, $value) - { - // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath - return "contains(normalize-space(@$attr), ' $value ') or substring(normalize-space(@$attr), 1, string-length('$value') + 1) = '$value ' or substring(normalize-space(@$attr), string-length(@$attr) - string-length('$value')) = ' $value' or @$attr = '$value'"; - } - - /** - * Returns the inner XML string of a provided DOMNode - * - * @brief Returns the inner XML string of a provided DOMNode - * - * @param DOMNode $node - * @return string - */ - private static function getInnerHTML(DOMNode $node) - { - $innerHTML = ''; - $children = $node->childNodes; - foreach ($children as $child) { - $innerHTML .= $child->ownerDocument->saveXML($child); - } - return $innerHTML; - } - -} + + */ +class OEmbed +{ + public static function replaceCallback($matches) + { + $embedurl = $matches[1]; + $j = self::fetchURL($embedurl); + $s = self::formatObject($j); + + return $s; + } + + /** + * @brief Get data from an URL to embed its content. + * + * @param string $embedurl The URL from which the data should be fetched. + * @param bool $no_rich_type If set to true rich type content won't be fetched. + * + * @return bool|object Returns object with embed content or false if no embedable + * content exists + */ + public static function fetchURL($embedurl, $no_rich_type = false) + { + $embedurl = trim($embedurl, "'"); + $embedurl = trim($embedurl, '"'); + + $a = get_app(); + + $condition = ['url' => normalise_link($embedurl)]; + $r = dba::selectFirst('oembed', ['content'], $condition); + if (DBM::is_result($r)) { + $txt = $r["content"]; + } else { + $txt = Cache::get($a->videowidth . $embedurl); + } + // These media files should now be caught in bbcode.php + // left here as a fallback in case this is called from another source + + $noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm"); + $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION); + + + if (is_null($txt)) { + $txt = ""; + + if (!in_array($ext, $noexts)) { + // try oembed autodiscovery + $redirects = 0; + $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*"); + if ($html_text) { + $dom = @DOMDocument::loadHTML($html_text); + if ($dom) { + $xpath = new DOMXPath($dom); + $entries = $xpath->query("//link[@type='application/json+oembed']"); + foreach ($entries as $e) { + $href = $e->getAttributeNode("href")->nodeValue; + $txt = fetch_url($href . '&maxwidth=' . $a->videowidth); + break; + } + $entries = $xpath->query("//link[@type='text/json+oembed']"); + foreach ($entries as $e) { + $href = $e->getAttributeNode("href")->nodeValue; + $txt = fetch_url($href . '&maxwidth=' . $a->videowidth); + break; + } + } + } + } + + $txt = trim($txt); + + if (!$txt || $txt[0] != "{") { + $txt = '{"type":"error"}'; + } else { //save in cache + $j = json_decode($txt); + if ($j->type != "error") { + dba::insert('oembed', array('url' => normalise_link($embedurl), + 'content' => $txt, 'created' => datetime_convert()), true); + } + + Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY); + } + } + + $j = json_decode($txt); + + if (!is_object($j)) { + return false; + } + + // Always embed the SSL version + if (isset($j->html)) { + $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"), array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html); + } + + $j->embedurl = $embedurl; + + // If fetching information doesn't work, then improve via internal functions + if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) { + $data = ParseUrl::getSiteinfoCached($embedurl, true, false); + $j->type = $data["type"]; + + if ($j->type == "photo") { + $j->url = $data["url"]; + //$j->width = $data["images"][0]["width"]; + //$j->height = $data["images"][0]["height"]; + } + + if (isset($data["title"])) { + $j->title = $data["title"]; + } + + if (isset($data["text"])) { + $j->description = $data["text"]; + } + + if (is_array($data["images"])) { + $j->thumbnail_url = $data["images"][0]["src"]; + $j->thumbnail_width = $data["images"][0]["width"]; + $j->thumbnail_height = $data["images"][0]["height"]; + } + } + + call_hooks('oembed_fetch_url', $embedurl, $j); + + return $j; + } + + public static function formatObject($j) + { + $embedurl = $j->embedurl; + $jhtml = $j->html; + $ret = '
'; + switch ($j->type) { + case "video": + if (isset($j->thumbnail_url)) { + $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200; + $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height : 180; + // make sure we don't attempt divide by zero, fallback is a 1:1 ratio + $tr = (($th) ? $tw / $th : 1); + + $th = 120; + $tw = $th * $tr; + $tpl = get_markup_template('oembed_video.tpl'); + $ret .= replace_macros($tpl, array( + '$baseurl' => System::baseUrl(), + '$embedurl' => $embedurl, + '$escapedhtml' => base64_encode($jhtml), + '$tw' => $tw, + '$th' => $th, + '$turl' => $j->thumbnail_url, + )); + } else { + $ret = $jhtml; + } + break; + case "photo": + $ret .= ''; + break; + case "link": + break; + case "rich": + if (self::isAllowedURL($embedurl)) { + $ret .= proxy_parse_html($jhtml); + } + break; + } + + $ret .= '
'; + // add link to source if not present in "rich" type + if ($j->type != 'rich' || !strpos($j->html, $embedurl)) { + $ret .= '

'; + if (isset($j->title)) { + if (isset($j->provider_name)) { + $ret .= $j->provider_name . ": "; + } + + $embedlink = (isset($j->title)) ? $j->title : $embedurl; + $ret .= '' . $embedlink . ''; + if (isset($j->author_name)) { + $ret .= ' (' . $j->author_name . ')'; + } + } elseif (isset($j->provider_name) || isset($j->author_name)) { + $embedlink = ""; + if (isset($j->provider_name)) { + $embedlink .= $j->provider_name; + } + + if (isset($j->author_name)) { + if ($embedlink != "") { + $embedlink .= ": "; + } + + $embedlink .= $j->author_name; + } + if (trim($embedlink) == "") { + $embedlink = $embedurl; + } + + $ret .= '' . $embedlink . ''; + } + $ret .= "

"; + } elseif (!strpos($j->html, $embedurl)) { + // add for html2bbcode conversion + $ret .= '' . $j->title . ''; + } + + $ret = str_replace("\n", "", $ret); + return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret)); + } + + public static function BBCode2HTML($text) + { + $stopoembed = Config::get("system", "no_oembed"); + if ($stopoembed == true) { + return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "" . t('Embedding disabled') . " : $1", $text); + } + return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text); + } + + /** + * Find .... + * and replace it with [embed]url[/embed] + */ + public static function HTML2BBCode($text) + { + // start parser only if 'oembed' is in text + if (strpos($text, "oembed")) { + + // convert non ascii chars to html entities + $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text)); + + // If it doesn't parse at all, just return the text. + $dom = @DOMDocument::loadHTML($html_text); + if (!$dom) { + return $text; + } + $xpath = new DOMXPath($dom); + + $xattr = self::buildXPath("class", "oembed"); + $entries = $xpath->query("//div[$xattr]"); + + $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed"); + foreach ($entries as $e) { + $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue; + if (!is_null($href)) { + $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e); + } + } + return self::getInnerHTML($dom->getElementsByTagName("body")->item(0)); + } else { + return $text; + } + } + + /** + * Determines if rich content OEmbed is allowed for the provided URL + * + * @brief Determines if rich content OEmbed is allowed for the provided URL + * @param string $url + * @return boolean + */ + public static function isAllowedURL($url) + { + if (!Config::get('system', 'no_oembed_rich_content')) { + return true; + } + + $domain = parse_url($url, PHP_URL_HOST); + if (!x($domain)) { + return false; + } + + $str_allowed = Config::get('system', 'allowed_oembed', ''); + if (!x($str_allowed)) { + return false; + } + + $allowed = explode(',', $str_allowed); + + return allowed_domain($domain, $allowed); + } + + public static function getHTML($url, $title = null) + { + // Always embed the SSL version + $url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"), + array("https://www.youtube.com/", "https://player.vimeo.com/"), $url); + + $o = OEmbed::fetchURL($url); + + if (!is_object($o) || $o->type == 'error') { + throw new Exception('OEmbed failed for URL: ' . $url); + } + + if (x($title)) { + $o->title = $title; + } + + $html = OEmbed::formatObject($o); + + return $html; + } + + /** + * @brief Generates the iframe HTML for an oembed attachment. + * + * Width and height are given by the remote, and are regularly too small for + * the generated iframe. + * + * The width is entirely discarded for the actual width of the post, while fixed + * height is used as a starting point before the inevitable resizing. + * + * Since the iframe is automatically resized on load, there are no need for ugly + * and impractical scrollbars. + * + * @todo This function is currently unused until someoneā„¢ adds support for a separate OEmbed domain + * + * @param string $src Original remote URL to embed + * @param string $width + * @param string $height + * @return string formatted HTML + * + * @see oembed_format_object() + */ + private static function iframe($src, $width, $height) + { + $a = get_app(); + + if (!$height || strstr($height, '%')) { + $height = '200'; + } + $width = '100%'; + + $src = System::baseUrl() . '/oembed/' . base64url_encode($src); + return ''; + } + + /** + * Generates an XPath query to select elements whose provided attribute contains + * the provided value in a space-separated list. + * + * @brief Generates attribute search XPath string + * + * @param string $attr Name of the attribute to seach + * @param string $value Value to search in a space-separated list + * @return string + */ + private static function buildXPath($attr, $value) + { + // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath + return "contains(normalize-space(@$attr), ' $value ') or substring(normalize-space(@$attr), 1, string-length('$value') + 1) = '$value ' or substring(normalize-space(@$attr), string-length(@$attr) - string-length('$value')) = ' $value' or @$attr = '$value'"; + } + + /** + * Returns the inner XML string of a provided DOMNode + * + * @brief Returns the inner XML string of a provided DOMNode + * + * @param DOMNode $node + * @return string + */ + private static function getInnerHTML(DOMNode $node) + { + $innerHTML = ''; + $children = $node->childNodes; + foreach ($children as $child) { + $innerHTML .= $child->ownerDocument->saveXML($child); + } + return $innerHTML; + } + +} diff --git a/src/Core/Cache.php b/src/Core/Cache.php index e2673595c..dfb6591b9 100644 --- a/src/Core/Cache.php +++ b/src/Core/Cache.php @@ -109,7 +109,7 @@ class Cache // Frequently clear cache self::clear(); - $r = dba::select('cache', array('v'), array('k' => $key), array('limit' => 1)); + $r = dba::selectFirst('cache', ['v'], ['k' => $key]); if (DBM::is_result($r)) { $cached = $r['v']; diff --git a/src/Core/Config.php b/src/Core/Config.php index 9a270511c..3b08dee6b 100644 --- a/src/Core/Config.php +++ b/src/Core/Config.php @@ -97,7 +97,7 @@ class Config } } - $ret = dba::select('config', array('v'), array('cat' => $family, 'k' => $key), array('limit' => 1)); + $ret = dba::selectFirst('config', ['v'], ['cat' => $family, 'k' => $key]); if (DBM::is_result($ret)) { // manage array value $val = (preg_match("|^a:[0-9]+:{.*}$|s", $ret['v']) ? unserialize($ret['v']) : $ret['v']); diff --git a/src/Core/PConfig.php b/src/Core/PConfig.php index 4bc7193a0..50fea0446 100644 --- a/src/Core/PConfig.php +++ b/src/Core/PConfig.php @@ -90,7 +90,7 @@ class PConfig } } - $ret = dba::select('pconfig', array('v'), array('uid' => $uid, 'cat' => $family, 'k' => $key), array('limit' => 1)); + $ret = dba::selectFirst('pconfig', ['v'], ['uid' => $uid, 'cat' => $family, 'k' => $key]); if (DBM::is_result($ret)) { $val = (preg_match("|^a:[0-9]+:{.*}$|s", $ret['v']) ? unserialize($ret['v']) : $ret['v']); $a->config[$uid][$family][$key] = $val; diff --git a/src/Core/Worker.php b/src/Core/Worker.php index 55e2b33a0..96e4a5bb1 100644 --- a/src/Core/Worker.php +++ b/src/Core/Worker.php @@ -165,7 +165,7 @@ class Worker private static function highestPriority() { $condition = array("`executed` <= ? AND NOT `done`", NULL_DATE); - $s = dba::select('workerqueue', array('priority'), $condition, array('limit' => 1, 'order' => array('priority'))); + $s = dba::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]); if (DBM::is_result($s)) { return $s["priority"]; } else { @@ -772,9 +772,9 @@ class Worker // Are there waiting processes with a higher priority than the currently highest? $result = dba::select( 'workerqueue', - array('id'), - array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority), - array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true) + ['id'], + ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority], + ['limit' => $limit, 'order' => ['priority', 'created']] ); while ($id = dba::fetch($result)) { @@ -788,9 +788,9 @@ class Worker // Give slower processes some processing time $result = dba::select( 'workerqueue', - array('id'), - array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority), - array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true) + ['id'], + ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority], + ['limit' => $limit, 'order' => ['priority', 'created']] ); while ($id = dba::fetch($result)) { @@ -807,9 +807,9 @@ class Worker if (!$found) { $result = dba::select( 'workerqueue', - array('id'), - array("`executed` <= ? AND NOT `done`", NULL_DATE), - array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true) + ['id'], + ["`executed` <= ? AND NOT `done`", NULL_DATE], + ['limit' => $limit, 'order' => ['priority', 'created']] ); while ($id = dba::fetch($result)) { diff --git a/src/Model/Contact.php b/src/Model/Contact.php index b0f5ef9f2..a78c796ed 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -103,7 +103,7 @@ class Contact extends BaseObject return true; } - $user = dba::select('user', ['uid', 'username', 'nickname'], ['uid' => $uid], ['limit' => 1]); + $user = dba::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]); if (!DBM::is_result($user)) { return false; } @@ -145,7 +145,7 @@ class Contact extends BaseObject public static function remove($id) { // We want just to make sure that we don't delete our "self" contact - $r = dba::select('contact', array('uid'), array('id' => $id, 'self' => false), array('limit' => 1)); + $r = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]); if (!DBM::is_result($r) || !intval($r['uid'])) { return; @@ -490,7 +490,7 @@ class Contact extends BaseObject return $menu; } - $r = dba::select('contact', array(), array('nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid), array('limit' => 1)); + $r = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]); if ($r) { return self::photoMenu($r, $uid); } else { @@ -653,18 +653,18 @@ class Contact extends BaseObject /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following // We first try the nurl (http://server.tld/nick), most common case - $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1)); + $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]); // Then the addr (nick@server.tld) if (!DBM::is_result($contact)) { - $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1)); + $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['addr' => $url, 'uid' => $uid]); } // Then the alias (which could be anything) if (!DBM::is_result($contact)) { // The link could be provided as http although we stored it as https $ssl_url = str_replace('http://', 'https://', $url); - $r = dba::select('contact', array('id', 'avatar', 'avatar-date'), array('`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid), array('limit' => 1)); + $r = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid]); $contact = dba::fetch($r); dba::close($r); } @@ -697,7 +697,7 @@ class Contact extends BaseObject } // Get data from the gcontact table - $gcontacts = dba::select('gcontact', array('name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'), array('nurl' => normalise_link($url)), array('limit' => 1)); + $gcontacts = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]); if (!DBM::is_result($gcontacts)) { return 0; } @@ -735,7 +735,7 @@ class Contact extends BaseObject $contact_id = $contacts[0]["id"]; // Update the newly created contact from data in the gcontact table - $gcontact = dba::select('gcontact', array('location', 'about', 'keywords', 'gender'), array('nurl' => normalise_link($data["url"])), array('limit' => 1)); + $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]); if (DBM::is_result($gcontact)) { // Only use the information when the probing hadn't fetched these values if ($data['keywords'] != '') { @@ -758,8 +758,8 @@ class Contact extends BaseObject self::updateAvatar($data["photo"], $uid, $contact_id); - $fields = array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'); - $contact = dba::select('contact', $fields, array('id' => $contact_id), array('limit' => 1)); + $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey']; + $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]); // This condition should always be true if (!DBM::is_result($contact)) { @@ -817,7 +817,7 @@ class Contact extends BaseObject return false; } - $blocked = dba::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1)); + $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]); if (!DBM::is_result($blocked)) { return false; } @@ -837,7 +837,7 @@ class Contact extends BaseObject return false; } - $hidden = dba::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1)); + $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]); if (!DBM::is_result($hidden)) { return false; } @@ -980,7 +980,7 @@ class Contact extends BaseObject public static function updateAvatar($avatar, $uid, $cid, $force = false) { // Limit = 1 returns the row so no need for dba:inArray() - $r = dba::select('contact', array('avatar', 'photo', 'thumb', 'micro', 'nurl'), array('id' => $cid), array('limit' => 1)); + $r = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]); if (!DBM::is_result($r)) { return false; } else { @@ -999,7 +999,7 @@ class Contact extends BaseObject // Update the public contact (contact id = 0) if ($uid != 0) { - $pcontact = dba::select('contact', array('id'), array('nurl' => $r[0]['nurl']), array('limit' => 1)); + $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $r[0]['nurl']]); if (DBM::is_result($pcontact)) { self::updateAvatar($avatar, 0, $pcontact['id'], $force); } @@ -1023,7 +1023,7 @@ class Contact extends BaseObject This will reliably kill your communication with Friendica contacts. */ - $r = dba::select('contact', ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'], ['id' => $id], ['limit' => 1]); + $r = dba::selectFirst('contact', ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'], ['id' => $id]); if (!DBM::is_result($r)) { return false; } @@ -1246,7 +1246,7 @@ class Contact extends BaseObject ); } - $r = dba::select('contact', ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid], ['limit' => 1]); + $r = dba::selectFirst('contact', ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]); if (!DBM::is_result($r)) { $result['message'] .= t('Unable to retrieve contact information.') . EOL; diff --git a/src/Model/GContact.php b/src/Model/GContact.php index 830f80e92..510afdf16 100644 --- a/src/Model/GContact.php +++ b/src/Model/GContact.php @@ -888,7 +888,7 @@ class GContact 'network', 'bd', 'gender', 'keywords', 'alias', 'contact-type', 'url', 'location', 'about'); - $old_contact = dba::select('contact', $fields, array('id' => $r[0]["id"]), array('limit' => 1)); + $old_contact = dba::selectFirst('contact', $fields, ['id' => $r[0]["id"]]); // Update it with the current values $fields = array('name' => $contact['name'], 'nick' => $contact['nick'], diff --git a/src/Model/Group.php b/src/Model/Group.php index db9ec331e..1746a3962 100644 --- a/src/Model/Group.php +++ b/src/Model/Group.php @@ -39,7 +39,7 @@ class Group extends BaseObject // all the old members are gone, but the group remains so we don't break any security // access lists. What we're doing here is reviving the dead group, but old content which // was restricted to this group may now be seen by the new group members. - $group = dba::select('group', ['deleted'], ['id' => $gid], ['limit' => 1]); + $group = dba::selectFirst('group', ['deleted'], ['id' => $gid]); if (DBM::is_result($group) && $group['deleted']) { dba::update('group', ['deleted' => 0], ['gid' => $gid]); notice(t('A deleted group with this name was revived. Existing item permissions may apply to this group and any future members. If this is not what you intended, please create another group with a different name.') . EOL); @@ -120,7 +120,7 @@ class Group extends BaseObject return false; } - $group = dba::select('group', ['id'], ['uid' => $uid, 'name' => $name], ['limit' => 1]); + $group = dba::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]); if (DBM::is_result($group)) { return $group['id']; } @@ -139,13 +139,13 @@ class Group extends BaseObject return false; } - $group = dba::select('group', ['uid'], ['gid' => $gid], ['limit' => 1]); + $group = dba::selectFirst('group', ['uid'], ['gid' => $gid]); if (!DBM::is_result($group)) { return false; } // remove group from default posting lists - $user = dba::select('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']], ['limit' => 1]); + $user = dba::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']]); if (DBM::is_result($user)) { $change = false; diff --git a/src/Model/Photo.php b/src/Model/Photo.php index a25b2fa9d..a91636b67 100644 --- a/src/Model/Photo.php +++ b/src/Model/Photo.php @@ -38,14 +38,14 @@ class Photo */ public static function store(Image $Image, $uid, $cid, $rid, $filename, $album, $scale, $profile = 0, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '', $desc = '') { - $r = dba::select('photo', array('guid'), array("`resource-id` = ? AND `guid` != ?", $rid, ''), array('limit' => 1)); + $r = dba::selectFirst('photo', ['guid'], ["`resource-id` = ? AND `guid` != ?", $rid, '']); if (DBM::is_result($r)) { $guid = $r['guid']; } else { $guid = get_guid(); } - $x = dba::select('photo', array('id'), array('resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale), array('limit' => 1)); + $x = dba::selectFirst('photo', ['id'], ['resource-id' => $rid, 'uid' => $uid, 'contact-id' => $cid, 'scale' => $scale]); $fields = array( 'uid' => $uid, @@ -88,8 +88,8 @@ class Photo */ public static function importProfilePhoto($photo, $uid, $cid, $quit_on_error = false) { - $r = dba::select( - 'photo', array('resource-id'), array('uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos'), array('limit' => 1) + $r = dba::selectFirst( + 'photo', ['resource-id'], ['uid' => $uid, 'contact-id' => $cid, 'scale' => 4, 'album' => 'Contact Photos'] ); if (DBM::is_result($r) && strlen($r['resource-id'])) { diff --git a/src/Model/Term.php b/src/Model/Term.php index 07dec5213..5f536cae4 100644 --- a/src/Model/Term.php +++ b/src/Model/Term.php @@ -16,13 +16,11 @@ class Term */ public static function createFromItem($itemid) { - $messages = dba::select('item', ['uid', 'deleted', 'file'], ['id' => $itemid], ['limit' => 1]); - if (!$messages) { + $message = dba::selectFirst('item', ['uid', 'deleted', 'file'], ['id' => $itemid]); + if (!\Friendica\Database\DBM::is_result($message)) { return; } - $message = $messages[0]; - // Clean up all tags q("DELETE FROM `term` WHERE `otype` = %d AND `oid` = %d AND `type` IN (%d, %d)", intval(TERM_OBJ_POST), @@ -30,18 +28,31 @@ class Term intval(TERM_FILE), intval(TERM_CATEGORY)); - if ($message["deleted"]) + if ($message["deleted"]) { return; + } if (preg_match_all("/\[(.*?)\]/ism", $message["file"], $files)) { foreach ($files[1] as $file) { - dba::insert('term', ['uid' => $message["uid"], 'oid' => $itemid, 'otype' => TERM_OBJ_POST, 'type' => TERM_FILE, 'term' => $file]); + dba::insert('term', [ + 'uid' => $message["uid"], + 'oid' => $itemid, + 'otype' => TERM_OBJ_POST, + 'type' => TERM_FILE, + 'term' => $file + ]); } } if (preg_match_all("/\<(.*?)\>/ism", $message["file"], $files)) { foreach ($files[1] as $file) { - dba::insert('term', ['uid' => $message["uid"], 'oid' => $itemid, 'otype' => TERM_OBJ_POST, 'type' => TERM_CATEGORY, 'term' => $file]); + dba::insert('term', [ + 'uid' => $message["uid"], + 'oid' => $itemid, + 'otype' => TERM_OBJ_POST, + 'type' => TERM_CATEGORY, + 'term' => $file + ]); } } } diff --git a/src/Model/User.php b/src/Model/User.php index c6d6c044d..7a6faaf66 100644 --- a/src/Model/User.php +++ b/src/Model/User.php @@ -84,7 +84,7 @@ class User return $default_group; } - $user = dba::select('user', ['def_gid'], ['uid' => $uid], ['limit' => 1]); + $user = dba::selectFirst('user', ['def_gid'], ['uid' => $uid]); if (DBM::is_result($user)) { $default_group = $user["def_gid"]; @@ -112,16 +112,14 @@ class User if (is_object($user_info)) { $user = (array) $user_info; } elseif (is_int($user_info)) { - $user = dba::select('user', - ['uid', 'password'], + $user = dba::selectFirst('user', ['uid', 'password'], [ 'uid' => $user_info, 'blocked' => 0, 'account_expired' => 0, 'account_removed' => 0, 'verified' => 1 - ], - ['limit' => 1] + ] ); } elseif (is_string($user_info)) { $user = dba::fetch_first('SELECT `uid`, `password` @@ -330,7 +328,7 @@ class User if ($insert_result) { $uid = dba::lastInsertId(); - $user = dba::select('user', [], ['uid' => $uid], ['limit' => 1]); + $user = dba::selectFirst('user', [], ['uid' => $uid]); } else { throw new Exception(t('An error occurred during registration. Please try again.')); } @@ -532,7 +530,7 @@ class User logger('Removing user: ' . $uid); - $user = dba::select('user', [], ['uid' => $uid], ['limit' => 1]); + $user = dba::selectFirst('user', [], ['uid' => $uid]); call_hooks('remove_user', $user); diff --git a/src/Module/Login.php b/src/Module/Login.php index b90ba9d1d..8ba4f1035 100644 --- a/src/Module/Login.php +++ b/src/Module/Login.php @@ -1,311 +1,306 @@ -get_baseurl()); - } - - return self::form(self::getApp()->get_baseurl(), $a->config['register_policy'] != REGISTER_CLOSED); - } - - public static function post() - { - session_unset(); - // OpenId Login - if ( - !x($_POST, 'password') - && ( - x($_POST, 'openid_url') - || x($_POST, 'username') - ) - ) { - $noid = Config::get('system', 'no_openid'); - - $openid_url = trim($_POST['openid_url'] ? : $_POST['username']); - - // if it's an email address or doesn't resolve to a URL, fail. - if ($noid || strpos($openid_url, '@') || !validate_url($openid_url)) { - notice(t('Login failed.') . EOL); - goaway(self::getApp()->get_baseurl()); - // NOTREACHED - } - - // Otherwise it's probably an openid. - try { - require_once 'library/openid.php'; - $openid = new LightOpenID; - $openid->identity = $openid_url; - $_SESSION['openid'] = $openid_url; - $_SESSION['remember'] = $_POST['remember']; - $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid'; - goaway($openid->authUrl()); - } catch (Exception $e) { - notice(t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '

' . t('The error message was:') . ' ' . $e->getMessage()); - } - // NOTREACHED - } - - if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') { - $record = null; - - $addon_auth = array( - 'username' => trim($_POST['username']), - 'password' => trim($_POST['password']), - 'authenticated' => 0, - 'user_record' => null - ); - - /* - * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record - * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained - * and later plugins should not interfere with an earlier one that succeeded. - */ - call_hooks('authenticate', $addon_auth); - - if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) { - $record = $addon_auth['user_record']; - } else { - $user_id = User::authenticate(trim($_POST['username']), trim($_POST['password'])); - if ($user_id) { - $record = dba::select('user', [], ['uid' => $user_id], ['limit' => 1]); - } - } - - if (!$record || !count($record)) { - logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']); - notice(t('Login failed.') . EOL); - goaway(self::getApp()->get_baseurl()); - } - - if (!$_POST['remember']) { - new_cookie(0); // 0 means delete on browser exit - } - - // if we haven't failed up this point, log them in. - $_SESSION['remember'] = $_POST['remember']; - $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC'); - authenticate_success($record, true, true); - - if (x($_SESSION, 'return_url')) { - $return_url = $_SESSION['return_url']; - unset($_SESSION['return_url']); - } else { - $return_url = ''; - } - - goaway($return_url); - } - } - - /** - * @brief Tries to auth the user from the cookie or session - * - * @todo Should be moved to Friendica\Core\Session when it's created - */ - public static function sessionAuth() - { - // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie. - if (isset($_COOKIE["Friendica"])) { - $data = json_decode($_COOKIE["Friendica"]); - if (isset($data->uid)) { - - $user = dba::select('user', - [], - [ - 'uid' => $data->uid, - 'blocked' => false, - 'account_expired' => false, - 'account_removed' => false, - 'verified' => true, - ], - ['limit' => 1] - ); - - if (DBM::is_result($user)) { - if ($data->hash != cookie_hash($user)) { - logger("Hash for user " . $data->uid . " doesn't fit."); - nuke_session(); - goaway(self::getApp()->get_baseurl()); - } - - // Renew the cookie - // Expires after 7 days by default, - // can be set via system.auth_cookie_lifetime - $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7); - new_cookie($authcookiedays * 24 * 60 * 60, $user); - - // Do the authentification if not done by now - if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) { - authenticate_success($user); - - if (Config::get('system', 'paranoia')) { - $_SESSION['addr'] = $data->ip; - } - } - } - } - } - - if (isset($_SESSION) && x($_SESSION, 'authenticated')) { - if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) { - $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", - intval($_SESSION['visitor_id']) - ); - if (DBM::is_result($r)) { - $a->contact = $r[0]; - } - } - - if (x($_SESSION, 'uid')) { - // already logged in user returning - $check = Config::get('system', 'paranoia'); - // extra paranoia - if the IP changed, log them out - if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) { - logger('Session address changed. Paranoid setting in effect, blocking session. ' . - $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']); - nuke_session(); - goaway(self::getApp()->get_baseurl()); - } - - $user = dba::select('user', - [], - [ - 'uid' => $_SESSION['uid'], - 'blocked' => false, - 'account_expired' => false, - 'account_removed' => false, - 'verified' => true, - ], - ['limit' => 1] - ); - if (!DBM::is_result($user)) { - nuke_session(); - goaway(self::getApp()->get_baseurl()); - } - - // Make sure to refresh the last login time for the user if the user - // stays logged in for a long time, e.g. with "Remember Me" - $login_refresh = false; - if (!x($_SESSION['last_login_date'])) { - $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC'); - } - if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) { - $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC'); - $login_refresh = true; - } - authenticate_success($user, false, false, $login_refresh); - } - } - } - - /** - * @brief Wrapper for adding a login box. - * - * @param string $return_url The url relative to the base the user should be sent - * back to after login completes - * @param bool $register If $register == true provide a registration link. - * This will most always depend on the value of $a->config['register_policy']. - * @param array $hiddens optional - * - * @return string Returns the complete html for inserting into the page - * - * @hooks 'login_hook' string $o - */ - public static function form($return_url = null, $register = false, $hiddens = []) - { - $a = self::getApp(); - $o = ''; - $reg = false; - if ($register) { - $reg = array( - 'title' => t('Create a New Account'), - 'desc' => t('Register') - ); - } - - $noid = Config::get('system', 'no_openid'); - - if (is_null($return_url)) { - $return_url = $a->query_string; - } - - if (local_user()) { - $tpl = get_markup_template('logout.tpl'); - } else { - $a->page['htmlhead'] .= replace_macros( - get_markup_template('login_head.tpl'), - [ - '$baseurl' => $a->get_baseurl(true) - ] - ); - - $tpl = get_markup_template('login.tpl'); - $_SESSION['return_url'] = $return_url; - } - - $o .= replace_macros( - $tpl, - [ - '$dest_url' => self::getApp()->get_baseurl(true) . '/login', - '$logout' => t('Logout'), - '$login' => t('Login'), - - '$lname' => array('username', t('Nickname or Email: ') , '', ''), - '$lpassword' => array('password', t('Password: '), '', ''), - '$lremember' => array('remember', t('Remember me'), 0, ''), - - '$openid' => !$noid, - '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''), - - '$hiddens' => $hiddens, - - '$register' => $reg, - - '$lostpass' => t('Forgot your password?'), - '$lostlink' => t('Password Reset'), - - '$tostitle' => t('Website Terms of Service'), - '$toslink' => t('terms of service'), - - '$privacytitle' => t('Website Privacy Policy'), - '$privacylink' => t('privacy policy'), - ] - ); - - call_hooks('login_hook', $o); - - return $o; - } -} +get_baseurl()); + } + + return self::form(self::getApp()->get_baseurl(), $a->config['register_policy'] != REGISTER_CLOSED); + } + + public static function post() + { + session_unset(); + // OpenId Login + if ( + !x($_POST, 'password') + && ( + x($_POST, 'openid_url') + || x($_POST, 'username') + ) + ) { + $noid = Config::get('system', 'no_openid'); + + $openid_url = trim($_POST['openid_url'] ? : $_POST['username']); + + // if it's an email address or doesn't resolve to a URL, fail. + if ($noid || strpos($openid_url, '@') || !validate_url($openid_url)) { + notice(t('Login failed.') . EOL); + goaway(self::getApp()->get_baseurl()); + // NOTREACHED + } + + // Otherwise it's probably an openid. + try { + require_once 'library/openid.php'; + $openid = new LightOpenID; + $openid->identity = $openid_url; + $_SESSION['openid'] = $openid_url; + $_SESSION['remember'] = $_POST['remember']; + $openid->returnUrl = self::getApp()->get_baseurl(true) . '/openid'; + goaway($openid->authUrl()); + } catch (Exception $e) { + notice(t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '

' . t('The error message was:') . ' ' . $e->getMessage()); + } + // NOTREACHED + } + + if (x($_POST, 'auth-params') && $_POST['auth-params'] === 'login') { + $record = null; + + $addon_auth = array( + 'username' => trim($_POST['username']), + 'password' => trim($_POST['password']), + 'authenticated' => 0, + 'user_record' => null + ); + + /* + * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record + * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained + * and later plugins should not interfere with an earlier one that succeeded. + */ + call_hooks('authenticate', $addon_auth); + + if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) { + $record = $addon_auth['user_record']; + } else { + $user_id = User::authenticate(trim($_POST['username']), trim($_POST['password'])); + if ($user_id) { + $record = dba::selectFirst('user', [], ['uid' => $user_id]); + } + } + + if (!$record || !count($record)) { + logger('authenticate: failed login attempt: ' . notags(trim($_POST['username'])) . ' from IP ' . $_SERVER['REMOTE_ADDR']); + notice(t('Login failed.') . EOL); + goaway(self::getApp()->get_baseurl()); + } + + if (!$_POST['remember']) { + new_cookie(0); // 0 means delete on browser exit + } + + // if we haven't failed up this point, log them in. + $_SESSION['remember'] = $_POST['remember']; + $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC'); + authenticate_success($record, true, true); + + if (x($_SESSION, 'return_url')) { + $return_url = $_SESSION['return_url']; + unset($_SESSION['return_url']); + } else { + $return_url = ''; + } + + goaway($return_url); + } + } + + /** + * @brief Tries to auth the user from the cookie or session + * + * @todo Should be moved to Friendica\Core\Session when it's created + */ + public static function sessionAuth() + { + // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie. + if (isset($_COOKIE["Friendica"])) { + $data = json_decode($_COOKIE["Friendica"]); + if (isset($data->uid)) { + + $user = dba::selectFirst('user', [], + [ + 'uid' => $data->uid, + 'blocked' => false, + 'account_expired' => false, + 'account_removed' => false, + 'verified' => true, + ] + ); + if (DBM::is_result($user)) { + if ($data->hash != cookie_hash($user)) { + logger("Hash for user " . $data->uid . " doesn't fit."); + nuke_session(); + goaway(self::getApp()->get_baseurl()); + } + + // Renew the cookie + // Expires after 7 days by default, + // can be set via system.auth_cookie_lifetime + $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7); + new_cookie($authcookiedays * 24 * 60 * 60, $user); + + // Do the authentification if not done by now + if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) { + authenticate_success($user); + + if (Config::get('system', 'paranoia')) { + $_SESSION['addr'] = $data->ip; + } + } + } + } + } + + if (isset($_SESSION) && x($_SESSION, 'authenticated')) { + if (x($_SESSION, 'visitor_id') && !x($_SESSION, 'uid')) { + $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", + intval($_SESSION['visitor_id']) + ); + if (DBM::is_result($r)) { + $a->contact = $r[0]; + } + } + + if (x($_SESSION, 'uid')) { + // already logged in user returning + $check = Config::get('system', 'paranoia'); + // extra paranoia - if the IP changed, log them out + if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) { + logger('Session address changed. Paranoid setting in effect, blocking session. ' . + $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']); + nuke_session(); + goaway(self::getApp()->get_baseurl()); + } + + $user = dba::selectFirst('user', [], + [ + 'uid' => $_SESSION['uid'], + 'blocked' => false, + 'account_expired' => false, + 'account_removed' => false, + 'verified' => true, + ] + ); + if (!DBM::is_result($user)) { + nuke_session(); + goaway(self::getApp()->get_baseurl()); + } + + // Make sure to refresh the last login time for the user if the user + // stays logged in for a long time, e.g. with "Remember Me" + $login_refresh = false; + if (!x($_SESSION['last_login_date'])) { + $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC'); + } + if (strcmp(datetime_convert('UTC', 'UTC', 'now - 12 hours'), $_SESSION['last_login_date']) > 0) { + $_SESSION['last_login_date'] = datetime_convert('UTC', 'UTC'); + $login_refresh = true; + } + authenticate_success($user, false, false, $login_refresh); + } + } + } + + /** + * @brief Wrapper for adding a login box. + * + * @param string $return_url The url relative to the base the user should be sent + * back to after login completes + * @param bool $register If $register == true provide a registration link. + * This will most always depend on the value of $a->config['register_policy']. + * @param array $hiddens optional + * + * @return string Returns the complete html for inserting into the page + * + * @hooks 'login_hook' string $o + */ + public static function form($return_url = null, $register = false, $hiddens = []) + { + $a = self::getApp(); + $o = ''; + $reg = false; + if ($register) { + $reg = array( + 'title' => t('Create a New Account'), + 'desc' => t('Register') + ); + } + + $noid = Config::get('system', 'no_openid'); + + if (is_null($return_url)) { + $return_url = $a->query_string; + } + + if (local_user()) { + $tpl = get_markup_template('logout.tpl'); + } else { + $a->page['htmlhead'] .= replace_macros( + get_markup_template('login_head.tpl'), + [ + '$baseurl' => $a->get_baseurl(true) + ] + ); + + $tpl = get_markup_template('login.tpl'); + $_SESSION['return_url'] = $return_url; + } + + $o .= replace_macros( + $tpl, + [ + '$dest_url' => self::getApp()->get_baseurl(true) . '/login', + '$logout' => t('Logout'), + '$login' => t('Login'), + + '$lname' => array('username', t('Nickname or Email: ') , '', ''), + '$lpassword' => array('password', t('Password: '), '', ''), + '$lremember' => array('remember', t('Remember me'), 0, ''), + + '$openid' => !$noid, + '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''), + + '$hiddens' => $hiddens, + + '$register' => $reg, + + '$lostpass' => t('Forgot your password?'), + '$lostlink' => t('Password Reset'), + + '$tostitle' => t('Website Terms of Service'), + '$toslink' => t('terms of service'), + + '$privacytitle' => t('Website Privacy Policy'), + '$privacylink' => t('privacy policy'), + ] + ); + + call_hooks('login_hook', $o); + + return $o; + } +} diff --git a/src/Network/FKOAuth1.php b/src/Network/FKOAuth1.php index ce2d4a6b8..07e15ad51 100644 --- a/src/Network/FKOAuth1.php +++ b/src/Network/FKOAuth1.php @@ -40,7 +40,7 @@ class FKOAuth1 extends OAuthServer { logger("FKOAuth1::loginUser $uid"); $a = get_app(); - $record = dba::select('user', array(), array('uid' => $uid, 'blocked' => 0, 'account_expired' => 0, 'account_removed' => 0, 'verified' => 1), array('limit' => 1)); + $record = dba::selectFirst('user', [], ['uid' => $uid, 'blocked' => 0, 'account_expired' => 0, 'account_removed' => 0, 'verified' => 1]); if (!DBM::is_result($record)) { logger('FKOAuth1::loginUser failure: ' . print_r($_SERVER, true), LOGGER_DEBUG); @@ -63,7 +63,7 @@ class FKOAuth1 extends OAuthServer $a->timezone = $a->user['timezone']; } - $r = dba::select('contact', array(), array('uid' => $_SESSION['uid'], 'self' => 1), array('limit' => 1)); + $r = dba::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => 1]); if (DBM::is_result($r)) { $a->contact = $r; diff --git a/src/Network/FKOAuthDataStore.php b/src/Network/FKOAuthDataStore.php index 424b6391e..ccb08ccbb 100644 --- a/src/Network/FKOAuthDataStore.php +++ b/src/Network/FKOAuthDataStore.php @@ -88,7 +88,7 @@ class FKOAuthDataStore extends OAuthDataStore */ public function lookup_nonce($consumer, $token, $nonce, $timestamp) { - $r = dba::select('tokens', ['id', 'secret'], ['client_id' => $consumer->key, 'id' => $nonce, 'expires' => $timestamp], ['limit' => 1]); + $r = dba::selectFirst('tokens', ['id', 'secret'], ['client_id' => $consumer->key, 'id' => $nonce, 'expires' => $timestamp]); if (DBM::is_result($r)) { return new \OAuthToken($r['id'], $r['secret']); diff --git a/src/Network/Probe.php b/src/Network/Probe.php index 8912088cb..57c1ed284 100644 --- a/src/Network/Probe.php +++ b/src/Network/Probe.php @@ -406,7 +406,7 @@ class Probe $condition = array('nurl' => normalise_link($data["url"])); - $old_fields = dba::select('gcontact', $fieldnames, $condition, array('limit' => 1)); + $old_fields = dba::selectFirst('gcontact', $fieldnames, $condition); dba::update('gcontact', $fields, $condition, $old_fields); @@ -439,7 +439,7 @@ class Probe $condition = array('nurl' => normalise_link($data["url"]), 'self' => false, 'uid' => 0); - $old_fields = dba::select('contact', $fieldnames, $condition, array('limit' => 1)); + $old_fields = dba::selectFirst('contact', $fieldnames, $condition); dba::update('contact', $fields, $condition, $old_fields); } diff --git a/src/Object/Post.php b/src/Object/Post.php index 260afa662..c5b97fc13 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -261,7 +261,7 @@ class Post extends BaseObject 'classundo' => $item['starred'] ? "" : "hidden", 'starred' => t('starred'), ); - $r = dba::select('thread', array('ignored'), array('uid' => $item['uid'], 'iid' => $item['id']), array('limit' => 1)); + $r = dba::selectFirst('thread', ['ignored'], ['uid' => $item['uid'], 'iid' => $item['id']]); if (DBM::is_result($r)) { $ignore = array( 'do' => t("ignore thread"), diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index 6b5f5d576..23220d04c 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -2015,7 +2015,7 @@ class Diaspora // like on comments have the comment as parent. So we need to fetch the toplevel parent if ($parent_item["id"] != $parent_item["parent"]) { - $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1)); + $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]); $origin = $toplevel["origin"]; } else { $origin = $parent_item["origin"]; @@ -2317,7 +2317,7 @@ class Diaspora $arr["last-child"] = 1; - $user = dba::select('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]], ['limit' => 1]); + $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]); $arr["allow_cid"] = $user["allow_cid"]; $arr["allow_gid"] = $user["allow_gid"]; @@ -2741,7 +2741,7 @@ class Diaspora while ($item = dba::fetch($r)) { // Fetch the parent item - $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1)); + $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]); // Only delete it if the parent author really fits if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) { @@ -3255,7 +3255,7 @@ class Diaspora // If the item belongs to a user, we take this user id. if ($item['uid'] == 0) { $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]; - $first_user = dba::select('user', ['uid'], $condition, ['limit' => 1]); + $first_user = dba::selectFirst('user', ['uid'], $condition); $owner = User::getOwnerDataById($first_user['uid']); } else { $owner = User::getOwnerDataById($item['uid']); diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index b12b5c932..af57ced7d 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -254,7 +254,7 @@ class Feed { if (!$simulate) { $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)", $importer["uid"], $item["uri"], NETWORK_FEED, NETWORK_DFRN]; - $previous = dba::select('item', ['id'], $condition, ['limit' => 1]); + $previous = dba::selectFirst('item', ['id'], $condition); if (DBM::is_result($previous)) { logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], LOGGER_DEBUG); continue; diff --git a/src/Protocol/OStatus.php b/src/Protocol/OStatus.php index 1140f7a4e..242af4604 100644 --- a/src/Protocol/OStatus.php +++ b/src/Protocol/OStatus.php @@ -70,9 +70,9 @@ class OStatus $found = false; if ($aliaslink != '') { - $condition = array("`uid` = ? AND `alias` = ? AND `network` != ?", - $importer["uid"], $aliaslink, NETWORK_STATUSNET); - $r = dba::select('contact', array(), $condition, array('limit' => 1)); + $condition = ["`uid` = ? AND `alias` = ? AND `network` != ?", + $importer["uid"], $aliaslink, NETWORK_STATUSNET]; + $r = dba::selectFirst('contact', [], $condition); if (DBM::is_result($r)) { $found = true; @@ -89,9 +89,9 @@ class OStatus $aliaslink = $author["author-link"]; } - $condition = array("`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"], - normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET); - $r = dba::select('contact', array(), $condition, array('limit' => 1)); + $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ?", $importer["uid"], + normalise_link($author["author-link"]), normalise_link($aliaslink), NETWORK_STATUSNET]; + $r = dba::selectFirst('contact', [], $condition); if (DBM::is_result($r)) { $found = true; @@ -104,9 +104,9 @@ class OStatus } if (!$found && ($addr != "")) { - $condition = array("`uid` = ? AND `addr` = ? AND `network` != ?", - $importer["uid"], $addr, NETWORK_STATUSNET); - $r = dba::select('contact', array(), $condition, array('limit' => 1)); + $condition = ["`uid` = ? AND `addr` = ? AND `network` != ?", + $importer["uid"], $addr, NETWORK_STATUSNET]; + $r = dba::selectFirst('contact', [], $condition); if (DBM::is_result($r)) { $found = true; @@ -207,8 +207,8 @@ class OStatus $cid = Contact::getIdForURL($aliaslink, 0); if ($cid) { - $fields = array('url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'); - $old_contact = dba::select('contact', $fields, array('id' => $cid), array('limit' => 1)); + $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location']; + $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]); // Update it with the current values $fields = array('url' => $author["author-link"], 'name' => $contact["name"], @@ -541,8 +541,8 @@ class OStatus */ private static function deleteNotice($item) { - $condition = array('uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']); - $deleted = dba::select('item', array('id', 'parent-uri'), $condition, array('limit' => 1)); + $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']]; + $deleted = dba::selectFirst('item', ['id', 'parent-uri'], $condition); if (!DBM::is_result($deleted)) { logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it. "); return; @@ -895,8 +895,8 @@ class OStatus */ private static function fetchRelated($related, $related_uri, $importer) { - $condition = array('`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON); - $conversation = dba::select('conversation', array('source', 'protocol'), $condition, array('limit' => 1)); + $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON]; + $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition); if (DBM::is_result($conversation)) { $stored = true; $xml = $conversation['source']; @@ -975,8 +975,8 @@ class OStatus // Finally we take the data that we fetched from "ostatus:conversation" if ($xml == '') { - $condition = array('item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV); - $conversation = dba::select('conversation', array('source'), $condition, array('limit' => 1)); + $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV]; + $conversation = dba::selectFirst('conversation', ['source'], $condition); if (DBM::is_result($conversation)) { $stored = true; logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG); diff --git a/src/Protocol/PortableContact.php b/src/Protocol/PortableContact.php index 1ff0594ca..f579a4019 100644 --- a/src/Protocol/PortableContact.php +++ b/src/Protocol/PortableContact.php @@ -66,7 +66,7 @@ class PortableContact if ($cid) { if (!$url || !$uid) { - $r = dba::select('contact', ['poco', 'uid'], ['id' => $cid], ['limit' => 1]); + $r = dba::selectFirst('contact', ['poco', 'uid'], ['id' => $cid]); if (DBM::is_result($r)) { $url = $r['poco']; $uid = $r['uid']; @@ -813,7 +813,7 @@ class PortableContact return false; } - $servers = dba::select('gserver', [], ['nurl' => normalise_link($server_url)], ['limit' => 1]); + $servers = dba::selectFirst('gserver', [], ['nurl' => normalise_link($server_url)]); if (DBM::is_result($servers)) { if ($servers["created"] <= NULL_DATE) { $fields = ['created' => datetime_convert()]; diff --git a/src/Util/ExAuth.php b/src/Util/ExAuth.php index b030169d8..5ae24534a 100644 --- a/src/Util/ExAuth.php +++ b/src/Util/ExAuth.php @@ -226,7 +226,7 @@ class ExAuth if ($a->get_hostname() == $aCommand[2]) { $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]); - $aUser = dba::select('user', ['uid', 'password'], ['nickname' => $sUser], ['limit' => 1]); + $aUser = dba::selectFirst('user', ['uid', 'password'], ['nickname' => $sUser]); if (DBM::is_result($aUser)) { $uid = $aUser['uid']; $success = User::authenticate($aUser, $aCommand[3]); diff --git a/src/Util/Lock.php b/src/Util/Lock.php index 87590c295..66a568811 100644 --- a/src/Util/Lock.php +++ b/src/Util/Lock.php @@ -126,7 +126,7 @@ class Lock do { dba::lock('locks'); - $lock = dba::select('locks', array('locked', 'pid'), array('name' => $fn_name), array('limit' => 1)); + $lock = dba::selectFirst('locks', ['locked', 'pid'], ['name' => $fn_name]); if (DBM::is_result($lock)) { if ($lock['locked']) { diff --git a/src/Worker/Expire.php b/src/Worker/Expire.php index e963d6d35..9b2308da3 100644 --- a/src/Worker/Expire.php +++ b/src/Worker/Expire.php @@ -39,7 +39,7 @@ class Expire { } return; } elseif (intval($param) > 0) { - $user = dba::select('user', array('uid', 'username', 'expire'), array('uid' => $param), array('limit' => 1)); + $user = dba::selectFirst('user', ['uid', 'username', 'expire'], ['uid' => $param]); if (DBM::is_result($user)) { logger('Expire items for user '.$user['uid'].' ('.$user['username'].') - interval: '.$user['expire'], LOGGER_DEBUG); item_expire($user['uid'], $user['expire']); diff --git a/src/Worker/Notifier.php b/src/Worker/Notifier.php index 5c86a95ef..710bcfa13 100644 --- a/src/Worker/Notifier.php +++ b/src/Worker/Notifier.php @@ -265,9 +265,9 @@ class Notifier { ($owner['id'] != $target_item['contact-id']) && ($target_item['uri'] === $target_item['parent-uri'])) { - $fields = array('forum', 'prv'); - $condition = array('id' => $target_item['contact-id']); - $contact = dba::select('contact', $fields, $condition, array('limit' => 1)); + $fields = ['forum', 'prv']; + $condition = ['id' => $target_item['contact-id']]; + $contact = dba::selectFirst('contact', $fields, $condition); if (!DBM::is_result($contact)) { // Should never happen return false; diff --git a/src/Worker/OnePoll.php b/src/Worker/OnePoll.php index a527bf0da..08dd23ad8 100644 --- a/src/Worker/OnePoll.php +++ b/src/Worker/OnePoll.php @@ -42,7 +42,7 @@ Class OnePoll $d = datetime_convert(); - $contact = dba::select('contact', [], ['id' => $contact_id], ['limit' => 1]); + $contact = dba::selectFirst('contact', [], ['id' => $contact_id]); if (!DBM::is_result($contact)) { logger('Contact not found or cannot be used.'); return; @@ -339,14 +339,14 @@ Class OnePoll logger("Mail: Enabled", LOGGER_DEBUG); $mbox = null; - $x = dba::select('user', array('prvkey'), array('uid' => $importer_uid), array('limit' => 1)); + $user = dba::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]); - $condition = array("`server` != '' AND `uid` = ?", $importer_uid); - $mailconf = dba::select('mailacct', array(), $condition, array('limit' => 1)); - if (DBM::is_result($x) && DBM::is_result($mailconf)) { + $condition = ["`server` != '' AND `uid` = ?", $importer_uid]; + $mailconf = dba::selectFirst('mailacct', [], $condition); + if (DBM::is_result($user) && DBM::is_result($mailconf)) { $mailbox = Email::constructMailboxName($mailconf); $password = ''; - openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $x['prvkey']); + openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']); $mbox = Email::connect($mailbox, $mailconf['user'], $password); unset($password); logger("Mail: Connect to " . $mailconf['user']); @@ -382,9 +382,9 @@ Class OnePoll $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>')); // Have we seen it before? - $fields = array('deleted', 'id'); - $condition = array('uid' => $importer_uid, 'uri' => $datarray['uri']); - $r = dba::select('item', $fields, $condition, array('limit' => 1)); + $fields = ['deleted', 'id']; + $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']]; + $r = dba::selectFirst('item', $fields, $condition); if (DBM::is_result($r)) { logger("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],LOGGER_DEBUG); diff --git a/src/Worker/Queue.php b/src/Worker/Queue.php index 179e37c07..1b8620a9d 100644 --- a/src/Worker/Queue.php +++ b/src/Worker/Queue.php @@ -80,7 +80,7 @@ class Queue $q_item = $r[0]; - $contact = dba::select('contact', [], ['id' => $q_item['cid']], ['limit' => 1]); + $contact = dba::selectFirst('contact', [], ['id' => $q_item['cid']]); if (!DBM::is_result($contact)) { remove_queue_item($q_item['id']); return; @@ -113,7 +113,7 @@ class Queue } } - $user = dba::select('user', [], ['uid' => $contact['uid']], ['limit' => 1]); + $user = dba::selectFirst('user', [], ['uid' => $contact['uid']]); if (!DBM::is_result($user)) { remove_queue_item($q_item['id']); return; diff --git a/util/global_community_silence.php b/util/global_community_silence.php index e6c936f0d..14cd06e7a 100755 --- a/util/global_community_silence.php +++ b/util/global_community_silence.php @@ -57,7 +57,7 @@ if (in_array($net['network'], array(NETWORK_PHANTOM, NETWORK_MAIL))) { exit(1); } $nurl = normalise_link($net['url']); -$r = dba::select("contact", array("id"), array("nurl" => $nurl, "uid" => 0), array("limit" => 1)); +$r = dba::selectFirst("contact", ["id"], ["nurl" => $nurl, "uid" => 0]); if (DBM::is_result($r)) { dba::update("contact", array("hidden" => true), array("id" => $r["id"])); echo "NOTICE: The account should be silenced from the global community page\r\n";