Completed
Pull Request — gcconnex (#1509)
by Nick
18:12
created

user.php ➔ remove_colleague()   D

Complexity

Conditions 13
Paths 424

Size

Total Lines 59
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 34
nc 424
nop 3
dl 0
loc 59
rs 4.6162
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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:

1
<?php
2
/*
3
 * Exposes API endpoints for User entities
4
 */
5
6
elgg_ws_expose_function(
7
	"get.user",
8
	"get_user_data",
9
	array(
10
		"profileemail" => array('type' => 'string', 'required' => true),
11
		"user" => array('type' => 'string', 'required' => false),
12
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
13
	),
14
	'Retrieves a user\'s profile information based on user id',
15
	'POST',
16
	true,
17
	false
18
);
19
20
elgg_ws_expose_function(
21
	"get.userexists",
22
	"get_user_exists",
23
	array(
24
		"user" => array('type' => 'string', 'required' => false),
25
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
26
	),
27
	'Retrieves whether a user exists based on user id',
28
	'POST',
29
	true,
30
	false
31
);
32
33
elgg_ws_expose_function(
34
	"get.useractivity",
35
	"get_user_activity",
36
	array(
37
		"profileemail" => array('type' => 'string', 'required' => true),
38
		"user" => array('type' => 'string', 'required' => true),
39
		"limit" => array('type' => 'int', 'required' => false, 'default' => 10),
40
		"offset" => array('type' => 'int', 'required' => false, 'default' => 0),
41
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
42
	),
43
	'Retrieves a user\'s activity information based on user id',
44
	'POST',
45
	true,
46
	false
47
);
48
49
elgg_ws_expose_function(
50
	"get.usergroups",
51
	"get_user_groups",
52
	array(
53
		"profileemail" => array('type' => 'string', 'required' => true),
54
		"user" => array('type' => 'string', 'required' => true),
55
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
56
	),
57
	'Retrieves a user\'s group information based on user id',
58
	'POST',
59
	true,
60
	false
61
);
62
63
elgg_ws_expose_function(
64
	"get.newsfeed",
65
	"get_newsfeed",
66
	array(
67
		"user" => array('type' => 'string', 'required' => true),
68
		"limit" => array('type' => 'int', 'required' => false, 'default' => 10),
69
		"offset" => array('type' => 'int', 'required' => false, 'default' => 0),
70
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
71
	),
72
	'Retrieves a user\'s newsfeed based on user id',
73
	'POST',
74
	true,
75
	false
76
);
77
78
elgg_ws_expose_function(
79
	"get.colleaguerequests",
80
	"get_colleague_requests",
81
	array(
82
		"user" => array('type' => 'string', 'required' => true),
83
		"limit" => array('type' => 'int', 'required' => false, 'default' => 10),
84
		"offset" => array('type' => 'int', 'required' => false, 'default' => 0),
85
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
86
	),
87
	'Retrieves a user\'s colleague requests based on user id',
88
	'POST',
89
	true,
90
	false
91
);
92
93
elgg_ws_expose_function(
94
	"add.colleague",
95
	"add_colleague",
96
	array(
97
		"profileemail" => array('type' => 'string', 'required' => true),
98
		"user" => array('type' => 'string', 'required' => true),
99
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
100
	),
101
	'Adds a colleague for a user based on user ids',
102
	'POST',
103
	true,
104
	false
105
);
106
107
elgg_ws_expose_function(
108
	"remove.colleague",
109
	"remove_colleague",
110
	array(
111
		"profileemail" => array('type' => 'string', 'required' => true),
112
		"user" => array('type' => 'string', 'required' => true),
113
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
114
	),
115
	'Removes a colleague for a user based on user ids',
116
	'POST',
117
	true,
118
	false
119
);
120
121
elgg_ws_expose_function(
122
	"approve.colleague",
123
	"approve_colleague",
124
	array(
125
		"profileemail" => array('type' => 'string', 'required' => true),
126
		"user" => array('type' => 'string', 'required' => true),
127
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
128
	),
129
	'Approves a colleague request for a user based on user ids',
130
	'POST',
131
	true,
132
	false
133
);
134
135
elgg_ws_expose_function(
136
	"decline.colleague",
137
	"decline_colleague",
138
	array(
139
		"profileemail" => array('type' => 'string', 'required' => true),
140
		"user" => array('type' => 'string', 'required' => true),
141
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
142
	),
143
	'Declines a colleague request for a user based on user ids',
144
	'POST',
145
	true,
146
	false
147
);
148
149
elgg_ws_expose_function(
150
	"revoke.colleague",
151
	"revoke_colleague",
152
	array(
153
		"profileemail" => array('type' => 'string', 'required' => true),
154
		"user" => array('type' => 'string', 'required' => true),
155
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
156
	),
157
	'Revokes a colleague request for a user based on user ids',
158
	'POST',
159
	true,
160
	false
161
);
162
163 View Code Duplication
function build_date($month, $year)
164
{
165
	switch ($month) {
166
		case 1:
167
			$string = "01/";
168
			break;
169
		case 2:
170
			$string = "02/";
171
			break;
172
		case 3:
173
			$string = "03/";
174
			break;
175
		case 4:
176
			$string = "04/";
177
			break;
178
		case 5:
179
			$string = "05/";
180
			break;
181
		case 6:
182
			$string = "06/";
183
			break;
184
		case 7:
185
			$string = "07/";
186
			break;
187
		case 8:
188
			$string = "08/";
189
			break;
190
		case 9:
191
			$string = "09/";
192
			break;
193
		case 10:
194
			$string = "10/";
195
			break;
196
		case 11:
197
			$string = "11/";
198
			break;
199
		case 12:
200
			$string = "12/";
201
			break;
202
	}
203
	return $string . $year;
0 ignored issues
show
Bug introduced by
The variable $string 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...
204
}
205
206
function get_user_data($profileemail, $user, $lang)
207
{
208
	$user_entity = is_numeric($profileemail) ? get_user($profileemail) : (strpos($profileemail, '@') !== false ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail));
209
	if (!$user_entity) {
210
		return "User was not found. Please try a different GUID, username, or email address";
211
	}
212
	if (!$user_entity instanceof ElggUser) {
213
		return "Invalid user. Please try a different GUID, username, or email address";
214
	}
215
216
	if ($user) {
217
		$viewer = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
218
		if (!$viewer) {
219
			return "Viewer user was not found. Please try a different GUID, username, or email address";
220
		}
221
		if (!$viewer instanceof ElggUser) {
222
			return "Invalid viewer user. Please try a different GUID, username, or email address";
223
		}
224
225
		$friends = $viewer->isFriendsWith($user_entity->guid);
226
	} else {
227
		$friends = false;
228
	}
229
230
	if (!elgg_is_logged_in()) {
231
		login($viewer);
0 ignored issues
show
Bug introduced by
The variable $viewer 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...
232
	}
233
234
	$user = array();
235
236
	$user['id'] = $user_entity->guid;
237
	$user['friend'] = $friends;
238
	$user['user_type'] = $user_entity->user_type;
239
	$user['username'] = $user_entity->username;
240
	$user['displayName'] = $user_entity->name;
241
	$user['email'] = $user_entity->email;
242
	$user['profileURL'] = $user_entity->getURL();
243
	$user['iconURL'] = $user_entity->geticon();
0 ignored issues
show
Deprecated Code introduced by
The method ElggEntity::getIcon() has been deprecated with message: 1.8 Use getIconURL()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
244
	$user['jobTitle'] = $user_entity->job;
245
246
	switch ($user_entity->user_type) {
247
		case "federal":
248
			$user['department'] = $user_entity->federal;
249
			break;
250
		case "student":
251 View Code Duplication
		case "academic":
252
			$institution = $user_entity->institution;
253
			$user['department'] = ($institution == 'university') ? $user_entity->university : ($institution == 'college' ? $user_entity->college : $user_entity->highschool);
254
			break;
255
		case "provincial":
256
			$user['department'] = $user_entity->provincial . ' / ' . $user_entity->ministry;
257
			break;
258
		default:
259
			$user['department'] = $user_entity->{$user_entity->user_type};
260
			break;
261
	}
262
263
	$user['telephone'] = $user_entity->phone;
264
	$user['mobile'] = $user_entity->mobile;
265
	$user['website'] = $user_entity->website;
266
267
	if ($user_entity->facebook) {
268
		$user['links']['facebook'] = "http://www.facebook.com/".$user_entity->facebook;
269
	}
270
	if ($user_entity->google) {
271
		$user['links']['google'] = "http://www.google.com/".$user_entity->google;
272
	}
273
	if ($user_entity->github) {
274
		$user['links']['github'] = "https://github.com/".$user_entity->github;
275
	}
276
	if ($user_entity->twitter) {
277
		$user['links']['twitter'] = "https://twitter.com/".$user_entity->twitter;
278
	}
279
	if ($user_entity->linkedin) {
280
		$user['links']['linkedin'] = "http://ca.linkedin.com/in/".$user_entity->linkedin;
281
	}
282
	if ($user_entity->pinterest) {
283
		$user['links']['pinterest'] = "http://www.pinterest.com/".$user_entity->pinterest;
284
	}
285
	if ($user_entity->tumblr) {
286
		$user['links']['tumblr'] = "https://www.tumblr.com/blog/".$user_entity->tumblr;
287
	}
288
	if ($user_entity->instagram) {
289
		$user['links']['instagram'] = "http://instagram.com/".$user_entity->instagram;
290
	}
291
	if ($user_entity->flickr) {
292
		$user['links']['flickr'] = "http://flickr.com/".$user_entity->flickr;
293
	}
294
	if ($user_entity->youtube) {
295
		$user['links']['youtube'] = "http://www.youtube.com/".$user_entity->youtube;
296
	}
297
298
	// About Me
299
	$about_me = strip_tags($user_entity->description, '<p>');
300
	$about_me = str_replace("<p>&nbsp;</p>", '', $about_me);
301
	$user['about_me'] = $about_me;
302
303
	// Education
304
	$educationEntity = elgg_get_entities(array(
305
		'owner_guid'=>$user['id'],
306
		'subtype'=>'education',
307
		'type' => 'object',
308
		'limit' => 0
309
	));
310
	$i = 0;
311
	foreach ($educationEntity as $school) {
312
		if ($school->access_id == ACCESS_PUBLIC || $school->access_id == ACCESS_LOGGED_IN || ($friends && $school->access_id == ACCESS_FRIENDS)) {
313
			$user['education']['item_'.$i]['school_name'] = $school->school;
314
315
			$user['education']['item_'.$i]['start_date'] = build_date($school->startdate, $school->startyear);
316
317 View Code Duplication
			if ($school->ongoing == "false") {
318
				$user['education']['item_'.$i]['end_date'] = build_date($school->enddate, $school->endyear);
319
			} else {
320
				$user['education']['item_'.$i]['end_date'] = "present/actuel";
321
			}
322
			$user['education']['item_'.$i]['degree'] = $school->degree;
323
			$user['education']['item_'.$i]['field_of_study'] = $school->field;
324
			$i++;
325
		}
326
	}
327
328
	// Experience
329
	$experienceEntity = elgg_get_entities(array(
330
		'owner_guid'=>$user['id'],
331
		'subtype'=>'experience',
332
		'type' => 'object',
333
		'limit' => 0
334
	));
335
	usort($experienceEntity, "sortDate");
336
	$i = 0;
337
	foreach ($experienceEntity as $job) {
338
		if ($job->access_id == ACCESS_PUBLIC || $job->access_id == ACCESS_LOGGED_IN || ($friends && $job->access_id == ACCESS_FRIENDS)) {
339
			$jobMetadata = elgg_get_metadata(array(
340
				'guid' => $job->guid,
341
				'limit' => 0
342
			));
343
344
			$user['experience']['item_'.$i]['job_title'] = $job->title;
345
			$user['experience']['item_'.$i]['organization'] = $job->organization;
346
			$user['experience']['item_'.$i]['start_date'] = build_date($job->startdate, $job->startyear);
347 View Code Duplication
			if ($job->ongoing == "false") {
348
				$user['experience']['item_'.$i]['end_date'] = build_date($job->enddate, $job->endyear);
349
			} else {
350
				$user['experience']['item_'.$i]['end_date'] = "present/actuel";
351
			}
352
			$user['experience']['item_'.$i]['responsibilities'] = $job->responsibilities;
353
354
			$j = 0;
355
			if (is_array($job->colleagues)) {
356
				foreach ($job->colleagues as $friend) {
357
					$friendEntity = get_user($friend);
358
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["id"] = $friendEntity->guid;
359
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["username"] = $friendEntity->username;
360
361
					//get and store user display name
362
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["displayName"] = $friendEntity->name;
363
364
					//get and store URL for profile
365
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["profileURL"] = $friendEntity->getURL();
366
367
					//get and store URL of profile avatar
368
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["iconURL"] = $friendEntity->geticon();
0 ignored issues
show
Deprecated Code introduced by
The method ElggEntity::getIcon() has been deprecated with message: 1.8 Use getIconURL()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
369
					$j++;
370
				}
371
			} elseif (!is_null($job->colleagues)) {
372
				$friendEntity = get_user($job->colleagues);
373
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["id"] = $friendEntity->guid;
374
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["username"] = $friendEntity->username;
375
376
				//get and store user display name
377
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["displayName"] = $friendEntity->name;
378
379
				//get and store URL for profile
380
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["profileURL"] = $friendEntity->getURL();
381
382
				//get and store URL of profile avatar
383
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["iconURL"] = $friendEntity->geticon();
0 ignored issues
show
Deprecated Code introduced by
The method ElggEntity::getIcon() has been deprecated with message: 1.8 Use getIconURL()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
384
			}
385
			$i++;
386
		}
387
	}
388
389
	// Skills
390
	if ($user_entity->skill_access == ACCESS_PUBLIC || $user_entity->skill_access == ACCESS_LOGGED_IN || ($friends && $user_entity->skill_access == ACCESS_FRIENDS)) {
391
		$skillsEntity = elgg_get_entities(array(
392
			'owner_guid'=>$user['id'],
393
			'subtype'=>'MySkill',
394
			'type' => 'object',
395
			'limit' => 0
396
		));
397
	}
398
	$i=0;
399 View Code Duplication
	foreach ($skillsEntity as $skill) {
0 ignored issues
show
Bug introduced by
The variable $skillsEntity 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...
400
		$user['skills']['item_'.$i]['skill'] = $skill->title;
401
402
		$j = 0;
403
		if (is_array($skill->endorsements)) {
404
			foreach ($skill->endorsements as $friend) {
405
				$friendEntity = get_user($friend);
406
				if ($friendEntity instanceof ElggUser) {
407
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["id"] = $friendEntity->guid;
408
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["username"] = $friendEntity->username;
409
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["displayName"] = $friendEntity->name;
410
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["profileURL"] = $friendEntity->getURL();
411
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["iconURL"] = $friendEntity->geticon();
0 ignored issues
show
Deprecated Code introduced by
The method ElggEntity::getIcon() has been deprecated with message: 1.8 Use getIconURL()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
412
				}
413
				$j++;
414
			}
415
		} elseif (!is_null($skill->endorsements)) {
416
			$friendEntity = get_user($skill->endorsements);
417
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["id"] = $friendEntity->guid;
418
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["username"] = $friendEntity->username;
419
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["displayName"] = $friendEntity->name;
420
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["profileURL"] = $friendEntity->getURL();
421
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["iconURL"] = $friendEntity->geticon();
0 ignored issues
show
Deprecated Code introduced by
The method ElggEntity::getIcon() has been deprecated with message: 1.8 Use getIconURL()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
422
		}
423
		$i++;
424
	}
425
426
	// Portfolio
427
	$portfolioEntity = elgg_get_entities(array(
428
		'owner_guid'=>$user['id'],
429
		'subtype'=>'portfolio',
430
		'type' => 'object',
431
		'limit' => 0
432
	));
433
	$i = 0;
434
	foreach ($portfolioEntity as $portfolio) {
435
		if ($portfolio->access_id == ACCESS_PUBLIC || $portfolio->access_id == ACCESS_LOGGED_IN || ($friends && $portfolio->access_id == ACCESS_FRIENDS)) {
436
			$user['portfolio']['item_'.$i]['title'] = $portfolio->title;
437
			$user['portfolio']['item_'.$i]['link'] = $portfolio->link;
438 View Code Duplication
			if ($portfolio->datestamped == "on") {
439
				$user['portfolio']['item_'.$i]['date'] = $portfolio->publishdate;
440
			}
441
			$user['portfolio']['item_'.$i]['description'] = $portfolio->description;
442
		}
443
	}
444
445
	$user['dateJoined'] = date("Y-m-d H:i:s", $user_entity->time_created);
446
	$user['lastActivity'] = date("Y-m-d H:i:s", $user_entity->last_action);
447
	$user['lastLogin'] = date("Y-m-d H:i:s", $user_entity->last_login);
448
449
	$options = array(
450
		'type' => 'object',
451
		'subtype' => 'thewire',
452
		'owner_guid' => $user_entity->guid,
453
		'limit' => 0
454
	);
455
	$wires = elgg_get_entities($options);
456
	$user['wires'] = count($wires);
457
458
	$options = array(
459
		'type' => 'object',
460
		'subtype' => 'blog',
461
		'owner_guid' => $user_entity->guid,
462
		'limit' => 0
463
	);
464
	$blogs = elgg_get_entities($options);
465
	$user['blogs'] = count($blogs);
466
467
	$colleagues = $user_entity->getFriends(array('limit' => 0));
468
	$user['colleagues'] = count($colleagues);
469
470
	return $user;
471
}
472
473 View Code Duplication
function get_user_exists($user, $lang)
474
{
475
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
476
477
	$valid = false;
478
	if ($user_entity instanceof ElggUser) {
479
		$is_validated = elgg_get_user_validation_status($user->guid);
480
		if ($is_validated) {
481
			$valid = true;
482
		}
483
	}
484
485
	return $valid;
486
}
487
488
function get_user_activity($profileemail, $user, $limit, $offset, $lang)
489
{
490
	$user_entity = is_numeric($profileemail) ? get_user($profileemail) : (strpos($profileemail, '@') !== false ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail));
491
	if (!$user_entity) {
492
		return "User was not found. Please try a different GUID, username, or email address";
493
	}
494
	if (!$user_entity instanceof ElggUser) {
495
		return "Invalid user. Please try a different GUID, username, or email address";
496
	}
497
498
	$viewer = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
499
	if (!$viewer) {
500
		return "Viewer user was not found. Please try a different GUID, username, or email address";
501
	}
502
	if (!$viewer instanceof ElggUser) {
503
		return "Invalid viewer user. Please try a different GUID, username, or email address";
504
	}
505
506
	if (!elgg_is_logged_in()) {
507
		login($viewer);
508
	}
509
510
	$all_activity = elgg_list_river(array(
511
		'subject_guid' => $user_entity->guid,
512
		'distinct' => false,
513
		'limit' => $limit,
514
		'offset' => $offset
515
	));
516
517
	$activity = json_decode($all_activity);
518
	foreach ($activity as $event) {
519
		$subject = get_user($event->subject_guid);
520
		$object = get_entity($event->object_guid);
521
		$event->userDetails = get_user_block($event->subject_guid, $lang);
522
523
		if ($object instanceof ElggUser) {
524
			$event->object = get_user_block($event->object_guid, $lang);
525
			$event->object['type'] = 'user';
526 View Code Duplication
		} elseif ($object instanceof ElggWire) {
527
			$event->object['type'] = 'wire';
528
			$event->object['wire'] = wire_filter($object->description);
529
530
			$thread_id = $object->wire_thread;
531
			$reshare = $object->getEntitiesFromRelationship(array("relationship" => "reshare", "limit" => 1))[0];
532
533
			$url = "";
534
			if (!empty($reshare)) {
535
				$url = $reshare->getURL();
536
			}
537
538
			$text = "";
539
			if (!empty($reshare->title)) {
540
				$text = $reshare->title;
541
			} elseif (!empty($reshare->name)) {
542
				$text = $reshare->name;
543
			} elseif (!empty($reshare->description)) {
544
				$text = elgg_get_excerpt($reshare->description, 140);
545
			}
546
547
			$event->shareURL = $url;
548
			$event->shareText = gc_explode_translation($text, $lang);
549
		} elseif ($object instanceof ElggGroup) {
550
			$event->object['type'] = 'group';
551
			$event->object['name'] = gc_explode_translation($object->name, $lang);
552
		} elseif ($object instanceof ElggDiscussionReply) {
553
			$event->object['type'] = 'discussion-reply';
554
			$original_discussion = get_entity($object->container_guid);
555
			$event->object['name'] = $original_discussion->title;
556
			$event->object['description'] = $object->description;
557
		} elseif ($object instanceof ElggFile) {
558
			$event->object['type'] = 'file';
559
			$event->object['name'] = $object->title;
560
			$event->object['description'] = $object->description;
561
		} elseif ($object instanceof ElggObject) {
562
			$event->object['type'] = 'discussion-add';
563
			$event->object['name'] = ($object->title) ? $object->title : $object->name;
564
			$event->object['description'] = $object->description;
565
566
			$other = get_entity($event->object_guid);
567
			$parent = get_entity($other->container_guid);
568
			if ($parent instanceof ElggGroup) {
569
				if (!isset($event->object['name'])) {
570
					$event->object['name'] = ($parent->title) ? $parent->title : $parent->name;
571
				}
572
			} else {
573
				if (!isset($event->object['name'])) {
574
					$event->object['name'] = ($parent->title) ? $parent->title : $parent->name;
575
				}
576
			}
577
		} else {
578
			//@TODO handle any unknown events
579
			if (strpos($object->title, '"en":') !== false) {
580
				$event->object['name'] = gc_explode_translation($object->title, $lang);
581
			} else {
582
				$event->object['name'] = $object->title;
583
			}
584
585
			if (strpos($object->description, '"en":') !== false) {
586
				$event->object['description'] = gc_explode_translation($object->description, $lang);
587
			} else {
588
				$event->object['description'] = $object->description;
589
			}
590
		}
591
	}
592
593
	return $activity;
594
}
595
596
function get_user_groups($profileemail, $user, $lang)
597
{
598
	$user_entity = is_numeric($profileemail) ? get_user($profileemail) : (strpos($profileemail, '@') !== false ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail));
599
	if (!$user_entity) {
600
		return "User was not found. Please try a different GUID, username, or email address";
601
	}
602
	if (!$user_entity instanceof ElggUser) {
603
		return "Invalid user. Please try a different GUID, username, or email address";
604
	}
605
606
	$viewer = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
607
	if (!$viewer) {
608
		return "Viewer user was not found. Please try a different GUID, username, or email address";
609
	}
610
	if (!$viewer instanceof ElggUser) {
611
		return "Invalid viewer user. Please try a different GUID, username, or email address";
612
	}
613
614
	if (!elgg_is_logged_in()) {
615
		login($viewer);
616
	}
617
618
	$all_groups = elgg_list_entities_from_relationship(array(
619
		'relationship' => 'member',
620
		'relationship_guid' => $user_entity->guid,
621
		'inverse_relationship' => false,
622
		'type' => 'group',
623
		'limit' => 0
624
	));
625
626
	$groups = json_decode($all_groups);
627
	foreach ($groups as $group) {
628
		$groupObj = get_entity($group->guid);
629
		$group->name = gc_explode_translation($group->name, $lang);
630
		$group->iconURL = $groupObj->geticon();
0 ignored issues
show
Deprecated Code introduced by
The method ElggEntity::getIcon() has been deprecated with message: 1.8 Use getIconURL()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
631
		$group->count = $groupObj->getMembers(array('count' => true));
632
		$group->description = clean_text(gc_explode_translation($group->description, $lang));
633
	}
634
635
	return $groups;
636
}
637
638
function get_newsfeed($user, $limit, $offset, $lang)
639
{
640
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
641
	if (!$user_entity) {
642
		return "User was not found. Please try a different GUID, username, or email address";
643
	}
644
	if (!$user_entity instanceof ElggUser) {
645
		return "Invalid user. Please try a different GUID, username, or email address";
646
	}
647
648
	if (!elgg_is_logged_in()) {
649
		login($user_entity);
650
	}
651
652
	$db_prefix = elgg_get_config('dbprefix');
653
654
	if ($user_entity) {
655
		// check if user exists and has friends or groups
656
		$hasfriends = $user_entity->getFriends();
657
		$hasgroups = $user_entity->getGroups();
658
		if ($hasgroups) {
659
			// loop through group guids
660
			$groups = $user_entity->getGroups(array('limit'=>0));
661
			$group_guids = array();
662
			foreach ($groups as $group) {
663
				$group_guids[] = $group->getGUID();
664
			}
665
		}
666
	}
667
668
	$actionTypes = array('comment', 'create', 'join', 'update', 'friend', 'reply');
669
670
	if (!$hasgroups && !$hasfriends) {
671
		// no friends and no groups :(
672
		$activity = '';
673
	} elseif (!$hasgroups && $hasfriends) {
0 ignored issues
show
Bug introduced by
The variable $hasgroups 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...
Bug introduced by
The variable $hasfriends 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...
674
		// has friends but no groups
675
		$optionsf['relationship_guid'] = $user_entity->guid;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$optionsf was never initialized. Although not strictly required by PHP, it is generally a good practice to add $optionsf = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
676
		$optionsf['relationship'] = 'friend';
677
		$optionsf['pagination'] = true;
678
679
		// turn off friend connections
680
		// remove friend connections from action types
681
		// load user's preference
682
		$filteredItems = array($user_entity->colleagueNotif);
683
		// filter out preference
684
		$optionsf['action_types'] = array_diff($actionTypes, $filteredItems);
685
686
		$activity = json_decode(newsfeed_list_river($optionsf));
687
	} elseif (!$hasfriends && $hasgroups) {
688
		// if no friends but groups
689
		$guids_in = implode(',', array_unique(array_filter($group_guids)));
0 ignored issues
show
Bug introduced by
The variable $group_guids 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...
690
691
		// display created content and replies and comments
692
		$optionsg['wheres'] = array("( oe.container_guid IN({$guids_in}) OR te.container_guid IN({$guids_in}) )");
0 ignored issues
show
Coding Style Comprehensibility introduced by
$optionsg was never initialized. Although not strictly required by PHP, it is generally a good practice to add $optionsg = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
693
		$optionsg['pagination'] = true;
694
		$activity = json_decode(newsfeed_list_river($optionsg));
695
	} else {
696
		// if friends and groups :3
697
		// turn off friend connections
698
		// remove friend connections from action types
699
		// load user's preference
700
		$filteredItems = array($user_entity->colleagueNotif);
701
		// filter out preference
702
		$optionsfg['action_types'] = array_diff($actionTypes, $filteredItems);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$optionsfg was never initialized. Although not strictly required by PHP, it is generally a good practice to add $optionsfg = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
703
704
		$guids_in = implode(',', array_unique(array_filter($group_guids)));
705
706
		// Groups + Friends activity query
707
		// This query grabs new created content and comments and replies in the groups the user is a member of *** te.container_guid grabs comments and replies
708
		$optionsfg['wheres'] = array(
709
			"( oe.container_guid IN({$guids_in})
710
         	OR te.container_guid IN({$guids_in}) )
711
        	OR rv.subject_guid IN (SELECT guid_two FROM {$db_prefix}entity_relationships WHERE guid_one=$user_entity->guid AND relationship='friend')"
712
		);
713
		$optionsfg['pagination'] = true;
714
		$activity = json_decode(newsfeed_list_river($optionsfg));
715
	}
716
717
	foreach ($activity as $event) {
718
		$subject = get_user($event->subject_guid);
719
		$object = get_entity($event->object_guid);
720
		$event->userDetails = get_user_block($event->subject_guid, $lang);
721
722
		$likes = elgg_get_annotations(array(
723
			'guid' => $event->object_guid,
724
			'annotation_name' => 'likes'
725
		));
726
		$event->likes = count($likes);
727
728
		$liked = elgg_get_annotations(array(
729
			'guid' => $event->object_guid,
730
			'annotation_owner_guid' => $user_entity->guid,
731
			'annotation_name' => 'likes'
732
		));
733
		$event->liked = count($liked) > 0;
734
735
		if ($object->description) {
736
			$object->description = str_replace("<p>&nbsp;</p>", '', $object->description);
737
		}
738
739
		if ($object instanceof ElggUser) {
740
			$event->object = get_user_block($event->object_guid, $lang);
741
			$event->object['type'] = 'user';
742 View Code Duplication
		} elseif ($object instanceof ElggWire) {
743
			$event->object['type'] = 'wire';
744
			$event->object['wire'] = wire_filter($object->description);
745
746
			$thread_id = $object->wire_thread;
747
			$reshare = $object->getEntitiesFromRelationship(array("relationship" => "reshare", "limit" => 1))[0];
748
749
			$url = "";
750
			if (!empty($reshare)) {
751
				$url = $reshare->getURL();
752
			}
753
754
			$text = "";
755
			if (!empty($reshare->title)) {
756
				$text = $reshare->title;
757
			} elseif (!empty($reshare->name)) {
758
				$text = $reshare->name;
759
			} elseif (!empty($reshare->description)) {
760
				$text = elgg_get_excerpt($reshare->description, 140);
761
			}
762
763
			$event->shareURL = $url;
764
			$event->shareText = gc_explode_translation($text, $lang);
765
		} elseif ($object instanceof ElggGroup) {
766
			$event->object['type'] = 'group';
767
			$event->object['name'] = gc_explode_translation($object->name, $lang);
768
			$event->object['description'] = gc_explode_translation($object->name, $lang);
769
770
			if (is_callable(array($object, 'getURL'))) {
771
				$event->object['url'] = $object->getURL();
772
			}
773
		} elseif ($object instanceof ElggDiscussionReply) {
774
			$event->object['type'] = 'discussion-reply';
775
			$original_discussion = get_entity($object->container_guid);
776
			$event->object['name'] = gc_explode_translation($original_discussion->title, $lang);
777
			$event->object['description'] = gc_explode_translation($object->description, $lang);
778
779
			if (is_callable(array($original_discussion, 'getURL'))) {
780
				$event->object['url'] = $original_discussion->getURL();
781
			}
782
		} elseif ($object instanceof ElggFile) {
783
			$event->object['type'] = 'file';
784
			$event->object['name'] = gc_explode_translation($object->title, $lang);
785
			$event->object['description'] = gc_explode_translation($object->description, $lang);
786
			$event->object['url'] = $object->getURL();
787
		} elseif ($object instanceof ElggObject) {
788
			$event->object['type'] = 'discussion-add';
789
790
			$name = ($object->title) ? $object->title : $object->name;
791
			if (empty(trim($name))) {
792
				$otherEntity = get_entity($object->container_guid);
793
				$name = ($otherEntity->title) ? $otherEntity->title : $otherEntity->name;
794
			}
795
			$event->object['name'] = $name;
796
797
			if (is_callable(array($object, 'getURL'))) {
798
				$event->object['url'] = $object->getURL();
799
			}
800
801
			$event->object['description'] = gc_explode_translation($object->description, $lang);
802
803
			$other = get_entity($object->container_guid);
804
			if ($other instanceof ElggGroup) {
805
				if (!isset($event->object['type'])) {
806
					$event->object['name'] = ($other->title) ? $other->title : $other->name;
807
				}
808
			} else {
809
				if (!isset($event->object['type'])) {
810
					$event->object['name'] = ($other->title) ? $other->title : $other->name;
811
				}
812
			}
813
814
			if (strpos($event->object['name'], '"en":') !== false) {
815
				$event->object['name'] = gc_explode_translation($event->object['name'], $lang);
816
			}
817
		} else {
818
			//@TODO handle any unknown events
819
			if (strpos($object->title, '"en":') !== false) {
820
				$event->object['name'] = gc_explode_translation($object->title, $lang);
821
			} else {
822
				$event->object['name'] = $object->title;
823
			}
824
825
			if (strpos($object->description, '"en":') !== false) {
826
				$event->object['description'] = gc_explode_translation($object->description, $lang);
827
			} else {
828
				$event->object['description'] = $object->description;
829
			}
830
831
			if (is_callable(array($object, 'getURL'))) {
832
				$event->object['url'] = $object->getURL();
833
			}
834
		}
835
	}
836
837
	return $activity;
838
}
839
840
function get_colleague_requests($user, $limit, $offset, $lang)
841
{
842
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
843
	if (!$user_entity) {
844
		return "User was not found. Please try a different GUID, username, or email address";
845
	}
846
	if (!$user_entity instanceof ElggUser) {
847
		return "Invalid user. Please try a different GUID, username, or email address";
848
	}
849
850
	if (!elgg_is_logged_in()) {
851
		login($user_entity);
852
	}
853
854
	$friendrequests = elgg_get_entities_from_relationship(array(
855
		"type" => "user",
856
		"relationship" => "friendrequest",
857
		"relationship_guid" => $user_entity->getGUID(),
858
		"inverse_relationship" => true,
859
		"limit" => $limit,
860
		"offset" => $offset
861
	));
862
863
	$data = array();
864
	foreach ($friendrequests as $member) {
865
		$member_obj = get_user($member->guid);
866
		$member_data = get_user_block($member->guid, $lang);
867
868
		$about = "";
869
		if ($member_obj->description) {
870
			$about = strip_tags($member_obj->description, '<p>');
871
			$about = str_replace("<p>&nbsp;</p>", '', $about);
872
		}
873
874
		$member_data['about'] = $about;
875
		$data[] = $member_data;
876
	}
877
878
	return $data;
879
}
880
881
function add_colleague($profileemail, $user, $lang)
882
{
883
	$friend = is_numeric($profileemail) ? get_user($profileemail) : (strpos($profileemail, '@') !== false ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail));
884
	if (!$friend) {
885
		return "User was not found. Please try a different GUID, username, or email address";
886
	}
887
	if (!$friend instanceof ElggUser) {
888
		return "Invalid user. Please try a different GUID, username, or email address";
889
	}
890
891
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
892
	if (!$user_entity) {
893
		return "Viewer user was not found. Please try a different GUID, username, or email address";
894
	}
895
	if (!$user_entity instanceof ElggUser) {
896
		return "Invalid viewer user. Please try a different GUID, username, or email address";
897
	}
898
899
	if (!elgg_is_logged_in()) {
900
		login($user_entity);
901
	}
902
903
	//Now we need to attempt to create the relationship
904
	if (empty($user_entity) || empty($friend)) {
905
		return elgg_echo("friend_request:add:failure");
906
	} else {
907
		//New for v1.1 - If the other user is already a friend (fan) of this user we should auto-approve the friend request...
908
		if (check_entity_relationship($friend->getGUID(), "friend", $user_entity->getGUID())) {
909
			try {
910
				$user_entity->addFriend($friend->getGUID());
911
				return true;
912
			} catch (Exception $e) {
913
				return elgg_echo("friends:add:failure", array($friend->name));
914
			}
915
		} elseif (check_entity_relationship($friend->getGUID(), "friendrequest", $user_entity->getGUID())) {
916
			// Check if your potential friend already invited you, if so make friends
917
			if (remove_entity_relationship($friend->getGUID(), "friendrequest", $user_entity->getGUID())) {
918
919
				// Friends mean reciprical...
920
				$user_entity->addFriend($friend->getGUID());
921
				$friend->addFriend($user_entity->getGUID());
922
923
				$n_result = notify_user(
924
					$friend->guid,
925
					$user_entity->guid,
926
					elgg_echo('friend:newfriend:subject', array(
927
						$user_entity->name,
928
						$user_entity->name,
929
					)),
930
					elgg_echo("friend:newfriend:body", array(
931
						$user_entity->name,
932
						$user_entity->getURL(),
933
						elgg_get_site_url().'notifications/personal/',
934
935
						$user_entity->name,
936
						$user_entity->getURL(),
937
						elgg_get_site_url().'notifications/personal/',
938
					))
939
				);
940
941
				// add to river
942
				elgg_create_river_item(array(
943
					"view" => "river/relationship/friend/create",
944
					"action_type" => "friend",
945
					"subject_guid" => $user_entity->getGUID(),
946
					"object_guid" => $friend->getGUID(),
947
				));
948
				elgg_create_river_item(array(
949
					"view" => "river/relationship/friend/create",
950
					"action_type" => "friend",
951
					"subject_guid" => $friend->getGUID(),
952
					"object_guid" => $user_entity->getGUID(),
953
				));
954
955
				return true;
956
			} else {
957
				return elgg_echo("friend_request:approve:fail", array($friend->name));
958
			}
959
		} else {
960
			try {
961 View Code Duplication
				if (!add_entity_relationship($user_entity->getGUID(), "friendrequest", $friend->getGUID())) {
962
					return elgg_echo("friend_request:add:exists", array($friend->name));
963
				}
964
			} catch (Exception $e) {	//register_error calls insert_data which CAN raise Exceptions.
965
				return elgg_echo("friend_request:add:exists", array($friend->name));
966
			}
967
		}
968
	}
969
}
970
971
function remove_colleague($profileemail, $user, $lang)
972
{
973
	$friend = is_numeric($profileemail) ? get_user($profileemail) : (strpos($profileemail, '@') !== false ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail));
974
	if (!$friend) {
975
		return "User was not found. Please try a different GUID, username, or email address";
976
	}
977
	if (!$friend instanceof ElggUser) {
978
		return "Invalid user. Please try a different GUID, username, or email address";
979
	}
980
981
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
982
	if (!$user_entity) {
983
		return "Viewer user was not found. Please try a different GUID, username, or email address";
984
	}
985
	if (!$user_entity instanceof ElggUser) {
986
		return "Invalid viewer user. Please try a different GUID, username, or email address";
987
	}
988
989
	if (!elgg_is_logged_in()) {
990
		login($user_entity);
991
	}
992
993
	if (!empty($friend)) {
994
		try {
995
			$user_entity->removeFriend($friend->getGUID());
996
997
			// remove river items
998
			elgg_delete_river(array(
999
				"view" => "river/relationship/friend/create",
1000
				"subject_guid" => $user_entity->getGUID(),
1001
				"object_guid" => $friend->getGUID()
1002
			));
1003
1004
			try {
1005
				//V1.1 - Old relationships might not have the 2 as friends...
1006
				$friend->removeFriend($user_entity->getGUID());
1007
1008
				// remove river items
1009
				elgg_delete_river(array(
1010
					"view" => "river/relationship/friend/create",
1011
					"subject_guid" => $friend->getGUID(),
1012
					"object_guid" => $user_entity->getGUID()
1013
				));
1014
1015
				// cyu - remove the relationship (if applicable) for the subscribed to user
1016
				remove_entity_relationship($user_entity->guid, 'cp_subscribed_to_email', $friend_guid);
0 ignored issues
show
Bug introduced by
The variable $friend_guid does not exist. Did you mean $friend?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1017
				remove_entity_relationship($user_entity->guid, 'cp_subscribe_to_site_mail', $friend_guid);
0 ignored issues
show
Bug introduced by
The variable $friend_guid does not exist. Did you mean $friend?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1018
1019
				return true;
1020
			} catch (Exception $e) {
1021
				// do nothing
1022
			}
1023
		} catch (Exception $e) {
1024
			return elgg_echo("friends:remove:failure", array($friend->name));
1025
		}
1026
	} else {
1027
		return elgg_echo("friends:remove:failure", array($friend_guid));
0 ignored issues
show
Bug introduced by
The variable $friend_guid does not exist. Did you mean $friend?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
1028
	}
1029
}
1030
1031
function approve_colleague($profileemail, $user, $lang)
1032
{
1033
	$friend = is_numeric($profileemail) ? get_user($profileemail) : (strpos($profileemail, '@') !== false ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail));
1034
	if (!$friend) {
1035
		return "User was not found. Please try a different GUID, username, or email address";
1036
	}
1037
	if (!$friend instanceof ElggUser) {
1038
		return "Invalid user. Please try a different GUID, username, or email address";
1039
	}
1040
1041
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
1042
	if (!$user_entity) {
1043
		return "Viewer user was not found. Please try a different GUID, username, or email address";
1044
	}
1045
	if (!$user_entity instanceof ElggUser) {
1046
		return "Invalid viewer user. Please try a different GUID, username, or email address";
1047
	}
1048
1049
	if (!elgg_is_logged_in()) {
1050
		login($user_entity);
1051
	}
1052
1053
	if (!empty($friend)) {
1054
		if (remove_entity_relationship($friend->getGUID(), "friendrequest", $user_entity->getGUID())) {
1055
			$user_entity->addFriend($friend->getGUID());
1056
			$friend->addFriend($user_entity->getGUID());			//Friends mean reciprical...
1057
1058
			// notify the user about the acceptance
1059
			$subject = elgg_echo("friend_request:approve:subject", array($user_entity->name, $user_entity->name));
1060
			$message = elgg_echo("friend_request:approve:message", array($user_entity->name, $user_entity->getURL(), $user_entity->name, $user_entity->getURL()));
1061
1062
			$params = array(
1063
				"action" => "add_friend",
1064
				"object" => $user_entity
1065
			);
1066
1067
			// cyu - 04/04/2016: use new notification system hook instead (if activated)
1068 View Code Duplication
			if (elgg_is_active_plugin('cp_notifications')) {
1069
				$message = array(
1070
					'object' => $user_entity,
1071
					'cp_request_guid' => $friend->getGUID(),
1072
					'cp_approver' => $user_entity->name,
1073
					'cp_approver_profile' => $user_entity->getURL(),
1074
					'cp_msg_type' => 'cp_friend_approve'
1075
				);
1076
				$result = elgg_trigger_plugin_hook('cp_overwrite_notification', 'all', $message);
1077
			} else {
1078
				notify_user($friend->getGUID(), $user_entity->getGUID(), $subject, $message, $params);
1079
			}
1080
1081
			// add to river
1082
			elgg_create_river_item(array(
1083
				"view" => "river/relationship/friend/create",
1084
				"action_type" => "friend",
1085
				"subject_guid" => $user_entity->getGUID(),
1086
				"object_guid" => $friend->getGUID(),
1087
			));
1088
			elgg_create_river_item(array(
1089
				"view" => "river/relationship/friend/create",
1090
				"action_type" => "friend",
1091
				"subject_guid" => $friend->getGUID(),
1092
				"object_guid" => $user_entity->getGUID(),
1093
			));
1094
1095
			return elgg_echo("friend_request:approve:successful", array($friend->name));
1096
		} else {
1097
			return elgg_echo("friend_request:approve:fail", array($friend->name));
1098
		}
1099
	}
1100
}
1101
1102
function decline_colleague($profileemail, $user, $lang)
1103
{
1104
	$friend = is_numeric($profileemail) ? get_user($profileemail) : (strpos($profileemail, '@') !== false ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail));
1105
	if (!$friend) {
1106
		return "User was not found. Please try a different GUID, username, or email address";
1107
	}
1108
	if (!$friend instanceof ElggUser) {
1109
		return "Invalid user. Please try a different GUID, username, or email address";
1110
	}
1111
1112
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
1113
	if (!$user_entity) {
1114
		return "Viewer user was not found. Please try a different GUID, username, or email address";
1115
	}
1116
	if (!$user_entity instanceof ElggUser) {
1117
		return "Invalid viewer user. Please try a different GUID, username, or email address";
1118
	}
1119
1120
	if (!elgg_is_logged_in()) {
1121
		login($user_entity);
1122
	}
1123
1124
	if (!empty($friend)) {
1125
		if (remove_entity_relationship($friend->getGUID(), "friendrequest", $user_entity->getGUID())) {
1126
			$subject = elgg_echo("friend_request:decline:subject", array($user_entity->name));
1127
			$message = elgg_echo("friend_request:decline:message", array($friend->name, $user_entity->name));
1128
1129
			return elgg_echo("friend_request:decline:success");
1130
		} else {
1131
			return elgg_echo("friend_request:decline:fail");
1132
		}
1133
	}
1134
}
1135
1136
function revoke_colleague($profileemail, $user, $lang)
1137
{
1138
	$friend = is_numeric($profileemail) ? get_user($profileemail) : (strpos($profileemail, '@') !== false ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail));
1139
	if (!$friend) {
1140
		return "User was not found. Please try a different GUID, username, or email address";
1141
	}
1142
	if (!$friend instanceof ElggUser) {
1143
		return "Invalid user. Please try a different GUID, username, or email address";
1144
	}
1145
1146
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
1147
	if (!$user_entity) {
1148
		return "Viewer user was not found. Please try a different GUID, username, or email address";
1149
	}
1150
	if (!$user_entity instanceof ElggUser) {
1151
		return "Invalid viewer user. Please try a different GUID, username, or email address";
1152
	}
1153
1154
	if (!elgg_is_logged_in()) {
1155
		login($user_entity);
1156
	}
1157
1158
	if (!empty($friend)) {
1159
		if (remove_entity_relationship($user_entity->getGUID(), "friendrequest", $friend->getGUID())) {
1160
			return elgg_echo("friend_request:revoke:success");
1161
		} else {
1162
			return elgg_echo("friend_request:revoke:fail");
1163
		}
1164
	}
1165
}
1166