Issues (4122)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

includes/search/SearchPostgres.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * PostgreSQL search engine
4
 *
5
 * Copyright © 2006-2007 Greg Sabino Mullane <[email protected]>
6
 * https://www.mediawiki.org/
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 2 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License along
19
 * with this program; if not, write to the Free Software Foundation, Inc.,
20
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
 * http://www.gnu.org/copyleft/gpl.html
22
 *
23
 * @file
24
 * @ingroup Search
25
 */
26
27
/**
28
 * Search engine hook base class for Postgres
29
 * @ingroup Search
30
 */
31
class SearchPostgres extends SearchDatabase {
32
	/**
33
	 * Perform a full text search query via tsearch2 and return a result set.
34
	 * Currently searches a page's current title (page.page_title) and
35
	 * latest revision article text (pagecontent.old_text)
36
	 *
37
	 * @param string $term Raw search term
38
	 * @return SqlSearchResultSet
39
	 */
40 View Code Duplication
	function searchTitle( $term ) {
41
		$q = $this->searchQuery( $term, 'titlevector', 'page_title' );
42
		$olderror = error_reporting( E_ERROR );
43
		$resultSet = $this->db->query( $q, 'SearchPostgres', true );
44
		error_reporting( $olderror );
45
		return new SqlSearchResultSet( $resultSet, $this->searchTerms );
0 ignored issues
show
It seems like $resultSet defined by $this->db->query($q, 'SearchPostgres', true) on line 43 can also be of type boolean; however, SqlSearchResultSet::__construct() does only seem to accept object<ResultWrapper>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
46
	}
47
48 View Code Duplication
	function searchText( $term ) {
49
		$q = $this->searchQuery( $term, 'textvector', 'old_text' );
50
		$olderror = error_reporting( E_ERROR );
51
		$resultSet = $this->db->query( $q, 'SearchPostgres', true );
52
		error_reporting( $olderror );
53
		return new SqlSearchResultSet( $resultSet, $this->searchTerms );
0 ignored issues
show
It seems like $resultSet defined by $this->db->query($q, 'SearchPostgres', true) on line 51 can also be of type boolean; however, SqlSearchResultSet::__construct() does only seem to accept object<ResultWrapper>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
54
	}
55
56
	/**
57
	 * Transform the user's search string into a better form for tsearch2
58
	 * Returns an SQL fragment consisting of quoted text to search for.
59
	 *
60
	 * @param string $term
61
	 *
62
	 * @return string
63
	 */
64
	function parseQuery( $term ) {
65
		wfDebug( "parseQuery received: $term \n" );
66
67
		# # No backslashes allowed
68
		$term = preg_replace( '/\\\/', '', $term );
69
70
		# # Collapse parens into nearby words:
71
		$term = preg_replace( '/\s*\(\s*/', ' (', $term );
72
		$term = preg_replace( '/\s*\)\s*/', ') ', $term );
73
74
		# # Treat colons as word separators:
75
		$term = preg_replace( '/:/', ' ', $term );
76
77
		$searchstring = '';
78
		$m = [];
79
		if ( preg_match_all( '/([-!]?)(\S+)\s*/', $term, $m, PREG_SET_ORDER ) ) {
80
			foreach ( $m as $terms ) {
81
				if ( strlen( $terms[1] ) ) {
82
					$searchstring .= ' & !';
83
				}
84
				if ( strtolower( $terms[2] ) === 'and' ) {
85
					$searchstring .= ' & ';
86
				} elseif ( strtolower( $terms[2] ) === 'or' || $terms[2] === '|' ) {
87
					$searchstring .= ' | ';
88
				} elseif ( strtolower( $terms[2] ) === 'not' ) {
89
					$searchstring .= ' & !';
90
				} else {
91
					$searchstring .= " & $terms[2]";
92
				}
93
			}
94
		}
95
96
		# # Strip out leading junk
97
		$searchstring = preg_replace( '/^[\s\&\|]+/', '', $searchstring );
98
99
		# # Remove any doubled-up operators
100
		$searchstring = preg_replace( '/([\!\&\|]) +(?:[\&\|] +)+/', "$1 ", $searchstring );
101
102
		# # Remove any non-spaced operators (e.g. "Zounds!")
103
		$searchstring = preg_replace( '/([^ ])[\!\&\|]/', "$1", $searchstring );
104
105
		# # Remove any trailing whitespace or operators
106
		$searchstring = preg_replace( '/[\s\!\&\|]+$/', '', $searchstring );
107
108
		# # Remove unnecessary quotes around everything
109
		$searchstring = preg_replace( '/^[\'"](.*)[\'"]$/', "$1", $searchstring );
110
111
		# # Quote the whole thing
112
		$searchstring = $this->db->addQuotes( $searchstring );
113
114
		wfDebug( "parseQuery returned: $searchstring \n" );
115
116
		return $searchstring;
117
	}
118
119
	/**
120
	 * Construct the full SQL query to do the search.
121
	 * @param string $term
122
	 * @param string $fulltext
123
	 * @param string $colname
124
	 * @return string
125
	 */
126
	function searchQuery( $term, $fulltext, $colname ) {
127
		# Get the SQL fragment for the given term
128
		$searchstring = $this->parseQuery( $term );
129
130
		# # We need a separate query here so gin does not complain about empty searches
131
		$sql = "SELECT to_tsquery($searchstring)";
132
		$res = $this->db->query( $sql );
133
		if ( !$res ) {
134
			# # TODO: Better output (example to catch: one 'two)
135
			die( "Sorry, that was not a valid search string. Please go back and try again" );
0 ignored issues
show
Coding Style Compatibility introduced by
The method searchQuery() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
136
		}
137
		$top = $res->fetchRow()[0];
138
139
		$this->searchTerms = [];
140
		if ( $top === "" ) { # # e.g. if only stopwords are used XXX return something better
141
			$query = "SELECT page_id, page_namespace, page_title, 0 AS score " .
142
				"FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
143
				"AND r.rev_text_id = c.old_id AND 1=0";
144
		} else {
145
			$m = [];
146
			if ( preg_match_all( "/'([^']+)'/", $top, $m, PREG_SET_ORDER ) ) {
147
				foreach ( $m as $terms ) {
148
					$this->searchTerms[$terms[1]] = $terms[1];
149
				}
150
			}
151
152
			$query = "SELECT page_id, page_namespace, page_title, " .
153
				"ts_rank($fulltext, to_tsquery($searchstring), 5) AS score " .
154
				"FROM page p, revision r, pagecontent c WHERE p.page_latest = r.rev_id " .
155
				"AND r.rev_text_id = c.old_id AND $fulltext @@ to_tsquery($searchstring)";
156
		}
157
158
		# # Namespaces - defaults to 0
159
		if ( !is_null( $this->namespaces ) ) { // null -> search all
160
			if ( count( $this->namespaces ) < 1 ) {
161
				$query .= ' AND page_namespace = 0';
162
			} else {
163
				$namespaces = $this->db->makeList( $this->namespaces );
164
				$query .= " AND page_namespace IN ($namespaces)";
165
			}
166
		}
167
168
		$query .= " ORDER BY score DESC, page_id DESC";
169
170
		$query .= $this->db->limitResult( '', $this->limit, $this->offset );
0 ignored issues
show
It seems like you code against a concrete implementation and not the interface IDatabase as the method limitResult() does only exist in the following implementations of said interface: Database, DatabaseMysql, DatabaseMysqlBase, DatabaseMysqli, DatabasePostgres, DatabaseSqlite.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
171
172
		wfDebug( "searchQuery returned: $query \n" );
173
174
		return $query;
175
	}
176
177
	# # Most of the work of these two functions are done automatically via triggers
178
179
	function update( $pageid, $title, $text ) {
180
		# # We don't want to index older revisions
181
		$sql = "UPDATE pagecontent SET textvector = NULL WHERE textvector IS NOT NULL and old_id IN " .
182
				"(SELECT DISTINCT rev_text_id FROM revision WHERE rev_page = " . intval( $pageid ) .
183
				" ORDER BY rev_text_id DESC OFFSET 1)";
184
		$this->db->query( $sql );
185
		return true;
186
	}
187
188
	function updateTitle( $id, $title ) {
189
		return true;
190
	}
191
192
}
193