-
Notifications
You must be signed in to change notification settings - Fork 988
/
Participants.php
1315 lines (1235 loc) · 63.6 KB
/
Participants.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.
*
* $Id$
*/
/**
* This is the model class for table "{{participants}}".
*
* The followings are the available columns in table '{{participants}}':
* @property string $participant_id
* @property string $firstname
* @property string $lastname
* @property string $email
* @property string $language
* @property string $blacklisted
* @property integer $owner_uid
*/
class Participants extends CActiveRecord
{
/**
* Returns the static model of Settings table
*
* @static
* @access public
* @param string $class
* @return Participants
*/
public static function model($class = __CLASS__)
{
return parent::model($class);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return '{{participants}}';
}
/**
* @return array validation rules for model attributes.
*/
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, language', 'length', 'max' => 40),
array('email', 'length', 'max' => 80),
array('blacklisted', 'length', 'max' => 1),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('participant_id, firstname, lastname, email, language, blacklisted, owner_uid', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
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(
);
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'participant_id' => 'Participant',
'firstname' => 'Firstname',
'lastname' => 'Lastname',
'email' => 'Email',
'language' => 'Language',
'blacklisted' => 'Blacklisted',
'owner_uid' => 'Owner Uid',
);
}
/**
* 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()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('participant_id', $this->participant_id, true);
$criteria->compare('firstname', $this->firstname, true);
$criteria->compare('lastname', $this->lastname, true);
$criteria->compare('email', $this->email, true);
$criteria->compare('language', $this->language, true);
$criteria->compare('blacklisted', $this->blacklisted, true);
$criteria->compare('owner_uid', $this->owner_uid);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
/*
* funcion for generation of unique id
*/
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
* Parameters : participant data
* Return Data : none
*/
function insertParticipant($data)
{
Yii::app()->db->createCommand()->insert('{{participants}}', $data);
}
/*
* This function updates the data edited in the jqgrid
* Parameters : data that is edited
* Return Data : None
*/
function updateRow($data)
{
Yii::app()->db->createCommand()
->update('{{participants}}',
$data,
'participant_id = :participant_id',
array(':participant_id'=>$data['participant_id']));
}
/*
* This function returns a list of participants who are either owned or shared
* with a specific user
*
* @params int $userid The ID of the user that we are listing participants for
*
* @return object containing all the users
*/
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');
$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();
}
function getParticipantsOwnerCount($userid)
{
return count(Yii::app()->db->createCommand()
->select('{{participants}}.*,{{participant_shares}}.can_edit')
->from('{{participants}}')
->leftJoin('{{participant_shares}}', '{{participants}}.participant_id={{participant_shares}}.participant_id')
->where('owner_uid = :userid1 OR share_uid = :userid2')
->bindParam(":userid1", $userid, PDO::PARAM_INT)
->bindParam(":userid2", $userid, PDO::PARAM_INT)
->queryAll());
}
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
*/
function getParticipantsSharedCount($userid)
{
return count(Yii::app()->db->createCommand()->select('{{participants}}.*, {{participant_shares}}.*')->from('{{participants}}')->join('{{participant_shares}}', '{{participant_shares}}.participant_id = {{participants}}.participant_id')->where('owner_uid = :userid')->bindParam(":userid", $userid, PDO::PARAM_INT)->queryAll());
}
function getParticipants($page, $limit,$attid)
{
$start = $limit * $page - $limit;
$selectValue = array();
$joinValue = array();
array_push($selectValue,"p.*");
array_push($selectValue,"luser.full_name as ownername");
array_push($joinValue,"left join {{users}} luser ON luser.uid=p.owner_uid");
foreach($attid as $key=>$attid)
{
$attid = $attid['attribute_id'];
array_push($selectValue,"attribute".$attid.".value as a".$attid);
array_push($joinValue,"LEFT JOIN {{participant_attribute}} attribute".$attid." ON attribute".$attid.".participant_id=p.participant_id AND attribute".$attid.".attribute_id=".$attid);
}
$data = Yii::app()->db->createCommand()
->select($selectValue)
->from('{{participants}} p')
->limit($limit, $start);
$data->setJoin($joinValue);
$allData = $data->queryAll();
return $allData;
}
function getSurveyCount($participant_id)
{
$count = count(Yii::app()->db->createCommand()->select('*')->from('{{survey_links}}')->where('participant_id = :participant_id')->bindParam(":participant_id", $participant_id, PDO::PARAM_INT)->queryAll());
return $count;
}
/*
* These functions delete the row marked in the navigator
* Parameters : row id's
* Return Data : None
*/
function deleteParticipant($rows)
{
/* 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. */
// Converting the comma seperated id's to an array to delete multiple rows
$rowid = explode(",", $rows);
foreach ($rowid as $row)
{
Yii::app()->db->createCommand()->delete(Participants::model()->tableName(), array('in', 'participant_id', $row));
Yii::app()->db->createCommand()->delete(Survey_links::model()->tableName(), array('in', 'participant_id', $row));
Yii::app()->db->createCommand()->delete(Participant_attribute::model()->tableName(), array('in', 'participant_id', $row));
}
}
function deleteParticipantToken($rows)
{
/* 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. */
$rowid = explode(",", $rows);
foreach ($rowid as $row)
{
$tokens = Yii::app()->db->createCommand()->select('*')->from('{{survey_links}}')->where('participant_id = :pid')->bindParam(":pid", $row, PDO::PARAM_INT)->queryAll();
foreach ($tokens as $key => $value)
{
$tokentable='{{tokens_'.intval($value['survey_id']).'}}';
if (Yii::app()->db->schema->getTable($tokentable))
{
Yii::app()->db->createCommand()
->delete('{{tokens_' . intval($value['survey_id']) . '}}', 'participant_id = :pid',array(':pid'=>$row)); // Deletes matching token table entries
//Yii::app()->db->createCommand()->delete(Tokens::model()->tableName(), array('in', 'participant_id', $row));
}
}
Yii::app()->db->createCommand()->delete(Participants::model()->tableName(), array('in', 'participant_id', $row));
Yii::app()->db->createCommand()->delete(Survey_links::model()->tableName(), array('in', 'participant_id', $row));
Yii::app()->db->createCommand()->delete(Participant_attribute::model()->tableName(), array('in', 'participant_id', $row));
}
}
function deleteParticipantTokenAnswer($rows)
{
/* 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. */
$rowid = explode(",", $rows);
foreach ($rowid as $row)
{
$tokens = Yii::app()->db->createCommand()
->select('*')
->from('{{survey_links}}')
->where('participant_id = :row')
->bindParam(":row", $row, PDO::PARAM_INT)
->queryAll();
foreach ($tokens as $key => $value)
{
$tokentable='{{tokens_'.intval($value['survey_id']).'}}';
if (Yii::app()->db->schema->getTable($tokentable))
{
$tokenid = Yii::app()->db->createCommand()
->select('token')
->from('{{tokens_' . intval($value['survey_id']) . '}}')
->where('participant_id = :pid')
->bindParam(":pid", $value['participant_id'], PDO::PARAM_INT)
->queryAll();
$token = $tokenid[0];
$surveytable='{{survey_'.intval($value['survey_id']).'}}';
if ($datas=Yii::app()->db->schema->getTable($surveytable))
{
if (!empty($token['token']) && isset($datas->columns['token'])) //Make sure we have a token value, and that tokens are used to link to the survey
{
$gettoken = Yii::app()->db->createCommand()
->select('*')
->from('{{survey_' . intval($value['survey_id']) . '}}')
->where('token = :token')
->bindParam(":token", $token['token'], PDO::PARAM_STR)
->queryAll();
$gettoken = $gettoken[0];
Yii::app()->db->createCommand()
->delete('{{survey_' . intval($value['survey_id']) . '}}', 'token = :token')
->bindParam(":token", $gettoken['token'], PDO::PARAM_STR); // Deletes matching responses from surveys
}
}
Yii::app()->db->createCommand()
->delete('{{tokens_' . intval($value['survey_id']) . '}}', 'participant_id = :pid' , array(':pid'=>$value['participant_id'])); // Deletes matching token table entries
}
}
Yii::app()->db->createCommand()->delete(Participants::model()->tableName(), array('in', 'participant_id', $row));
Yii::app()->db->createCommand()->delete(Survey_links::model()->tableName(), array('in', 'participant_id', $row));
Yii::app()->db->createCommand()->delete(Participant_attribute::model()->tableName(), array('in', 'participant_id', $row));
}
}
/*
* Builds a select query for searching through participants limited to searches with only one line (no more than 3 entries in condition array)
*
* Deprecated, use "getParticipantsSearchMultiple()" instead.
*
* */
function getParticipantsSearch($condition, $page, $limit)
{
$start = $limit * $page - $limit;
$command = new CDbCriteria;
$command->condition = '';
$lang = Yii::app()->session['adminlang'];
$start = $limit * $page - $limit;
if(is_numeric($condition[2])) $condition[2]=intval($condition[2]);
switch($condition[1])
{
case 'equal':
$operator="=";
break;
case 'contains':
$operator="LIKE";
$condition[2]="%".$condition[2]."%";
break;
case 'notequal':
$operator="!=";
break;
case 'notcontains':
$operator="NOT LIKE";
$condition[2]="%".$condition[2]."%";
break;
case 'greaterthan':
$operator=">";
break;
case 'lessthan':
$operator="<";
}
if($condition[0]=="survey")
{
$lang = Yii::app()->session['adminlang'];
$command->addCondition('participant_id IN (SELECT distinct {{survey_links}}.participant_id FROM {{survey_links}}, {{surveys_languagesettings}} WHERE {{survey_links}}.survey_id = {{surveys_languagesettings}}.surveyls_survey_id AND {{surveys_languagesettings}}.surveyls_language=:lang AND ({{surveys_languagesettings}}.surveyls_title '.$operator.' :param1 OR {{survey_links}}.survey_id '.$operator.' :param2))');
$command->params=array(':lang'=>$lang, ':param1'=>$condition[2] , ':param2'=>$condition[2]);
}
elseif($condition[0]=="owner_name")
{
$userid = Yii::app()->db->createCommand()
->select('uid')
->where('full_name '.$operator.' :condition_2')
->from('{{users}}')
->bindParam("condition_2", $condition[2], PDO::PARAM_STR)
->queryAll();
$uid = $userid[0];
$command->addCondition('owner_uid = :uid');
$command->params=array(':uid'=>$uid['uid']);
}
elseif (is_numeric($condition[0])) //Searching for an attribute
{
$command->addCondition('participant_id IN (SELECT distinct {{participant_attribute}}.participant_id FROM {{participant_attribute}} WHERE {{participant_attribute}}.attribute_id = :condition_0 AND {{participant_attribute}}.value '.$operator.' :condition_2)');
$command->params=array(':condition_0'=>$condition[0], ':condition_2'=>$condition[2]);
}
else
{
$command->addCondition($condition[0] . ' '.$operator.' :condition_2');
$command->params=array(':condition_2'=>$condition[2]);
}
if ($page == 0 && $limit == 0)
{
$arr = Participants::model()->findAll($command);
$data = array();
foreach ($arr as $t)
{
$data[$t->participant_id] = $t->attributes;
}
}
else
{
$command->limit = $limit;
$command->offset = $start;
$arr = Participants::model()->findAll($command);
$data = array();
foreach ($arr as $t)
{
$data[$t->participant_id] = $t->attributes;
}
}
return $data;
}
/*
* Function builds a select query for searches through participants using the $condition field passed
* which is in the format "firstfield||sqloperator||value||booleanoperator||secondfield||sqloperator||value||booleanoperator||etc||etc||etc"
* for example: "firstname||equal||Jason||and||lastname||equal||Cleeland" will produce SQL along the lines of "WHERE firstname = 'Jason' AND lastname=='Cleeland'"
*
* @param array $condition an array containing the search string exploded using || so that "firstname||equal||jason" is $condition(1=>'firstname', 2=>'equal', 3=>'jason')
* @param int $page Which page number to display
* @param in $limit The limit/number of reords to return
*
* @returns array $output
*
*
* */
function getParticipantsSearchMultiple($condition, $page, $limit)
{
//http://localhost/limesurvey_yii/admin/participants/getParticipantsResults_json/search/email||contains||gov||and||firstname||contains||AL
//First contains fieldname, second contains method, third contains value, fourth contains BOOLEAN SQL and, or
//As we iterate through the conditions we build up the $command query by adding conditions to it
//
$i = 0;
$tobedonelater = array();
$start = $limit * $page - $limit;
$command = new CDbCriteria;
$command->condition = '';
//The following code performs an IN-SQL order, but this only works for standard participant fields
//For the time being, lets stick to just sorting the collected results, some thinking
//needs to be done about how we can sort the actual fullo query when combining with calculated
//or attribute based fields. I've switched this off, but left the code for future reference. JC
if(1==2)
{
$sord = Yii::app()->request->getPost('sord'); //Sort order
$sidx = Yii::app()->request->getPost('sidx'); //Sort index
if(is_numeric($sidx) || $sidx=="survey") {
$sord=""; $sidx="";
}
if(!empty($sidx)) {
$sortorder="$sidx $sord";
} else {
$sortorder="";
}
if(!empty($sortorder))
{
$command->order=$sortorder;
}
}
$con = count($condition);
while ($i < $con)
{
if ($i < 3) //Special set just for the first query/condition
{
if(is_numeric($condition[2])) $condition[2]=intval($condition[2]);
switch($condition[1])
{
case 'equal':
$operator="=";
break;
case 'contains':
$operator="LIKE";
$condition[2]="%".$condition[2]."%";
break;
case 'beginswith':
$operator="LIKE";
$condition[2]=$condition[2]."%";
break;
case 'notequal':
$operator="!=";
break;
case 'notcontains':
$operator="NOT LIKE";
$condition[2]="%".$condition[2]."%";
break;
case 'greaterthan':
$operator=">";
break;
case 'lessthan':
$operator="<";
}
if($condition[0]=="survey")
{
$lang = Yii::app()->session['adminlang'];
$command->addCondition('participant_id IN (SELECT distinct {{survey_links}}.participant_id FROM {{survey_links}}, {{surveys_languagesettings}} WHERE {{survey_links}}.survey_id = {{surveys_languagesettings}}.surveyls_survey_id AND {{surveys_languagesettings}}.surveyls_language=:lang AND {{survey_links}}.survey_id '.$operator.' :param)');
$command->params=array(':lang'=>$lang, ':param'=>$condition[2]);
}
elseif($condition[0]=="surveys") //Search by quantity of linked surveys
{
$addon = ($operator == "<") ? " OR participant_id NOT IN (SELECT distinct participant_id FROM {{survey_links}})" : "";
$command->addCondition('participant_id IN (SELECT participant_id FROM {{survey_links}} GROUP BY participant_id HAVING count(*) '.$operator.' :param2 ORDER BY count(*))'.$addon);
$command->params=array(':param2'=>$condition[2]);
}
elseif($condition[0]=="owner_name")
{
$userid = Yii::app()->db->createCommand()
->select('uid')
->where('full_name '.$operator.' :condition_2')
->from('{{users}}')
->bindParam("condition_2", $condition[2], PDO::PARAM_STR)
->queryAll();
$uid = $userid[0];
$command->addCondition('owner_uid = :uid');
$command->params=array(':uid'=>$uid['uid']);
}
elseif (is_numeric($condition[0])) //Searching for an attribute
{
$command->addCondition('participant_id IN (SELECT distinct {{participant_attribute}}.participant_id FROM {{participant_attribute}} WHERE {{participant_attribute}}.attribute_id = :condition_0 AND {{participant_attribute}}.value '.$operator.' :condition_2)');
$command->params=array(':condition_0'=>$condition[0], ':condition_2'=>$condition[2]);
}
else
{
$command->addCondition($condition[0] . ' '.$operator.' :condition_2');
$command->params=array(':condition_2'=>$condition[2]);
}
$i+=3;
}
else if ($condition[$i] != '') //This section deals with subsequent filter conditions that have boolean joiner
{
if(is_numeric($condition[$i+3])) $condition[$i+3]=intval($condition[$i+3]); //Force the type of numeric values to be numeric
$booloperator=strtoupper($condition[$i]);
$condition1name=":condition_".($i+1);
$condition2name=":condition_".($i+3);
switch($condition[$i+2])
{
case 'equal':
$operator="=";
break;
case 'contains':
$operator="LIKE";
$condition[$i+3]="%".$condition[$i+3]."%";
break;
case 'beginswith':
$operator="LIKE";
$condition[$i+3]=$condition[$i+3]."%";
break;
case 'notequal':
$operator="!=";
break;
case 'notcontains':
$operator="NOT LIKE";
$condition[$i+3]="%".$condition[$i+3]."%";
break;
case 'greaterthan':
$operator=">";
break;
case 'lessthan':
$operator="<";
}
if($condition[$i+1]=="survey")
{
$lang = Yii::app()->session['adminlang'];
$command->addCondition('participant_id IN (SELECT distinct {{survey_links}}.participant_id FROM {{survey_links}}, {{surveys_languagesettings}} WHERE {{survey_links}}.survey_id = {{surveys_languagesettings}}.surveyls_survey_id AND {{surveys_languagesettings}}.surveyls_language=:lang AND ({{surveys_languagesettings}}.surveyls_title '.$operator.' '.$condition2name.'1 OR {{survey_links}}.survey_id '.$operator.' '.$condition2name.'2))', $booloperator);
$command->params=array_merge($command->params, array(':lang'=>$lang, $condition2name.'1'=>$condition[$i+3], $condition2name.'2'=>$condition[$i+3]));
} elseif ($condition[$i+1]=="surveys") //search by quantity of linked surveys
{
$addon = ($operator == "<") ? " OR participant_id NOT IN (SELECT distinct participant_id FROM {{survey_links}})" : "";
$command->addCondition('participant_id IN (SELECT participant_id FROM {{survey_links}} GROUP BY participant_id HAVING count(*) '.$operator.' '.$condition2name.' ORDER BY count(*))'.$addon);
$command->params=array_merge($command->params, array($condition2name=>$condition[$i+3]));
}
elseif($condition[$i+1]=="owner_name")
{
$userid = Yii::app()->db->createCommand()
->select('uid')
->where('full_name '.$operator.' '.$condition2name)
->from('{{users}}')
->bindParam($condition2name, $condition[$i+3], PDO::PARAM_STR)
->queryAll();
$uid=array();
foreach($userid as $row) {$uid[]=$row['uid'];}
$command->addInCondition('owner_uid', $uid, $booloperator);
}
elseif (is_numeric($condition[$i+1])) //Searching for an attribute
{
$command->addCondition('participant_id IN (SELECT distinct {{participant_attribute}}.participant_id FROM {{participant_attribute}} WHERE {{participant_attribute}}.attribute_id = '.$condition1name.' AND {{participant_attribute}}.value '.$operator.' '.$condition2name.')', $booloperator);
$command->params=array_merge($command->params, array($condition1name=>$condition[$i+1], $condition2name=>$condition[$i+3]));
}
else
{
$command->addCondition($condition[$i+1] . ' '.$operator.' '.$condition2name, $booloperator);
$command->params=array_merge($command->params, array($condition2name=>$condition[$i+3]));
}
$i = $i + 4;
}
else
{
$i = $i + 4;
}
}
if ($page == 0 && $limit == 0)
{
$arr = Participants::model()->findAll($command);
$data = array();
foreach ($arr as $t)
{
$data[$t->participant_id] = $t->attributes;
}
}
else
{
$command->limit = $limit;
$command->offset = $start;
$arr = Participants::model()->findAll($command);
$data = array();
foreach ($arr as $t)
{
$data[$t->participant_id] = $t->attributes;
}
}
return $data;
}
/**
* Returns true if participant_id has ownership or shared rights over this participant false if not
*
* @param mixed $participant_id
* @returns bool true/false
*/
function is_owner($participant_id)
{
$userid = Yii::app()->session['loginID'];
$is_owner = Yii::app()->db->createCommand()->select('participant_id')->where('participant_id = :participant_id AND owner_uid = :userid')->from('{{participants}}')->bindParam(":participant_id", $participant_id, PDO::PARAM_STR)->bindParam(":userid", $userid, PDO::PARAM_INT)->queryAll();
$is_shared = Yii::app()->db->createCommand()->select('participant_id')->where('participant_id = :participant_id AND share_uid = :userid')->from('{{participant_shares}}')->bindParam(":participant_id", $participant_id, PDO::PARAM_STR)->bindParam(":userid", $userid, PDO::PARAM_INT)->queryAll();
if (count($is_shared) || count($is_owner))
{
return true;
}
else
{
return false;
}
}
/*
* This funciton is responsible for showing all the participant's shared by a particular user based on the user id
*/
function getParticipantShared($userid)
{
return Yii::app()->db->createCommand()->select('{{participants}}.*, {{participant_shares}}.*')->from('{{participants}}')->join('{{participant_shares}}', '{{participant_shares}}.participant_id = {{participants}}.participant_id')->where('owner_uid = :userid')->bindParam(":userid", $userid, PDO::PARAM_INT)->queryAll();
}
/*
* This funciton is responsible for showing all the participant's shared to the superadmin
*/
function getParticipantSharedAll()
{
return Yii::app()->db->createCommand()->select('{{participants}}.*,{{participant_shares}}.*')->from('{{participants}}')->join('{{participant_shares}}', '{{participant_shares}}.participant_id = {{participants}}.participant_id')->queryAll();
}
/*
* Copies central attributes/participants to an individual survey token table
*
* @param int $surveyid The survey id
* @param array $mapped An array containing a list of already existing/mapped attributes in the form of "token_field_name"=>"participant_attribute_id"
* @param array $newcreate An array containing new attributes to create in the tokens table
* @param string $participantid A comma seperated string containing the participant ids of the participants we are adding
* @param bool $overwriteauto If true, overwrite automatically mapped data
* @param bool $overwriteman If true, overwrite manually mapped data
* @param bool $overwritest If true, overwrite standard fields (ie: names, email, participant_id, token)
* @param bool $createautomap If true, rename the fieldnames of automapped attributes so that in future they are automatically mapped
* */
function copytosurveyatt($surveyid, $mapped, $newcreate, $participantid, $overwriteauto=false, $overwriteman=false, $overwritest=false, $createautomap=true)
{
Yii::app()->loadHelper('common');
$duplicate = 0;
$sucessfull = 0;
$participantid = explode(",", $participantid); //List of participant ids to add to tokens table
if ($participantid[0] == "") { $participantid = array_slice($participantid, 1); }
$number2add = sanitize_int(count($newcreate)); //Number of tokens being created
$tokenattributefieldnames=array(); //Will contain descriptions of existing token attribute fields
$tokenfieldnames=array(); //Will contain the actual field names of existing token attribute fields
$attributesadded = array(); //Will contain the actual field name of any new token attribute fields
$attributeidadded = array(); //Will contain the description of any new token attribute fields
$fieldcontents = array(); //Will contain serialised info for the surveys.attributedescriptions field
$surveyinfo=getSurveyInfo($surveyid);
$defaultsurveylang=$surveyinfo['surveyls_language'];
$arr = Yii::app()->db
->createCommand()
->select('*')
->from("{{tokens_$surveyid}}")
->queryRow();
if (is_array($arr))
{
$tokenfieldnames = array_keys($arr);
$tokenattributefieldnames = array_filter($tokenfieldnames, 'filterForAttributes');
}
/* Rename an existing attribute in the token table to this attribute so
* it maps automatically in future.
*
* Fieldname renamed from the $key of $mappeed to the $val of $mapped
* */
if($createautomap=="true") {
foreach($mapped as $key=>$val) {
if(is_numeric($val)) {
$newname = 'attribute_cpdb_' . intval($val);
//Rename the field in the tokens_[sid] table
Yii::app()->db
->createCommand()
->renameColumn('{{tokens_' . intval($surveyid) . '}}', $key, $newname);
//Make the field a TEXT field
Yii::app()->db
->createCommand()
->alterColumn('{{tokens_' . intval($surveyid) . '}}', $newname, 'TEXT');
/* Update the attributedescriptions info */
$previousatt = Yii::app()->db
->createCommand()
->select('attributedescriptions')
->from('{{surveys}}')
->where("sid = ".$surveyid);
$patt=$previousatt->queryRow();
$previousattribute = unserialize($patt['attributedescriptions']);
$previousattribute[$newname]=$previousattribute[$key];
unset($previousattribute[$key]);
//Rename the token field the name of the participant_attribute
$attributedetails=ParticipantAttributeNames::getAttributeNames($val);
$previousattribute[$newname]['description']=$attributedetails[0]['attribute_name'];
$previousattribute=serialize($previousattribute);
Yii::app()->db
->createCommand()
->update('{{surveys}}',
array("attributedescriptions" => $previousattribute),
'sid = '.$surveyid); //load description in the surveys table
//Finally, update the $mapped key/val pair to reflect the new keyname of $newname
$mapped[$newname]=$mapped[$key];
unset($mapped[$key]);
}
}
}
foreach ($tokenattributefieldnames as $key => $value)
{
if ($value[10] == 'c') /* Existence of 'c' as 11th letter assume it is a CPDB link */
{
$attid = substr($value, 15);
$mapped[$value] = $attid;
} elseif (is_numeric($value[10]))
{
$mapped[$key]=$value;
}
}
if (!empty($newcreate)) //Create new fields in the tokens table
{
foreach ($newcreate as $key => $value)
{
$newfieldname='attribute_cpdb_'.$value;
$fields[$newfieldname] = array('type' => 'VARCHAR', 'constraint' => '255');
$attname = Yii::app()->db
->createCommand()
->select('{{participant_attribute_names_lang}}.attribute_name, {{participant_attribute_names_lang}}.lang')
->from('{{participant_attribute_names}}')
->join('{{participant_attribute_names_lang}}', '{{participant_attribute_names}}.attribute_id = {{participant_attribute_names_lang}}.attribute_id')
->where('{{participant_attribute_names}}.attribute_id = :attrid ')
->bindParam(":attrid", $value, PDO::PARAM_INT);
$attributename = $attname->queryAll();
foreach($attributename as $att) {
$languages[$att['lang']]=$att['attribute_name'];
}
//Check first for the default survey language
if(isset($languages[$defaultsurveylang])) {
$newname=$languages[$defaultsurveylang];
} elseif (isset($language[Yii::app()->session['adminlang']])) {
$newname=$languages[Yii::app()->session['adminlang']];
} else {
$newname=$attributename[0]['attribute_name']; //Choose the first item in the list
}
$tokenattributefieldnames[] = $newfieldname;
$fieldcontents[$newfieldname]=array("description"=>$newname,
"mandatory"=>"N",
"show_register"=>"N");
array_push($attributeidadded, 'attribute_cpdb_' . $value);
array_push($attributesadded, $value);
}
//Update the attributedescriptions in the survey table to include the newly created attributes
$previousatt = Yii::app()->db
->createCommand()
->select('attributedescriptions')
->where("sid = :sid")
->from('{{surveys}}')
->bindParam(":sid", $surveyid, PDO::PARAM_INT);
$previousattribute = $previousatt->queryRow();
$previousattribute = unserialize($previousattribute['attributedescriptions']);
foreach($fieldcontents as $key=>$val) {
$previousattribute[$key]=$val;
}
$previousattribute = serialize($previousattribute);
Yii::app()->db
->createCommand()
->update('{{surveys}}',
array("attributedescriptions" => $previousattribute), 'sid = '.intval($surveyid)); // load description in the surveys table
//Actually create the fields in the tokens table
foreach ($fields as $key => $value)
{
Yii::app()->db
->createCommand("ALTER TABLE {{tokens_$surveyid}} ADD COLUMN ". Yii::app()->db->quoteColumnName($key) ." ". $value['type'] ." ( ".intval($value['constraint'])." )")
->query(); // add columns in token's table
}
}
//Write each participant to the survey token table
foreach ($participantid as $key => $participant)
{
$writearray = array();
$participantdata = Yii::app()->db->createCommand()->select('firstname,lastname,email,language,blacklisted')->where('participant_id = :pid')->from('{{participants}}')->bindParam(":pid", $participant, PDO::PARAM_INT);
$tobeinserted = $participantdata->queryRow();
/* Search for matching participant name/email in the survey token table */
$query = Yii::app()->db->createCommand()->select('*')->from('{{tokens_' . $surveyid . '}}')
->where('firstname = :firstname AND lastname = :lastname AND email = :email')
->bindParam(":firstname", $tobeinserted['firstname'], PDO::PARAM_STR)->bindParam(":lastname", $tobeinserted['lastname'], PDO::PARAM_STR)->bindParam(":email", $tobeinserted['email'], PDO::PARAM_STR)->queryAll();
if (count($query) > 0)
{
//Participant already exists in token table - don't copy
$duplicate++;
// Here is where we can put code for overwriting the attribute data if so required
if($overwriteauto=="true") {
//If there are new attributes created, add those values to the token entry for this participant
if (!empty($newcreate))
{
$numberofattributes = count($attributesadded);
for ($a = 0; $a < $numberofattributes; $a++)
{
Participants::updateTokenAttributeValue($surveyid, $participant,$attributesadded[$a],$attributeidadded[$a]);
}
}
//If there are automapped attributes, add those values to the token entry for this participant
if (!empty($mapped))
{
foreach ($mapped as $key => $value)
{
if ($key[10] == 'c') { //We know it's automapped because the 11th letter is 'c'
Participants::updateTokenAttributeValue($surveyid, $participant, $value, $key);
}
}
}
}
if($overwriteman=="true") {
//If there are any manually mapped attributes, add those values to the token entry for this participant
if (!empty($mapped))
{
foreach ($mapped as $key => $value)
{
if ($key[10] != 'c' && $key[9]=='_') { //It's not an auto field because it's 11th character isn't 'c'
Participants::updateTokenAttributeValue($surveyid, $participant, $value, $key);
}
}
}
}
if($overwritest=="true") {
if(!empty($mapped))
{
foreach($mapped as $key=>$value)
{
if((strlen($key) > 8 && $key[10] != 'c' && $key[9] !='_') || strlen($key) < 9) {
Participants::updateTokenAttributeValue($surveyid, $participant, $value, $key);
}
}
}
}
}
else
{
//Create a new token entry for this participant
$writearray = array('participant_id' => $participant,
'firstname' => $tobeinserted['firstname'],
'lastname' => $tobeinserted['lastname'],
'email' => $tobeinserted['email'],
'emailstatus' => 'OK',
'language' => $tobeinserted['language']);
Yii::app()->db
->createCommand()
->insert('{{tokens_' . $surveyid . '}}', $writearray);
$insertedtokenid = getLastInsertID('{{tokens_' . $surveyid . '}}');
$time = time();
//Create a survey link for the new token entry
$data = array(
'participant_id' => $participant,
'token_id' => $insertedtokenid,
'survey_id' => $surveyid,
'date_created' => date('Y-m-d H:i:s', $time));
Yii::app()->db->createCommand()->insert('{{survey_links}}', $data);
//If there are new attributes created, add those values to the token entry for this participant
if (!empty($newcreate))
{
$numberofattributes = count($attributesadded);
for ($a = 0; $a < $numberofattributes; $a++)
{
Participants::updateTokenAttributeValue($surveyid, $participant,$attributesadded[$a],$attributeidadded[$a]);
}
}
//If there are any automatically mapped attributes, add those values to the token entry for this participant
if (!empty($mapped))
{
foreach ($mapped as $key => $value)
{
Participants::updateTokenAttributeValue($surveyid, $participant, $value, $key);
}
}
$sucessfull++;
}
}
$returndata = array('success' => $sucessfull, 'duplicate' => $duplicate, 'overwriteauto'=>$overwriteauto, 'overwriteman'=>$overwriteman);
return $returndata;
}
/*
* Updates a field in the token table with a value from the participant attributes table
*
* @param int $surveyId Survey ID number
* @param int $participantId unique key for the participant
* @param int $participantAttributeId the unique key for the participant_attribute table
* @param int $tokenFieldName fieldname in the token table
*
* @return bool true/false
* */
function updateTokenAttributeValue($surveyId, $participantId, $participantAttributeId, $tokenFieldname) {
//Get the value from the participant_attribute field
$val = Yii::app()->db
->createCommand()
->select('value')
->where('participant_id = :participant_id AND attribute_id = :attrid')
->from('{{participant_attribute}}')
->bindParam("participant_id", $participantId, PDO::PARAM_STR)
->bindParam("attrid", $participantAttributeId, PDO::PARAM_INT);
$value = $val->queryRow();
//Update the token entry with those values
if (isset($value['value']))
{
$data = array($tokenFieldname => $value['value']);
Yii::app()->db
->createCommand()
->update("{{tokens_$surveyId}}", $data, "participant_id = '$participantId'");
}
return true;
}
/*
* Updates or creates a field in the token table with a value from the participant attributes table
*
* @param int $surveyId Survey ID number
* @param int $participantId unique key for the participant
* @param int $participantAttributeId the unique key for the participant_attribute table
* @param int $tokenFieldName fieldname in the token table
*
* @return bool true/false
* */
function updateAttributeValueToken($surveyId, $participantId, $participantAttributeId, $tokenFieldname) {
$val = Yii::app()->db
->createCommand()
->select($tokenFieldname)