-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
elections.php
482 lines (438 loc) · 13.1 KB
/
elections.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
<?php
require_once 'elections.civix.php';
use \Symfony\Component\DependencyInjection\ContainerBuilder;
use \Symfony\Component\Config\Resource\FileResource;
use CRM_Elections_ExtensionUtil as E;
/**
* Implements hook_civicrm_container()
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_container/
*
* @return void
*/
function elections_civicrm_container(ContainerBuilder $container) {
$container->addResource(new FileResource(E::path('CRM/Elections/Tokens.php')));
$dispatcher = $container->findDefinition('dispatcher');
$dispatcher->addMethodCall('addListener', ['civi.token.eval', ['CRM_Elections_Tokens', 'evaluate']]);
$dispatcher->addMethodCall('addListener', ['civi.token.list', ['CRM_Elections_Tokens', 'register']]);
$container->addCompilerPass(new Civi\Elections\CompilerPass());
}
/**
* Implements hook_civicrm_config().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_config
*/
function elections_civicrm_config(&$config) {
_elections_civix_civicrm_config($config);
}
/**
* Implements hook_civicrm_install().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_install
*/
function elections_civicrm_install() {
_elections_civix_civicrm_install();
}
/**
* Implements hook_civicrm_enable().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_enable
*/
function elections_civicrm_enable() {
_elections_civix_civicrm_enable();
}
// --- Functions below this ship commented out. Uncomment as required. ---
/**
* Implements hook_civicrm_preProcess().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_preProcess
*
*/
function elections_civicrm_preProcess($formName, &$form) {
if ($formName == 'CRM_Core_Form_ShortCode') {
$form->components['elections'] = array(
'label' => 'Elections',
'select' => array(),
);
$form->components['electioninfo'] = array(
'label' => 'Election Info',
'select' => array(
'key' => 'id',
'entity' => 'Election',
'api' => array(
'params' => array(
'is_deleted' => 0,
),
),
),
);
$form->options[] = array(
'key' => 'action',
'components' => array('elections'),
'options' => array(
'visible' => 'Display visible elections',
'hidden' => 'Display non visible elections',
),
);
}
}
/**
* Hide breadcrumb and Footer from the pages/forms.
* @param $pageOrForm
*/
function hideNonRequiredItemsOnPage($pageOrForm) {
$pageOrForm->assign('breadcrumb', FALSE);
$pageOrForm->assign('urlIsPublic', TRUE);
}
if (CRM_Core_Config::singleton()->userFramework == 'WordPress') {
/**
* Add wordpress filters to expose Election pages as shortcode.
*/
if (function_exists('add_filter')) {
add_filter('shortcode_atts_civicrm', 'elections_amend_shortcode_attributes', 10, 4);
add_filter('civicrm_shortcode_preprocess_atts', 'elections_civicrm_amend_args', 10, 2);
}
/**
* Filter the CiviCRM shortcode arguments.
*
* Add our components and a CiviCRM path.
*
* @param array $args Existing shortcode arguments.
* @param array $shortcode_atts Shortcode attributes.
* @return array $args Modified shortcode arguments.
*/
function elections_civicrm_amend_args($args, $shortcode_atts) {
$args['fs'] = TRUE;
if ($shortcode_atts['component'] == 'elections') {
$args['q'] = 'civicrm/elections';
$args['component'] = 'elections';
if ($shortcode_atts['action'] != 'all') {
$args['eaction'] = $shortcode_atts['action'];
if ($shortcode_atts['viewpageid']) {
$args['evaction'] = get_permalink($shortcode_atts['viewpageid']);
}
}
}
if ($shortcode_atts['component'] == 'electioninfo') {
$args['q'] = 'civicrm/elections/view';
$args['component'] = 'electioninfo';
if (isset($shortcode_atts['id']) && !empty($shortcode_atts['id'])) {
$args['eid'] = $shortcode_atts['id'];
$args['sse'] = TRUE;
}
}
return $args;
}
/**
* Ammend custom shortcode attributes for this extension.
*
* @param $out
* @param $pairs
* @param $atts
* @param $shortcodename
* @return mixed
*/
function elections_amend_shortcode_attributes($out, $pairs, $atts, $shortcodename) {
if (isset($atts['viewpageid']) && !empty($atts['viewpageid'])) {
$out['viewpageid'] = $atts['viewpageid'];
}
return $out;
}
}
/**
* Implements hook_civicrm_navigationMenu().
*
* @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_navigationMenu
*
*/
function elections_civicrm_navigationMenu(&$menu) {
_elections_civix_insert_navigation_menu($menu, NULL, [
'label' => E::ts('Elections'),
'name' => 'Elections',
'icon' => 'crm-i fa-check-square-o',
'url' => 'civicrm/elections',
'permission' => 'administer CiviCRM',
'weight' => 62,
]);
_elections_civix_insert_navigation_menu($menu, 'Administer/System Settings', [
'label' => E::ts('Elections Settings'),
'name' => 'configureElections',
'url' => 'civicrm/admin/setting/elections',
'permission' => 'administer CiviCRM',
]);
}
/**
* Implements hook_civicrm_coreResourceList().
*
*/
function elections_civicrm_coreResourceList(&$list, $region) {
Civi::resources()->addStyleFile('au.com.agileware.elections', 'css/electionforms.css', 0, $region);
}
/**
* Check if logged in user is member of any election admin group.
*
* @return bool
* @throws CiviCRM_API3_Exception
*/
function isElectionAdmin() {
return CRM_Core_Permission::check('administer Elections');
}
/**
* Thorw unathorized message if logged in contact is not allowed to perform certain actions.
*
* @throws CRM_Extension_Exception
* @throws CiviCRM_API3_Exception
*/
function throwUnauthorizedMessageIfRequired($formOrPage) {
if (!isElectionAdmin()) {
throwAccessDeniedException($formOrPage, 'You are not authorized to perform this action.');
return TRUE;
}
return FALSE;
}
/**
* Throw accesss denied exception with custom message.
*
* @param $exceptionMessage
* @throws CRM_Extension_Exception
*/
function throwAccessDeniedException($formOrPage, $exceptionMessage, $pageOptions = array()) {
$formOrPage->thorwError = TRUE;
$formOrPage->assign('errormessage', $exceptionMessage);
if (empty($pageOptions)) {
$pageOptions['return_button_text'] = 'Return to Elections';
$pageOptions['return_button_action'] = CRM_Utils_System::url('civicrm/elections');
}
foreach ($pageOptions as $optionKey => $pageOption) {
$formOrPage->assign($optionKey, $pageOption);
}
}
/**
* Throw accesss denied exception if non-member is trying accept a member related page.
*
* @param $exceptionMessage
* @throws CRM_Extension_Exception
*/
function throwNonMemberAccessDenied($formOrPage) {
$formOrPage->assign('nonmember', TRUE);
throwAccessDeniedException($formOrPage, 'You may only see this page if you are a member.');
}
/**
* Throw access denied exception for a page.
*
* @throws CRM_Extension_Exception
*/
function throwAccessDeniedPage($formOrPage) {
$formOrPage->thorwError = TRUE;
$formOrPage->assign('errormessage', "You're not authorized to access this page.");
}
/**
* Get election id from URL.
*
* @return mixed
* @throws CRM_Core_Exception
* @throws CRM_Extension_Exception
*/
function retrieveElectionIdFromUrl($form) {
$eId = CRM_Utils_Request::retrieve('eid', 'Positive', $form, FALSE, 0);
if (!$eId) {
throwAccessDeniedPage($form);
return -1;
}
return $eId;
}
/**
* Check if page/form request is by wordpress shortcode.
*
* @return bool
* @throws CRM_Core_Exception
*/
function isRequestUsingShortCode() {
$form = NULL;
$fs = CRM_Utils_Request::retrieve('fs', 'Boolean', $form, FALSE, FALSE);
return ($fs) ? TRUE : FALSE;
}
/**
* Find an election by given id.
*
* @param $electionId
* @param $throwErrorIfNotFound
* @return CRM_Elections_BAO_Election
* @throws CRM_Extension_Exception
*/
function findElectionById($electionId, $throwErrorIfNotFound = TRUE) {
if (!$electionId) {
throw new CRM_Extension_Exception('You are not authorised to access this page.');
}
$election = new CRM_Elections_BAO_Election();
$election->id = $electionId;
if (!$election->find(TRUE) && $throwErrorIfNotFound) {
throw new CRM_Extension_Exception('You are not authorised to access this page.');
}
$election->assignStatues();
return $election;
}
/**
* Declare a activity type which records nomination activity.
*
* Implements hook_civicrm_managed().
*/
function elections_civicrm_managed(&$entities) {
$entities[] = array(
'module' => 'au.com.agileware.elections',
'name' => 'nomination_option_value',
'entity' => 'OptionValue',
'cleanup' => 'never',
'params' => array(
'version' => 3,
'option_group_id' => 'activity_type',
'label' => "Nomination",
'name' => "Nomination",
'description' => "Nominated a member",
'is_reserved' => 1,
'weight' => 1,
'is_active' => 1,
),
);
$entities[] = array(
'module' => 'au.com.agileware.elections',
'name' => 'vote_option_value',
'entity' => 'OptionValue',
'cleanup' => 'never',
'params' => array(
'version' => 3,
'option_group_id' => 'activity_type',
'label' => "Vote",
'name' => "Vote",
'description' => "Voted in an election",
'is_reserved' => 1,
'weight' => 1,
'is_active' => 1,
),
);
}
/**
* Check if logged in member has current membership return if he/she is allowed to vote/nominate in election.
*
* @return bool
* @throws CiviCRM_API3_Exception
*/
function isLoggedInMemberAllowedToVote($electionId, $contactId = NULL) {
if ($contactId == NULL) {
$contactId = CRM_Core_Session::singleton()->getLoggedInContactID();
}
$election = findElectionById($electionId);
$groupIds = $election->allowed_groups;
if (!empty($groupIds)) {
$groupIds = explode(",", strval($groupIds));
}
if (count($groupIds) == 0 || empty($groupIds)) {
return FALSE;
}
$groups = civicrm_api3('GroupContact', 'get', [
'sequential' => TRUE,
'contact_id' => $contactId,
'options' => ['limit' => 0],
]);
$contactGroups = array_column($groups['values'], 'group_id');
$groupsCount = count(array_intersect($contactGroups, $groupIds));
// Check if contact belongs to any of the selected smart groups.
if ($groupsCount == 0) {
$smartGroups = CRM_Contact_BAO_GroupContactCache::contactGroup(CRM_Core_Session::singleton()->getLoggedInContactID());
if (isset($smartGroups['group'])) {
$smartGroups = array_column($smartGroups['group'], 'id');
$groupsCount = count(array_intersect($smartGroups, $groupIds));
}
}
return ($groupsCount > 0) ? TRUE : FALSE;
}
/**
* Check if members are allowed to re-vote.
*
* @param $electionId
*
* @return bool
*/
function isMemberAllowedToReVote($electionId) {
$election = findElectionById($electionId);
return ($election->allow_revote != 0);
}
/**
* Check if logged in user has already voted or not.
*
* @param $electionId
* @return bool
* @throws CiviCRM_API3_Exception
*/
function hasLoggedInUserAlreadyVoted($electionId, $memberId = NULL) {
if (!$memberId) {
$memberId = CRM_Core_Session::singleton()->getLoggedInContactID();
}
$votesCount = civicrm_api3('ElectionVote', 'getcount', [
'sequential' => TRUE,
'member_id' => $memberId,
'election_nomination_id.election_position_id.election_id.id' => $electionId,
'options' => ['limit' => 0],
]);
return ($votesCount > 0);
}
/**
* Check if logged in user has already voted or not.
*
* @param $electionId
* @return bool
* @throws CiviCRM_API3_Exception
*/
function getLoggedInUserVoteDate($electionId) {
$voteDate = civicrm_api3('ElectionVote', 'get', [
'sequential' => TRUE,
'return' => array('created_at'),
'options' => ['limit' => 0],
'member_id' => CRM_Core_Session::singleton()->getLoggedInContactID(),
'election_nomination_id.election_position_id.election_id.id' => $electionId,
]);
$voteDate = $voteDate['values'][0]['created_at'];
return $voteDate;
}
/**
* Implements hook_civicrm_permission().
*
*/
function elections_civicrm_permission(&$permissions) {
$permissions['administer Elections'] = [
'label' => E::ts('CiviCRM: administer elections'),
'description' => E::ts('Grants the necessary permissions for administrating elections in CiviCRM.'),
];
$permissions['view Elections'] = [
'label' => E::ts('CiviCRM: view elections'),
'description' => E::ts('Grants the necessary permissions for participating in elections.'),
];
}
/**
* Shuffle the array keeping the keys.
*
* @param $list
* @return array
*/
function elections_shuffle_assoc($list) {
if (!is_array($list)) {
return $list;
}
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}
/**
* @param $entity
* @param $action
* @param $params
* @param $permissions
* Implements hook_civicrm_alterAPIPermissions().
*/
function elections_civicrm_alterAPIPermissions($entity, $action, &$params, &$permissions) {
$permissions['election_nominee']['getlist'] = array('view Elections');
}