Completed
Push — add-pleio-mod ( 6d68a5 )
by
unknown
28:07
created

functions.php ➔ query_the_posts()   F

Complexity

Conditions 24
Paths 2340

Size

Total Lines 111
Code Lines 78

Duplication

Lines 12
Ratio 10.81 %

Importance

Changes 0
Metric Value
cc 24
eloc 78
nc 2340
nop 10
dl 12
loc 111
rs 2
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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'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', '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
		"limit" => array('type' => 'int', 'required' => false, 'default' => 10),
178
		"offset" => array('type' => 'int', 'required' => false, 'default' => 0),
179
		"from_date" => array('type' => 'string', 'required' => false, 'default' => ""),
180
		"to_date" => array('type' => 'string', 'required' => false, 'default' => ""),
181
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
182
	),
183
	'Query GCcollab data based on user-given parameters',
184
	'POST',
185
	false,
186
	false
187
);
188
189
function query_the_posts($user, $password, $object, $query, $group, $limit, $offset, $from_date, $to_date, $lang)
190
{
191
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
192
	if (!$user_entity) {
193
		return "User was not found. Please try a different GUID, username, or email address";
194
	}
195
	if (!$user_entity instanceof ElggUser) {
196
		return "Invalid user. Please try a different GUID, username, or email address";
197
	}
198
199
    $valid = elgg_authenticate($user_entity->username, $password);
200
201
    $type = "object";
202
    $subtype = "";
203
    switch ($object) {
204
    	case "blog":
205
    		$subtype = "blog";
206
        	break;
207
        case "discussion":
208
    		$subtype = "groupforumtopic";
209
        	break;
210
        case "event":
211
    		$subtype = "event_calendar";
212
        	break;
213
        case "group":
214
    		$type = "group";
215
        	break;
216
        case "opportunity":
217
    		$subtype = "mission";
218
        	break;
219
        case "wire":
220
    		$subtype = "thewire";
221
        	break;
222
        default:
223
    		return "Please use one of the following object types: 'blog', 'discussion', 'event', 'group', 'opportunity', 'wire'";
224
        	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...
225
	}
226
227
    $data = "Username/password combination is not correct.";
228
	if ($valid === true) {
229
		if (!elgg_is_logged_in()) {
230
			login($user_entity);
231
		}
232
233
		$db_prefix = elgg_get_config('dbprefix');
234
235
		$params = array(
236
			'type' => $type,
237
			'subtype' => $subtype,
238
			'limit' => $limit,
239
			'offset' => $offset
240
		);
241
242
		if ($query) {
243
			if ($object == "group") {
244
				$params['joins'] = array("JOIN {$db_prefix}groups_entity ge ON e.guid = ge.guid");
245
				$params['wheres'] = array("(ge.name LIKE '%" . $query . "%' OR ge.description LIKE '%" . $query . "%')");
246 View Code Duplication
			} else {
247
				$params['joins'] = array("JOIN {$db_prefix}objects_entity oe ON e.guid = oe.guid");
248
				$params['wheres'] = array("(oe.title LIKE '%" . $query . "%' OR oe.description LIKE '%" . $query . "%')");
249
			}
250
		}
251
252
		if ($group) {
253
			$params['container_guid'] = $group;
254
		}
255
256 View Code Duplication
		if ($from_date) {
257
			$params['joins'] = array("JOIN {$db_prefix}entities fd ON e.guid = fd.guid");
258
			$params['wheres'] = array("(fd.time_updated >= " . strtotime($from_date) . ")");
259
		}
260 View Code Duplication
		if ($to_date) {
261
			$params['joins'] = array("JOIN {$db_prefix}entities td ON e.guid = td.guid");
262
			$params['wheres'] = array("(td.time_updated <= " . strtotime($to_date) . ")");
263
		}
264
265
		$ia = elgg_set_ignore_access(true);
266
		$data = json_decode(elgg_list_entities_from_metadata($params));
267
268
		if( $object == "discussion" ){
269
			foreach ($data as $discussion) {
270
				$all_replies = elgg_list_entities_from_metadata(array(
271
					'type' => 'object',
272
					'subtype' => 'discussion_reply',
273
					'container_guid' => $discussion->guid
274
				));
275
				$replies = json_decode($all_replies);
276
277
				if(count($replies) > 0) {
278
					$replies = array_reverse($replies);
279
280
					$discussionsArray = array();
281
					foreach ($replies as $reply) {
282
						$discussionsArray[] = $reply;
283
					}
284
					$discussion->replies = $discussionsArray;
285
				}
286
			}
287
		} else {
288
			foreach ($data as $item) {
289
				$replies = get_entity_comments($item->guid);
290
				if( $replies->count > 0 ){
291
					$item->replies = get_entity_comments($item->guid);
292
				}
293
			}
294
		}
295
		elgg_set_ignore_access($ia);
296
	}
297
298
	return $data;
299
}
300
301
elgg_ws_expose_function(
302
	"login.redirect",
303
	"login_and_redirect",
304
	array(
305
		"user" => array('type' => 'string', 'required' => true),
306
		"password" => array('type' => 'string', 'required' => true),
307
		"redirect_en" => array('type' => 'string', 'required' => true),
308
		"redirect_fr" => array('type' => 'string', 'required' => true),
309
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
310
	),
311
	'Login user into GCcollab and redirect them',
312
	'POST',
313
	false,
314
	false
315
);
316
317
function login_and_redirect($user, $password, $redirect_en, $redirect_fr, $lang)
0 ignored issues
show
Coding Style introduced by
login_and_redirect 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...
318
{
319
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
320
	if (!$user_entity) {
321
		header("Location: " . $_SERVER['HTTP_REFERER']);
322
		exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function login_and_redirect() 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...
323
	}
324
	if (!$user_entity instanceof ElggUser) {
325
		header("Location: " . $_SERVER['HTTP_REFERER']);
326
		exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function login_and_redirect() 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...
327
	}
328
329
    $valid = elgg_authenticate($user_entity->username, $password);
330
331
	if ($valid === true) {
332
		login($user_entity);
333
334
		if($lang == "fr"){
335
			setcookie("gcconnex_lang", "fr");
336
			header("Location: $redirect_fr");
337
			exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function login_and_redirect() 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...
338
		} else {
339
			setcookie("gcconnex_lang", "en");
340
			header("Location: $redirect_en");
341
			exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function login_and_redirect() 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...
342
		}
343
	} else {
344
		header("Location: " . $_SERVER['HTTP_REFERER']);
345
		exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function login_and_redirect() 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...
346
	}
347
}
348