Completed
Pull Request — gcconnex (#1517)
by Nick
16:05
created

api.php ➔ exportEntity()   B

Complexity

Conditions 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
dl 0
loc 22
rs 8.9197
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(
60
	$type,
61
	$subtype = false,
62
	$guid = null,
63
	$since = null,
64
	$before = null,
65
	$limit = null,
66
	$resume = null,
67
	$sort = false
68
) {
69
	$where = ['a.enabled = "yes"'];
70
	if ($type !== 'export') {
71
		$where[] = 'a.type = "' . mysql_escape_string($type) . '"';
72
	}
73
	if ($subtype !== false) {
74
		$subtype_id = get_data("select id from ".elgg_get_config('dbprefix')."entity_subtypes where subtype = '$subtype'")[0]->id;
75
		$where[] = 'a.subtype = ' . $subtype_id;
76
	} else {
77
		$subtype_id = 0;
78
	}
79
80
	if (!is_null($guid) && is_numeric($guid)) {
81
		$where[] = 'a.guid = ' . mysql_escape_string(intval($guid));
82
	}
83
	if (is_numeric($since)) {
84
		$where[] = 'a.time_updated > ' . mysql_escape_string($since);
85
	}
86
	if (is_numeric($before)) {
87
		$where[] = 'a.time_updated < ' . mysql_escape_string($before);
88
	}
89
90
	$limit_sql = '';
91
	if (is_numeric($limit)) {
92
		$limit_sql = 'LIMIT ' . mysql_escape_string($limit);
93
	}
94
	$where_sql = '';
95
	if (count($where) > 0) {
96
		$where_sql = 'WHERE ' . implode(' AND ', $where);
97
	}
98
	if ($sort) {
99
		$sort_sql = 'ORDER BY a.time_updated ASC';
100
	}
101
	try {
102
		$sql = '
103
    SELECT
104
      a.guid
105
    FROM
106
      '.elgg_get_config('dbprefix').'entities a
107
    ' . $where_sql . '
108
    ' . $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...
109
    ' . $limit_sql;
110
111
		$result = mysql_query($sql, _elgg_services()->db->getLink('read'));
112
		yield mysql_num_rows($result);
113
		$emit = !is_numeric($resume);
114
		while ($row = mysql_fetch_object($result)) {
115
			if ($emit) {
116
				yield $row->guid;
117
			}
118
			if (!$emit) {
119
				if ($row->guid == $resume) {
120
					$emit = true;
121
				}
122
			}
123
		}
124
	} catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
125
	}
126
}
127
128
/**
129
* Iterate over list of GUIDs and yields the complete object as a row.
130
*
131
* @param mixed $entity_guids Array of entity GUIDs
132
*/
133
function mm_api_entity_export($entity_guids)
134
{
135
	function exportEntity($entity_or_guid)
136
	{
137
		if (is_object($entity_or_guid)) {
138
			$entity = $entity_or_guid;
139
		} else {
140
			$entity = get_entity($entity_or_guid);
141
			if (!is_object($entity)) {
142
				$ret = new \stdClass;
143
				$ret->guid = $entity_or_guid;
144
				$ret->__error__ = 'Not found';
145
				return $ret;
146
			}
147
		}
148
		$ret = new \stdClass;
149
		$exportable_values = $entity->getExportableValues();
150
		foreach ($exportable_values as $v) {
151
			$ret->$v = $entity->$v;
152
		}
153
		$ret->url = $entity->getURL();
154
		$ret->subtype_name = $entity->getSubtype();
155
		return $ret;
156
	}
157
158
	$skipped_counter = false;
159
	foreach ($entity_guids as $uguid) {
160
		if (!$skipped_counter) {
161
			$skipped_counter = true;
162
			continue;
163
		}
164
		if ($object = get_entity($uguid)) {
165
			$options = array(
166
				'guid' => $object->guid,
167
				'limit' => 0
168
			);
169
170
			$metadata = elgg_get_metadata($options);
171
			$annotations = elgg_get_annotations($options);
172
			$relationships = get_entity_relationships($object->guid);
173
			$relationships2 = get_entity_relationships($object->guid, true);
174
175
			$data = exportEntity($object);
176
177
			if ($metadata) {
178
				foreach ($metadata as $v) {
179
					$prop = $v->name;
180
					$data->$prop = $v->value;
181
				}
182
			}
183
			if ($annotations) {
184
				foreach ($annotations as $v) {
185
					$data->annotations[$v->name] = $v->value;
186
				}
187
			}
188 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...
189
				foreach ($relationships as $v) {
190
					$data->relationships[] = array(
191
						'direction' => 'OUT',
192
						'time_created' => $v->time_created,
193
						'id' => $v->id,
194
						'entity' => exportEntity($v->guid_two),
195
						'relationship' => $v->relationship,
196
					);
197
				}
198
			}
199 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...
200
				foreach ($relationships2 as $v) {
201
					$data->relationships[] = array(
202
						'direction' => 'IN',
203
						'time_created' => $v->time_created,
204
						'id' => $v->id,
205
						'entity' => exportEntity($v->guid_one),
206
						'relationship' => $v->relationship,
207
					);
208
				}
209
			}
210
			yield [ 'object' => $object, 'export' => $data ];
211
		}
212
	}
213
}
214
215
// Public key of server authorized to make requests against this API.
216
define('PUBLIC_KEY', "-----BEGIN PUBLIC KEY-----
217
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAmYj9ceaqHi7UmUmhE8e/
218
eU/02ZEJeLD8HN7Ku+VN8IB1dIwoSibvoxWZv5bfKnVajkGvud88TMNw3NwqO1jP
219
b2XiXs/1VvJkqHC/KYkd82iDUOdiDxvXtl8ZxVRA3m4WjtTIB8eJCZitc75fNrzl
220
fshoP0XQfbNQBBvfP7IBvPIhNuRPgmRMcDdzisqM+c2mAAzQQ04AZ11olhTZzYW0
221
HEx6vExkdNBXy/Q0pWas5Zvxe4eTONi7ls14GMKzMeecDnlbQh6P/dCf9ZGF06eM
222
biMSsnUiYeGsCgtAm9voq0omuVaDY6BDtlsJ50UyMnS5cCIkQrA1Vlt6g8MNt3jh
223
yXX8L0SxORCBiLGobFnxMSqvuxZkHjp7Jq/k4S3JK2mYxWlJHzcOB8yioI99ErqU
224
IO+2bqljuNe9v95bh3wu82UjhpU+gmbL5TMqR3mVGGH6mW2WJaRkujQL9hK/efde
225
V5T4oSM85QajxodYF4nsnhVjmQLzyDxQcVTyj6yQk+cwr68guOMkh389G29Kxgoi
226
otz1VvR5vYO5/KOFRDkELA8XLEIWtKmwYXTwmwzjX36GdeQpDny3JGJMlBPP7xVd
227
cBCzK/zh7Ize/pWhN5KSAhJ/a0jByClU0VtMD5d8da6dClWkO6k+Mg9nynSsIAOr
228
ALJ7RZP/EF2k6WwUtdrGluUCAwEAAQ==
229
-----END PUBLIC KEY-----
230
");
231