/
Participant.php
2137 lines (1957 loc) · 88.7 KB
/
Participant.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* LimeSurvey
* Copyright (C) 2007-2011 The LimeSurvey Project Team / Carsten Schmitz
* All rights reserved.
* License: GNU/GPL License v2 or later, see LICENSE.php
* LimeSurvey is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*
*/
/**
* Specific exception for our purpose
* Used to spit out error messages if mapping attributes doesn't work.
*/
class CPDBException extends Exception
{
}
/**
* This is the model class for table "{{participants}}".
*
* The followings are the available columns in table '{{participants}}':
* @property string $participant_id Primary Key
* @property string $firstname
* @property string $lastname
* @property string $email
* @property string $language
* @property integer $blacklisted
* @property integer $owner_uid
* @property integer $created_by
* @property string $created Date-time of creation
* @property string $modified Date-time of modification
*
* @property User $owner
* @property SurveyLink[] $surveylinks
* @property ParticipantAttribute[] $participantAttributes
* @property ParticipantShare[] $shares
*
* @property string $buttons
* @property string $checkbox
* @property array $allExtraAttributes
* @property integer|string $countActiveSurveys
* @property string $blacklistSwitchButton
* @property array $columns
* @property string $ownersList
*/
class Participant extends LSActiveRecord
{
public $extraCondition;
public $countActiveSurveys;
public $id;
/**
* @inheritdoc
* @return Participant
*/
public static function model($class = __CLASS__)
{
/** @var self $model */
$model = parent::model($class);
return $model;
}
/** @inheritdoc */
public function tableName()
{
return '{{participants}}';
}
/** @inheritdoc */
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('participant_id, blacklisted, owner_uid', 'required'),
array('owner_uid', 'numerical', 'integerOnly' => true),
array('participant_id', 'length', 'max' => 50),
array('firstname, lastname', 'length', 'max' => 150),
array('language', 'length', 'max' => 40),
array('firstname, lastname, language', 'LSYii_Validators'),
array('email', 'length', 'max' => 254),
array('blacklisted', 'length', 'max' => 1),
// Please remove those attributes that should not be searched.
array('participant_id, firstname, lastname, email, language, countActiveSurveys, blacklisted, owner.full_name', 'safe', 'on' => 'search'),
);
}
/** @inheritdoc */
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'owner' => array(self::HAS_ONE, 'User', array('uid' => 'owner_uid')),
'surveylinks' => array(self::HAS_MANY, 'SurveyLink', 'participant_id'),
'participantAttributes' => array(self::HAS_MANY, 'ParticipantAttribute', 'participant_id'),
'shares' => array(self::HAS_MANY, 'ParticipantShare', 'participant_id')
);
}
// public function getCountActiveSurveys(){
// $count = count($this->surveylinks);
// return $count ;
// return ($count!==0 ? $count : '');
// }
/**
* @return string
*/
public function getButtons()
{
$buttons = "<div style='white-space: nowrap'>";
$raw_button_template = ""
. "<button class='btn btn-default btn-xs %s %s' role='button' data-toggle='tooltip' title='%s' onclick='return false;'>" //extra class //title
. "<i class='fa fa-%s' ></i>" //icon class
. "</button>";
if ($this->userHasPermissionToEdit()) {
// Edit button
$editData = array(
'action_participant_editModal',
'',
gT("Edit this participant"),
'edit'
);
$buttons .= vsprintf($raw_button_template, $editData);
// Only owner or superadmin can delete
$userId = Yii::app()->user->id;
$isSuperAdmin = Permission::model()->hasGlobalPermission('superadmin', 'read');
if ($this->owner_uid == $userId || $isSuperAdmin) {
// Delete button
$deleteData = array(
'action_participant_deleteModal',
'text-danger',
gT("Delete this participant"),
'trash text-danger'
);
$buttons .= vsprintf($raw_button_template, $deleteData);
// Share this participant
$infoData = array(
'action_participant_shareParticipant',
'',
gT("Share this participant"),
'share'
);
$buttons .= vsprintf($raw_button_template, $infoData);
} else {
// Invisible button
$deleteData = array(
'action_participant_deleteModal invisible',
'text-danger',
gT("Delete this participant"),
'trash text-danger'
);
$buttons .= vsprintf($raw_button_template, $deleteData);
$infoData = array(
'action_participant_shareParticipant invisible',
'',
gT("Share this participant"),
'share'
);
$buttons .= vsprintf($raw_button_template, $infoData);
}
} else {
// Three empty buttons for correct alignment
// TODO: For some reason, the delete button is smaller than the others
$editData = array(
'action_participant_editModal invisible',
'',
gT("Edit this participant"),
'edit'
);
$buttons .= vsprintf($raw_button_template, $editData);
$buttons .= vsprintf($raw_button_template, $editData);
$deleteData = array(
'action_participant_deleteModal invisible',
'text-danger',
gT("Delete this participant"),
'trash text-danger'
);
$buttons .= vsprintf($raw_button_template, $deleteData);
}
// Survey information
$infoData = array(
'action_participant_infoModal',
'',
gT("List active surveys"),
'search'
);
$buttons .= vsprintf($raw_button_template, $infoData);
// Add participant to survey
$infoData = array(
'action_participant_addToSurvey',
'',
gT("Add participant to survey"),
'user-plus'
);
$buttons .= vsprintf($raw_button_template, $infoData);
$buttons .= "</div>";
return $buttons;
}
/**
* @return string html
*/
public function getCheckbox()
{
return "<input type='checkbox' class='selector_participantCheckbox' name='selectedParticipant[]' value='".$this->id."' >";
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
$returnArray = array(
'participant_id' => gT('Participant'),
'firstname' => gT('First name'),
'lastname' => gT('Last name'),
'email' => gT('Email address'),
'language' => gT('Language'),
'blacklisted' => gT('Blacklisted'),
'owner_uid' => gT('Owner ID'),
'surveyid' => gT('Active survey ID'),
'created' => gT('Created on')
);
foreach ($this->allExtraAttributes as $name => $attribute) {
$returnArray[$name] = $attribute['defaultname'];
}
return $returnArray;
}
/**
* @return array
*/
public function getAllExtraAttributes()
{
$allAttributes = ParticipantAttributeName::model()->getAllAttributes();
$extraAttributes = array();
foreach ($allAttributes as $attribute) {
$extraAttributes["ea_".$attribute['attribute_id']] = $attribute;
}
return $extraAttributes;
}
/**
* Get options for a drop-down attribute
* @param string $attribute_id
* @return array
*/
public function getOptionsForAttribute($attribute_id)
{
//if ($this->attribute_type != 'DD') {
//throw new \CInvalidArgumentException('Only drop-down attributes have options');
//}
//$attribute_id = $this->attribute_id;
$result = Yii::app()->db->createCommand()
->select('*')
->from('{{participant_attribute_values}}')
->where('attribute_id=:attribute_id', array('attribute_id' => $attribute_id))
->queryAll();
return $result;
}
public function getAllUsedLanguagesWithRealName()
{
$lang_array = array();
$languages = $this->findAll(array(
'select'=>'t.language',
'group'=>'t.language',
'distinct'=>true,
));
foreach ($languages as $language) {
$lang_array[$language['language']] = getLanguageNameFromCode($language['language'], false);
}
return $lang_array;
}
/**
* @param string $attributeTextId E.g. ea_145
* @param mixed $attribute_id
* @return string
*/
public function getParticipantAttribute($attributeTextId, $attribute_id = false)
{
if ($attribute_id == false) {
list(,$attribute_id) = explode('_', $attributeTextId);
}
$participantAttributes = ParticipantAttribute::model()->getAttributeInfo($this->participant_id);
foreach ($participantAttributes as $singleAttribute) {
if ($singleAttribute['attribute_id'] == $attribute_id) {
return $singleAttribute['value'];
}
}
return "";
}
/**
* @return int|string
*/
public function getCountActiveSurveys()
{
$activeSurveys = $this->surveylinks;
return count($activeSurveys) > 0 ? count($activeSurveys) : "";
}
/**
* @return string HTML
*/
public function getBlacklistSwitchbutton()
{
if ($this->userHasPermissionToEdit()) {
$inputHtml = "<input type='checkbox' data-size='small' data-on-color='warning' data-off-color='primary' data-off-text='".gT('No')."' data-on-text='".gT('Yes')."' class='action_changeBlacklistStatus' "
. ($this->blacklisted == "Y" ? "checked" : "")
. "/>";
return $inputHtml;
} else {
if ($this->blacklisted == 'Y') {
return gT('Yes');
} else {
return gT('No');
}
}
}
/**
* @return array
*/
public function getColumns()
{
$cols = array(
array(
"name" => 'checkbox',
"type" => 'raw',
"header" => "<input type='checkbox' id='action_toggleAllParticipant' />",
"filter" => false
),
array(
"name" => 'buttons',
"type" => 'raw',
"header" => gT("Action"),
"filter" => false
),
array(
"name" => 'lastname'
),
array(
"name" => 'firstname'
),
array(
"name" => 'email'
),
array(
"name" => 'language',
"value" => 'getLanguageNameFromCode($data->language, false)',
'filter' => $this->allUsedLanguagesWithRealName
),
array(
"name" => 'countActiveSurveys',
"value" => '$data->getCountActiveSurveys()',
"header" => gT("Active surveys"),
"htmlOptions" => array('width' => '80px')
),
array(
"name" => 'owner.full_name',
"header" => gT("Owner"),
"filter" => $this->getOwnersList($this->owner_uid)
),
array(
"name" => 'blacklisted',
"value" => '$data->getBlacklistSwitchbutton()',
"type" => "raw",
"filter" => array('N' => gT("No"), 'Y'=>gT('Yes'))
),
array(
'name' => 'created',
'value' => '$data->createdFormatted',
'type' => 'raw',
)
);
$extraAttributeParams = Yii::app()->request->getParam('extraAttribute');
foreach ($this->allExtraAttributes as $name => $attribute) {
if ($attribute['visible'] == "FALSE") {
continue;
}
$col_array = array(
"value" => '$data->getParticipantAttribute($this->id)',
"id" => $name,
"header" => $attribute['defaultname'],
"type" => "raw",
);
//textbox
if ($attribute['attribute_type'] == "TB") {
$col_array["filter"] = TbHtml::textField("extraAttribute[".$name."]", $extraAttributeParams[$name]);
}
//dropdown
else if ($attribute['attribute_type'] == "DD") {
$options_raw = $this->getOptionsForAttribute($attribute['attribute_id']);
$options_array = array(
''=>''
);
foreach ($options_raw as $option) {
$options_array[$option['value']] = $option['value'];
}
$col_array["filter"] = TbHtml::dropDownList("extraAttribute[".$name."]", $extraAttributeParams[$name], $options_array);
}
//date -> still a text field, too many errors with the gridview
else if ($attribute['attribute_type'] == "DP") {
$col_array["filter"] = TbHtml::textField("extraAttribute[".$name."]", $extraAttributeParams[$name]);
}
$cols[] = $col_array;
}
return $cols;
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
$sort = new CSort;
$sort->defaultOrder = 'lastname';
$sortAttributes = array(
'lastname'=>array(
'asc'=>'t.lastname',
'desc'=>'t.lastname desc',
),
'firstname'=>array(
'asc'=>'t.firstname',
'desc'=>'t.firstname desc',
),
'email'=>array(
'asc'=>'t.email',
'desc'=>'t.email desc',
),
'language'=>array(
'asc'=>'t.language',
'desc'=>'t.language desc',
),
'owner.full_name'=>array(
'asc'=>'owner.full_name',
'desc'=>'owner.full_name desc',
),
'blacklisted'=>array(
'asc'=>'t.blacklisted',
'desc'=>'t.blacklisted desc',
),
'countActiveSurveys'=>array(
'asc'=>'countActiveSurveys',
'desc'=>'countActiveSurveys desc',
),
'created' => array(
'asc' => 't.created asc',
'desc' => 't.created desc'
)
);
$criteria = new CDbCriteria;
$criteria->join = 'LEFT JOIN {{participant_shares}} AS shares ON t.participant_id = shares.participant_id AND (shares.share_uid = '.Yii::app()->user->id.' OR shares.share_uid = -1)';
$criteria->compare('t.firstname', $this->firstname, true, 'AND', true);
$criteria->compare('t.lastname', $this->lastname, true, 'AND', true);
$criteria->compare('t.email', $this->email, true, 'AND', true);
$criteria->compare('t.language', $this->language, true);
$criteria->compare('t.blacklisted', $this->blacklisted, true);
$criteria->compare('t.owner_uid', $this->owner_uid);
$extraAttributeParams = Yii::app()->request->getParam('extraAttribute');
$extraAttributeValues = array();
//Create the filter for the extra attributes
foreach ($this->allExtraAttributes as $name => $attribute) {
if (isset($extraAttributeParams[$name]) && $extraAttributeParams[$name]) {
$extraAttributeValues[$name] = $extraAttributeParams[$name];
}
}
// Include a query for each extra attribute to filter
foreach ($extraAttributeValues as $attributeId => $value) {
$attributeType = $this->allExtraAttributes[$attributeId]['attribute_type'];
$attributeId = (int) substr($attributeId, 3);
// Use "LIKE" for text-box, equal for other types
if ($attributeType == 'TB') {
$callParticipantAttributes = "SELECT DISTINCT pa.participant_id FROM {{participant_attribute}} AS pa WHERE attribute_id = '".$attributeId."' AND value LIKE '%".$value."%'";
} else {
$callParticipantAttributes = "SELECT DISTINCT pa.participant_id FROM {{participant_attribute}} AS pa WHERE attribute_id = '".$attributeId."' AND value = '".$value."'";
}
$criteria->addCondition('t.participant_id IN ('.$callParticipantAttributes.')');
}
$DBCountActiveSurveys = SurveyLink::model()->tableName();
$sqlCountActiveSurveys = "(SELECT COUNT(*) FROM ".$DBCountActiveSurveys." cas WHERE cas.participant_id = t.participant_id )";
$criteria->select = array(
't.*',
'shares.share_uid',
'shares.date_added',
'shares.can_edit',
$sqlCountActiveSurveys.' AS countActiveSurveys',
't.participant_id AS id', // This is need to avoid confusion between t.participant_id and shares.participant_id
);
if ($this->extraCondition) {
$criteria->mergeWith($this->extraCondition);
}
$sort->attributes = $sortAttributes;
$sort->defaultOrder = 't.lastname ASC';
// Users can only see: 1) Participants they own; 2) participants shared with them; and 3) participants shared with everyone
// Superadmins can see all users.
$isSuperAdmin = Permission::model()->hasGlobalPermission('superadmin', 'read');
if (!$isSuperAdmin) {
$criteria->addCondition('t.owner_uid = '.Yii::app()->user->id.' OR '.Yii::app()->user->id.' = shares.share_uid OR shares.share_uid = -1');
}
$pageSize = Yii::app()->user->getState('pageSizeParticipantView', Yii::app()->params['defaultPageSize']);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort' => $sort,
'pagination' => array(
'pageSize' => $pageSize
)
));
}
/**
* @param int $selected Owner id
* @return string HTML
*/
public function getOwnersList($selected)
{
$owner_ids = Yii::app()->db->createCommand()
->selectDistinct('owner_uid')
->from('{{participants}}')
->queryAll();
$ownerList = array(''=>"");
foreach ($owner_ids as $id) {
/** @var User $oUser */
$oUser = User::model()->findByPk($id['owner_uid']);
$ownerList[$id['owner_uid']] = $oUser->full_name;
}
return TbHtml::dropDownList('Participant[owner_uid]', $selected, $ownerList);
}
public function addSurveyFilter($conditions)
{
$this->extraCondition = $this->getParticipantsSearchMultipleCondition($conditions);
}
/**
* Function for generation of unique id
* @return string
*/
public static function gen_uuid()
{
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0xffff)
);
}
/**
* This function is responsible for adding the participant to the database
* @param array $aData Participant data
* @return string|Participant Error message on failure, participant object on success
*/
public function insertParticipant($aData)
{
$oParticipant = new self;
foreach ($aData as $sField => $sValue) {
$oParticipant->$sField = $sValue;
}
try {
$result = $oParticipant->save();
if (!$result) {
return $this->flattenErrorMessages($oParticipant->getErrors());
}
return $oParticipant;
} catch (Exception $e) {
return $e->getMessage();
}
}
/**
* Takes result from model->getErrors() and creates a
* long string of all messages.
* @param array $errors
* @return string
*/
private function flattenErrorMessages(array $errors)
{
$result = '';
foreach ($errors as $error) {
$result .= $error[0].' ';
}
return $result;
}
/**
* Returns the primary key of this table
*
* @access public
* @return string
*/
public function primaryKey()
{
return 'participant_id';
}
/**
* This function updates the data edited in the view
*
* @param array $data
* @return void
*/
public function updateRow($data)
{
$record = $this->findByPk($data['participant_id']);
foreach ($data as $key => $value) {
$record->$key = $value;
}
$record->save();
}
/**
* This function returns a list of participants who are either owned or shared
* with a specific user
*
* @param int $userid The ID of the user that we are listing participants for
*
* @return Participant[] objects containing all the users
*/
public function getParticipantsOwner($userid)
{
$subquery = Yii::app()->db->createCommand()
->select('{{participants}}.participant_id,{{participant_shares}}.can_edit')
->from('{{participants}}')
->leftJoin('{{participant_shares}}', ' {{participants}}.participant_id={{participant_shares}}.participant_id')
->where('owner_uid = :userid1 OR share_uid = :userid2')
->group('{{participants}}.participant_id,{{participant_shares}}.can_edit');
$command = Yii::app()->db->createCommand()
->select('p.*, ps.can_edit')
->from('{{participants}} p')
->join('('.$subquery->getText().') ps', 'ps.participant_id = p.participant_id')
->bindParam(":userid1", $userid, PDO::PARAM_INT)
->bindParam(":userid2", $userid, PDO::PARAM_INT);
return $command->queryAll();
}
/**
* @param integer $userid
* @return int
*/
public function getParticipantsOwnerCount($userid)
{
$command = Yii::app()->db->createCommand()
->select('count(*)')
->from('{{participants}} p')
->leftJoin('{{participant_shares}} ps', 'ps.participant_id = p.participant_id')
->where('p.owner_uid = :userid1 OR ps.share_uid = :userid2')
->bindParam(":userid1", $userid, PDO::PARAM_INT)
->bindParam(":userid2", $userid, PDO::PARAM_INT);
return $command->queryScalar();
}
/**
* Get the number of participants, no restrictions
*
* @return string
*/
public function getParticipantsCountWithoutLimit()
{
return Participant::model()->count();
}
/**
* @return Participant[]
*/
public function getParticipantsWithoutLimit()
{
return Yii::app()->db->createCommand()->select('*')->from('{{participants}}')->queryAll();
}
/**
* This function combines the shared participant and the central participant
* table and searches for any reference of owner id in the combined record
* of the two tables
*
* @param int $userid The id of the owner
* @return int The number of participants owned by $userid who are shared
*/
public function getParticipantsSharedCount($userid)
{
$count = Yii::app()->db->createCommand()->select('count(*)')->from('{{participants}}')->join('{{participant_shares}}', '{{participant_shares}}.participant_id = {{participants}}.participant_id')->where('owner_uid = :userid')->bindParam(":userid", $userid, PDO::PARAM_INT)->queryScalar();
return $count;
}
/**
* @param integer $page
* @param integer $limit
* @param array $attid
* @param string|null $order
* @param CDbCriteria $search
* @param integer $userid
* @return array
* @throws CException
*/
public function getParticipants($page, $limit, $attid, $order = null, $search = null, $userid = null)
{
$data = $this->getParticipantsSelectCommand(false, $attid, $search, $userid, $page, $limit, $order);
$allData = $data->queryAll();
return $allData;
}
/**
* Duplicated from getparticipants, only to have a count
*
* @param array $attid
* @param CDbCriteria $search
* @param int $userid
* @return int
*/
public function getParticipantsCount($attid, $search = null, $userid = null)
{
$data = $this->getParticipantsSelectCommand(true, $attid, $search, $userid);
return $data->queryScalar();
}
/**
* @param bool $count
* @param array $attid
* @param CDbCriteria $search
* @param integer $userid
* @param integer $page
* @param integer $limit
* @param string|null $order
* @return CDbCommand
*/
private function getParticipantsSelectCommand($count = false, $attid, $search = null, $userid = null, $page = null, $limit = null, $order = null)
{
$selectValue = array();
$joinValue = array();
$selectValue[] = "p.*";
$selectValue[] = "luser.full_name as ownername";
$selectValue[] = "luser.users_name as username";
$aAllAttributes = ParticipantAttributeName::model()->getAllAttributes();
foreach ($aAllAttributes as $aAttribute) {
if (!is_null($search) && strpos($search->condition, 'attribute'.$aAttribute['attribute_id']) !== false) {
$attid[$aAttribute['attribute_id']] = $aAttribute;
}
}
// Add survey count subquery
$subQuery = Yii::app()->db->createCommand()
->select('count(*) survey')
->from('{{survey_links}} sl')
->where('sl.participant_id = p.participant_id');
$selectValue[] = sprintf('(%s) survey', $subQuery->getText());
array_push($joinValue, "left join {{users}} luser ON luser.uid=p.owner_uid");
foreach ($attid as $iAttributeID=>$aAttributeDetails) {
if ($iAttributeID == 0) {
continue;
}
$sDatabaseType = Yii::app()->db->getDriverName();
if ($sDatabaseType == 'mssql' || $sDatabaseType == "sqlsrv" || $sDatabaseType == 'dblib') {
$selectValue[] = "cast(attribute".$iAttributeID.".value as varchar(max)) as a".$iAttributeID;
} else {
$selectValue[] = "attribute".$iAttributeID.".value as a".$iAttributeID;
}
array_push($joinValue, "LEFT JOIN {{participant_attribute}} attribute".$iAttributeID." ON attribute".$iAttributeID.".participant_id=p.participant_id AND attribute".$iAttributeID.".attribute_id=".$iAttributeID);
}
$aConditions = array(); // this wil hold all conditions
$aParams = array();
if (!is_null($userid)) {
// We are not superadmin so we need to limit to our own or shared with us
$selectValue[] = '{{participant_shares}}.can_edit';
$joinValue[] = 'LEFT JOIN {{participant_shares}} ON p.participant_id={{participant_shares}}.participant_id';
$aConditions[] = 'p.owner_uid = :userid1 OR {{participant_shares}}.share_uid = :userid2 OR {{participant_shares}}.share_uid = 0';
}
if ($count) {
$selectValue = 'count(*) as cnt';
}
$data = Yii::app()->db->createCommand()
->select($selectValue)
->from('{{participants}} p');
$data->setJoin($joinValue);
if (!empty($search)) {
$aSearch = $search->toArray();
$aConditions[] = $aSearch['condition'];
$aParams = $aSearch['params'];
}
if (Yii::app()->getConfig('hideblacklisted') == 'Y') {
$aConditions[] = "blacklisted<>'Y'";
}
$condition = ''; // This will be the final condition
foreach ($aConditions as $idx => $newCondition) {
if ($idx > 0) {
$condition .= ' AND ';
}
$condition .= '('.$newCondition.')';
}
if (!empty($condition)) {
$data->setWhere($condition);
}
if (!$count) {
// Apply order and limits
if (!empty($order)) {
$data->setOrder($order);
}
if ($page <> 0) {
$offset = ($page - 1) * $limit;
$data->offset($offset)
->limit($limit);
}
}
$data->bindValues($aParams);
if (!is_null($userid)) {
$data->bindParam(":userid1", $userid, PDO::PARAM_INT)
->bindParam(":userid2", $userid, PDO::PARAM_INT);
}
return $data;
}
/**
* @return int
*/
public function getSurveyCount($participant_id)
{
$count = Yii::app()->db->createCommand()->select('count(*)')->from('{{survey_links}}')->where('participant_id = :participant_id')->bindParam(":participant_id", $participant_id, PDO::PARAM_INT)->queryScalar();
return $count;
}
/**
* This function deletes the participant from the participants table,
* references in the survey_links table (but not in matching tokens tables)
* and then all the participants attributes.
* @param string $rows Participants ID separated by comma
* @param bool $bFilter
* @return int number of deleted participants
*/
public function deleteParticipants($rows, $bFilter = true)
{
// Converting the comma separated IDs to an array and assign chunks of 100 entries to have a reasonable query size
$aParticipantsIDChunks = array_chunk(explode(",", $rows), 100);
$deletedParticipants = 0;
foreach ($aParticipantsIDChunks as $aParticipantsIDs) {
if ($bFilter) {
$aParticipantsIDs = $this->filterParticipantIDs($aParticipantsIDs);
}
foreach ($aParticipantsIDs as $aID) {
$oParticipant = Participant::model()->findByPk($aID);
if ($oParticipant) {
$oParticipant->delete();
$deletedParticipants++;
}
$oParticipantShare = ParticipantShare::model()->findByAttributes(array(
'participant_id' => $aID
));
if ($oParticipantShare) {
$oParticipantShare->delete();
}
}
Yii::app()->db->createCommand()->delete(Participant::model()->tableName(), array('in', 'participant_id', $aParticipantsIDs));
// Delete survey links
Yii::app()->db->createCommand()->delete(SurveyLink::model()->tableName(), array('in', 'participant_id', $aParticipantsIDs));
// Delete participant attributes
Yii::app()->db->createCommand()->delete(ParticipantAttribute::model()->tableName(), array('in', 'participant_id', $aParticipantsIDs));
}
return $deletedParticipants;
}
/**
* Filter an array of participants IDs according to permissions of the person being logged in
*
* @param mixed $aParticipantIDs
* @return int[]
*/
public function filterParticipantIDs($aParticipantIDs)
{
// If not super admin filter the participant IDs first to owner only
if (!Permission::model()->hasGlobalPermission('superadmin', 'read')) {
$aCondition = array('and', 'owner_uid=:owner_uid', array('in', 'participant_id', $aParticipantIDs));
$aParameter = array(':owner_uid'=>Yii::app()->session['loginID']);
$aParticipantIDs = Yii::app()->db->createCommand()
->select('participant_id')
->from(Participant::model() ->tableName())
->where($aCondition, $aParameter)
->queryColumn();
}
return $aParticipantIDs;
}
/**
* Deletes CPDB participants identified by their participant ID from survey participants tables
*
* @param string $sParticipantsIDs
* @return integer Number of deleted participants
*/
public function deleteParticipantToken($sParticipantsIDs)
{
/* This function deletes the participant from the participants table,
the participant from any tokens table they're in (using the survey_links table to find them)
and then all the participants attributes. */
$aParticipantsIDChunks = array_chunk(explode(",", $sParticipantsIDs), 100);
$iDeletedParticipants = 0;
foreach ($aParticipantsIDChunks as $aParticipantsIDs) {
$aParticipantsIDs = $this->filterParticipantIDs($aParticipantsIDs);
$aSurveyIDs = Yii::app()->db->createCommand()
->selectDistinct('survey_id')
->from(SurveyLink::model()->tableName())
->where(array('in', 'participant_id', $aParticipantsIDs))
->queryColumn();
foreach ($aSurveyIDs as $iSurveyID) {
$survey = Survey::model()->findByPk($iSurveyID);
if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'delete')) {
$sTokenTable = $survey->tokensTableName;
if (Yii::app()->db->schema->getTable($sTokenTable)) {
Yii::app()->db->createCommand()->delete($sTokenTable, array('in', 'participant_id', $aParticipantsIDs));
}
}
}
$iDeletedParticipants += $this->deleteParticipants($sParticipantsIDs, false);
}
return $iDeletedParticipants;
}
/**
* This function deletes the participant from the participants table,
* the participant from any tokens table they're in (using the survey_links table to find them),
* all responses in surveys they've been linked to,
* and then all the participants attributes.
*
* @param string $sParticipantsIDs
* @return integer Number of deleted participants
*/
public function deleteParticipantTokenAnswer($sParticipantsIDs)
{
$aParticipantsIDs = explode(",", $sParticipantsIDs);
$aParticipantsIDs = $this->filterParticipantIDs($aParticipantsIDs);
$iDeletedParticipants = 0;
foreach ($aParticipantsIDs as $row) {
/** @var SurveyLink[] $tokens */
$tokens = Yii::app()->db->createCommand()
->select('*')
->from(SurveyLink::model()->tableName())
->where('participant_id = :row')
->bindParam(":row", $row, PDO::PARAM_INT)
->queryAll();
foreach ($tokens as $key => $surveyLink) {