jQueryServer::success()   C
last analyzed

Complexity

Conditions 7
Paths 13

Size

Total Lines 34
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 24
nc 13
nop 1
dl 0
loc 34
rs 6.7272
c 0
b 0
f 0
1
`
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 21 and the first side effect is on line 1.

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
<?php
3
use PhpQuery\PhpQueryObject;
4
use PhpQuery\PhpQuery;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, PhpQuery.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
6
/**
7
 * jQuery Server Plugin
8
 *
9
 * Backend class using PhpQuery.
10
 *
11
 * @version 0.5.1
12
 * @author Tobiasz Cudnik <tobiasz.cudnik/gmail.com>
13
 * @link http://code.google.com/p/phpquery/wiki/jQueryServer
14
 * @link http://code.google.com/p/phpquery/
15
 * @todo local files support (safe...)
16
 * @todo respond with proper HTTP code
17
 * @todo persistant thread support (with timeout...)
18
 * @todo 2.0: JSON RPC - Zend_Json_Server
19
 * @todo 2.0: XML RPC ?
20
 */
21
class jQueryServer {
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...
22
  public $config = array(
23
    'allowedRefererHosts' => array(
24
      '.'
25
    ),
26
    'refererMustMatch' => true,
27
  );
28
  public $calls = null;
29
  public $options = null;
30
  public $allowedHosts = null;
31
  function __construct($data) {
0 ignored issues
show
Best Practice introduced by
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...
Coding Style introduced by
__construct uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
32
    $pq = null;
0 ignored issues
show
Unused Code introduced by
$pq 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...
33
    include_once(dirname(__FILE__) . '/../PhpQuery/PhpQuery.php');
34
    if (file_exists(dirname(__FILE__) . '/jQueryServer.config.php')) {
35
      include_once(dirname(__FILE__) . '/jQueryServer.config.php');
36
      if ($jQueryServerConfig)
37
        $this->config = array_merge_recursive($this->config, $jQueryServerConfig);
0 ignored issues
show
Bug introduced by
The variable $jQueryServerConfig 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...
38
    }
39
    if ($this->config['refererMustMatch']) {
40
      foreach ($this->config['allowedRefererHosts'] as $i => $host)
41
        if ($host == '.')
42
          $this->config['allowedRefererHosts'][$i] = $_SERVER['HTTP_HOST'];
43
      $referer = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);
44
      $authorized = $referer
0 ignored issues
show
Bug Best Practice introduced by
The expression $referer of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
45
        && in_array($referer, $this->config['allowedRefererHosts']);
46
      if (!$authorized) {
47
        throw new \Exception("Host '{$_SERVER['HTTP_REFERER']}' not authorized to make requests.");
48
        return;
0 ignored issues
show
Unused Code introduced by
return; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
49
      }
50
    }
51
    //		PhpQueryClass::$debug = true;
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% 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...
52
    //		if (! function_exists('json_decode')) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
53
    //			include_once(dirname(__FILE__).'/JSON.php');
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% 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...
54
    //			$this->json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
55
    //		}
56
    //		$data = $this->jsonDecode($data);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
57
    $data = PhpQuery::parseJSON($data);
58
    // load document (required for first $data element)
59
    if (is_array($data[0]) && isset($data[0]['url'])) {
60
      $this->options = $data[0];
61
      $ajax = $this->options;
62
      $this->calls = array_slice($data, 1);
63
      $ajax['success'] = array(
64
        $this,
65
        'success'
66
      );
67
      PhpQuery::ajax($ajax);
68
    }
69
    else {
70
      throw new \Exception("URL needed to download content");
71
    }
72
  }
73
  public function success($response) {
74
    $pq = PhpQuery::newDocument($response);
75
    foreach ($this->calls as $k => $r) {
76
      // check if method exists
77
      if (!method_exists(get_class($pq), $r['method'])) {
78
        throw new \Exception("Method '{$r['method']}' not implemented in PhpQuery, sorry...");
79
        // execute method
80
      }
81
      else {
82
        $pq = call_user_func_array(array(
83
          $pq,
84
          $r['method']
85
        ), $r['arguments']);
86
      }
87
    }
88
    if (!isset($this->options['dataType']))
89
      $this->options['dataType'] = '';
90
    switch (strtolower($this->options['dataType'])) {
91
      case 'json':
92
        if ($pq instanceof PhpQueryObject) {
93
          $results = array();
94
          foreach ($pq as $node)
95
            $results[] = pq($node)->htmlOuter();
96
          print PhpQuery::toJSON($results);
97
        }
98
        else {
99
          print PhpQuery::toJSON($pq);
100
        }
101
        break;
102
      default:
103
        print $pq;
0 ignored issues
show
Security Cross-Site Scripting introduced by
$pq can contain request data and is used in output context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_POST, and $_POST['data'] is passed to jQueryServer::__construct()
    in src/Proxy/jQueryServer.php on line 118
  2. Data is passed through trim(), and Data is decoded by json_decode()
    in vendor/src/PhpQuery.php on line 1173
  3. $data is assigned
    in src/Proxy/jQueryServer.php on line 57
  4. $data is passed through array_slice(), and jQueryServer::$calls is assigned
    in src/Proxy/jQueryServer.php on line 62
  5. Tainted property jQueryServer::$calls is read, and $r is assigned
    in src/Proxy/jQueryServer.php on line 75
  6. $r['arguments'] is passed through call_user_func_array()
    in src/Proxy/jQueryServer.php on line 85
  7. $pq is assigned
    in src/Proxy/jQueryServer.php on line 82

Preventing Cross-Site-Scripting Attacks

Cross-Site-Scripting allows an attacker to inject malicious code into your website - in particular Javascript code, and have that code executed with the privileges of a visiting user. This can be used to obtain data, or perform actions on behalf of that visiting user.

In order to prevent this, make sure to escape all user-provided data:

// for HTML
$sanitized = htmlentities($tainted, ENT_QUOTES);

// for URLs
$sanitized = urlencode($tainted);

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
104
    }
105
    // output results
106
  }
107
  //	public function jsonEncode($data) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
108
  //		return function_exists('json_encode')
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
109
  //			? json_encode($data)
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
110
  //			: $this->json->encode($data);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
111
  //	}
112
  //	public function jsonDecode($data) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
113
  //		return function_exists('json_decode')
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
114
  //			? json_decode($data, true)
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
115
  //			: $this->json->decode($data);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
116
  //	}
117
}
118
new jQueryServer($_POST['data']);