Passed
Push — gcconnex ( a660c9...3f6bf9 )
by
unknown
46s
created

user.php ➔ decline_colleague()   D

Complexity

Conditions 12
Paths 136

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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