Completed
Pull Request — gcconnex (#1506)
by
unknown
15:24
created

user.php ➔ get_user_groups()   C

Complexity

Conditions 11
Paths 104

Size

Total Lines 31
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 23
nc 104
nop 3
dl 0
loc 31
rs 5.1999
c 0
b 0
f 0

How to fix   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 View Code Duplication
function build_date($month, $year){
122
	switch($month){
123
		case 1:
124
			$string = "01/";
125
			break;
126
		case 2:
127
			$string = "02/";
128
			break;
129
		case 3:
130
			$string = "03/";
131
			break;
132
		case 4:
133
			$string = "04/";
134
			break;
135
		case 5:
136
			$string = "05/";
137
			break;
138
		case 6:
139
			$string = "06/";
140
			break;
141
		case 7:
142
			$string = "07/";
143
			break;
144
		case 8:
145
			$string = "08/";
146
			break;
147
		case 9:
148
			$string = "09/";
149
			break;
150
		case 10:
151
			$string = "10/";
152
			break;
153
		case 11:
154
			$string = "11/";
155
			break;
156
		case 12:
157
			$string = "12/";
158
			break;
159
	}	
160
	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...
161
}
162
163
function get_user_data( $profileemail, $user, $lang ){
164
	$user_entity = is_numeric($profileemail) ? get_user($profileemail) : ( strpos($profileemail, '@') !== FALSE ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail) );
165
 	if( !$user_entity ) return "User was not found. Please try a different GUID, username, or email address";
166
	if( !$user_entity instanceof ElggUser ) return "Invalid user. Please try a different GUID, username, or email address";
167
168
	if( $user ){
169
		$viewer = is_numeric($user) ? get_user($user) : ( strpos($user, '@') !== FALSE ? get_user_by_email($user)[0] : get_user_by_username($user) );
170
	 	if( !$viewer ) return "Viewer user was not found. Please try a different GUID, username, or email address";
171
		if( !$viewer instanceof ElggUser ) return "Invalid viewer user. Please try a different GUID, username, or email address";
172
		
173
		$friends = $viewer->isFriendsWith($user_entity->guid);
174
	} else {
175
		$friends = false;
176
	}
177
178
	if( !elgg_is_logged_in() )
179
		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...
180
181
	$user = array();
182
183
	$user['id'] = $user_entity->guid;
184
	$user['friend'] = $friends;
185
	$user['user_type'] = $user_entity->user_type;
186
	$user['username'] = $user_entity->username;
187
	$user['displayName'] = $user_entity->name;
188
	$user['email'] = $user_entity->email;
189
	$user['profileURL'] = $user_entity->getURL();
190
	$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...
191
	$user['jobTitle'] = $user_entity->job;
192
193
	switch ($user_entity->user_type) {
194
		case "federal":
195
			$user['department'] = $user_entity->federal;
196
			break;
197
		case "student":
198 View Code Duplication
		case "academic":
199
			$institution = $user_entity->institution;
200
		    $user['department'] = ($institution == 'university') ? $user_entity->university : ($institution == 'college' ? $user_entity->college : $user_entity->highschool);
201
			break;
202
		case "provincial":
203
			$user['department'] = $user_entity->provincial . ' / ' . $user_entity->ministry;
204
			break;
205
		default:
206
			$user['department'] = $user_entity->{$user_entity->user_type};
207
			break;
208
	}
209
210
	$user['telephone'] = $user_entity->phone;
211
	$user['mobile'] = $user_entity->mobile;
212
	$user['website'] = $user_entity->website;
213
214
	if( $user_entity->facebook )
215
		$user['links']['facebook'] = "http://www.facebook.com/".$user_entity->facebook;
216
	if( $user_entity->google )
217
		$user['links']['google'] = "http://www.google.com/".$user_entity->google;
218
	if( $user_entity->github )
219
		$user['links']['github'] = "https://github.com/".$user_entity->github;
220
	if( $user_entity->twitter )
221
		$user['links']['twitter'] = "https://twitter.com/".$user_entity->twitter;
222
	if( $user_entity->linkedin )
223
		$user['links']['linkedin'] = "http://ca.linkedin.com/in/".$user_entity->linkedin;
224
	if( $user_entity->pinterest )
225
		$user['links']['pinterest'] = "http://www.pinterest.com/".$user_entity->pinterest;
226
	if( $user_entity->tumblr )
227
		$user['links']['tumblr'] = "https://www.tumblr.com/blog/".$user_entity->tumblr;
228
	if( $user_entity->instagram )
229
		$user['links']['instagram'] = "http://instagram.com/".$user_entity->instagram;
230
	if( $user_entity->flickr )
231
		$user['links']['flickr'] = "http://flickr.com/".$user_entity->flickr;
232
	if( $user_entity->youtube )
233
		$user['links']['youtube'] = "http://www.youtube.com/".$user_entity->youtube;
234
235
	// About Me
236
	$about_me = strip_tags($user_entity->description, '<p>');
237
	$about_me = str_replace("<p>&nbsp;</p>", '', $about_me);
238
	$user['about_me'] = $about_me;
239
	
240
	// Education
241
	$educationEntity = elgg_get_entities(array(
242
		'owner_guid'=>$user['id'],
243
		'subtype'=>'education',
244
		'type' => 'object',
245
		'limit' => 0
246
	));
247
	$i = 0;
248
	foreach( $educationEntity as $school ){
249
		if( $school->access_id == ACCESS_PUBLIC || $school->access_id == ACCESS_LOGGED_IN || ($friends && $school->access_id == ACCESS_FRIENDS) ){
250
			$user['education']['item_'.$i]['school_name'] = $school->school;
251
			
252
			$user['education']['item_'.$i]['start_date'] = build_date($school->startdate, $school->startyear);
253
			
254 View Code Duplication
			if($school->ongoing == "false"){
255
				$user['education']['item_'.$i]['end_date'] = build_date($school->enddate,$school->endyear);
256
			}else{
257
				$user['education']['item_'.$i]['end_date'] = "present/actuel";
258
			}
259
			$user['education']['item_'.$i]['degree'] = $school->degree;
260
			$user['education']['item_'.$i]['field_of_study'] = $school->field;
261
			$i++;
262
		}
263
	}
264
265
	// Experience
266
	$experienceEntity = elgg_get_entities(array(
267
		'owner_guid'=>$user['id'],
268
		'subtype'=>'experience',
269
		'type' => 'object',
270
		'limit' => 0
271
	));
272
	usort($experienceEntity, "sortDate");
273
	$i = 0;
274
	foreach( $experienceEntity as $job ){
275
		if( $job->access_id == ACCESS_PUBLIC || $job->access_id == ACCESS_LOGGED_IN || ($friends && $job->access_id == ACCESS_FRIENDS) ){
276
			$jobMetadata = elgg_get_metadata(array(
277
				'guid' => $job->guid,
278
				'limit' => 0
279
			));
280
			//foreach ($jobMetadata as $data)
281
			//	$user['job'][$i++][$data->name] = $data->value;
282
283
			$user['experience']['item_'.$i]['job_title'] = $job->title;
284
			$user['experience']['item_'.$i]['organization'] = $job->organization;
285
			$user['experience']['item_'.$i]['start_date'] = build_date($job->startdate, $job->startyear);
286 View Code Duplication
			if ($job->ongoing == "false"){
287
				$user['experience']['item_'.$i]['end_date'] = build_date($job->enddate, $job->endyear);
288
			}else{
289
				$user['experience']['item_'.$i]['end_date'] = "present/actuel";
290
			}
291
			$user['experience']['item_'.$i]['responsibilities'] = $job->responsibilities;
292
			//$user['experience']['item_'.$i]['colleagues'] = $job->colleagues;
293
			$j = 0;
294
			if( is_array($job->colleagues) ){
295
				foreach( $job->colleagues as $friend ){
296
					$friendEntity = get_user($friend);
297
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["id"] = $friendEntity->guid;
298
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["username"] = $friendEntity->username;
299
	
300
					//get and store user display name
301
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["displayName"] = $friendEntity->name;
302
	
303
					//get and store URL for profile
304
					$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["profileURL"] = $friendEntity->getURL();
305
	
306
					//get and store URL of profile avatar
307
					$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...
308
					$j++;
309
				}
310
			} else if( !is_null($job->colleagues) ){
311
				$friendEntity = get_user($job->colleagues);
312
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["id"] = $friendEntity->guid;
313
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["username"] = $friendEntity->username;
314
	
315
				//get and store user display name
316
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["displayName"] = $friendEntity->name;
317
		
318
				//get and store URL for profile
319
				$user['experience']['item_'.$i]['colleagues']['colleague_'.$j]["profileURL"] = $friendEntity->getURL();
320
	
321
				//get and store URL of profile avatar
322
				$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...
323
					
324
			}
325
			$i++;
326
		}
327
	}
328
329
	// Skills
330
	if( $user_entity->skill_access == ACCESS_PUBLIC || $user_entity->skill_access == ACCESS_LOGGED_IN || ($friends && $user_entity->skill_access == ACCESS_FRIENDS) ){
331
		$skillsEntity = elgg_get_entities(array(
332
			'owner_guid'=>$user['id'],
333
			'subtype'=>'MySkill',
334
			'type' => 'object',
335
			'limit' => 0
336
		));
337
	}
338
	$i=0;
339 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...
340
		$user['skills']['item_'.$i]['skill'] = $skill->title;
341
		//$user['skills']['item_'.$i]['endorsements'] = $skill->endorsements;
342
		$j = 0;
343
		if( is_array($skill->endorsements) ){
344
			foreach( $skill->endorsements as $friend ){
345
				$friendEntity = get_user($friend);
346
				if( $friendEntity instanceof ElggUser ){
347
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["id"] = $friendEntity->guid; 
348
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["username"] = $friendEntity->username;
349
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["displayName"] = $friendEntity->name;
350
					$user['skills']['item_'.$i]['endorsements']["user_".$j]["profileURL"] = $friendEntity->getURL();
351
					$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...
352
				}
353
				$j++;
354
			}
355
		} else if( !is_null($skill->endorsements) ){
356
			$friendEntity = get_user($skill->endorsements);
357
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["id"] = $friendEntity->guid; 
358
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["username"] = $friendEntity->username;
359
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["displayName"] = $friendEntity->name;
360
			$user['skills']['item_'.$i]['endorsements']["user_".$j]["profileURL"] = $friendEntity->getURL();
361
			$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...
362
		}
363
		$i++;
364
	}
365
366
	// Portfolio
367
	$portfolioEntity = elgg_get_entities(array(
368
		'owner_guid'=>$user['id'],
369
		'subtype'=>'portfolio',
370
		'type' => 'object',
371
		'limit' => 0
372
	));
373
	$i = 0;
374
	foreach( $portfolioEntity as $portfolio ){
375
		if( $portfolio->access_id == ACCESS_PUBLIC || $portfolio->access_id == ACCESS_LOGGED_IN || ($friends && $portfolio->access_id == ACCESS_FRIENDS) ){
376
			$user['portfolio']['item_'.$i]['title'] = $portfolio->title;
377
			$user['portfolio']['item_'.$i]['link'] = $portfolio->link;
378 View Code Duplication
			if($portfolio->datestamped == "on")
379
				$user['portfolio']['item_'.$i]['date'] = $portfolio->publishdate;
380
			$user['portfolio']['item_'.$i]['description'] = $portfolio->description;
381
		}
382
	}
383
384
	$user['dateJoined'] = date("Y-m-d H:i:s", $user_entity->time_created);
385
	$user['lastActivity'] = date("Y-m-d H:i:s", $user_entity->last_action);
386
	$user['lastLogin'] = date("Y-m-d H:i:s", $user_entity->last_login);
387
388
	$options = array(
389
		'type' => 'object',
390
		'subtype' => 'thewire',
391
		'owner_guid' => $user_entity->guid,
392
		'limit' => 0
393
	);
394
	$wires = elgg_get_entities($options);
395
	$user['wires'] = count($wires);
396
397
	$options = array(
398
		'type' => 'object',
399
		'subtype' => 'blog',
400
		'owner_guid' => $user_entity->guid,
401
		'limit' => 0
402
	);
403
	$blogs = elgg_get_entities($options);
404
	$user['blogs'] = count($blogs);
405
406
	$colleagues = $user_entity->getFriends(array('limit' => 0));
407
	$user['colleagues'] = count($colleagues);
408
409
	return $user;
410
}
411
412 View Code Duplication
function get_user_exists( $user, $lang ){
413
	$user_entity = is_numeric($user) ? get_user($user) : ( strpos($user, '@') !== FALSE ? get_user_by_email($user)[0] : get_user_by_username($user) );
414
415
	$valid = false;
416
	if( $user_entity instanceof ElggUser ){
417
		$is_validated = elgg_get_user_validation_status($user->guid);
418
		if( $is_validated ){
419
			$valid = true;
420
		}
421
	}
422
423
	return $valid;
424
}
425
426
function get_user_activity( $profileemail, $user, $limit, $offset, $lang ){
427
	$user_entity = is_numeric($profileemail) ? get_user($profileemail) : ( strpos($profileemail, '@') !== FALSE ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail) );
428
 	if( !$user_entity ) return "User was not found. Please try a different GUID, username, or email address";
429
	if( !$user_entity instanceof ElggUser ) return "Invalid user. Please try a different GUID, username, or email address";
430
431
	$viewer = is_numeric($user) ? get_user($user) : ( strpos($user, '@') !== FALSE ? get_user_by_email($user)[0] : get_user_by_username($user) );
432
 	if( !$viewer ) return "Viewer user was not found. Please try a different GUID, username, or email address";
433
	if( !$viewer instanceof ElggUser ) return "Invalid viewer user. Please try a different GUID, username, or email address";
434
435
	if( !elgg_is_logged_in() )
436
		login($viewer);
437
	
438
	$all_activity = elgg_list_river(array(
439
		'subject_guid' => $user_entity->guid,
440
		'distinct' => false,
441
		'limit' => $limit,
442
		'offset' => $offset
443
	));
444
445
	$activity = json_decode($all_activity);
446
	foreach( $activity as $event ){
447
		$subject = get_user($event->subject_guid);
448
		$object = get_entity($event->object_guid);
449
		$event->userDetails = get_user_block($event->subject_guid, $lang);
450
451
		if( $object instanceof ElggUser ){
452
			$event->object = get_user_block($event->object_guid, $lang);
453
			$event->object['type'] = 'user';
454
		} else if( $object instanceof ElggWire ){
455
			$event->object['type'] = 'wire';
456
			$event->object['wire'] = wire_filter($object->description);
457
					
458
			$thread_id = $object->wire_thread;
459
			$reshare = $object->getEntitiesFromRelationship(array("relationship" => "reshare", "limit" => 1))[0];
460
461
			$url = "";
462
			if( !empty( $reshare ) ){
463
				$url = $reshare->getURL();
464
			}
465
466
			$text = "";
467
			if ( !empty($reshare->title) ) {
468
				$text = $reshare->title;
469
			} else if ( !empty($reshare->name) ) {
470
				$text = $reshare->name;
471
			} else if ( !empty($reshare->description) ) {
472
				$text = elgg_get_excerpt($reshare->description, 140);
473
			}
474
475
			$event->shareURL = $url;
476
			$event->shareText = gc_explode_translation($text, $lang);
477
		} else if( $object instanceof ElggGroup ){
478
			$event->object['type'] = 'group';
479
			$event->object['name'] = gc_explode_translation($object->name, $lang);
480
		} else if( $object instanceof ElggDiscussionReply ){
481
			$event->object['type'] = 'discussion-reply';
482
			$original_discussion = get_entity($object->container_guid);
483
			$event->object['name'] = $original_discussion->title;
484
			$event->object['description'] = $object->description;
485
		} else if( $object instanceof ElggFile ){
486
			$event->object['type'] = 'file';
487
			$event->object['name'] = $object->title;
488
			$event->object['description'] = $object->description;
489
		} else if( $object instanceof ElggObject ){
490
			$event->object['type'] = 'discussion-add';
491
			$event->object['name'] = ( $object->title ) ? $object->title : $object->name;
492
			$event->object['description'] = $object->description;
493
494
			$other = get_entity($event->object_guid);
495
			$parent = get_entity($other->container_guid);
496 View Code Duplication
			if( $parent instanceof ElggGroup ){
497
				if( !isset($event->object['name']) )
498
					$event->object['name'] = ( $parent->title ) ? $parent->title : $parent->name;
499
			} else {
500
				if( !isset($event->object['name']) )
501
					$event->object['name'] = ( $parent->title ) ? $parent->title : $parent->name;
502
			}
503
		} else {
504
			//@TODO handle any unknown events
505
			if (strpos($object->title, '"en":') !== false) {
506
				$event->object['name'] = gc_explode_translation($object->title, $lang);
507
			} else {
508
				$event->object['name'] = $object->title;
509
			}
510
511
			if (strpos($object->description, '"en":') !== false) {
512
				$event->object['description'] = gc_explode_translation($object->description, $lang);
513
			} else {
514
				$event->object['description'] = $object->description;
515
			}
516
		}
517
	}
518
519
	return $activity;
520
}
521
522
function get_user_groups( $profileemail, $user, $lang ){
523
	$user_entity = is_numeric($profileemail) ? get_user($profileemail) : ( strpos($profileemail, '@') !== FALSE ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail) );
524
 	if( !$user_entity ) return "User was not found. Please try a different GUID, username, or email address";
525
	if( !$user_entity instanceof ElggUser ) return "Invalid user. Please try a different GUID, username, or email address";
526
527
	$viewer = is_numeric($user) ? get_user($user) : ( strpos($user, '@') !== FALSE ? get_user_by_email($user)[0] : get_user_by_username($user) );
528
 	if( !$viewer ) return "Viewer user was not found. Please try a different GUID, username, or email address";
529
	if( !$viewer instanceof ElggUser ) return "Invalid viewer user. Please try a different GUID, username, or email address";
530
531
	if( !elgg_is_logged_in() )
532
		login($viewer);
533
534
	$all_groups = elgg_list_entities_from_relationship(array(
535
	    'relationship' => 'member', 
536
	    'relationship_guid' => $user_entity->guid, 
537
	    'inverse_relationship' => FALSE, 
538
	    'type' => 'group', 
539
	    'limit' => 0
540
	));
541
542
	$groups = json_decode($all_groups);
543
	foreach($groups as $group){
544
		$groupObj = get_entity($group->guid);
545
		$group->name = gc_explode_translation($group->name, $lang);
546
		$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...
547
		$group->count = $groupObj->getMembers(array('count' => true));
548
		$group->description = clean_text(gc_explode_translation($group->description, $lang));
549
	}
550
551
	return $groups;
552
}
553
554
function get_newsfeed( $user, $limit, $offset, $lang ){
555
	$user_entity = is_numeric($user) ? get_user($user) : ( strpos($user, '@') !== FALSE ? get_user_by_email($user)[0] : get_user_by_username($user) );
556
 	if( !$user_entity ) return "User was not found. Please try a different GUID, username, or email address";
557
	if( !$user_entity instanceof ElggUser ) return "Invalid user. Please try a different GUID, username, or email address";
558
	
559
	if( !elgg_is_logged_in() )
560
		login($user_entity);
561
562
	$db_prefix = elgg_get_config('dbprefix');
563
    
564
    if( $user_entity ){
565
        // check if user exists and has friends or groups
566
        $hasfriends = $user_entity->getFriends();
567
        $hasgroups = $user_entity->getGroups();
568
        if( $hasgroups ){
569
            // loop through group guids
570
            $groups = $user_entity->getGroups(array('limit'=>0));
571
            $group_guids = array();
572
            foreach( $groups as $group ){
573
                $group_guids[] = $group->getGUID();
574
            }
575
        }
576
    }
577
578
    $actionTypes = array('comment', 'create', 'join', 'update', 'friend', 'reply');
579
580
    if( !$hasgroups && !$hasfriends ){
581
        // no friends and no groups :(
582
        $activity = '';
583
    } else if( !$hasgroups && $hasfriends ){
584
        // has friends but no groups
585
        $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...
586
        $optionsf['relationship'] = 'friend';
587
        $optionsf['pagination'] = true;
588
589
        // turn off friend connections
590
        // remove friend connections from action types
591
        // load user's preference
592
        $filteredItems = array($user_entity->colleagueNotif);
593
        // filter out preference
594
        $optionsf['action_types'] = array_diff( $actionTypes, $filteredItems );
595
596
        $activity = json_decode(newsfeed_list_river($optionsf));
597
    } else if( !$hasfriends && $hasgroups ){
0 ignored issues
show
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...
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...
598
        // if no friends but groups
599
        $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...
600
        
601
        // display created content and replies and comments
602
        $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...
603
        $optionsg['pagination'] = true;
604
        $activity = json_decode(newsfeed_list_river($optionsg));
605
    } else {
606
        // if friends and groups :3
607
        // turn off friend connections
608
        // remove friend connections from action types
609
        // load user's preference
610
        $filteredItems = array($user_entity->colleagueNotif);
611
        // filter out preference
612
        $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...
613
614
        $guids_in = implode(',', array_unique(array_filter($group_guids)));
615
616
        // Groups + Friends activity query
617
        // 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
618
        $optionsfg['wheres'] = array(
619
    		"( oe.container_guid IN({$guids_in})
620
         	OR te.container_guid IN({$guids_in}) )
621
        	OR rv.subject_guid IN (SELECT guid_two FROM {$db_prefix}entity_relationships WHERE guid_one=$user_entity->guid AND relationship='friend')"
622
        );
623
        $optionsfg['pagination'] = true;
624
        $activity = json_decode(newsfeed_list_river($optionsfg));
625
    }
626
627
    foreach( $activity as $event ){
628
		$subject = get_user($event->subject_guid);
629
		$object = get_entity($event->object_guid);
630
		$event->userDetails = get_user_block($event->subject_guid, $lang);
631
632
		$likes = elgg_get_annotations(array(
633
			'guid' => $event->object_guid,
634
			'annotation_name' => 'likes'
635
		));
636
		$event->likes = count($likes);
637
638
		$liked = elgg_get_annotations(array(
639
			'guid' => $event->object_guid,
640
			'annotation_owner_guid' => $user_entity->guid,
641
			'annotation_name' => 'likes'
642
		));
643
		$event->liked = count($liked) > 0;
644
645
		if($object->description){
646
			$object->description = str_replace("<p>&nbsp;</p>", '', $object->description);
647
		}
648
649
		if( $object instanceof ElggUser ){
650
			$event->object = get_user_block($event->object_guid, $lang);
651
			$event->object['type'] = 'user';
652
		} else if( $object instanceof ElggWire ){
653
			$event->object['type'] = 'wire';
654
			$event->object['wire'] = wire_filter($object->description);
655
			
656
			$thread_id = $object->wire_thread;
657
			$reshare = $object->getEntitiesFromRelationship(array("relationship" => "reshare", "limit" => 1))[0];
658
659
			$url = "";
660
			if( !empty( $reshare ) ){
661
				$url = $reshare->getURL();
662
			}
663
664
			$text = "";
665
			if ( !empty($reshare->title) ) {
666
				$text = $reshare->title;
667
			} else if ( !empty($reshare->name) ) {
668
				$text = $reshare->name;
669
			} else if ( !empty($reshare->description) ) {
670
				$text = elgg_get_excerpt($reshare->description, 140);
671
			}
672
673
			$event->shareURL = $url;
674
			$event->shareText = gc_explode_translation($text, $lang);
675
		} else if( $object instanceof ElggGroup ){
676
			$event->object['type'] = 'group';
677
			$event->object['name'] = gc_explode_translation($object->name, $lang);
678
			$event->object['description'] = gc_explode_translation($object->name, $lang);
679
			
680
			if( is_callable(array($object, 'getURL')) ){
681
				$event->object['url'] = $object->getURL();
682
			}
683
		} else if( $object instanceof ElggDiscussionReply ){
684
			$event->object['type'] = 'discussion-reply';
685
			$original_discussion = get_entity($object->container_guid);
686
			$event->object['name'] = gc_explode_translation($original_discussion->title, $lang);
687
			$event->object['description'] = gc_explode_translation($object->description, $lang);
688
			
689
			if( is_callable(array($original_discussion, 'getURL')) ){
690
				$event->object['url'] = $original_discussion->getURL();
691
			}
692
		} else if( $object instanceof ElggFile ){
693
			$event->object['type'] = 'file';
694
			$event->object['name'] = gc_explode_translation($object->title, $lang);
695
			$event->object['description'] = gc_explode_translation($object->description, $lang);
696
			$event->object['url'] = $object->getURL();
697
		} else if( $object instanceof ElggObject ){
698
			$event->object['type'] = 'discussion-add';
699
700
			$name = ( $object->title ) ? $object->title : $object->name;
701
			if( empty(trim($name)) ){
702
				$otherEntity = get_entity($object->container_guid);
703
				$name = ( $otherEntity->title ) ? $otherEntity->title : $otherEntity->name;
704
			}
705
			$event->object['name'] = $name;
706
			
707
			if( is_callable(array($object, 'getURL')) ){
708
				$event->object['url'] = $object->getURL();
709
			}
710
711
			$event->object['description'] = gc_explode_translation($object->description, $lang);
712
713
			$other = get_entity($object->container_guid);
714 View Code Duplication
			if( $other instanceof ElggGroup ){
715
				if( !isset($event->object['type']) )
716
					$event->object['name'] = ( $other->title ) ? $other->title : $other->name;
717
			} else {
718
				if( !isset($event->object['type']) )
719
					$event->object['name'] = ( $other->title ) ? $other->title : $other->name;
720
			}
721
722
			if (strpos($event->object['name'], '"en":') !== false) {
723
				$event->object['name'] = gc_explode_translation($event->object['name'], $lang);
724
			}
725
		} else {
726
			//@TODO handle any unknown events
727
			if (strpos($object->title, '"en":') !== false) {
728
				$event->object['name'] = gc_explode_translation($object->title, $lang);
729
			} else {
730
				$event->object['name'] = $object->title;
731
			}
732
733
			if (strpos($object->description, '"en":') !== false) {
734
				$event->object['description'] = gc_explode_translation($object->description, $lang);
735
			} else {
736
				$event->object['description'] = $object->description;
737
			}
738
			
739
			if( is_callable(array($object, 'getURL')) ){
740
				$event->object['url'] = $object->getURL();
741
			}
742
		}
743
	}
744
745
	return $activity;
746
}
747
748
function get_colleague_requests( $user, $limit, $offset, $lang ){
749
	$user_entity = is_numeric($user) ? get_user($user) : ( strpos($user, '@') !== FALSE ? get_user_by_email($user)[0] : get_user_by_username($user) );
750
 	if( !$user_entity ) return "User was not found. Please try a different GUID, username, or email address";
751
	if( !$user_entity instanceof ElggUser ) return "Invalid user. Please try a different GUID, username, or email address";
752
	
753
	if( !elgg_is_logged_in() )
754
		login($user_entity);
755
756
	$friendrequests = elgg_list_entities_from_relationship(array(
757
		"type" => "user",
758
		"relationship" => "friendrequest",
759
		"relationship_guid" => $user_entity->getGUID(),
760
		"inverse_relationship" => true,
761
		"limit" => $limit,
762
		"offset" => $offset
763
	));
764
	$friendrequests = json_decode($friendrequests);
765
766
	return $friendrequests;
767
}
768
769
function add_colleague( $profileemail, $user, $lang ){
770
	$friend = is_numeric($profileemail) ? get_user($profileemail) : ( strpos($profileemail, '@') !== FALSE ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail) );
771
 	if( !$friend ) return "User was not found. Please try a different GUID, username, or email address";
772
	if( !$friend instanceof ElggUser ) return "Invalid user. Please try a different GUID, username, or email address";
773
774
	$user_entity = is_numeric($user) ? get_user($user) : ( strpos($user, '@') !== FALSE ? get_user_by_email($user)[0] : get_user_by_username($user) );
775
 	if( !$user_entity ) return "Viewer user was not found. Please try a different GUID, username, or email address";
776
	if( !$user_entity instanceof ElggUser ) return "Invalid viewer user. Please try a different GUID, username, or email address";
777
778
	if( !elgg_is_logged_in() )
779
		login($user_entity);
780
781
	//Now we need to attempt to create the relationship
782
	if (empty($user_entity) || empty($friend)) {
783
		return elgg_echo("friend_request:add:failure");
784
	} else {
785
		//New for v1.1 - If the other user is already a friend (fan) of this user we should auto-approve the friend request...
786
		if (check_entity_relationship($friend->getGUID(), "friend", $user_entity->getGUID())) {
787
			try {
788
				$user_entity->addFriend($friend->getGUID());
789
				return true;
790
			} catch (Exception $e) {
791
				return elgg_echo("friends:add:failure", array($friend->name));
792
			}
793
		} else if (check_entity_relationship($friend->getGUID(), "friendrequest", $user_entity->getGUID())) {
794
			// Check if your potential friend already invited you, if so make friends
795
			if (remove_entity_relationship($friend->getGUID(), "friendrequest", $user_entity->getGUID())) {
796
				
797
				// Friends mean reciprical...
798
				$user_entity->addFriend($friend->getGUID());
799
				$friend->addFriend($user_entity->getGUID());
800
801
				$n_result = notify_user(
802
					$friend->guid,
803
					$user_entity->guid,
804
					elgg_echo('friend:newfriend:subject', array(
805
						$user_entity->name,
806
						$user_entity->name,				
807
					)),
808
					elgg_echo("friend:newfriend:body", array(
809
						$user_entity->name, 
810
						$user_entity->getURL(),
811
						elgg_get_site_url().'notifications/personal/',
812
						
813
						$user_entity->name, 
814
						$user_entity->getURL(),
815
						elgg_get_site_url().'notifications/personal/',
816
					))
817
				);
818
				
819
				// add to river
820
				elgg_create_river_item(array(
821
					"view" => "river/relationship/friend/create",
822
					"action_type" => "friend",
823
					"subject_guid" => $user_entity->getGUID(),
824
					"object_guid" => $friend->getGUID(),
825
				));
826
				elgg_create_river_item(array(
827
					"view" => "river/relationship/friend/create",
828
					"action_type" => "friend",
829
					"subject_guid" => $friend->getGUID(),
830
					"object_guid" => $user_entity->getGUID(),
831
				));
832
833
				return true;
834
			} else {
835
				return elgg_echo("friend_request:approve:fail", array($friend->name));
836
			}
837
		} else {
838
			try {
839 View Code Duplication
				if (!add_entity_relationship($user_entity->getGUID(), "friendrequest", $friend->getGUID())) {
840
					return elgg_echo("friend_request:add:exists", array($friend->name));
841
				}
842
			} catch (Exception $e) {	//register_error calls insert_data which CAN raise Exceptions.
843
				return elgg_echo("friend_request:add:exists", array($friend->name));
844
			}
845
		}
846
	}
847
}
848
849
function remove_colleague( $profileemail, $user, $lang ){
850
	$friend = is_numeric($profileemail) ? get_user($profileemail) : ( strpos($profileemail, '@') !== FALSE ? get_user_by_email($profileemail)[0] : get_user_by_username($profileemail) );
851
 	if( !$friend ) return "User was not found. Please try a different GUID, username, or email address";
852
	if( !$friend instanceof ElggUser ) return "Invalid user. Please try a different GUID, username, or email address";
853
854
	$user_entity = is_numeric($user) ? get_user($user) : ( strpos($user, '@') !== FALSE ? get_user_by_email($user)[0] : get_user_by_username($user) );
855
 	if( !$user_entity ) return "Viewer user was not found. Please try a different GUID, username, or email address";
856
	if( !$user_entity instanceof ElggUser ) return "Invalid viewer user. Please try a different GUID, username, or email address";
857
858
	if( !elgg_is_logged_in() )
859
		login($user_entity);
860
861
	if (!empty($friend)) {
862
		try{
863
			$user_entity->removeFriend($friend->getGUID());
864
			
865
			// remove river items
866
			elgg_delete_river(array(
867
				"view" => "river/relationship/friend/create",
868
				"subject_guid" => $user_entity->getGUID(),
869
				"object_guid" => $friend->getGUID()
870
			));
871
			
872
			try {
873
				//V1.1 - Old relationships might not have the 2 as friends...
874
				$friend->removeFriend($user_entity->getGUID());
875
				
876
				// remove river items
877
				elgg_delete_river(array(
878
					"view" => "river/relationship/friend/create",
879
					"subject_guid" => $friend->getGUID(),
880
					"object_guid" => $user_entity->getGUID()
881
				));
882
883
				// cyu - remove the relationship (if applicable) for the subscribed to user
884
				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...
885
				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...
886
887
				return true;
888
			} catch (Exception $e) {
889
				// do nothing
890
			}
891
		} catch (Exception $e) {
892
			return elgg_echo("friends:remove:failure", array($friend->name));
893
		}
894
	} else {
895
		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...
896
	}
897
}