missions-searching.php ➔ mm_analyze_advanced_search_element()   F
last analyzed

Complexity

Conditions 92
Paths 140

Size

Total Lines 385

Duplication

Lines 35
Ratio 9.09 %

Code Coverage

Tests 0
CRAP Score 8556

Importance

Changes 0
Metric Value
cc 92
nc 140
nop 2
dl 35
loc 385
ccs 0
cts 343
cp 0
crap 8556
rs 3.0666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * Author: National Research Council Canada
4
 * Website: http://www.nrc-cnrc.gc.ca/eng/rd/ict/
5
 *
6
 * License: Creative Commons Attribution 3.0 Unported License
7
 * Copyright: Her Majesty the Queen in Right of Canada, 2015
8
 */
9
10
/*
11
 * Handles the call to the database using elgg_get_entities_from_metadata.
12
 * Sets the resulting array and count of the array to SESSION variables if the count is not 0.
13
 * Also handles intersecting with any array that currently exists within SESSION.
14
 */
15
function mm_search_database_for_missions($query_array, $query_operand, $limit, $mission_state_include_array = ['posted'])
16
{
17
    $options = array();
18
    $mission_count = '';
19
    $missions = '';
20
    $filtered_array = array_filter($query_array);
21
    $dbprefix = elgg_get_config("dbprefix");
22
23
    if(empty($filtered_array)) {
24
        register_error(elgg_echo('missions:error:no_search_values'));
25
        return false;
26
    }
27
28
    foreach($filtered_array as $key => $array) {
29
        $filtered_array[$key]['operand'] = htmlspecialchars_decode($array['operand']);
30
    }
31
32
    if ( strcasecmp( $query_operand, 'OR' ) === 0 ){
33
        $options['type'] = 'object';
34
        $options['subtype'] = 'mission';
35
        $options['metadata_name_value_pairs_operator'] = $query_operand;
36
        $options['metadata_case_sensitive'] = false;
37
        if ($limit > 0) $options['limit'] = $limit;
38
        $options['wheres'][] = 'e.owner_guid IN (SELECT guid FROM '.$dbprefix.'users_entity user WHERE user.name LIKE "' . mysql_escape_string($filtered_array[0]['value']) . '")';
39
        $all_missions = elgg_get_entities_from_metadata($options);
40
        array_pop($options['wheres']);
41
42
        // split the search into separate queries to prevent slowdown from 10+ join queries using 'OR'
43
        foreach ($filtered_array as $array) {
44
            $options['metadata_name_value_pairs'] = array($array);
45
            $some_missions = elgg_get_entities_from_metadata($options);
46
            $all_missions = array_merge( $all_missions, $some_missions );
47
        }
48
49
        $missions = array();
50
        foreach ($all_missions as $mission) {
51
            $missions[$mission->guid] = $mission;
52
        }
53
        // Filter opportunities based on their state.  Inclusive.
54
        // WHY: We may only want to search for archived or open opportunities which have different states.
55
        foreach($missions as $key => $mission) {
56
            $include_opportunity = false;
57
            foreach ($mission_state_include_array as $include_state) {
58
                if ($mission->state == $include_state) {
59
                    $include_opportunity = true;
60
                    last;
61
                }
62
            }
63
            if ($include_opportunity == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
64
                unset($missions[$key]);
65
            }
66
        }
67
    }
68
    else {
69
        // Setting options with which the query will be built.
70
        $options['type'] = 'object';
71
        $options['subtype'] = 'mission';
72
        $options['metadata_name_value_pairs'] = $filtered_array;
73
        $options['metadata_name_value_pairs_operator'] = $query_operand;
74
        $options['metadata_case_sensitive'] = false;
75
        $options['limit'] = $limit;
76
        $missions = elgg_get_entities_from_metadata($options);
77
78
        foreach($missions as $key => $mission) {
79
            if($mission->state != 'posted') {
80
                unset($missions[$key]);
81
            }
82
        }
83
    }
84
85
    $mission_count = count($missions);
86
    if ($mission_count == 0) {
87
        register_error(elgg_echo('missions:error:entity_does_not_exist'));
88
        return false;
89
    } else {
90
        $_SESSION['mission_count'] = $mission_count;
91
        $_SESSION['mission_search_set'] = $missions;
92
        $_SESSION['mission_search_set_timestamp'] = time();
93
94
        return true;
95
    }
96
}
97
98
/*
99
 * Small function to compare missions according to their guid.
100
 */
101
function mm_compare_guid($a, $b)
102
{
103
    if ($a->guid == $b->guid) {
104
        return 0;
105
    }
106
    if ($a->guid > $b->guid) {
107
        return 1;
108
    }
109
    return - 1;
110
}
111
112
/*
113
 * Analyzes the selection values and selection element values in order to construct a WHERE statement.
114
 * This is for when Javascript is enabled.
115
 */
116
function mm_analyze_advanced_search_element($place, $array)
117
{
118
    $form_name = $_SESSION['mission_search_switch'];
119
    $returner = array();
120
121
    switch(trim($array[$form_name.'_'.$place])) {
122
        // Returns an empty array if
123
        case '':
124
            break;
125
126
        case elgg_echo('missions:user_department'):
127
            if (trim($array[$form_name.'_'.$place.'_element']) != '') {
128
                $returner['name'] = 'department';
129
                $returner['operand'] = 'LIKE';
130
                $returner['value'] = '%' . $array[$form_name.'_'.$place.'_element'].'%';
131
            }
132
            break;
133
134
        case elgg_echo('missions:opt_in'):
135
            if(trim($array[$form_name.'_'.$place.'_element']) != '') {
136
                $name_option = '';
137
                switch($array[$form_name.'_'.$place.'_element']) {
138
                    case elgg_echo('gcconnex_profile:opt:micro_missionseek'):
139
                        $name_option = 'opt_in_missions';
140
                        break;
141
                    case elgg_echo('gcconnex_profile:opt:micro_mission'):
142
                        $name_option = 'opt_in_missionCreate';
143
                        break;
144
                    case elgg_echo('gcconnex_profile:opt:assignment_deployment_seek'):
145
                        $name_option = 'opt_in_assignSeek';
146
                        break;
147
                    case elgg_echo('gcconnex_profile:opt:assignment_deployment_create'):
148
                        $name_option = 'opt_in_assignCreate';
149
                        break;
150
                    case elgg_echo('gcconnex_profile:opt:deployment_seek'):
151
                        $name_option = 'opt_in_deploySeek';
152
                        break;
153
                    case elgg_echo('gcconnex_profile:opt:deployment_create'):
154
                        $name_option = 'opt_in_deployCreate';
155
                        break;
156
                    case elgg_echo('gcconnex_profile:opt:job_swap'):
157
                        $name_option = 'opt_in_swap';
158
                        break;
159
                    case elgg_echo('gcconnex_profile:opt:job_rotate'):
160
                        $name_option = 'opt_in_rotation';
161
                        break;
162
163
                    // Development
164
                    case elgg_echo('gcconnex_profile:opt:mentored'):
165
                        $name_option = 'opt_in_mentored';
166
                        break;
167
                    case elgg_echo('gcconnex_profile:opt:mentoring'):
168
                        $name_option = 'opt_in_mentoring';
169
                        break;
170
                    case elgg_echo('gcconnex_profile:opt:shadowed'):
171
                        $name_option = 'opt_in_shadowed';
172
                        break;
173
                    case elgg_echo('gcconnex_profile:opt:shadowing'):
174
                        $name_option = 'opt_in_shadowing';
175
                        break;
176
                    case elgg_echo('gcconnex_profile:opt:job_sharing'):
177
                        $name_option = 'opt_in_jobshare';
178
                        break;
179
                    case elgg_echo('gcconnex_profile:opt:peer_coached'):
180
                        $name_option = 'opt_in_pcSeek';
181
                        break;
182
                    case elgg_echo('gcconnex_profile:opt:peer_coaching'):
183
                        $name_option = 'opt_in_pcCreate';
184
                        break;
185
                    case elgg_echo('gcconnex_profile:opt:skill_sharing'):
186
                        $name_option = 'opt_in_ssSeek';
187
                        break;
188
                    case elgg_echo('gcconnex_profile:opt:skill_sharing_create'):
189
                        $name_option = 'opt_in_ssCreate';
190
                        break;
191
192
                    /* MW - Added for GCcollab */
193
                    case elgg_echo('gcconnex_profile:opt:casual_seek'):
194
                        $name_option = 'opt_in_casual_seek';
195
                        break;
196
                    case elgg_echo('gcconnex_profile:opt:casual_create'):
197
                        $name_option = 'opt_in_casual_create';
198
                        break;
199
                    case elgg_echo('gcconnex_profile:opt:student_seek'):
200
                        $name_option = 'opt_in_student_seek';
201
                        break;
202
                    case elgg_echo('gcconnex_profile:opt:student_create'):
203
                        $name_option = 'opt_in_student_create';
204
                        break;
205
                    case elgg_echo('gcconnex_profile:opt:collaboration_seek'):
206
                        $name_option = 'opt_in_collaboration_seek';
207
                        break;
208
                    case elgg_echo('gcconnex_profile:opt:collaboration_create'):
209
                        $name_option = 'opt_in_collaboration_create';
210
                        break;
211
                    case elgg_echo('gcconnex_profile:opt:interchange_seek'):
212
                        $name_option = 'opt_in_interchange_seek';
213
                        break;
214
                    case elgg_echo('gcconnex_profile:opt:interchange_create'):
215
                        $name_option = 'opt_in_interchange_create';
216
                        break;
217
                }
218
                $returner['name'] = $name_option;
219
                $returner['operand'] = '=';
220
                $returner['value'] = 'gcconnex_profile:opt:yes';
221
            }
222
            break;
223
224
        case elgg_echo('missions:portfolio'):
225
            if(trim($array[$form_name.'_'.$place.'_element_value']) != '') {
226
                $name_option = '';
227
                $operand_option = 'LIKE';
228
                $value_option = '%' . $array[$form_name.'_'.$place.'_element_value'].'%';
229
                switch($array[$form_name.'_'.$place.'_element']) {
230
                    case elgg_echo('missions:title'):
231
                        $name_option = 'title';
232
                        break;
233 View Code Duplication
                    case elgg_echo('missions:publication_date'):
234
                        $name_option = 'pubdate';
235
                        $operand_option = $array[$form_name.'_'.$place.'_element_operand'];
236
                        $value_option = $array[$form_name.'_'.$place.'_element_value'];
237
                        break;
238
                }
239
                $returner['name'] = $name_option;
240
                $returner['operand'] = $operand_option;
241
                $returner['value'] = $value_option;
242
                $returner['extra_option'] = 'portfolio';
243
            }
244
            break;
245
246 View Code Duplication
        case elgg_echo('missions:skill'):
247
            if(trim($array[$form_name.'_'.$place.'_element']) != '') {
248
                $returner['name'] = 'title';
249
                $returner['operand'] = 'LIKE';
250
                $returner['value'] = '%' . $array[$form_name.'_'.$place.'_element'].'%';
251
                $returner['extra_option'] = 'MySkill';
252
            }
253
            break;
254
255
        case elgg_echo('missions:experience'):
256
            if(trim($array[$form_name.'_'.$place.'_element_value']) != '') {
257
                $name_option = '';
258
                $operand_option = 'LIKE';
259
                $value_option = '%' . $array[$form_name.'_'.$place.'_element_value'].'%';
260
                switch($array[$form_name.'_'.$place.'_element']) {
261
                    case elgg_echo('missions:title'):
262
                        $name_option = 'title';
263
                        break;
264
                    case elgg_echo('missions:organization'):
265
                        $name_option = 'organization';
266
                        break;
267 View Code Duplication
                    case elgg_echo('missions:end_year'):
268
                        $name_option = 'endyear';
269
                        $operand_option = $array[$form_name.'_'.$place.'_element_operand'];
270
                        $value_option = $array[$form_name.'_'.$place.'_element_value'];
271
                        break;
272
                }
273
                $returner['name'] = $name_option;
274
                $returner['operand'] = $operand_option;
275
                $returner['value'] = $value_option;
276
                $returner['extra_option'] = 'experience';
277
            }
278
            break;
279
280
        case elgg_echo('missions:education'):
281
            if(trim($array[$form_name.'_'.$place.'_element_value']) != '') {
282
                $name_option = '';
283
                $operand_option = 'LIKE';
284
                $value_option = '%' . $array[$form_name.'_'.$place.'_element_value'].'%';
285
                switch($array[$form_name.'_'.$place.'_element']) {
286
                    case elgg_echo('missions:title'):
287
                        $name_option = 'title';
288
                        break;
289
                    case elgg_echo('missions:degree'):
290
                        $name_option = 'degree';
291
                        break;
292
                    case elgg_echo('missions:field'):
293
                        $name_option = 'field';
294
                        break;
295 View Code Duplication
                    case elgg_echo('missions:end_year'):
296
                        $name_option = 'endyear';
297
                        $operand_option = $array[$form_name.'_'.$place.'_element_operand'];
298
                        $value_option = $array[$form_name.'_'.$place.'_element_value'];
299
                        break;
300
                }
301
                $returner['name'] = $name_option;
302
                $returner['operand'] = $operand_option;
303
                $returner['value'] = $value_option;
304
                $returner['extra_option'] = 'education';
305
            }
306
            break;
307
308
        //
309
        case elgg_echo('missions:start_time'):
310
        case elgg_echo('missions:duration'):
311
            if (trim($array[$form_name.'_'.$place.'_element'])) {
312
                $name_option = '';
313
                // Selects which day will be searched.
314
                switch ($array[$form_name.'_'.$place.'_element_day']) {
315
                    case elgg_echo('missions:mon'):
316
                        $name_option = 'mon';
317
                        break;
318
                    case elgg_echo('missions:tue'):
319
                        $name_option = 'tue';
320
                        break;
321
                    case elgg_echo('missions:wed'):
322
                        $name_option = 'wed';
323
                        break;
324
                    case elgg_echo('missions:thu'):
325
                        $name_option = 'thu';
326
                        break;
327
                    case elgg_echo('missions:fri'):
328
                        $name_option = 'fri';
329
                        break;
330
                    case elgg_echo('missions:sat'):
331
                        $name_option = 'sat';
332
                        break;
333
                    case elgg_echo('missions:sun'):
334
                        $name_option = 'sun';
335
                        break;
336
                }
337
338
                if($array[$form_name.'_'.$place] == elgg_echo('missions:start_time')) {
339
                    $name_option .= '_start';
340
                }
341
                if($array[$form_name.'_'.$place] == elgg_echo('missions:duration')) {
342
                     $name_option .= '_duration';
343
                }
344
345
                $operand_option = $array[$form_name.'_'.$place.'_operand'];
346
                // Packs the input hour and time for comparison with the packed elements in the database.
347
                $returner['name'] = $name_option;
348
                $returner['operand'] = $array[$form_name.'_'.$place.'_operand'];
349
                $returner['value'] = $array[$form_name.'_'.$place.'_element'];
350
            }
351
            break;
352
353
        case elgg_echo('missions:period'):
354
            if(trim($array[$form_name.'_'.$place.'_element']) != '') {
355
                $returner['name'] = 'time_interval';
356
                $returner['operand'] = '=';
357
                $returner['value'] = $array[$form_name.'_'.$place.'_element'];
358
            }
359
              break;
360
361
        case elgg_echo('missions:time'):
362
            if (trim($array[$form_name.'_'.$place.'_element']) != '') {
363
                $returner['name'] = 'time_commitment';
364
                $returner['operand'] = $array[$form_name.'_'.$place.'_operand'];
365
                $returner['value'] = $array[$form_name.'_'.$place.'_element'];
366
            }
367
            break;
368
369
        // Selects language element which requires packing.
370
        case elgg_echo('missions:language'):
371
            if (trim($array[$form_name.'_'.$place.'_element_lwc']) != '' || trim($array[$form_name.'_'.$place.'_element_lwe']) != '' || trim($array[$form_name.'_'.$place.'_element_lop']) != '') {
372
                $name_option = '';
373
                // Selects which language will be searched
374
                switch ($array[$form_name.'_'.$place.'_element']) {
375
                    case elgg_echo('missions:english'):
376
                        $name_option = 'english';
377
                        break;
378
                    case elgg_echo('missions:french'):
379
                        $name_option = 'french';
380
                        break;
381
                }
382
383
                $option_value = $name_option;
384
                $language_requirement_array = array($array[$form_name.'_'.$place.'_element_lwc'], $array[$form_name.'_'.$place.'_element_lwe'], $array[$form_name.'_'.$place.'_element_lop']);
385
                foreach($language_requirement_array as $value) {
386
                    switch($value) {
387
                        case 'A':
388
                            $option_value .= '[Aa-]';
389
                            break;
390
                        case 'B':
391
                            $option_value .= '[ABab-]';
392
                            break;
393
                        case 'C':
394
                            $option_value .= '[ABCabc-]';
395
                            break;
396
                        default:
397
                            $option_value .= '[-]';
398
                    }
399
                }
400
401
                // Packs the input written comprehension, written expression and oral proficiency for comparison with the packed elements in the database.
402
                //$option_value = mm_pack_language($array[$form_name.'_' . $place . '_element_lwc'], $array[$form_name.'_' . $place . '_element_lwe'], $array[$form_name.'_' . $place . '_element_lop'], $name_option);
403
                $returner['name'] = $name_option;
404
                $returner['operand'] = 'REGEXP';
405
                $returner['value'] = $option_value;
406
            }
407
            break;
408
409
        // The next 3 are select elements that require a MySQL LIKE comparison.
410
        case elgg_echo('missions:key_skills'):
411
            if (trim($array[$form_name.'_'.$place.'_element']) != '') {
412
                $returner['name'] = 'key_skills';
413
                $returner['operand'] = 'LIKE';
414
                $returner['value'] = '%' . $array[$form_name.'_'.$place.'_element'] . '%';
415
            }
416
            break;
417
418
        case elgg_echo('missions:location'):
419
            if (trim($array[$form_name.'_'.$place.'_element']) != '') {
420
                $returner['name'] = 'location';
421
                $returner['operand'] = 'LIKE';
422
                $returner['value'] = '%' . $array[$form_name.'_'.$place.'_element'] . '%';
423
            }
424
            break;
425
426
        case elgg_echo('missions:type'):
427
            if (trim($array[$form_name.'_'.$place.'_element']) != '') {
428
                $returner['name'] = 'job_type';
429
                $returner['operand'] = '=';
430
                $returner['value'] = $array[$form_name.'_'.$place.'_element'];
431
            }
432
            break;
433
434
        // The next 5 are selects elements that require a direct equivalence comparison.
435
        case elgg_echo('missions:title'):
436
            if (trim($array[$form_name.'_'.$place.'_element']) != '') {
437
                $returner['name'] = 'job_title';
438
                $returner['operand'] = 'LIKE';
439
                $returner['value'] = '%' . $array[$form_name.'_'.$place.'_element'] . '%';
440
            }
441
            break;
442
443
        case elgg_echo('missions:security_clearance'):
444
            if (trim($array[$form_name.'_'.$place.'_element']) != '') {
445
                $returner['name'] = 'security';
446
                $returner['operand'] = '=';
447
                $returner['value'] = $array[$form_name.'_'.$place.'_element'];
448
            }
449
            break;
450
451 View Code Duplication
        case elgg_echo('missions:department'):
452
            if (trim($array[$form_name.'_'.$place.'_element']) != '') {
453
                if(get_current_language() == 'fr') {
454
                    $returner['name'] = 'department_path_french';
455
                }
456
                else {
457
                    $returner['name'] = 'department_path_english';
458
                }
459
                $returner['operand'] = 'LIKE';
460
                $returner['value'] = '%' . $array[$form_name.'_'.$place.'_element'] . '%';
461
            }
462
            break;
463
464
        case elgg_echo('missions:work_remotely'):
465
            $returner['name'] = 'remotely';
466
            $returner['operand'] = '=';
467
            if($array[$form_name.'_'.$place.'_element']) {
468
                $returner['value'] = 'on';
469
            }
470
            else {
471
                $returner['value'] = 0;
472
            }
473
            break;
474
475
        case elgg_echo('missions:program_area'):
476
            $returner['name'] = 'program_area';
477
            $returner['operand'] = '=';
478
            $returner['value'] = $array[$form_name.'_'.$place.'_element'];
479
            break;
480
            
481
    // Group and level
482
        case elgg_echo('missions:groupandlevel'):
483
            $returner['groupandlevel_group'] = array(
484
                'name'      =>  'gl_group',
485
                'operand'   =>  '=',
486
                'value'     =>  $array[$form_name.'_'.$place.'_element']
487
            );
488
489
            if ($array[$form_name.'_'.$place.'_operand'] !== 'all'){
490
                $returner['groupandlevel_level'] = array(
491
                    'name'      => 'gl_level',
492
                    'operand'   => $array[$form_name.'_'.$place.'_operand'],
493
                    'value'     => $array[$form_name.'_'.$place.'_element_lvl']
494
                );
495
            }
496
            break;
497
    }
498
499
    return $returner;
500
}
501
502
/*
503
 * Analyzes the selection values and selection element values in order to construct a WHERE statement.
504
 * This is for when Javascript is disabled.
505
 */
506
function mm_analyze_backup($place, $array)
507
{
508
    $returner = array();
509
510
    $name_option = '';
511
    $operand_option = '';
512
    $value_option = '';
513
    $extra_option = '';
514
515
    // If the selection element has been chosen.
516
    if (trim($array[$form_name.'_'.$place]) != '') {
517
        // Base operand and value.
518
        $operand_option = '=';
519
        $value_option = $array['backup_' . $place];
520
        // Modifies name, operand and/or value depending on which selection element was chosen.
521
        switch ($array[$form_name.'_'.$place]) {
0 ignored issues
show
Bug introduced by
The variable $form_name does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
522
            case elgg_echo('missions:title'):
523
                $name_option = 'job_title';
524
                break;
525
526 View Code Duplication
            case elgg_echo('missions:type'):
527
                $name_option = 'job_type';
528
                $operand_option = 'LIKE';
529
                $value_option = '%' . $array['backup_' . $place] . '%';
530
                break;
531
532
            case elgg_echo('missions:department'):
533
                $name_option = 'department';
534
                break;
535
536
            case elgg_echo('missions:location'):
537
                $name_option = 'location';
538
                break;
539
540 View Code Duplication
            case elgg_echo('missions:key_skills'):
541
                $name_option = 'key_skills';
542
                $operand_option = 'LIKE';
543
                $value_option = '%' . $array['backup_' . $place] . '%';
544
                break;
545
546
            case elgg_echo('missions:security_clearance'):
547
                $name_option = 'security';
548
                break;
549
550
            // In the language case, the value needs to have the format {language}{LWC}{LWE}{LOP}
551
            case elgg_echo('missions:language'):
552
                switch ($array['backup_' . $place]) {
553 View Code Duplication
                    case (strpos($array['backup_' . $place], 'english') !== false):
554
                        $name_option = 'english';
555
                        break;
556 View Code Duplication
                    case (strpos($array['backup_' . $place], 'french') !== false):
557
                        $name_option = 'french';
558
                        break;
559
                    default:
560
                        return array();
561
                }
562
                $operand_option = '=';
563
                break;
564
565
            // In the time case, the value needs to have the format {day}_{start/end}{hour}:{min}
566
            case elgg_echo('missions:duration'):
567
            case elgg_echo('missions:start_time'):
568
                switch ($array['backup_' . $place]) {
569 View Code Duplication
                    case (strpos($array['backup_' . $place], 'mon_start') !== false):
570
                        $name_option = 'mon_start';
571
                        break;
572 View Code Duplication
                    case (strpos($array['backup_' . $place], 'mon_duration') !== false):
573
                        $name_option = 'mon_duration';
574
                        break;
575 View Code Duplication
                    case (strpos($array['backup_' . $place], 'tue_start') !== false):
576
                        $name_option = 'tue_start';
577
                        break;
578 View Code Duplication
                    case (strpos($array['backup_' . $place], 'tue_duration') !== false):
579
                        $name_option = 'tue_duration';
580
                        break;
581 View Code Duplication
                    case (strpos($array['backup_' . $place], 'wed_start') !== false):
582
                        $name_option = 'wed_start';
583
                        break;
584 View Code Duplication
                    case (strpos($array['backup_' . $place], 'wed_duration') !== false):
585
                        $name_option = 'wed_duration';
586
                        break;
587 View Code Duplication
                    case (strpos($array['backup_' . $place], 'thu_start') !== false):
588
                        $name_option = 'thu_start';
589
                        break;
590 View Code Duplication
                    case (strpos($array['backup_' . $place], 'thu_duration') !== false):
591
                        $name_option = 'thu_duration';
592
                        break;
593 View Code Duplication
                    case (strpos($array['backup_' . $place], 'fri_start') !== false):
594
                        $name_option = 'fri_start';
595
                        break;
596 View Code Duplication
                    case (strpos($array['backup_' . $place], 'fri_duration') !== false):
597
                        $name_option = 'fri_duration';
598
                        break;
599 View Code Duplication
                    case (strpos($array['backup_' . $place], 'sat_start') !== false):
600
                        $name_option = 'sat_start';
601
                        break;
602 View Code Duplication
                    case (strpos($array['backup_' . $place], 'sat_duration') !== false):
603
                        $name_option = 'sat_duration';
604
                        break;
605 View Code Duplication
                    case (strpos($array['backup_' . $place], 'sun_start') !== false):
606
                        $name_option = 'sun_start';
607
                        break;
608 View Code Duplication
                    case (strpos($array['backup_' . $place], 'sun_duration') !== false):
609
                        $name_option = 'sun_duration';
610
                        break;
611
                    default:
612
                        return array();
613
                }
614
                $operand_option = '=';
615
                break;
616
617
            case elgg_echo('missions:skill'):
618
                $name_option = 'title';
619
                $operand_option = 'LIKE';
620
                $value_option = '%' . $array[$form_name.'_'.$place.'_element'] . '%';
621
                $extra_option = 'MySkill';
622
                break;
623
624 View Code Duplication
            case elgg_echo('missions:experience'):
625
                $name_option = 'title';
626
                $operand_option = 'LIKE';
627
                $value_option = '%' . $array[$form_name.'_'.$place.'_element_value'] . '%';
628
                $extra_option = 'experience';
629
                break;
630
631 View Code Duplication
            case elgg_echo('missions:education'):
632
                $name_option = 'title';
633
                $operand_option = 'LIKE';
634
                $value_option = '%' . $array[$form_name.'_'.$place.'_element_value'] . '%';
635
                $extra_option = 'education';
636
                break;
637
638 View Code Duplication
            case elgg_echo('missions:portfolio'):
639
                $name_option = 'title';
640
                $operand_option = 'LIKE';
641
                $value_option = '%' . $array[$form_name.'_'.$place.'_element_value'] . '%';
642
                $extra_option = 'portfolio';
643
                break;
644
645
            case elgg_echo('missions:work_remotely'):
646
                $name_option = 'remotely';
647
                break;
648
649
            case elgg_echo('missions:program_area'):
650
                $name_option = 'program_area';
651
                break;
652
        }
653
        $returner['name'] = $name_option;
654
        $returner['operand'] = $operand_option;
655
        $returner['value'] = $value_option;
656
        $returner['extra_option'] = $extra_option;
657
    }
658
659
    return $returner;
660
}
661
662
/*
663
 * Basic search functionality for candidate searching.
664
 * Checks education, experience and skill attributes from user profiles.
665
 */
666
function mm_simple_search_database_for_candidates($query_array, $limit, $offset=0)
667
{
668
669
    $filtered_array = array_filter($query_array);
670
    if (empty($filtered_array)) {
671
        register_error(elgg_echo('missions:error:no_search_values'));
672
        return false;
673
    }
674
675
    if (function_exists('\NRC\EUS\get') && \NRC\EUS\ready()) {
676
      $MemberSearch = \NRC\EUS\get();
677
      $term = '';
678
      foreach ($query_array as $t) {
679
        $term .= "{$t}* ";
680
      }
681
      $term = trim($term);
682
      $results = $MemberSearch->search($term, $limit, $offset);
683
684
      $candidate_count = $results['total'];
685
686
687
      $search_feedback = array();
688
      $pairs = array();
689
      foreach ($results['users'] as $user) {
690
691
        $pairs[] = array(
692
            'name' => 'guid',
693
            'value' => $user['user_guid'],
694
            'operand' => '='
695
        );
696
697
        if (!isset($search_feedback[$user['user_guid']])) {
698
            $search_feedback[$user['user_guid']] = '';
699
        }
700 View Code Duplication
        if ($user['matched_using']['education'] == 1) {
701
          $search_feedback[$user['user_guid']] .= elgg_echo('missions:school_name') . ': ' . $user['education'] . ',';
702
        }
703 View Code Duplication
        if ($user['matched_using']['experience'] == 1) {
704
            $search_feedback[$user['user_guid']] .= elgg_echo('missions:job_title') . ': ' . $user['experience'] . ',';
705
        }
706 View Code Duplication
        if ($user['matched_using']['gc_skills'] == 1) {
707
            $search_feedback[$user['user_guid']] .= elgg_echo('missions:skill') . ': ' . $user['gc_skills'] . ',';
708
        }
709 View Code Duplication
        if ($user['matched_using']['portfolio'] == 1) {
710
            $search_feedback[$user['user_guid']] .= elgg_echo('missions:portfolio') . ': ' . $user['portfolio'] . ',';
711
        }
712 View Code Duplication
        if ($user['matched_using']['name'] == 1) {
713
            $search_feedback[$user['user_guid']] .= elgg_echo('missions:name') . ': ' . $user['name'] . ',';
714
        }
715 View Code Duplication
        if ($user['matched_using']['contactemail'] == 1) {
716
            $search_feedback[$user['user_guid']] .= elgg_echo('missions:email') . ': ' . $user['contactemail'] . ',';
717
        }
718
      }
719
720
      if ($candidate_count > 0) {
721
        $unique_owners_entity = elgg_get_entities_from_attributes(array(
722
            'type' => 'user', 'limit' => 0,
723
            'attribute_name_value_pairs' => $pairs,
724
            'attribute_name_value_pairs_operator' => 'OR'
725
        ));
726
727
        // SORT ORDER LOST, resort results based on initial query.
728
        $sorted = array();
729
        foreach ($unique_owners_entity as $owner) {
730
            $sorted[] = array_search($owner->guid, array_keys($search_feedback));
731
        }
732
733
        array_multisort($sorted, $unique_owners_entity);
734
      }
735
    } else {
736
737
      $dbprefix = elgg_get_config("dbprefix");
738
      $only_opt_in = false; // Only include members who have opted-in to the platform
739
      $opt_in_sql = '';
740
741
      // TODO: Later versions of ELGG support parameterized queries... DO THAT.
742
      $ms_search = array(); $s_search = array(); $u_search = array();
743
      foreach ($query_array as $term) {
744
          $t = mysql_escape_string(trim($term)) . '*';
745
          $ms_search[] = "(MATCH(a.string) AGAINST(\"$t\" IN BOOLEAN MODE))";
746
          $s_search[] = "(MATCH(eoe.title) AGAINST(\"$t\" IN BOOLEAN MODE))";
747
          $u_search[] = "(MATCH(a.name) AGAINST(\"$t\" IN BOOLEAN MODE))";
748
      }
749
750
      $metadata_search = implode(' AND ', $ms_search);
751
      $metadata_relevance = implode(' + ', $ms_search) . ' + 0';
752
      $skill_search = implode(' AND ', $s_search);
753
      $skill_relevance = implode(' + ', $s_search) . ' + 0';
754
      $user_search = implode(' AND ', $u_search);
755
      $user_relevance = implode(' + ', $u_search) . ' + 0';
756
757
      $search_query_metadata = "
758
          SELECT
759
              c.guid AS user_guid,
760
              CONCAT(d.string, ':::::', a.string) AS field,
761
              ($metadata_relevance) as relevance
762
          FROM
763
              {$dbprefix}metastrings a
764
              LEFT JOIN {$dbprefix}metadata b ON a.id = b.value_id
765
              LEFT JOIN {$dbprefix}users_entity c ON c.guid = b.owner_guid
766
              LEFT JOIN {$dbprefix}metastrings d ON b.name_id = d.id
767
          WHERE
768
              c.guid IS NOT null
769
              AND d.string IN ('contactemail')
770
              AND ($metadata_search)
771
      ";
772
      $search_user_name = "
773
          SELECT
774
              a.guid as user_guid,
775
              CONCAT('name:::::', a.name) as field,
776
              ($user_relevance) as relevance
777
          FROM
778
              {$dbprefix}users_entity a
779
          WHERE
780
              ($user_search)
781
      ";
782
      $search_query_subtypes = "
783
          SELECT
784
              eue.guid as user_guid,
785
              CONCAT(es.subtype, ':::::', eoe.title) as field,
786
              ($skill_search) as relevance
787
              $opt_in_select
0 ignored issues
show
Bug introduced by
The variable $opt_in_select does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
788
          FROM
789
              {$dbprefix}metastrings ems
790
              LEFT JOIN {$dbprefix}metadata em ON ems.id = em.value_id
791
              LEFT JOIN {$dbprefix}users_entity eue ON eue.guid = em.owner_guid
792
              LEFT JOIN {$dbprefix}entities ee ON CAST(ee.guid as char(10)) = ems.string
793
              LEFT JOIN {$dbprefix}entity_subtypes es ON es.id = ee.subtype
794
              LEFT JOIN {$dbprefix}objects_entity eoe ON ee.guid = eoe.guid
795
          WHERE
796
              eue.guid IS NOT NULL
797
              AND ee.subtype IN (SELECT id FROM {$dbprefix}entity_subtypes WHERE subtype IN ('MySkill', 'education', 'experience', 'portfolio'))
798
              AND ($skill_search)
799
      ";
800
801
      $search_wrapper = "
802
      SELECT SQL_CALC_FOUND_ROWS
803
          user_guid,
804
          GROUP_CONCAT(DISTINCT field SEPARATOR '!!!!!') as reason,
805
          SUM(relevance) as relevance
806
      FROM (";
807
      $search_wrapper .= $search_user_name;
808
      $search_wrapper .= "\nUNION\n" . $search_query_metadata;
809
      $search_wrapper .= "\nUNION\n" . $search_query_subtypes;
810
      $search_wrapper .= "\n) matches\n";
811
      if ($only_opt_in) {
812
          $search_wrapper .= "
813
              LEFT JOIN {$dbprefix}metadata b ON b.owner_guid = user_guid
814
              LEFT JOIN {$dbprefix}metastrings a ON a.id = b.name_id
815
              LEFT JOIN {$dbprefix}metastrings c ON c.id = b.value_id
816
          WHERE
817
              match(a.string) against ('opt_in_*' IN BOOLEAN MODE)
818
              AND c.string = 'gcconnex_profile:opt:yes'
819
          ";
820
      }
821
      $search_wrapper .= "GROUP BY user_guid ORDER BY relevance DESC, reason LIMIT $offset, $limit;";
822
      $results = get_data($search_wrapper);
823
      $total_users = get_data('SELECT FOUND_ROWS() as total_users;')[0]->total_users;
824
825
      if (elgg_get_plugin_setting('search_limit', 'missions') !== '-1') {
826
        $candidate_count = min(elgg_get_plugin_setting('search_limit', 'missions'), $total_users);
827
      } else {
828
        $candidate_count = $total_users;
829
      }
830
831
      if (count($results) > 0) {
832
          $search_feedback = array();
833
          foreach($results as $result) {
834
              $reasons = array();
835
              $reason_values = array();
836
              $reasons_tmp = explode('!!!!!', $result->reason);
837
              foreach ($reasons_tmp as $rt) {
838
                  $sp = explode(':::::', $rt);
839
                  $reasons[] = $sp[0];
840
                  $reason_values[$sp[0]] = $sp[1];
841
              }
842
              if (!isset($search_feedback[$result->user_guid])) {
843
                  $search_feedback[$result->user_guid] = '';
844
              }
845 View Code Duplication
              if (in_array('education', $reasons)) {
846
                  $search_feedback[$result->user_guid] .= elgg_echo('missions:school_name') . ': ' . $reason_values['education'] . ',';
847
              }
848 View Code Duplication
              if (in_array('experience', $reasons)) {
849
                  $search_feedback[$result->user_guid] .= elgg_echo('missions:job_title') . ': ' . $reason_values['experience'] . ',';
850
              }
851 View Code Duplication
              if (in_array('MySkill', $reasons)) {
852
                  $search_feedback[$result->user_guid] .= elgg_echo('missions:skill') . ': ' . $reason_values['MySkill'] . ',';
853
              }
854 View Code Duplication
              if (in_array('portfolio', $reasons)) {
855
                  $search_feedback[$result->user_guid] .= elgg_echo('missions:portfolio') . ': ' . $reason_values['portfolio'] . ',';
856
              }
857
              if (in_array('name', $reasons)) {
858
                  $search_feedback[$result->user_guid] .= elgg_echo('missions:name') . ': ' . $reason_values['name'] . ',';
859
              }
860 View Code Duplication
              if (in_array('contactemail', $reasons)) {
861
                  $search_feedback[$result->user_guid] .= elgg_echo('missions:email') . ': ' . $reason_values['contactemail'] . ',';
862
              }
863
          }
864
865
          $pairs = array();
866
          foreach(array_keys($search_feedback) as $guid) {
867
              $pairs[] = array(
868
                  'name' => 'guid',
869
                  'value' => $guid,
870
                  'operand' => '='
871
              );
872
          }
873
          $unique_owners_entity = elgg_get_entities_from_attributes(array(
874
              'type' => 'user', 'limit' => 0,
875
              'attribute_name_value_pairs' => $pairs,
876
              'attribute_name_value_pairs_operator' => 'OR'
877
          ));
878
879
          // SORT ORDER LOST, resort results based on initial query.
880
          $sorted = array();
881
          foreach ($unique_owners_entity as $owner) {
882
              $sorted[] = array_search($owner->guid, array_keys($search_feedback));
883
          }
884
885
          array_multisort($sorted, $unique_owners_entity);
886
      }
887
    }
888
889
    if ($candidate_count == 0) {
890
        register_error(elgg_echo('missions:error:candidate_does_not_exist'));
891
        return false;
892
    } else {
893
        $_SESSION['candidate_count'] = $candidate_count;
894
        $_SESSION['candidate_search_set'] = $unique_owners_entity;
0 ignored issues
show
Bug introduced by
The variable $unique_owners_entity 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...
895
        $_SESSION['candidate_search_set_timestamp'] = time();
896
        $_SESSION['candidate_search_feedback'] = $search_feedback;
0 ignored issues
show
Bug introduced by
The variable $search_feedback 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...
897
        $_SESSION['candidate_search_feedback_timestamp'] = time();
898
        $_SESSION['candidate_search_query_array'] = $query_array;
899
900
        return true;
901
    }
902
}
903
904
/*
905
 * Advanced search functionality for candidate searching.
906
 * Checks education, experience and skill attributes and metadata from user profiles.
907
 */
908
function mm_advanced_search_database_for_candidates($query_array, $query_operand, $limit) {
909
    $users_returned_by_attribute = array();
910
    $users_returned_by_metadata = array();
911
    $is_attribute_searched = false;
912
    $is_metadata_searched = false;
913
    $candidates = array();
914
915
    $filtered_array = array_filter($query_array);
916
    if (empty($filtered_array)) {
917
        register_error(elgg_echo('missions:error:no_search_values'));
918
        return false;
919
    }
920
921
    // Handles each query individually.
922
    foreach($filtered_array as $array) {
923
        // Sets up an education and experience array search for title (not metadata).
924
        if($array['name'] == 'title') {
925
            $options_attribute['type'] = 'object';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options_attribute was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options_attribute = 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...
926
            $options_attribute['subtypes'] = $array['extra_option'];
0 ignored issues
show
Bug introduced by
The variable $options_attribute 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...
927
            $options_attribute['joins'] = array('INNER JOIN ' . elgg_get_config('dbprefix') . 'objects_entity g ON (g.guid = e.guid)');
928
            $options_attribute['wheres'] = array("g." . $array['name'] . " " . $array['operand'] . " '" . $array['value'] . "'");
929
            if ($limit > 0) $options_attribute['limit'] = $limit;
930
            $entities = elgg_get_entities($options_attribute);
931
932
            $entity_owners = array();
933
            $count = 0;
934
            foreach($entities as $entity) {
935
                $entity_owners[$count] = $entity->owner_guid;
936
                $count++;
937
            }
938
939
            // Adds the results of the query to a pool of results.
940 View Code Duplication
            if(empty($users_returned_by_attribute)) {
941
                $users_returned_by_attribute = array_unique($entity_owners);
942
            }
943
            else {
944
                $users_returned_by_attribute = array_unique(array_intersect($users_returned_by_attribute, $entity_owners));
945
            }
946
            // Notes that attributes have been searched during this function call.
947
            $is_attribute_searched = true;
948
        }
949
950
        else if(strpos($array['name'], 'opt_in') !== false || strpos($array['name'], 'department') !== false) {
951
            $options_attribute['type'] = 'user';
952
            $options_metadata['metadata_name_value_pairs'] = array(array('name' => $array['name'], 'operand' => $array['operand'], 'value' => $array['value']));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$options_metadata was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options_metadata = 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...
953
            $options_metadata['limit'] = $limit;
0 ignored issues
show
Bug introduced by
The variable $options_metadata 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...
954
            $options_metadata['metadata_case_sensitive'] = false;
955
            $entities = elgg_get_entities_from_metadata($options_metadata);
956
957
            $entity_owners = array();
958
            $count = 0;
959
            foreach($entities as $entity) {
960
                $entity_owners[$count] = $entity->guid;
961
                $count++;
962
            }
963
964
            // Adds the results of the query to a pool of results.
965 View Code Duplication
            if(empty($users_returned_by_metadata)) {
966
                $users_returned_by_metadata = array_unique($entity_owners);
967
            }
968
            else {
969
                $users_returned_by_metadata = array_unique(array_intersect($users_returned_by_metadata, $entity_owners));
970
            }
971
            // Notes that metadata have been searched during this function call.
972
            $is_metadata_searched = true;
973
        }
974
975
        // Sets up metadata serach.
976
        else {
977
            $operand_temp = htmlspecialchars_decode($array['operand']);
978
979
            $options_metadata['type'] = 'object';
980
            $options_metadata['subtypes'] = $array['extra_option'];
981
            $options_metadata['metadata_name_value_pairs'] = array(array('name' => $array['name'], 'operand' => $operand_temp, 'value' => $array['value']));
982
            $options_metadata['limit'] = $limit;
983
            $options_metadata['metadata_case_sensitive'] = false;
984
            $entities = elgg_get_entities_from_metadata($options_metadata);
985
986
            $entity_owners = array();
987
            $count = 0;
988
            foreach($entities as $entity) {
989
                $entity_owners[$count] = $entity->owner_guid;
990
                $count++;
991
            }
992
993
            // Adds the results of the query to a pool of results.
994 View Code Duplication
            if(empty($users_returned_by_metadata)) {
995
                $users_returned_by_metadata = array_unique($entity_owners);
996
            }
997
            else {
998
                $users_returned_by_metadata = array_unique(array_intersect($users_returned_by_metadata, $entity_owners));
999
            }
1000
            // Notes that metadata have been searched during this function call.
1001
            $is_metadata_searched = true;
1002
        }
1003
    }
1004
1005
    // Intersects the results into a single pool.
1006
    if($is_attribute_searched && $is_metadata_searched) {
1007
        $candidates = array_intersect($users_returned_by_attribute, $users_returned_by_metadata);
1008
    }
1009
    // If only metadata or only attributes have been searched then intersection is unecessary.
1010
    if($is_attribute_searched && !$is_metadata_searched) {
1011
        $candidates = $users_returned_by_attribute;
1012
    }
1013
    if(!$is_attribute_searched && $is_metadata_searched) {
1014
        $candidates = $users_returned_by_metadata;
1015
    }
1016
1017
    $final_users = mm_guids_to_entities_with_opt(array_slice($candidates, 0, $limit));
1018
    $final_count = count($final_users);
1019
1020
    if ($final_count == 0) {
1021
        register_error(elgg_echo('missions:error:candidate_does_not_exist'));
1022
        return false;
1023
    } else {
1024
        $_SESSION['candidate_count'] = $final_count;
1025
        $_SESSION['candidate_search_set'] = $final_users;
1026
        $_SESSION['candidate_search_set_timestamp'] = time();
1027
        unset($_SESSION['candidate_search_feedback']);
1028
1029
        return true;
1030
    }
1031
}
1032
1033
/*
1034
 * Turns an array of guids into an array of entities.
1035
 */
1036
function mm_guids_to_entities_with_opt($candidates) {
1037
    $count_c = 0;
1038
    $count_p = 0;
1039
    $candidates_users = array();
1040
    $potentials_users = array();
1041
    foreach($candidates as $candidate) {
1042
        $user_temp = get_user($candidate);
1043
        if(check_if_opted_in($user_temp)) {
1044
            $candidates_users[$count_c] = $user_temp;
1045
            $count_c++;
1046
        }
1047
        else {
1048
            $potentials_users[$count_p] = $user_temp;
1049
            $count_p++;
1050
        }
1051
    }
1052
1053
    return array_merge($candidates_users, $potentials_users);
1054
}
1055