Completed
Push — Api_opt ( 47a261...24829b )
by
unknown
69:01 queued 36:29
created

functions.php ➔ query_the_posts()   D

Complexity

Conditions 15
Paths 228

Size

Total Lines 68
Code Lines 50

Duplication

Lines 5
Ratio 7.35 %

Importance

Changes 0
Metric Value
cc 15
eloc 50
nc 228
nop 8
dl 5
loc 68
rs 4.7145
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', '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
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
180
	),
181
	'Query GCcollab data based on user-given parameters',
182
	'POST',
183
	false,
184
	false
185
);
186
187
function query_the_posts($user, $password, $object, $query, $group, $limit, $offset, $lang)
188
{
189
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
190
	if (!$user_entity) {
191
		return "User was not found. Please try a different GUID, username, or email address";
192
	}
193
	if (!$user_entity instanceof ElggUser) {
194
		return "Invalid user. Please try a different GUID, username, or email address";
195
	}
196
197
    $valid = elgg_authenticate($user_entity->username, $password);
198
199
    $type = "object";
200
    $subtype = "";
201
    switch ($object) {
202
    	case "blog":
203
    		$subtype = "blog";
204
        	break;
205
        case "discussion":
206
    		$subtype = "groupforumtopic";
207
        	break;
208
        case "event":
209
    		$subtype = "event_calendar";
210
        	break;
211
        case "group":
212
    		$type = "group";
213
        	break;
214
        case "opportunity":
215
    		$subtype = "mission";
216
        	break;
217
        case "wire":
218
    		$subtype = "thewire";
219
        	break;
220
        default:
221
    		return "Please use one of the following object types: 'blog', 'discussion', 'event', 'group', 'opportunity', 'wire'";
222
        	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...
223
	}
224
225
    $data = "Username/password combination is not correct.";
226
	if ($valid === true) {
227
		if (!elgg_is_logged_in()) {
228
			login($user_entity);
229
		}
230
231
		$params = array(
232
			'type' => $type,
233
			'subtype' => $subtype,
234
			'limit' => $limit,
235
			'offset' => $offset
236
		);
237
238 View Code Duplication
		if ($query) {
239
			$db_prefix = elgg_get_config('dbprefix');
240
			$params['joins'] = array("JOIN {$db_prefix}objects_entity oe ON e.guid = oe.guid");
241
			$params['wheres'] = array("(oe.title LIKE '%" . $query . "%' OR oe.description LIKE '%" . $query . "%')");
242
		}
243
244
		if ($group) {
245
			$params['container_guid'] = $group;
246
		}
247
248
		$ia = elgg_set_ignore_access(true);
249
		$data = json_decode(elgg_list_entities_from_metadata($params));
250
		elgg_set_ignore_access($ia);
251
	}
252
253
	return $data;
254
}
255
256
elgg_ws_expose_function(
257
	"login.redirect",
258
	"login_and_redirect",
259
	array(
260
		"user" => array('type' => 'string', 'required' => true),
261
		"password" => array('type' => 'string', 'required' => true),
262
		"redirect_en" => array('type' => 'string', 'required' => true),
263
		"redirect_fr" => array('type' => 'string', 'required' => true),
264
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
265
	),
266
	'Login user into GCcollab and redirect them',
267
	'POST',
268
	false,
269
	false
270
);
271
272
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...
273
{
274
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
275
	if (!$user_entity) {
276
		header("Location: " . $_SERVER['HTTP_REFERER']);
277
		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...
278
	}
279
	if (!$user_entity instanceof ElggUser) {
280
		header("Location: " . $_SERVER['HTTP_REFERER']);
281
		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...
282
	}
283
284
    $valid = elgg_authenticate($user_entity->username, $password);
285
286
	if ($valid === true) {
287
		login($user_entity);
288
289
		if($lang == "fr"){
290
			setcookie("gcconnex_lang", "fr");
291
			header("Location: $redirect_fr");
292
			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...
293
		} else {
294
			setcookie("gcconnex_lang", "en");
295
			header("Location: $redirect_en");
296
			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...
297
		}
298
	} else {
299
		header("Location: " . $_SERVER['HTTP_REFERER']);
300
		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...
301
	}
302
}
303