Completed
Push — master ( 62cb27...c16962 )
by mains
03:25
created

php/JodelAccount.php (11 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
class JodelAccount
4
{
5
    public $accessToken;
6
    public $expirationDate;
7
    public $refreshToken;
8
    public $distinctId;
9
    public $deviceUid;
10
11
    //is the Account a Bot or Spider?
12
    public $isBot;
13
    
14
    // array of voted Jodels
15
    public $votes;
16
17
    //Location of the Account
18
    public $location;
19
20
    function __construct($deviceUid = NULL, $isBot = FALSE)
21
    {
22
        if($deviceUid == NULL)
23
        {
24
            $this->deviceUid = $this->createAccount();
25
        }
26
        else
27
        {
28
            $this->deviceUid = $deviceUid;
29
        }
30
31
        $this->isBot        = $isBot;
32
        $this->location     = $this->getLocation();
33
34
        if(!$this->isTokenFresh())
35
        {
36
            $this->refreshToken();
37
        }
38
        $this->accessToken  = $this->getAccessToken();
0 ignored issues
show
Equals sign not aligned correctly; expected 1 space but found 2 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
39
40
       /* if($this->isAccountVerified() != 1)
41
        {
42
            $this->showCaptcha();
43
            //$this->verifyCaptcha();
44
        }*/
45
    }
46
47
/*
48
    function showCaptcha()
49
    {
50
        $accountCreator = new GetCaptcha();
51
        $accountCreator->setAccessToken($this->accessToken);
52
        $captcha = $accountCreator->execute();
53
54
        echo $captcha['image_url'];
55
        echo('<br><img width="100%" src="' . $captcha['image_url'] . '">');
56
        echo "<br>Key: " . $captcha['key'];
57
        echo "<br>";
58
59
        //Form
60
        
61
        echo '<form method="get">';
62
        echo    '<p>Enter Key (copy pasta from top): <input type="text" value="' . $captcha['key'] . '" name="key" /></p>';
63
        echo    '<p>Find the Coons (example: they are on picture 3, 4 and 5. You enter 2-3-4. Becouse we start counting at 0): <input type="text" name="solution" /></p>';
64
        echo    '<input type="hidden" name="deviceUid" value="' . $this->deviceUid . '">';
65
        echo    '<input type="hidden" name="pw" value="">';
66
        echo    '<p><input type="submit" /></p>';
67
        echo '</form>';
68
69
        die();
70
        
71
    }
72
    */
73
74
    function getCaptcha()
75
    {
76
        $accountCreator = new GetCaptcha();
77
        $accountCreator->setAccessToken($this->accessToken);
78
        $captcha = $accountCreator->execute();
79
80
        return array("image_url" => $captcha['image_url'], "key" => $captcha['key']);
81
    }
82
83
    function isAccountVerified()
84
    {
85
        $accountCreator = new GetUserConfig();
86
        $accountCreator->setAccessToken($this->accessToken);
87
        $data = $accountCreator->execute();
88
89
        //error_log(print_r($data, true));
90
91
        return $data['verified'];
92
    }
93
94
    function getGeocodingToken()
0 ignored issues
show
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
95
    {
96
        $config = parse_ini_file('config/config.ini.php');
97
        if(!isset($config['geocodingToken']) ||
98
            $config['geocodingToken'] == NULL ||
99
            $config['geocodingToken'] == '' ||
100
            $config['geocodingToken'] == 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
101
        {
102
            error_log("Please set a Google Maps Geocoding Token!");
103
        }
104
        else
105
        {
106
            return $config['geocodingToken'];
107
        }
108
    }
109
110
    function locationEquals($city)
0 ignored issues
show
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
111
    {
112
        $db = new DatabaseConnect();
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $db. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
Equals sign not aligned with surrounding assignments; expected 5 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
113
        $result = $db->query("SELECT * FROM accounts WHERE device_uid='" . $this->deviceUid  . "'");
114
        
115
        $location = new Location();
116
        
117 View Code Duplication
        if ($result->num_rows > 0)
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
        {
119
            // output data of each row
120
            while($row = $result->fetch_assoc())
121
            {
122
                $location->setLat($row['lat']);
123
                $location->setLng($row['lng']);
124
                $location->setCityName($row['name']);
125
            }
126
        }
127
        else
128
        {
129
            error_log("Error no Location found - getLocation");
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal Error no Location found - getLocation does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
130
        }
131
132
        if($location->getCityName() == $city)
0 ignored issues
show
The if-else statement can be simplified to return $location->getCityName() == $city;.
Loading history...
133
        {
134
            return TRUE;
135
        }  
136
        else
137
        {
138
            return FALSE;
139
        }
140
    }
141
142
    function setLocation()
143
    {
144
        //Is Channel or City
145
        if(substr($_GET['city'], 0, 1) === '#')
146
        {
147
            return htmlspecialchars($_GET['city']) . " " . $this->location->cityName;
148
        }                
149
        else
150
        {
151
            $url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . htmlspecialchars($_GET['city']) . '&key=' . $this->getGeocodingToken();
152
            $result = Requests::post($url);
153
            if(json_decode($result->body, true)['status'] == 'ZERO_RESULTS' || json_decode($result->body, true)['status'] == 'INVALID_REQUEST')
154
            {
155
                return "0 results";
156
            }
157
            else
158
            {
159
                $name = json_decode($result->body, true)['results']['0']['address_components']['0']['long_name'];
160
                $lat = json_decode($result->body, true)['results']['0']['geometry']['location']['lat'];
161
                $lng = json_decode($result->body, true)['results']['0']['geometry']['location']['lng'];
162
163
                $location = new Location();
164
                $location->setLat($lat);
165
                $location->setLng($lng);
166
                $location->setCityName($name);
167
                $accountCreator = new UpdateLocation();
168
                $accountCreator->setLocation($location);
169
                $accountCreator->setAccessToken($this->accessToken);
170
                $data = $accountCreator->execute();
171
172
                //safe location to db
173
                $db = new DatabaseConnect();
174
175
                if($data == 'Success')
176
                {
177
                    $result = $db->query("UPDATE accounts 
178
                            SET name='" . $name . "',
179
                                lat='" . $lat . "',
180
                                lng='" . $lng . "'
181
                            WHERE access_token='" . $this->accessToken . "'");
182
183
                    if($result === false)
184
                    {
185
                            echo "Updating location failed: (" . $db->errno . ") " . $db->error;
186
                    }
187
                    else
188
                    {
189
                        user_log('User with JodelDeviceId:' . $this->deviceUid .  ' [' . $_SERVER['REMOTE_ADDR'] . '][' . $_SERVER ['HTTP_USER_AGENT'] . '] changed to Location: ' . $name);
190
                    }
191
                }
192
193
                return $name;
194
            }
195
        }
196
    }
197
198
    function getLocation()
199
    {
200
        $db = new DatabaseConnect();
201
        $result = $db->query("SELECT * FROM accounts WHERE device_uid='" . $this->deviceUid  . "'");
202
        
203
        $location = new Location();
204
        
205 View Code Duplication
        if ($result->num_rows > 0)
206
        {
207
            // output data of each row
208
            while($row = $result->fetch_assoc())
209
            {
210
                $location->setLat($row['lat']);
211
                $location->setLng($row['lng']);
212
                $location->setCityName($row['name']);
213
            }
214
        }
215
        else
216
        {
217
            echo "Error: 0 results";
218
            error_log("Error no Location found - getLocation");
219
        }
220
221
        return $location;
222
    }
223
224
    function verifyCaptcha()
225
    {
226
        if(isset($_GET['deviceUid']))
227
        {
228
            $deviceUid = $_GET['deviceUid'];
229
            $jodelAccountForVerify = new JodelAccount($deviceUid);
230
        }
231
        else if(isset($_POST['deviceUid']))
232
        {
233
            $deviceUid = $_POST['deviceUid'];
234
            $jodelAccountForVerify = new JodelAccount($deviceUid);
235
        }
236
        else
237
        {
238
            $deviceUid = $this->deviceUid;
239
            $jodelAccountForVerify = $this;
240
        }
241
242
        $solution = $_GET['solution'];
243
        $solution = array_map('intval', explode('-', $solution));
244
245
        $accountCreator = new PostCaptcha();
246
        $accountCreator->setAccessToken($jodelAccountForVerify->accessToken);
247
        $accountCreator->captchaKey = $_GET['key'];
248
        $accountCreator->captchaSolution = $solution;
249
        $verified = $accountCreator->execute();
250
251
        if(isset($verified->status_code))
252
        {
253
            return $verified->status_code;
254
        }
255
        return $verified['verified'];
256
    }
257
258
    //ToDo Spider Check
259
    function votePostId($postId, $vote)
260
    {
261
        if(!$this->isBot)
262
        {
263
            if(!$this->isAccountVerified())
264
            {
265
                error_log('Account is not Verified! jodelAccount.php Line 279');
266
                return FALSE;
267
            }
268
            else
0 ignored issues
show
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
269
            {
270
                
271
            }
272
273
            if(!$this->hasVoted($postId))
274
            {
275
                if($vote == "up")
276
                {
277
                    $accountCreator = new Upvote();
278
                }
279
                else if($vote == "down")
280
                {
281
                    $accountCreator = new Downvote();
282
                }
283
284
                $accountCreator->setAccessToken($this->accessToken);
285
                $accountCreator->postId = htmlspecialchars($postId);
286
                $data = $accountCreator->execute();
287
288
                user_log('User voted: ' . print_r($data, true));
289
290
                if(array_key_exists('post', $data))
291
                {
292
                    $this->addVoteWithPostIdAndType($postId, $vote);
293
                    return TRUE;
294
                }
295
                else if(array_key_exists('error', $data))
296
                {
297
                    error_log('Could not vote - Error: ' . $data['error']);
298
                    return FALSE;
299
                }
300
                else
301
                {
302
                    error_log('Could not vote: ' . print_r($data, true));
303
                    return FALSE;
304
                } 
305
            }
306
            else
307
            {
308
                return FALSE;
309
            }
310
        }
311
        else
312
        {
313
            return FALSE;
314
        }
315
    }
316
317
    //ToDo Spider Check
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
318
    function sendJodel($location, $view)
319
    {
320
        if($this->isAccountVerified() != 1)
321
        {
322
            $this->showCaptcha();
323
            //$this->verifyCaptcha();
324
        }
325
326
        $accountCreator = new SendJodel();
327
328
        if(isset($_POST['ancestor']))
329
        {
330
            $ancestor = $_POST['ancestor'];
331
            $accountCreator->ancestor = $ancestor;
332
        }
333
        if(isset($_POST['color']))
334
        {
335
            $color = $_POST['color'];
336
            switch ($color) {
337
                case '8ABDB0':
338
                    $color = '8ABDB0';
339
                    break;
340
                case '9EC41C':
341
                    $color = '9EC41C';
342
                    break;
343
                case '06A3CB':
344
                    $color = '06A3CB';
345
                    break;
346
                case 'FFBA00':
347
                    $color = 'FFBA00';
348
                    break;
349
                case 'DD5F5F':
350
                    $color = 'DD5F5F';
351
                    break;
352
                case 'FF9908':
353
                    $color = 'FF9908';
354
                    break;
355
                default:
356
                    $color = '8ABDB0';
357
                    break;
358
            }
359
            $accountCreator->color = $color;
360
        }
361
362
        $accountCreatorLocation = new UpdateLocation();
363
        $accountCreatorLocation->setLocation($location);
364
        $accountCreatorLocation->setAccessToken($this->accessToken);
365
        $data = $accountCreatorLocation->execute();
366
        
367
		if($data != 'Success')
368
		{
369
			error_log('Could not set location befor Post: ' . print_r($data, true));
370
		}
371
372
        $accountCreator->location = $this->location;
373
374
        $image = '';
375
        if(isset($_FILES['image']) && $_FILES['image']['size'] > 0)
376
        {
377
            $image = file_get_contents($_FILES['image']['tmp_name']);
378
        }
379
        
380
        $accountCreator->image = $image;
381
        
382
        $accountCreator->setAccessToken($this->accessToken);
383
        $data = $accountCreator->execute();
384
385
        if(isset($data['error']) && $data['error'] == 'length')
386
        {
387
            $errorMsg = 'Error: The input was to long';
388
            return $errorMsg;
389
        }
390
391
        user_log('User posted: ' . print_r($data, true));
392
393
        if(isset($_POST['ancestor']))
394
        {
395
            header('Location: ' . $view->toUrl());
396
            exit;
397
        }
398
        else
399
        {
400
            header('Location: ' . $view->baseUrl);
401
            exit;
402
        }
403
    }
404
405
    function isTokenFresh()
406
    {
407
        $db = new DatabaseConnect();  
408
        $result = $db->query("SELECT * FROM accounts WHERE device_uid='" . $this->deviceUid . "'");
409
410
        if ($result->num_rows > 0)
411
        {
412
            // output data of each row
413
            while($row = $result->fetch_assoc())
414
            {
415
                    $expiration_date = $row["expiration_date"];
416
            }
417
        }
418
        else
419
        {
420
            error_log('0 results');
421
        }
422
423
        if($expiration_date <= time())
424
        {
425
           return FALSE;
426
        }
427
        
428
        return TRUE;
429
    }
430
431
    function refreshToken()
432
    {
433
        $accountCreator = new CreateUser();
434
        $accountCreator->setAccessToken($this->accessToken);
435
        $accountCreator->setDeviceUid($this->deviceUid);
436
        $accountCreator->setLocation($this->location);
437
        $data = $accountCreator->execute();
438
439
        $access_token = (string)$data[0]['access_token'];
440
        $expiration_date = $data[0]['expiration_date'];
441
        $device_uid = (string)$data[1];
442
        
443
        $db = new DatabaseConnect();  
444
        $result = $db->query("UPDATE accounts 
445
                                SET access_token='" . $access_token . "',
446
                                    expiration_date='" . $expiration_date . "'
447
                                WHERE device_uid='" . $device_uid . "'");
448
449 View Code Duplication
        if($result === false){
450
                error_log("Adding account failed: (" . $db->errno . ") " . $db->error);
451
        }   
452
    }
453
454
455
456
    function getAccessToken()
457
    {
458
        $db = new DatabaseConnect();
459
        $result = $db->query("SELECT * FROM accounts WHERE device_uid='" . $this->deviceUid  . "'");
460
        
461
        $accessToken;
462
        
463
        if ($result->num_rows > 0)
464
        {
465
            // output data of each row
466
            while($row = $result->fetch_assoc())
467
            {
468
                $accessToken = $row['access_token'];
469
            }
470
        }
471
        else
472
        {
473
            error_log('Error: 0 results');
474
        }
475
476
        return $accessToken;
477
    }
478
479
480
    function getKarma()
481
    {
482
        $accountCreator = new GetKarma();
483
        $accountCreator->setAccessToken($this->accessToken);
484
        $data = $accountCreator->execute();
485
        
486
        return $data['karma'];
487
    }
488
489
    function hasVoted($postId)
490
    {
491
        $db = new DatabaseConnect();
492
493
        $postId = $db->real_escape_string($postId);
494
495
        $result = $db->query("SELECT id FROM votes WHERE (postId = '" . $postId . "' AND device_uid = '" . $this->deviceUid . "')");
496
        
497 View Code Duplication
        if($result === false)
498
        {
499
            $error = db_error();
500
            echo $error;
501
            error_log("Adding Vote failed: (" . $result->errno . ") " . $result->error);
502
        }
503
504
        if($result->num_rows == 0)
505
        {
506
            return FALSE;
507
        }
508
        else
509
        {
510
            return TRUE;
511
        }
512
    }
513
514
    function addVoteWithPostIdAndType($postId, $voteType)
515
    {
516
        $db = new DatabaseConnect();
517
518
        $postId = $db->real_escape_string($postId);
519
        $voteType = $db->real_escape_string($voteType);
520
        
521
        if($this->hasVoted($postId))
522
        {
523
            return "Already voted";
524
        }
525
526
        $result = $db->query("INSERT INTO votes (device_uid, postId, type)
527
                        VALUES ('" . $this->deviceUid . "','" . $postId . "','" . $voteType . "')");
528
        
529 View Code Duplication
        if($result === false){
530
                $error = db_error();
531
                echo $error;
532
                echo "Adding Vote failed: (" . $result->errno . ") " . $result->error;
533
        }       
534
    }
535
536
    function registerAccount($location) {
537
        $accountCreator = new CreateUser();
538
        $accountCreator->setLocation($location);
539
        $data = $accountCreator->execute();
540
        
541
        $access_token = (string)$data[0]['access_token'];
542
        $refresh_token = (string)$data[0]['refresh_token'];
543
        $token_type = (string)$data[0]['token_type'];
544
        $expires_in = $data[0]['expires_in'];
545
        $expiration_date = $data[0]['expiration_date'];
546
        $distinct_id = (string)$data[0]['distinct_id'];
547
        $device_uid = (string)$data[1];
548
549
        $name = $location->cityName;
550
        $lat = $location->lat;
551
        $lng = $location->lng;
552
        
553
        $db = new DatabaseConnect();  
554
        $result = $db->query("INSERT INTO accounts (access_token, refresh_token, token_type,
555
                        expires_in, expiration_date, distinct_id, device_uid, name, lat, lng)
556
                        VALUES ('" . $access_token . "','" . $refresh_token . "','" . $token_type .
557
                        "','" .  $expires_in . "','" . $expiration_date . "','" . $distinct_id .
558
                        "','" . $device_uid . "','" . $name . "','" . $lat . "','" . $lng . "') ");
559
560
        $success = TRUE;
561 View Code Duplication
        if($result === false){
562
                $error = $db->error();
563
                echo $error;
564
                echo "Adding account failed: (" . $result->errno . ") " . $result->error;
565
                $success = FALSE;
566
        }   
567
        
568
        return $device_uid;
569
    }
570
571
    function createAccount()
572
    {
573
        $config = parse_ini_file('config/config.ini.php');
574
        $location = new Location();
575
        $location->setLat($config['default_lat']);
576
        $location->setLng($config['default_lng']);
577
        $location->setCityName($config['default_location']);
578
579
        $deviceUid = $this->registerAccount($location);
580
581
        return $deviceUid;
582
    }
583
}