Issues (268)

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.

code/control/TwitterCallback.php (28 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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 11 and the first side effect is on line 6.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
4
if (!file_exists('Zend/Oauth.php')) {
5
    // The autoloader can skip this if TwitterCallback is called before twitter/_config is included
6
    require_once dirname(dirname(dirname(__FILE__))) . '/_config.php';
7
}
8
9
require_once  dirname(dirname(dirname(__FILE__))).'/thirdparty/Zend/Oauth/Consumer.php';
10
11
class TwitterCallback extends SocialIntegrationControllerBaseClass implements SocialIntegrationAPIInterface
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
12
{
13
14
//======================================= AVAILABLE METHODS ===============================================
15
16
17
    /**
18
     * Maximum number of followers that can be retrieved
19
     * @var Int
20
     */
21
    private static $number_of_friends_that_can_be_retrieved = 1200;
22
    public static function set_number_of_friends_that_can_be_retrieved($n)
23
    {
24
        self::$number_of_friends_that_can_be_retrieved = $s;
0 ignored issues
show
The variable $s does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
25
    }
26
    public static function get_number_of_friends_that_can_be_retrieved()
27
    {
28
        return self::$number_of_friends_that_can_be_retrieved;
29
    }
30
31
    /**
32
     * Standard SS variable determining what this controller can do
33
     * @var Array
34
     */
35
    public static $allowed_actions = array(
36
        'TwitterConnect',
37
        'Connect',
38
        'Login',
39
        'FinishTwitter',
40
        'remove',
41
        'test'
42
    );
43
44
45
//======================================= CONFIGURATION STATIC ===============================================
46
47
48
    /**
49
     * Get from Twitter
50
     * @var String
51
     */
52
    protected static $consumer_secret = null;
53
    public static function set_consumer_secret($s)
54
    {
55
        self::$consumer_secret = $s;
56
    }
57
    public static function get_consumer_secret()
58
    {
59
        return self::$consumer_secret;
60
    }
61
62
    /**
63
     * Get from Twitter
64
     * @var String
65
     */
66
    protected static $consumer_key = null;
67
    public static function set_consumer_key($s)
68
    {
69
        self::$consumer_key = $s;
70
    }
71
    public static function get_consumer_key()
72
    {
73
        return self::$consumer_key;
74
    }
75
76
//======================================= CONFIGURATION NON-STATIC ===============================================
77
78
79
//======================================= THIRD-PARTY CONNECTION ===============================================
80
81
    /**
82
     * used to hold the Zend_Oauth_Consumer
83
     * we keep one for each callback
84
     * the default callback is nocallback
85
     * @var array
86
     */
87
    protected static $zend_oauth_consumer_class = null;
88
89
    /**
90
     * when creating a new Zend_Oauth_Consumer
91
     * we also return the configs
92
     * To access the standard config use:
93
     * self::$zend_oauth_consumer_class_config["nocallback"];
94
     *
95
     * @var Array
96
     */
97
    protected static $zend_oauth_consumer_class_config = null;
98
99
    /**
100
     * holds an instance of the Zend_Oauth_Consumer class
101
     * @return Zend_Oauth_Consumer
102
     */
103
    private static function get_zend_oauth_consumer_class($callback = "nocallback")
104
    {
105
        if (!self::$consumer_key || !self::$consumer_secret) {
106
            user_error("You must set the following variables: TwitterCallback::consumer_secret AND TwitterCallback::consumer_key");
107
        }
108
        if (!isset(self::$zend_oauth_consumer_class[$callback])) {
109
            if ($callback && $callback != "nocallback") {
110
                $config["callbackUrl"] = $callback;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = 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...
111
            }
112
            $config['consumerKey'] = self::$consumer_key;
0 ignored issues
show
The variable $config does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
113
            $config['consumerSecret'] = self::$consumer_secret;
114
            $config['siteUrl'] = 'https://api.twitter.com/oauth';
115
            $config['authorizeUrl'] = 'https://api.twitter.com/oauth/authenticate';
116
            self::$zend_oauth_consumer_class[$callback] = new Zend_Oauth_Consumer($config);
117
            self::$zend_oauth_consumer_class_config[$callback] = $config;
118
        }
119
        return self::$zend_oauth_consumer_class[$callback];
120
    }
121
122
    /**
123
     * used to hold the twitter class
124
     * @var Twitter
125
     */
126
    private static $twitter_class = null;
127
128
    /**
129
     * holds an instance of the Twitter Connect Class
130
     * @return Twitter Class
131
     */
132
    private static function get_twitter_class()
133
    {
134
        if (!self::$twitter_class) {
135
            $member = Member::currentUser();
136
            if ($member && $member->TwitterID) {
137
                require_once(dirname(dirname(dirname(__FILE__))).'/thirdparty/twitter/Twitter.php');
138
                require_once(dirname(dirname(dirname(__FILE__))).'/thirdparty/twitter/Exception.php');
139
                self::$twitter_class = new TijsVerkoyen\Twitter\Twitter(self::$consumer_key, self::$consumer_secret);
0 ignored issues
show
Documentation Bug introduced by
It seems like new \TijsVerkoyen\Twitte...self::$consumer_secret) of type object<TijsVerkoyen\Twitter\Twitter> is incompatible with the declared type object<Twitter> of property $twitter_class.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
140
                if ($member->TwitterToken && $member->TwitterSecret) {
141
                    self::$twitter_class->setOAuthToken($member->TwitterToken);
142
                    self::$twitter_class->setOAuthTokenSecret($member->TwitterSecret);
143
                }
144
            }
145
        }
146
        return self::$twitter_class;
147
    }
148
149
150
//======================================= STATIC METHODS ===============================================
151
152
    /**
153
     *
154
     * @ return Array | Null
155
     */
156
    public static function get_current_user()
157
    {
158
        $member = Member::currentUser();
159
        if ($member && $member->TwitterID) {
160
            $twitterClass = self::get_twitter_class();
161
            return new ArrayData($twitterClass->usersShow($member->TwitterID));
162
        } else {
163
            return null;
164
        }
165
    }
166
167
    /**
168
     * returns true on success
169
     * Message + Link can not be more than 140 characters!
170
     * TODO: check how that works with "link making small techniques".
171
     * @param Int | Member | String $to
172
     * @param String $message
173
     * @param String $link - link to send with message
174
     * @param Array $otherVariables - other variables used in message.
175
     * @return boolean
176
     */
177
    public static function send_message(
178
        $to = 0,
179
        $message,
0 ignored issues
show
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
180
        $link = "",
181
        $otherVariables = array()
182
    ) {
183
        if ($to instanceof Member) {
184
            $to = $to->TwitterID;
185
        }
186
        $member = Member::currentUser();
187
        if ($member) {
188
            if ($twitterClass = self::get_twitter_class()) {
189
                $twitterDetails = self::is_valid_user($to);
190
                if (!empty($twitterDetails["screen_name"])) {
191
                    $toScreenName = $twitterDetails["screen_name"];
192
                    $message = trim(strip_tags(stripslashes($message)));
193
                    $message = "@$toScreenName ".$message." ".$link;
194
                    $twitterClass->statusesUpdate($message);
195
                    //followers can also get a direct message
196
                    $followers = self::get_list_of_friends(-1);
197
                    $isFollower = false;
198
                    foreach ($followers as $follower) {
199
                        if ($follower["id"] == $to) {
200
                            $isFollower = true;
201
                        }
202
                    }
203
                    if ($isFollower) {
204
                        $text = $message." ".$link;
205
                        $userId = $to;
206
                        $includeEntities = false;
0 ignored issues
show
$includeEntities is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
207
                        //returns the user's details as an array if sent successfully
208
                        //and a string with error message if sent unsuccessfully
209
                        $outcome = $twitterClass->directMessagesNew($userId, $screenName = null, $text);
210
                        if (is_array($outcome)) {
211
                            return true;
212
                        } else {
213
                            SS_Log::log($outcome, SS_Log::NOTICE);
214
                        }
215
                    }
216
                    return true;
217
                } else {
218
                    SS_Log::log("Twitter user not found", SS_Log::NOTICE);
219
                }
220
            }
221
        }
222
        return false;
223
    }
224
225
226
    /**
227
     *
228
     * If we can not find enough followers, we add any user.
229
     *
230
     * @param Int $limit - the number of users returned, set to -1 to return maximum
231
     * @param String $search - the users searched for
0 ignored issues
show
There is no parameter named $search. Did you maybe mean $searchString?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
232
     *
233
     * @return Array (array("id" => ..., "name" => ...., "picture" => ...))
234
     */
235
    public static function get_list_of_friends($limit = 12, $searchString = "")
236
    {
237
        if ($limit == -1) {
238
            $limit = self::get_number_of_friends_that_can_be_retrieved();
239
        }
240
        //defining variables
241
        $rawArray = array();
242
        $finalArray = array();
243
        $member = Member::currentUser();
244
        if ($member) {
245
            if ($twitterClass = self::get_twitter_class()) {
246
                //get list of followers
247
                $followersArray = $twitterClass->followersIds($member->TwitterID);
248
                $followersArrayIDs = empty($followersArray["ids"]) ? array() :$followersArray["ids"];
249
                $ids = "";
250
                $count = 0;
251
                if (count($followersArrayIDs)) {
252
                    //getting them in packs of 100
253
                    foreach ($followersArrayIDs as $followerID) {
254
                        $ids .= "{$followerID},";
255
                        $count++;
256
                        if (!($count % 100) || $count == count($followersArrayIDs)) {
257
                            $nextArray = $twitterClass->usersLookup($ids);
258
                            if (is_array($nextArray) && count($nextArray)) {
259
                                $rawArray += $nextArray;
260
                            } else {
261
                                break;
262
                            }
263
                            $ids = "";
264
                        }
265
                    }
266
                }
267
                //we are retrieving more so that we can select the right ones.
268
                if ($searchString) {
269
                    $searchResults = $twitterClass->usersSearch("q=".$searchString."}", $page = null, $count = null, $includeEntities = null);
270
                    if (count($searchResults)) {
271
                        $rawArray += $searchResults;
272
                    }
273
                }
274
                //adding ourselves if we are in dev mode
275
                if (Director::isDev()) {
276
                    $rawArray[] = $twitterClass->usersShow($member->TwitterID);
277
                }
278
                if (count($rawArray)) {
279
                    $limitCount = 0;
280
                    foreach ($rawArray as $friend) {
281
                        if (empty($friend["id"])) {
282
                            $friend["id"] = 0;
283
                        }
284
                        if (empty($friend["name"])) {
285
                            $friend["name"] = "";
286
                        }
287
                        if (empty($friend["screen_name"])) {
288
                            $friend["screen_name"] = "";
289
                        }
290
                        if (empty($friend["profile_image_url"])) {
291
                            $friend["profile_image_url"] = self::get_default_avatar();
292
                        }
293
                        $haystack = $friend["name"].$friend["screen_name"];
294
                        if (!$searchString || stripos("-".$haystack, $searchString)) {
295
                            $name =$friend["name"];
296
                            $name .= " (";
297
                            $name .= $friend["screen_name"];
298
                            $name .= ")";
299
                            $finalArray[$friend["id"]] = array(
300
                                "id" => $friend["id"],
301
                                "name" => $name,
302
                                "picture" => $friend["profile_image_url"]
303
                            );
304
                            $limitCount++;
305
                        }
306
                        if ($limitCount > $limit) {
307
                            break;
308
                        }
309
                    }
310
                }
311
            }
312
        }
313
        return $finalArray;
314
    }
315
316
    /**
317
     * checks if a user exists and returns an array of
318
     * friend details if they exist.
319
     * @return false | array
0 ignored issues
show
Should the return type not be boolean?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
320
     */
321
    public function user_lookup($screen_name)
322
    {
323
        $rawArray = array();
324
        if ($twitterClass = self::get_twitter_class()) {
325
            //we are retrieving more so that we can select the right ones.
326
            //return $twitterClass->usersShow("", $screen_name);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
327
            $searchResults = $twitterClass->usersSearch("q=".$screen_name."}");
328
            if (count($searchResults)) {
329
                $rawArray += $searchResults;
330
            }
331
            if (count($rawArray)) {
332
                foreach ($rawArray as $friend) {
333
                    if (empty($friend["id"])) {
334
                        $friend["id"] = 0;
335
                    }
336
                    if (empty($friend["name"])) {
337
                        $friend["name"] = "";
338
                    }
339
                    if (empty($friend["screen_name"])) {
340
                        $friend["screen_name"] = "";
341
                    }
342
                    if (empty($friend["profile_image_url"])) {
343
                        $friend["profile_image_url"] = self::get_default_avatar();
344
                    }
345
                    if (strtolower($friend["screen_name"]) == strtolower($screen_name)) {
346
                        return $friend;
347
                    }
348
                }
349
            }
350
        }
351
        return false;
352
    }
353
354
    /**
355
     * checks if a user exists
356
     * @param String $id - screen_name
0 ignored issues
show
There is no parameter named $id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
357
     */
358
    public static function is_valid_user($idOrScreenName)
359
    {
360
        if (is_numeric($idOrScreenName) && intval($idOrScreenName) == $idOrScreenName) {
361
            $twitterClass = self::get_twitter_class();
362
            $userData = $twitterClass->usersShow($idOrScreenName);
363
        } else {
364
            $userData = self::user_lookup($idOrScreenName);
365
        }
366
        if (is_array($userData)) {
367
            if (!count($userData)) {
368
                $userData = null;
369
            }
370
        }
371
        return  $userData ? $userData : false;
372
    }
373
374
    public static function get_updates($lastNumber = 12)
375
    {
376
        $member = Member::currentUser();
377
        if ($member) {
378
            if ($twitterClass = self::get_twitter_class()) {
379
                return $twitterClass->statusesUserTimeline(
380
                    $member->TwitterID, //$userId = null,
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
381
                    $screenName = null,
382
                    $sinceId = null,
383
                    $lastNumber, //$count
384
                    $maxId = null,
385
                    $trimUser = null,
386
                    $excludeReplies = true,
387
                    $contributorDetails = null,
388
                    $includeRts = null
389
                );
390
            } else {
391
                user_error("could not find twitter class");
392
            }
393
        } else {
394
            return "not logged in";
395
        }
396
    }
397
//======================================= STANDARD SS METHODS ===============================================
398
399
400
401 View Code Duplication
    public function __construct()
0 ignored issues
show
This method seems to be duplicated in 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...
402
    {
403
        if (self::$consumer_secret == null || self::$consumer_key == null) {
404
            user_error('Cannot instigate a TwitterCallback object without a consumer secret and key', E_USER_ERROR);
405
        }
406
        parent::__construct();
407
    }
408
409
410
//======================================= CONNECT ===============================================
411
412
413
    /**
414
     * easy access to the connection
415
     *
416
     */
417 View Code Duplication
    public function TwitterConnect()
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...
This method seems to be duplicated in 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...
418
    {
419
        if ($this->isAjax()) {
420
            return $this->connectUser($this->Link('FinishTwitter'));
421
        } else {
422
            Session::set("BackURL", $this->returnURL());
423
            return $this->connectUser($this->returnURL());
424
        }
425
    }
426
427
    /**
428
     * STEP 1 of the connecting process
429
     * @param String $returnTo - the URL to return to
430
     * @param Array $extra - additional paramaters
431
     */
432
    public function connectUser($returnTo = '', array $extra = array())
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...
The parameter $extra is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
433
    {
434
        $token = SecurityToken::inst();
435
        if ($returnTo) {
436
            $returnTo = $token->addToUrl($returnTo);
437
            $returnTo = urlencode($returnTo);
438
        }
439
        $callback = $this->AbsoluteLink('Connect?ret=' . $returnTo);
440
        $callback = $token->addToUrl($callback);
441
        $consumer = self::get_zend_oauth_consumer_class($callback);
442
        $token = $consumer->getRequestToken();
443
        Session::set('Twitter.Request.Token', serialize($token));
444
        $url = $consumer->getRedirectUrl(array(
445
            'force_login' => 'true'
446
        ));
447
        return self::curr()->redirect($url);
448
    }
449
450
    /**
451
     * Connects the current user.
452
     * completes connecting process
453
     * @param SS_HTTPRequest $reg
0 ignored issues
show
There is no parameter named $reg. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
454
     */
455
    public function Connect(SS_HTTPRequest $req)
456
    {
457
        $token = SecurityToken::inst();
458
        if (!$token->checkRequest($req)) {
459
            return $this->httpError(400);
460
        }
461
        $data = null;
462
        $access = null;
463
        $user = 0;
464
        if ($req->getVars() && !$req->getVar('denied') && Session::get('Twitter.Request.Token')) {
465
            $consumer = self::get_zend_oauth_consumer_class();
466
            $token = Session::get('Twitter.Request.Token');
467
            if (is_string($token)) {
468
                $token = unserialize($token);
469
            }
470
            try {
471
                $access = $consumer->getAccessToken($req->getVars(), $token);
472
                $client = $access->getHttpClient(self::$zend_oauth_consumer_class_config["nocallback"]);
473
                $client->setUri('https://api.twitter.com/1.1/account/verify_credentials.json');
474
                $client->setMethod(Zend_Http_Client::GET);
475
                $client->setParameterGet('skip_status', 't');
476
                $response = $client->request();
477
478
                $data = $response->getBody();
479
                $data = json_decode($data);
480
                if (!isset($data->id)) {
481
                    user_error("There was an error accessing the twitter account");
482
                }
483
                $user = $data->id;
484
                Session::set('Twitter', array(
0 ignored issues
show
array('ID' => $data->id,... => $data->screen_name) is of type array<string,?,{"ID":"?","Handle":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
485
                    'ID' => $data->id,
486
                    'Handle' => $data->screen_name,
487
                ));
488
            } catch (Exception $e) {
489
                $this->httpError(500, $e->getMessage());
490
                SS_Log::log($e, SS_Log::ERR);
491
            }
492
        } else {
493
            SS_Log::log("could not connect to twitter", SS_Log::NOTICE);
494
        }
495
        Session::clear('Twitter.Request.Token');
496 View Code Duplication
        if ($data && $user && is_numeric($user) && $access) {
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...
497
            $this->updateUserFromTwitterData($user, $data, $access, false);
498
        }
499
        $returnURL = $this->returnURL();
500
        return $this->redirect($returnURL);
501
    }
502
503
    /**
504
     *
505
     *
506
     * cleans up the twitter connection
507
     * Do we really need this?
508
     */
509 View Code Duplication
    public function FinishTwitter($request)
0 ignored issues
show
This method seems to be duplicated in 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...
510
    {
511
        $token = SecurityToken::inst();
512
        if (!$token->checkRequest($request)) {
513
            return $this->httpError(400);
514
        }
515
        //end security check
516
        if ($this->CurrentMember()->TwitterID) {
517
            $array = array(
518
                'handle' => $this->CurrentMember()->TwitterHandle,
519
                'removeLink' => $token->addToUrl($this->Link('RemoveTwitter')),
520
            );
521
            return '
522
				<script type="text/javascript">//<![CDATA[
523
					opener.TwitterResponse(' . Convert::raw2json($array) . ');
524
					window.close();
525
				//]]></script>';
526
        } else {
527
            return '<script type="text/javascript">window.close();</script>';
528
        }
529
    }
530
531
532
//======================================= LOGIN USER ===============================================
533
534
    public function loginUser()
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...
535
    {
536
        $token = SecurityToken::inst();
537
        $callback = $this->AbsoluteLink('Login');
538
        $callback = $token->addToUrl($callback);
539
        $consumer = self::get_zend_oauth_consumer_class($callback);
540
        $token = $consumer->getRequestToken();
541
        Session::set('Twitter.Request.Token', serialize($token));
542
        $url = $consumer->getRedirectUrl();
543
        return self::curr()->redirect($url);
544
    }
545
546
547
    /**
548
     * works with the login form
549
     */
550
    public function Login(SS_HTTPRequest $req)
551
    {
552
        $token = SecurityToken::inst();
553
        if (!$token->checkRequest($req)) {
554
            return $this->httpError(400);
555
        }
556
        if ($req->getVar('denied')) {
557
            Session::set('FormInfo.TwitterLoginForm_LoginForm.formError.message', 'Login cancelled.');
558
            Session::set('FormInfo.TwitterLoginForm_LoginForm.formError.type', 'error');
559
            return $this->redirect('Security/login#TwitterLoginForm_LoginForm_tab');
560
        }
561
        $consumer = self::get_zend_oauth_consumer_class();
562
        $token = Session::get('Twitter.Request.Token');
563
        if (is_string($token)) {
564
            $token = unserialize($token);
565
        }
566
        try {
567
            $access = $consumer->getAccessToken($req->getVars(), $token);
568
            $client = $access->getHttpClient(self::$zend_oauth_consumer_class_config["nocallback"]);
569
            $client->setUri('https://api.twitter.com/1.1/account/verify_credentials.json');
570
            $client->setMethod(Zend_Http_Client::GET);
571
            $client->setParameterGet('skip_status', 't');
572
            $response = $client->request();
573
            $data = $response->getBody();
574
            $data = json_decode($data);
575
            $user = $data->id;
576
        } catch (Exception $e) {
577
            Session::set('FormInfo.TwitterLoginForm_LoginForm.formError.message', $e->getMessage());
578
            Session::set('FormInfo.TwitterLoginForm_LoginForm.formError.type', 'error');
579
            SS_Log::log($e, SS_Log::ERR);
580
            return $this->redirect('Security/login#TwitterLoginForm_LoginForm_tab');
581
        }
582
        if (!is_numeric($user)) {
583
            Session::set('FormInfo.TwitterLoginForm_LoginForm.formError.message', 'Invalid user id received from Twitter.');
584
            Session::set('FormInfo.TwitterLoginForm_LoginForm.formError.type', 'error');
585
            return $this->redirect('Security/login#TwitterLoginForm_LoginForm_tab');
586
        }
587 View Code Duplication
        if ($data && $user && is_numeric($user) && $access) {
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...
588
            $this->updateUserFromTwitterData($user, $data, $access, Session::get('SessionForms.TwitterLoginForm.Remember'));
589
        }
590
        $backURL = $this->returnURL();
591
        return $this->redirect($backURL);
592
    }
593
594 View Code Duplication
    public function remove($request = null)
0 ignored issues
show
This method seems to be duplicated in 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...
595
    {
596
        $token = SecurityToken::inst();
597
        if (!$token->checkRequest($request)) {
598
            return $this->httpError(400);
599
        }
600
        return $this->RemoveTwitter($request);
601
    }
602
603
604
    // ============================================== REMOVE TWITTER ========================
605
606
    public function RemoveTwitter($request)
0 ignored issues
show
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
607
    {
608
        //security
609
        //remove twitter identification
610
        $m = $this->CurrentMember();
611
        if ($m) {
612
            $m->TwitterID = $m->TwitterSecret = $m->TwitterToken = $m->TwitterPicture = $m->TwitterName = $m->TwitterScreenName  = null;
613
            $m->write();
614
        }
615
        $returnURL = $this->returnURL();
616
        $this->redirect($returnURL);
617
    }
618
619
//========================================================== HELPER FUNCTIONS =====================================
620
621
622
623
    /**
624
     * Saves the Twitter data to the member and logs in the member if that has not been done yet.
625
     * @param Int $user - the ID of the current twitter user
626
     * @param Object $twitterData - the data returned from twitter
627
     * @param Object $access - access token
628
     * @param Boolean $keepLoggedIn - does the user stay logged in
629
     * @return Member
630
     */
631
    protected function updateUserFromTwitterData($user, $twitterData, $access, $keepLoggedIn = false)
632
    {
633
        if (is_array($twitterData)) {
634
            $obj = new DataObject();
635
            foreach ($twitterData as $key => $value) {
636
                $obj->$key = $value;
637
            }
638
            $twitterData = $obj;
639
        }
640
        //find member
641
        $member = DataObject::get_one('Member', '"TwitterID" = \'' . Convert::raw2sql($user) . '\'');
642
        if (!$member) {
643
            $member = Member::currentUser();
644
            if (!$member) {
645
                $member = new Member();
646
            }
647
        }
648
        $member->TwitterToken = $access->getParam('oauth_token');
649
        $member->TwitterSecret = $access->getParam('oauth_token_secret');
650
        $member->TwitterID = empty($user) ? 0 : $user;
651
        $member->TwitterPicture = empty($twitterData->profile_image_url) ? "" : $twitterData->profile_image_url;
652
        $member->TwitterName = empty($twitterData->name) ? "" : $twitterData->name;
653
        $member->TwitterScreenName = empty($twitterData->screen_name) ? "" : $twitterData->screen_name;
654
        if (!$twitterData->name) {
655
            $twitterData->name = $twitterData->screen_name;
656
        }
657
        if (!$member->FirstName && !$member->Surname && $twitterData->name) {
658
            $member->FirstName = $twitterData->name;
659
            if ($twitterDataNameArray = explode(" ", $twitterData->name)) {
660
                if (is_array($twitterDataNameArray) && count($twitterDataNameArray) == 2) {
661
                    $member->FirstName = $twitterDataNameArray[0];
662
                    $member->Surname = $twitterDataNameArray[1];
663
                }
664
            }
665
        }
666
        $member->write();
667
        $oldMember = Member::currentUser();
668 View Code Duplication
        if ($oldMember) {
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...
669
            if ($oldMember->ID != $member->ID) {
670
                $oldMember->logout();
671
                $member->login($keepLoggedIn);
672
            } 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...
673
                //already logged in - nothing to do.
674
            }
675
        } else {
676
            $member->login($keepLoggedIn);
677
        }
678
        return $member;
679
    }
680
681
682
//========================================================== TESTS =====================================
683
684
    public function meondatabase()
685
    {
686
        $member = Member::currentUser();
687
        if ($member) {
688
            echo "<ul>";
689
            echo "<li>TwitterID: ".$member->TwitterID."</li>";
690
            echo "<li>TwitterName: ".$member->TwitterName."</li>";
691
            echo "<li>TwitterScreenName: ".$member->TwitterScreenName."</li>";
692
            echo "<li>TwitterToken: ".$member->TwitterToken."</li>";
693
            echo "<li>TwitterSecret: ".$member->TwitterSecret."</li>";
694
            echo "<li>TwitterPicture: ".$member->TwitterPicture."</li>";
695
            echo "</ul>";
696
        } else {
697
            echo "<h2>You are not logged in.</h2>";
698
        }
699
    }
700
}
701