Completed
Pull Request — gcconnex (#1471)
by
unknown
16:57
created

api.php ➔ exportEntity()   A

Complexity

Conditions 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
dl 0
loc 21
rs 9.0534
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
global $meta_fields;
13
$meta_fields = [
14
  'education',
15
  'work',
16
  'gc_skills',
17
  'portfolio',
18
];
19
20
/**
21
* Verify that the API request has the appropriate X-Custom-Authorization
22
* header, and make sure the script has all require privileges to run.
23
*
24
* Responds with a 403 if authorization is missing or invalid.
25
*
26
*/
27
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...
28
29
  if (
30
      !isset($_SERVER['HTTP_X_CUSTOM_AUTHORIZATION'])
31
      || (!openssl_public_decrypt(base64_decode($_SERVER['HTTP_X_CUSTOM_AUTHORIZATION']), $decrypted, PUBLIC_KEY))
32
      || ($decrypted !== '-- NRC -- LPSS -- GCTools -- Sig -- dsaj9843uj80w7IJHYS&UHSJY(*IOIJHY*')
33
    ) {
34
    header('HTTP/1.0 403 Forbidden');
35
    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...
36
  }
37
38
  # Ensure API has full access
39
  session_destroy();
40
  elgg_set_ignore_access(true);
41
42
  # Increase the script timeout value
43
  set_time_limit(14400);
44
}
45
46
/**
47
* Generator that finds the GUIDs of the entities defined by the search critera.
48
*
49
* @param str $type Desired entity type.  (object, user)
50
* @param str $subtype Desired subtype.  (mission)
51
* @param int $guid GUID of single object, for single entity fetch.
52
* @param int $since: Fetch objects 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...
53
* @param int $before: Fetch obhects 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...
54
* @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...
55
* @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...
56
*
57
* @return Generator[] Guid iterable
58
*/
59
function mm_api_get_entity_guids($type, $subtype = false, $guid = null,
60
$since = null, $before = null, $limit = null, $resume = null, $sort = false) {
61
  $where = ['a.enabled = "yes"'];
62
  if ($type !== 'export') {
63
    $where[] = 'a.type = "' . mysql_escape_string($type) . '"';
64
  }
65
  if ($subtype !== false) {
66
    $subtype_id = get_data("select id from ".elgg_get_config('dbprefix')."entity_subtypes where subtype = '$subtype'")[0]->id;
67
    $where[] = 'a.subtype = ' . $subtype_id;
68
  } else $subtype_id = 0;
69
70
  if (!is_null($guid) && is_numeric($guid)) {
71
    $where[] = 'a.guid = ' . mysql_escape_string(intval($guid));
72
  }
73
  if (is_numeric($since)) {
74
    $where[] = 'a.time_updated > ' . mysql_escape_string($since);
75
  }
76
  if (is_numeric($before)) {
77
    $where[] = 'a.time_updated < ' . mysql_escape_string($before);
78
  }
79
80
  $limit_sql = '';
81
  if (is_numeric($limit)) {
82
    $limit_sql = 'LIMIT ' . mysql_escape_string($limit);
83
  }
84
  $where_sql = '';
85
  if (count($where) > 0) {
86
    $where_sql = 'WHERE ' . implode(' AND ', $where);
87
  }
88
  if ($sort) {
89
    $sort_sql = 'ORDER BY a.time_updated ASC';
90
  }
91
  try {
92
    $sql = '
93
    SELECT
94
      a.guid
95
    FROM
96
      '.elgg_get_config('dbprefix').'entities a
97
    ' . $where_sql . '
98
    ' . $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...
99
    ' . $limit_sql;
100
101
    $result = mysql_query($sql, _elgg_services()->db->getLink('read'));
102
    yield mysql_num_rows($result);
103
    $emit = !is_numeric($resume);
104
    while ($row = mysql_fetch_object($result)) {
105
      if ($emit) {
106
        yield $row->guid;
107
      }
108
      if (!$emit) {
109
        if ($row->guid == $resume) {
110
          $emit = true;
111
        }
112
      }
113
    }
114
  } catch (Exception $e) {
115
    //
116
  }
117
}
118
119
/**
120
* Iterate over list of GUIDs and yields the complete object as a row.
121
*
122
* @param mixed $entity_guids Array of entity GUIDs
123
*/
124
function mm_api_entity_export($entity_guids) {
125
  function exportEntity($entity_or_guid) {
126
    if (is_object($entity_or_guid)) {
127
      $entity = $entity_or_guid;
128
    } else {
129
      $entity = get_entity($entity_or_guid);
130
      if (!is_object($entity)) {
131
        $ret = new \stdClass;
132
        $ret->guid = $entity_or_guid;
133
        $ret->__error__ = 'Not found';
134
        return $ret;
135
      }
136
    }
137
    $ret = new \stdClass;
138
    $exportable_values = $entity->getExportableValues();
139
    foreach ($exportable_values as $v) {
140
      $ret->$v = $entity->$v;
141
    }
142
    $ret->url = $entity->getURL();
143
    $ret->subtype_name = $entity->getSubtype();
144
    return $ret;
145
  }
146
147
  $skipped_counter = false;
148
  foreach ($entity_guids as $uguid) {
149
    if (!$skipped_counter) {
150
      $skipped_counter = true;
151
      continue;
152
    }
153
    if ($object = get_entity($uguid)) {
154
      $options = array(
155
        'guid' => $object->guid,
156
        'limit' => 0
157
      );
158
159
      $metadata = elgg_get_metadata($options);
160
      $annotations = elgg_get_annotations($options);
161
      $relationships = get_entity_relationships($object->guid);
162
      $relationships2 = get_entity_relationships($object->guid, true);
163
164
      $data = exportEntity($object);
165
166
      if ($metadata) {
167
        foreach ($metadata as $v) {
168
          $prop = $v->name;
169
          $data->$prop = $v->value;
170
        }
171
      }
172
      if ($annotations) {
173
        foreach ($annotations as $v) {
174
          $data->annotations[$v->name] = $v->value;
175
        }
176
      }
177 View Code Duplication
      if ($relationships) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $relationships of type ElggRelationship[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
178
        foreach ($relationships as $v) {
179
          $data->relationships[] = array(
180
            'direction' => 'OUT',
181
            'time_created' => $v->time_created,
182
            'id' => $v->id,
183
            'entity' => exportEntity($v->guid_two),
184
            'relationship' => $v->relationship,
185
          );
186
        }
187
      }
188 View Code Duplication
      if ($relationships2) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $relationships2 of type ElggRelationship[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
189
        foreach ($relationships2 as $v) {
190
          $data->relationships[] = array(
191
            'direction' => 'IN',
192
            'time_created' => $v->time_created,
193
            'id' => $v->id,
194
            'entity' => exportEntity($v->guid_one),
195
            'relationship' => $v->relationship,
196
          );
197
        }
198
      }
199
      yield [ 'object' => $object, 'export' => $data ];
200
    }
201
  }
202
}
203
204
// Public key of server authorized to make requests against this API.
205
define('PUBLIC_KEY', "-----BEGIN PUBLIC KEY-----
206
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAmYj9ceaqHi7UmUmhE8e/
207
eU/02ZEJeLD8HN7Ku+VN8IB1dIwoSibvoxWZv5bfKnVajkGvud88TMNw3NwqO1jP
208
b2XiXs/1VvJkqHC/KYkd82iDUOdiDxvXtl8ZxVRA3m4WjtTIB8eJCZitc75fNrzl
209
fshoP0XQfbNQBBvfP7IBvPIhNuRPgmRMcDdzisqM+c2mAAzQQ04AZ11olhTZzYW0
210
HEx6vExkdNBXy/Q0pWas5Zvxe4eTONi7ls14GMKzMeecDnlbQh6P/dCf9ZGF06eM
211
biMSsnUiYeGsCgtAm9voq0omuVaDY6BDtlsJ50UyMnS5cCIkQrA1Vlt6g8MNt3jh
212
yXX8L0SxORCBiLGobFnxMSqvuxZkHjp7Jq/k4S3JK2mYxWlJHzcOB8yioI99ErqU
213
IO+2bqljuNe9v95bh3wu82UjhpU+gmbL5TMqR3mVGGH6mW2WJaRkujQL9hK/efde
214
V5T4oSM85QajxodYF4nsnhVjmQLzyDxQcVTyj6yQk+cwr68guOMkh389G29Kxgoi
215
otz1VvR5vYO5/KOFRDkELA8XLEIWtKmwYXTwmwzjX36GdeQpDny3JGJMlBPP7xVd
216
cBCzK/zh7Ize/pWhN5KSAhJ/a0jByClU0VtMD5d8da6dClWkO6k+Mg9nynSsIAOr
217
ALJ7RZP/EF2k6WwUtdrGluUCAwEAAQ==
218
-----END PUBLIC KEY-----
219
");
220
221
?>
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...