Issues (17)

Security Analysis    no request data  

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.

lib/ElectionProcess/VotesProcess.php (6 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
    Condorcet PHP - Election manager and results calculator.
4
    Designed for the Condorcet method. Integrating a large number of algorithms extending Condorcet. Expandable for all types of voting systems.
5
6
    By Julien Boudry and contributors - MIT LICENSE (Please read LICENSE.txt)
7
    https://github.com/julien-boudry/Condorcet
8
*/
9
declare(strict_types=1);
10
11
namespace CondorcetPHP\Condorcet\ElectionProcess;
12
13
use CondorcetPHP\Condorcet\{CondorcetUtil, Vote};
14
use CondorcetPHP\Condorcet\DataManager\VotesManager;
15
use CondorcetPHP\Condorcet\Throwable\{CondorcetException, CondorcetInternalException};
16
17
// Manage Results for Election class
18
trait VotesProcess
19
{
20
21
/////////// CONSTRUCTOR ///////////
22
23
    // Data and global options
24
    protected $_Votes; // Votes list
25
    protected $_voteFastMode = false; // When parsing vote, avoid unnecessary checks 
26
27
28
/////////// VOTES LIST ///////////
29
30
    // How many votes are registered ?
31 12
    public function countVotes ($tags = null, bool $with = true) : int
32
    {
33 12
        return $this->_Votes->countVotes(VoteUtil::tagsConvert($tags),$with);
34
    }
35
36 1
    public function countInvalidVoteWithConstraints () : int
37
    {
38 1
        return $this->_Votes->countInvalidVoteWithConstraints();
39
    }
40
41 1
    public function countValidVoteWithConstraints () : int
42
    {
43 1
        return $this->countVotes() - $this->countInvalidVoteWithConstraints();
44
    }
45
46
    // Sum votes weight
47 2
    public function sumVotesWeight () : int
48
    {
49 2
        return $this->_Votes->sumVotesWeight(false);
50
    }
51
52 6
    public function sumValidVotesWeightWithConstraints () : int
53
    {
54 6
        return $this->_Votes->sumVotesWeight(true);
55
    }
56
57
    // Get the votes registered list
58 13
    public function getVotesList ($tags = null, bool $with = true) : array
59
    {
60 13
        return $this->_Votes->getVotesList(VoteUtil::tagsConvert($tags), $with);
61
    }
62
63 5
    public function getVotesListAsString () : string
64
    {
65 5
        return $this->_Votes->getVotesListAsString();
66
    }
67
68 102
    public function getVotesManager () : VotesManager
69
    {
70 102
        return $this->_Votes;
71
    }
72
73 3
    public function getVotesListGenerator ($tags = null, bool $with = true) : \Generator
74
    {
75 3
        return $this->_Votes->getVotesListGenerator(VoteUtil::tagsConvert($tags), $with);
76
    }
77
78 9
    public function getVoteKey (Vote $vote) : ?int
79
    {
80 9
        return $this->_Votes->getVoteKey($vote);
81
    }
82
83
84
/////////// ADD & REMOVE VOTE ///////////
85
86
    // Add a single vote. Array key is the rank, each candidate in a rank are separate by ',' It is not necessary to register the last rank.
87 129
    public function addVote ($vote, $tags = null) : Vote
88
    {
89 129
        $this->prepareVoteInput($vote, $tags);
90
91
        // Check Max Vote Count
92 129
        if ( self::$_maxVoteNumber !== null && $this->countVotes() >= self::$_maxVoteNumber ) :
93 1
            throw new CondorcetException(16, (string) self::$_maxVoteNumber);
94
        endif;
95
96
        // Register vote
97 129
        return $this->registerVote($vote, $tags); // Return the vote object
98
    }
99
100 7
    public function prepareUpdateVote (Vote $existVote) : void
101
    {
102 7
        $this->_Votes->UpdateAndResetComputing($this->getVoteKey($existVote),2);
103 7
    }
104
105 7
    public function finishUpdateVote (Vote $existVote) : void
106
    {
107 7
        $this->_Votes->UpdateAndResetComputing($this->getVoteKey($existVote),1);
108
109 7
        if ($this->_Votes->isUsingHandler()) :
110 1
            $this->_Votes[$this->getVoteKey($existVote)] = $existVote;
111
        endif;
112 7
    }
113
114 129
    public function checkVoteCandidate (Vote $vote) : bool
115
    {
116 129
        if (!$this->_voteFastMode) :
117 53
            $linkCount = $vote->countLinks();
118 53
            $links = $vote->getLinks();
119 53
            $linkCheck = ( $linkCount === 0 || ($linkCount === 1 && reset($links) === $this) );
120
121 53
            foreach ($vote->getAllCandidates() as $candidate) :
122 53
                if (!$linkCheck && $candidate->getProvisionalState() && !$this->isRegisteredCandidate($candidate, true) && $this->isRegisteredCandidate($candidate, false)) :
0 ignored issues
show
It seems like isRegisteredCandidate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
123 53
                    return false;
124
                endif;
125
            endforeach;
126
        endif;
127
128 129
        $ranking = $vote->getRanking();
129
130 129
        $change = $this->convertRankingCandidates($ranking);
131
132 129
        if ($change) :
133 17
            $vote->setRanking(  $ranking,
134 17
                                ( abs($vote->getTimestamp() - microtime(true)) > 0.5 ) ? ($vote->getTimestamp() + 0.001) : null
135
            );
136
        endif;
137
138 129
        return true;
139
    }
140
141 129
    public function convertRankingCandidates (array &$ranking) : bool
142
    {
143 129
        $change = false;
144
145 129
        foreach ($ranking as $rank => &$choice) :
146 129
            foreach ($choice as $choiceKey => &$candidate) :
147 129
                if ( !$this->isRegisteredCandidate($candidate, true) ) :
0 ignored issues
show
It seems like isRegisteredCandidate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
148 112
                    if ($candidate->getProvisionalState() && $this->isRegisteredCandidate($candidate, false)) :
0 ignored issues
show
It seems like isRegisteredCandidate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
149 111
                            $candidate = $this->_Candidates[$this->getCandidateKey((string) $candidate)];
0 ignored issues
show
The property _Candidates does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
It seems like getCandidateKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
150 129
                            $change = true;
151
                    endif;
152
                endif;
153
            endforeach;
154
        endforeach;
155
156 129
        return $change;
157
    }
158
159
    // Write a new vote
160 129
    protected function registerVote (Vote $vote, $tag = null) : Vote
161
    {
162
        // Vote identifiant
163 129
        $vote->addTags($tag);
164
        
165
        // Register
166
        try {
167 129
            $vote->registerLink($this);
168 129
            $this->_Votes[] = $vote;
169 1
        } catch (CondorcetInternalException $e) {
170
            // Security : Check if vote object not already register
171 1
            throw new CondorcetException(31);
172
        }
173
174 129
        return $vote;
175
    }
176
177 4
    public function removeVotes (Vote $votes_input) : bool
178
    {    
179 4
        $key = $this->getVoteKey($votes_input);
180 4
        if ($key !== null) :
181 4
            $deletedVote = $this->_Votes[$key];
182 4
            $rem[] = $deletedVote;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$rem was never initialized. Although not strictly required by PHP, it is generally a good practice to add $rem = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
183
184 4
            unset($this->_Votes[$key]);
185
186 4
            $deletedVote->destroyLink($this);
187
188 4
            return true;
189
        else :
190
            throw new CondorcetException(33);
191
        endif;
192
193
    }
194
195 4
    public function removeVotesByTags ($tags, bool $with = true) : array
196
    {    
197 4
        $rem = [];
198
199
        // Prepare Tags
200 4
        $tags = VoteUtil::tagsConvert($tags);
201
202
        // Deleting
203 4
        foreach ($this->getVotesList($tags, $with) as $key => $value) :
204 4
            $deletedVote = $this->_Votes[$key];
205 4
            $rem[] = $deletedVote;
206
207 4
            unset($this->_Votes[$key]);
208
209 4
            $deletedVote->destroyLink($this);
210
        endforeach;
211
212 4
        return $rem;
213
    }
214
215
216
/////////// PARSE VOTE ///////////
217
218
    // Return the well formated vote to use.
219 129
    protected function prepareVoteInput (&$vote, $tag = null) : void
220
    {
221 129
        if (!($vote instanceof Vote)) :
222 19
            $vote = new Vote ($vote, $tag, null, $this);
223
        endif;
224
225
        // Check array format && Make checkVoteCandidate
226 129
        if ( !$this->checkVoteCandidate($vote) ) :
227
            throw new CondorcetException(5);
228
        endif;
229 129
    }
230
231 2
    public function addVotesFromJson (string $input) : int
232
    {
233 2
        $input = CondorcetUtil::prepareJson($input);
234
235
            //////
236
237 1
        $adding = [];
238 1
        $count = 0;
239
240 1
        foreach ($input as $record) :
241 1
            if (empty($record['vote'])) :
242 1
                continue;
243
            endif;
244
245 1
            $tags = !isset($record['tag']) ? null : $record['tag'];
246 1
            $multiple = !isset($record['multi']) ? 1 : $record['multi'];
247
248 1
            $adding_predicted_count = $count + $multiple;
249
250 1
            if (self::$_maxVoteNumber && self::$_maxVoteNumber < ($this->countVotes() + $adding_predicted_count)) :
251
                throw new CondorcetException(16, self::$_maxParseIteration);
252
            endif;
253
254 1
            if (self::$_maxParseIteration !== null && $adding_predicted_count >= self::$_maxParseIteration) :
255
                throw new CondorcetException(12, self::$_maxParseIteration);
256
            endif;
257
258 1
            $newVote = new Vote ($record['vote'], $tags, null, $this);
259
260 1
            $adding[] = ['multiple' => $multiple, 'vote' => $newVote];
261
262 1
            $count += $multiple;
263
        endforeach;
264
265 1
        $this->_voteFastMode = true;
266
267 1
        foreach ($adding as $oneLine) :
268 1
            for ($i = 1 ; $i <= $oneLine['multiple'] ; $i++) :
269 1
                if ($i !== $oneLine['multiple']) :
270 1
                    $this->addVote(clone $oneLine['vote']);
271
                else :
272 1
                    $this->addVote($oneLine['vote']);
273
                endif;
274
            endfor;
275
        endforeach;
276
277 1
        $this->_voteFastMode = false;
278
279 1
        return $count;
280
    }
281
282 91
    public function parseVotes (string $input, bool $isFile = false) : int
283
    {
284 91
        $input = CondorcetUtil::prepareParse($input, $isFile);
285
286 91
        $adding = [];
287 91
        $count = 0;
288
289 91
        foreach ($input as $line) :
290
            // Empty Line
291 91
            if (empty($line)) :
292 79
                continue;
293
            endif;
294
295
            // Multiples
296 91
            $multiple = VoteUtil::parseAnalysingOneLine(mb_strpos($line, '*'),$line);
297
298
            // Vote Weight
299 91
            $weight = VoteUtil::parseAnalysingOneLine(mb_strpos($line, '^'),$line);
300
301
            // Tags + vote
302 91
            if (mb_strpos($line, '||') !== false) :
303 7
                $data = explode('||', $line);
304
305 7
                $vote = $data[1];
306 7
                $tags = $data[0];
307
            // Vote without tags
308
            else :
309 89
                $vote = $line;
310 89
                $tags = null;
311
            endif;
312
313 91
            $adding_predicted_count = $count + $multiple;
314
315 91
            if (self::$_maxVoteNumber && self::$_maxVoteNumber < ($this->countVotes() + $adding_predicted_count)) :
316 1
                throw new CondorcetException(16, (string) self::$_maxParseIteration);
317
            endif;
318
319 91
            if (self::$_maxParseIteration !== null && $adding_predicted_count >= self::$_maxParseIteration) :
320 2
                throw new CondorcetException(12, (string) self::$_maxParseIteration);
321
            endif;
322
323 90
            $newVote = new Vote ($vote, $tags, null, $this);
324 90
            $newVote->setWeight($weight);
325
326 90
            $adding[] = ['multiple' => $multiple, 'vote' => $newVote];
327
328 90
            $count += $multiple;
329
        endforeach;
330
331 89
        $this->_voteFastMode = true;
332
333 89
        foreach ($adding as $oneLine) :
334 89
            for ($i = 1 ; $i <= $oneLine['multiple'] ; $i++) :
335 89
                if ($i !== $oneLine['multiple']) :
336 73
                    $this->addVote(clone $oneLine['vote']);
337
                else :
338 89
                    $this->addVote($oneLine['vote']);
339
                endif;
340
            endfor;
341
        endforeach;
342
343 89
        $this->_voteFastMode = false;
344
345 89
        return $count;
346
    }
347
348
}
349