Completed
Push — recommendation-api-updates ( 5dc1c7 )
by
unknown
21:29
created

api.php ➔ createInvalidEntityObject()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
* NRC Recommendation Platform API Library
5
* Copyright (c) 2017 National Research Council Canada
6
*
7
* Author: Luc Belliveau <[email protected]>
8
*
9
*/
10
header('Content-Type: application/json');
11
12
/**
13
* Verify that the API request has the appropriate X-Custom-Authorization
14
* header, and make sure the script has all require privileges to run.
15
*
16
* Responds with a 403 if authorization is missing or invalid.
17
*
18
*/
19
function mm_api_secure() {
0 ignored issues
show
Coding Style introduced by
mm_api_secure 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...
20
21
  if (
22
      !isset($_SERVER['HTTP_X_CUSTOM_AUTHORIZATION'])
23
      || (!openssl_public_decrypt(base64_decode($_SERVER['HTTP_X_CUSTOM_AUTHORIZATION']), $decrypted, PUBLIC_KEY))
24
      || ($decrypted !== '-- NRC -- LPSS -- GCTools -- Sig -- dsaj9843uj80w7IJHYS&UHSJY(*IOIJHY*')
25
    ) {
26
    header('HTTP/1.0 403 Forbidden');
27
    exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The function mm_api_secure() contains an exit expression.

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

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

Loading history...
28
  }
29
30
  # Ensure API has full access
31
  session_destroy();
32
  elgg_set_ignore_access(true);
33
34
  # Increase the script timeout value
35
  set_time_limit(14400);
36
}
37
38
/**
39
* Generator that finds the GUIDs of the entities defined by the search critera.
40
* The first value yielded is the total number of guids found.
41
*
42
* @param str $type Desired entity type.  (object, user, export)
43
* @param str $subtype Desired subtype.  (mission)
44
* @param int $guid GUID of single object, for single entity fetch.
45
* @param int $since: Fetch entities that have been modified since the specified time
0 ignored issues
show
Documentation introduced by
There is no parameter named $since:. Did you maybe mean $since?

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...
46
* @param int $before: Fetch entities that have been modified before the specified time
0 ignored issues
show
Documentation introduced by
There is no parameter named $before:. Did you maybe mean $before?

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...
47
* @param int $limit: Fetch at most X entities.
0 ignored issues
show
Documentation introduced by
There is no parameter named $limit:. Did you maybe mean $limit?

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...
48
* @param int $resume: Resume starting at the specified GUID.
0 ignored issues
show
Documentation introduced by
There is no parameter named $resume:. Did you maybe mean $resume?

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...
49
* @param bool $sort: If true sorts entities based on time created.
0 ignored issues
show
Bug introduced by
There is no parameter named $sort:. 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...
50
* @param str $omit: Comma separated list of GUIDs to omit.
0 ignored issues
show
Bug introduced by
There is no parameter named $omit:. 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...
51
*
52
* @return Generator[] Guid iterable
53
*/
54
function mm_api_get_entity_guids($type, $subtype = false, $guid = null,
55
$since = null, $before = null, $limit = null, $resume = null, $sort = false,
56
$omit = null) {
57
  $where = ['a.enabled = "yes"'];
58
  if ($type !== 'export') {
59
    $where[] = 'a.type = "' . mysql_escape_string($type) . '"';
60
  }
61
  if ($subtype !== false) {
62
    $subtype_id = get_data("select id from ".elgg_get_config('dbprefix')."entity_subtypes where subtype = '$subtype'")[0]->id;
63
    $where[] = 'a.subtype = ' . $subtype_id;
64
  } else $subtype_id = 0;
65
66
  if (!is_null($guid) && is_numeric($guid)) {
67
    $where[] = 'a.guid = ' . mysql_escape_string(intval($guid));
68
  }
69
  if (is_numeric($since)) {
70
    $where[] = 'a.time_updated > ' . mysql_escape_string($since);
71
  }
72
  if (is_numeric($before)) {
73
    $where[] = 'a.time_updated < ' . mysql_escape_string($before);
74
  }
75
  if (!is_null($omit)) {
76
    $omitGuids = explode(',', $omit);
77
    if (count($omitGuids) > 0) {
78
      $ogs = [];
79
      foreach ($omitGuids as $og) {
80
        $ogs[] = mysql_escape_string(intval($og));
81
      }
82
      $where[] = 'a.guid NOT IN ('.implode(',', $ogs).')';
83
    }
84
  }
85
86
  $where_sql = '';
87
  if (count($where) > 0) {
88
    $where_sql = 'WHERE ' . implode(' AND ', $where);
89
  }
90
  if ($sort) {
91
    $sort_sql = 'ORDER BY a.time_updated ASC';
92
  }
93
  try {
94
    $sql = '
95
    SELECT
96
      a.guid
97
    FROM
98
      '.elgg_get_config('dbprefix').'entities a
99
    ' . $where_sql . '
100
    ' . $sort_sql;
0 ignored issues
show
Bug introduced by
The variable $sort_sql 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...
101
    $result = mysql_query($sql, _elgg_services()->db->getLink('read'));
102
    yield mysql_num_rows($result);
103
    $emit = !is_numeric($resume);
104
    $max = (is_numeric($limit) && ($limit > 0)) ? $limit : false;
105
    $count = 0;
106
    while ($row = mysql_fetch_object($result)) {
107
      if ($emit) {
108
        $count += 1;
109
        yield $row->guid;
110
        if (($max !== false) && ($count >= $max)) break;
111
      }
112
      if (!$emit) {
113
        if ($row->guid == $resume) {
114
          $emit = true;
115
        }
116
      }
117
    }
118
  } catch (Exception $e) {
119
    //
120
  }
121
}
122
123
/**
124
* Iterate over list of GUIDs and yields the complete object as a row.
125
*
126
* @param mixed $entity_guids Array of entity GUIDs
127
*/
128
function mm_api_entity_export($entity_guids) {
129
  function createInvalidEntityObject($guid) {
130
    $ret = new \stdClass;
131
    $ret->guid = $guid;
132
    $ret->__error__ = 'Incomplete Entity Error';
133
    return $ret;
134
  }
135
  function exportEntity($entity_or_guid) {
136
    // List of fields not to include in any export
137
    $omit = array('password', 'password_hash', 'salt');
138
    if (is_object($entity_or_guid)) {
139
      $entity = $entity_or_guid;
140
    } else {
141
      $entity = get_entity($entity_or_guid);
142
      if (!is_object($entity)) {
143
        $invalidObj = createInvalidEntityObject($entity_or_guid);
144
        return [$invalidObj, $invalidObj];
145
      }
146
    }
147
    $ret = new \stdClass;
148
    $exportable_values = $entity->getExportableValues();
149
    foreach ($exportable_values as $v) {
150
      $ret->$v = $entity->$v;
151
    }
152
    foreach ($entity as $field=>$value) {
153
      if (!in_array($field, $exportable_values) && !in_array($field, $omit)) {
154
        $ret->$field = $value;
155
      }
156
    }
157
    $ret->url = $entity->getURL();
158
    $ret->subtype_name = $entity->getSubtype();
159
    return [$entity, $ret];
160
  }
161
  function dismount($object) {
162
    $reflectionClass = new ReflectionClass(get_class($object));
163
    $array = array();
164
    foreach ($reflectionClass->getProperties() as $property) {
165
        $property->setAccessible(true);
166
        $array[$property->getName()] = $property->getValue($object);
167
        $property->setAccessible(false);
168
    }
169
    return $array;
170
  }
171
172
  while ($entity_guids->valid()) {
173
    yield ',';
174
175
    $uguid = $entity_guids->current();
176
    $objectData = exportEntity($uguid);
177
    $object = $objectData[0];
178
    $data = $objectData[1];
179
180
    $options = array(
181
      'guid' => $object->guid,
182
      'limit' => 0
183
    );
184
185
    $metadata = elgg_get_metadata($options);
186
    $annotations = elgg_get_annotations($options);
187
188
    if ($metadata) {
189
      foreach ($metadata as $v) {
190
        $prop = $v->name;
191
        if (!isset($data->$prop)) $data->$prop = $object->$prop;
192
      }
193
    }
194
    if ($annotations) {
195
      foreach ($annotations as $v) {
196
        if (!isset($data->annotations[$v->name])) {
197
          $data->annotations[$v->name] = [];
198
        };
199
        $data->annotations[$v->name][] = dismount($v);
200
      }
201
    }
202
    yield '{'.substr(json_encode($data), 1, -1) . ',"relationships":[';
203
204
    $relstart = false;
205
    $reltable = elgg_get_config('dbprefix') . 'entity_relationships';
206
    $relationships = mysql_unbuffered_query(
207
      "SELECT * from $reltable where guid_one = {$object->guid}",
208
      _elgg_services()->db->getLink('read')
209
    );
210 View Code Duplication
    while ($v = mysql_fetch_object($relationships)) {
211
      yield (($relstart) ? ',' : '') . json_encode(array(
212
        'direction' => 'OUT',
213
        'time_created' => $v->time_created,
214
        'id' => $v->id,
215
        'relationship' => $v->relationship,
216
        'entity' => $v->guid_two,
217
      ));
218
      $relstart = true;
219
    }
220
    mysql_free_result($relationships);
221
222
    $relationships2 = mysql_unbuffered_query(
223
      "SELECT * from $reltable where guid_two = {$object->guid}",
224
      _elgg_services()->db->getLink('read')
225
    );
226 View Code Duplication
    while ($v = mysql_fetch_object($relationships2)) {
227
      yield (($relstart) ? ',' : '') . json_encode(array(
228
        'direction' => 'IN',
229
        'time_created' => $v->time_created,
230
        'id' => $v->id,
231
        'relationship' => $v->relationship,
232
        'entity' => $v->guid_one,
233
      ));
234
      $relstart = true;
235
    }
236
    mysql_free_result($relationships2);
237
    yield ']}';
238
    $entity_guids->next();
239
  }
240
}
241
242
// Public key of server authorized to make requests against this API.
243
define('PUBLIC_KEY', "-----BEGIN PUBLIC KEY-----
244
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAmYj9ceaqHi7UmUmhE8e/
245
eU/02ZEJeLD8HN7Ku+VN8IB1dIwoSibvoxWZv5bfKnVajkGvud88TMNw3NwqO1jP
246
b2XiXs/1VvJkqHC/KYkd82iDUOdiDxvXtl8ZxVRA3m4WjtTIB8eJCZitc75fNrzl
247
fshoP0XQfbNQBBvfP7IBvPIhNuRPgmRMcDdzisqM+c2mAAzQQ04AZ11olhTZzYW0
248
HEx6vExkdNBXy/Q0pWas5Zvxe4eTONi7ls14GMKzMeecDnlbQh6P/dCf9ZGF06eM
249
biMSsnUiYeGsCgtAm9voq0omuVaDY6BDtlsJ50UyMnS5cCIkQrA1Vlt6g8MNt3jh
250
yXX8L0SxORCBiLGobFnxMSqvuxZkHjp7Jq/k4S3JK2mYxWlJHzcOB8yioI99ErqU
251
IO+2bqljuNe9v95bh3wu82UjhpU+gmbL5TMqR3mVGGH6mW2WJaRkujQL9hK/efde
252
V5T4oSM85QajxodYF4nsnhVjmQLzyDxQcVTyj6yQk+cwr68guOMkh389G29Kxgoi
253
otz1VvR5vYO5/KOFRDkELA8XLEIWtKmwYXTwmwzjX36GdeQpDny3JGJMlBPP7xVd
254
cBCzK/zh7Ize/pWhN5KSAhJ/a0jByClU0VtMD5d8da6dClWkO6k+Mg9nynSsIAOr
255
ALJ7RZP/EF2k6WwUtdrGluUCAwEAAQ==
256
-----END PUBLIC KEY-----
257
");
258
259
?>
0 ignored issues
show
Best Practice introduced by
It is not recommended to use PHP's closing tag ?> in files other than templates.

Using a closing tag in PHP files that only contain PHP code is not recommended as you might accidentally add whitespace after the closing tag which would then be output by PHP. This can cause severe problems, for example headers cannot be sent anymore.

A simple precaution is to leave off the closing tag as it is not required, and it also has no negative effects whatsoever.

Loading history...