functions.php ➔ query_the_posts()   F
last analyzed

Complexity

Conditions 26
Paths 2436

Size

Total Lines 135

Duplication

Lines 25
Ratio 18.52 %

Importance

Changes 0
Metric Value
cc 26
nc 2436
nop 11
dl 25
loc 135
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/*
3
 * GC Mobile API functions.php
4
 */
5
6
function get_user_block($userid, $lang = "en")
7
{
8
	$user_entity = is_numeric($userid) ? get_user($userid) : (strpos($userid, '@') !== false ? get_user_by_email($userid)[0] : get_user_by_username($userid));
9
10
	if (!$user_entity) {
11
		return "";
12
	}
13
14
	if (!$user_entity instanceof ElggUser) {
15
		return "";
16
	}
17
18
	$user = array();
19
	$user['user_id'] = $user_entity->guid;
20
	$user['username'] = $user_entity->username;
21
	$user['displayName'] = $user_entity->name;
22
	$user['email'] = $user_entity->email;
23
	$user['profileURL'] = $user_entity->getURL();
24
	$user['iconURL'] = $user_entity->getIconURL();
25
	$user['dateJoined'] = date("Y-m-d H:i:s", $user_entity->time_created);
26
27
	$userType = $user_entity->user_type;
28
	$user['user_type'] = elgg_echo("gcRegister:occupation:{$userType}", [], $lang);
29
	$department = "";
30
31
	if ($userType == 'federal') {
32
		$deptObj = elgg_get_entities(array(
33
			'type' => 'object',
34
			'subtype' => 'federal_departments',
35
		));
36
		$depts = get_entity($deptObj[0]->guid);
37
38
		$federal_departments = array();
39
		if ($lang == 'en') {
40
			$federal_departments = json_decode($depts->federal_departments_en, true);
41
		} else {
42
			$federal_departments = json_decode($depts->federal_departments_fr, true);
43
		}
44
45
		$department = $federal_departments[$user_entity->federal];
46
47
		// otherwise if user is student or academic
48 View Code Duplication
	} elseif ($userType == 'student' || $userType == 'academic') {
49
		$institution = $user_entity->institution;
50
		$department = ($institution == 'university') ? $user_entity->university : ($institution == 'college' ? $user_entity->college : $user_entity->highschool);
51
52
		// otherwise if user is provincial employee
53
	} elseif ($userType == 'provincial') {
54
		$provObj = elgg_get_entities(array(
55
			'type' => 'object',
56
			'subtype' => 'provinces',
57
		));
58
		$provs = get_entity($provObj[0]->guid);
59
60
		$provinces = array();
61
		if ($lang == 'en') {
62
			$provinces = json_decode($provs->provinces_en, true);
63
		} else {
64
			$provinces = json_decode($provs->provinces_fr, true);
65
		}
66
67
		$minObj = elgg_get_entities(array(
68
			'type' => 'object',
69
			'subtype' => 'ministries',
70
		));
71
		$mins = get_entity($minObj[0]->guid);
72
73
		$ministries = array();
74
		if ($lang == 'en') {
75
			$ministries = json_decode($mins->ministries_en, true);
76
		} else {
77
			$ministries = json_decode($mins->ministries_fr, true);
78
		}
79
80
		$department = $provinces[$user_entity->provincial];
81
		if ($user_entity->ministry && $user_entity->ministry !== "default_invalid_value") {
82
			$department .= ' / ' . $ministries[$user_entity->provincial][$user_entity->ministry];
83
		}
84
85
		// otherwise show basic info
86
	} else {
87
		$department = $user_entity->$userType;
88
	}
89
	$user['organization'] = $department;
90
	$user['job'] = $user_entity->job;
91
92
	return $user;
93
}
94
95
function get_entity_comments($guid)
96
{
97
	$entity = get_entity($guid);
98
99
	$comments = array();
100
	$comments['count'] = $entity->countComments();
101
	$commentEntites = elgg_get_entities(array(
102
		'type' => 'object',
103
		'subtype' => 'comment',
104
		'container_guid' => $entity->guid,
105
		'order_by' => 'time_created asc'
106
	));
107
108
	$i = 0;
109 View Code Duplication
	foreach ($commentEntites as $comment) {
110
		$i++;
111
		$comments['comment_'.$i] = array('comment_user'=>get_userBlock($comment->getOwner()),'comment_text'=>$comment->description,'comment_date'=>date("Y-m-d H:i:s", $comment->time_created));
112
	}
113
	return $comments;
114
}
115
116 View Code Duplication
function wire_filter($text)
117
{
118
	$site_url = elgg_get_site_url();
119
120
	$text = ''.$text;
121
122
	// email addresses
123
	$text = preg_replace('/(^|[^\w])([\w\-\.]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})/i', '$1<a href="mailto:$2@$3">$2@$3</a>', $text);
124
125
	// links
126
	$text = parse_urls($text);
127
128
	// usernames
129
	$text = preg_replace('/(^|[^\w])@([\p{L}\p{Nd}._]+)/u', '$1<a href="' . $site_url . 'thewire/owner/$2">@$2</a>', $text);
130
131
	// hashtags
132
	$text = preg_replace('/(^|[^\w])#(\w*[^\s\d!-\/:-@]+\w*)/', '$1<a href="' . $site_url . 'thewire/tag/$2">#$2</a>', $text);
133
134
	$text = trim($text);
135
136
	return $text;
137
}
138
139
function clean_text($text)
140
{
141
	return trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($text))))));
142
}
143
144
function replace_accents($str)
145
{
146
	$a = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', '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', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o');
148
	return str_replace($a, $b, $str);
149
}
150
151 View Code Duplication
function create_username($str, $a_char = array("'", "-", "."))
152
{
153
	$string = replace_accents(mb_strtolower(strtok($str, '@')));
154
	foreach ($a_char as $temp) {
155
		$pos = strpos($string, $temp);
156
		if ($pos) {
157
			$mend = '';
158
			$a_split = explode($temp, $string);
159
			foreach ($a_split as $temp2) {
160
				$mend .= ucfirst($temp2).$temp;
161
			}
162
			$string = substr($mend, 0, -1);
163
		}
164
	}
165
	return ucfirst($string);
166
}
167
168
elgg_ws_expose_function(
169
	"query.posts",
170
	"query_the_posts",
171
	array(
172
		"user" => array('type' => 'string', 'required' => true),
173
		"password" => array('type' => 'string', 'required' => true),
174
		"object" => array('type' => 'string', 'required' => false, 'default' => ""),
175
		"query" => array('type' => 'string', 'required' => false, 'default' => ""),
176
		"group" => array('type' => 'string', 'required' => false, 'default' => ""),
177
		"guid" => array('type' => 'string', 'required' => false, 'default' => ""),
178
		"limit" => array('type' => 'int', 'required' => false, 'default' => 10),
179
		"offset" => array('type' => 'int', 'required' => false, 'default' => 0),
180
		"from_date" => array('type' => 'string', 'required' => false, 'default' => ""),
181
		"to_date" => array('type' => 'string', 'required' => false, 'default' => ""),
182
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
183
	),
184
	'Query GCcollab data based on user-given parameters',
185
	'POST',
186
	false,
187
	false
188
);
189
190
function query_the_posts($user, $password, $object, $query, $group, $guid, $limit, $offset, $from_date, $to_date, $lang)
191
{
192
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
193
	if (!$user_entity) {
194
		return "User was not found. Please try a different GUID, username, or email address";
195
	}
196
	if (!$user_entity instanceof ElggUser) {
197
		return "Invalid user. Please try a different GUID, username, or email address";
198
	}
199
200
    $valid = elgg_authenticate($user_entity->username, $password);
201
202
    $type = "object";
203
    $subtype = "";
204
    switch ($object) {
205
    	case "blog":
206
    		$subtype = "blog";
207
        	break;
208
        case "discussion":
209
    		$subtype = "groupforumtopic";
210
        	break;
211
        case "event":
212
    		$subtype = "event_calendar";
213
        	break;
214
        case "group":
215
    		$type = "group";
216
        	break;
217
        case "opportunity":
218
    		$subtype = "mission";
219
        	break;
220
        case "wire":
221
    		$subtype = "thewire";
222
        	break;
223
        default:
224
    		return "Please use one of the following object types: 'blog', 'discussion', 'event', 'group', 'opportunity', 'wire'";
225
        	break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
226
	}
227
228
    $data = "Username/password combination is not correct.";
229
	if ($valid === true) {
230
		if (!elgg_is_logged_in()) {
231
			login($user_entity);
232
		}
233
234
		if ($guid) {
235
236
			$data = json_decode(elgg_list_entities(array(
237
				'type' => $type,
238
				'subtype' => $subtype,
239
				'guid' => $guid
240
			)));
241
242
			$replies = json_decode(elgg_list_entities(array(
243
				'type' => 'object',
244
				'subtype' => 'comment',
245
				'container_guid' => $item->guid
0 ignored issues
show
Bug introduced by
The variable $item seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
246
			)));
247
			if( count($replies) > 0 ){
248
				$data[0]->replies = $replies;
249
			}
250
251
		} else {
252
253
			$db_prefix = elgg_get_config('dbprefix');
254
255
			$params = array(
256
				'type' => $type,
257
				'subtype' => $subtype,
258
				'limit' => $limit,
259
				'offset' => $offset
260
			);
261
262
			if ($query) {
263
				if ($object == "group") {
264
					$params['joins'] = array("JOIN {$db_prefix}groups_entity ge ON e.guid = ge.guid");
265
					$params['wheres'] = array("(ge.name LIKE '%" . $query . "%' OR ge.description LIKE '%" . $query . "%')");
266 View Code Duplication
				} else {
267
					$params['joins'] = array("JOIN {$db_prefix}objects_entity oe ON e.guid = oe.guid");
268
					$params['wheres'] = array("(oe.title LIKE '%" . $query . "%' OR oe.description LIKE '%" . $query . "%')");
269
				}
270
			}
271
272
			if ($group) {
273
				$params['container_guid'] = $group;
274
			}
275
276 View Code Duplication
			if ($from_date) {
277
				$params['joins'] = array("JOIN {$db_prefix}entities fd ON e.guid = fd.guid");
278
				$params['wheres'] = array("(fd.time_updated >= " . strtotime($from_date) . ")");
279
			}
280 View Code Duplication
			if ($to_date) {
281
				$params['joins'] = array("JOIN {$db_prefix}entities td ON e.guid = td.guid");
282
				$params['wheres'] = array("(td.time_updated <= " . strtotime($to_date) . ")");
283
			}
284
285
			$ia = elgg_set_ignore_access(true);
286
			$data = json_decode(elgg_list_entities_from_metadata($params));
287
288
			if( $object == "discussion" ){
289
				foreach ($data as $discussion) {
290
					$replies = json_decode(elgg_list_entities_from_metadata(array(
291
						'type' => 'object',
292
						'subtype' => 'discussion_reply',
293
						'container_guid' => $discussion->guid
294
					)));
295
296
					if( count($replies) > 0 ){
297
						$replies = array_reverse($replies);
298
299
						$discussionsArray = array();
300
						foreach ($replies as $reply) {
301
							$discussionsArray[] = $reply;
302
						}
303
						$discussion->replies = $discussionsArray;
304
					}
305
				}
306 View Code Duplication
			} else {
307
				foreach ($data as $item) {
308
					$replies = json_decode(elgg_list_entities(array(
309
						'type' => 'object',
310
						'subtype' => 'comment',
311
						'container_guid' => $item->guid
312
					)));
313
314
					if( count($replies) > 0 ){
315
						$item->replies = $replies;
316
					}
317
				}
318
			}
319
			elgg_set_ignore_access($ia);
320
		}
321
	}
322
323
	return $data;
324
}
325