/
LimesurveyApi.php
570 lines (522 loc) · 18.7 KB
/
LimesurveyApi.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
<?php
namespace LimeSurvey\PluginManager;
use Yii;
use User;
use PluginDynamic;
use SurveyDynamic;
use Template;
/**
* Class exposing a Limesurvey API to plugins.
* This class is instantiated by the plugin manager,
* plugins can obtain it by calling getAPI() on the plugin manager.
*/
class LimesurveyApi
{
/**
* Read a key from the application config, and when not set
* return the default value
*
* @param string $key The key to search for in the application config
* @param mixed $defaultValue Value to return when not found, default is false
* @return string
*/
public function getConfigKey($key, $defaultValue = false)
{
return App()->getConfig($key, $defaultValue);
}
/**
* Generates the real table name from plugin and tablename.
* @param iPlugin $plugin
* @param string $tableName
*/
protected function getTableName(iPlugin $plugin, $tableName)
{
return App()->getDb()->tablePrefix.strtolower($plugin->getName())."_$tableName";
}
/**
* Sets a flash message to be shown to the user.
* @param html $message
*/
public function setFlash($message, $key = 'api')
{
// @todo Remove direct session usage.
\Yii::app()->user->setFlash($key, $message);
}
/**
* Builds and executes a SQL statement for creating a new DB table.
* @param \QuickMenu $plugin The plugin object, id or name.
* @param string $sTableName the name of the table to be created. The name will be properly quoted and prefixed by the method.
* @param array $aColumns the columns (name=>definition) in the new table.
* @param string $sOptions additional SQL fragment that will be appended to the generated SQL.
* @return integer number of rows affected by the execution.
*/
public function createTable($plugin, $sTableName, $aColumns, $sOptions = null)
{
if (null !== $sTableName = $this->getTableName($plugin, $sTableName)) {
return App()->getDb()->createCommand()->createTable($sTableName, $aColumns, $sOptions);
}
return false;
}
/**
* Builds and executes a SQL statement for dropping a DB table.
* @param mixed $plugin The plugin object, id or name.
* @param string $sTableName the name of the table to be created. The name will be properly quoted and prefixed by the method.
*/
public function dropTable($plugin, $sTableName)
{
if (null !== $sTableName = $this->getTableName($plugin, $sTableName)) {
return App()->getDb()->createCommand()->dropTable($sTableName);
}
return false;
}
public function createUrl($route, array $params)
{
return App()->createAbsoluteUrl($route, $params);
}
/**
* Gets an activerecord object associated to the table.
* @param iPlugin $plugin
* @param string $sTableName Name of the table.
* @param string $bPluginTable True if the table is plugin specific.
* @return \Plugin|null
*/
public function getTable(iPlugin $plugin, $sTableName, $bPluginTable = true)
{
if ($bPluginTable) {
$table = $this->getTableName($plugin, $sTableName);
} else {
$table = $sTableName;
}
if (isset($table)) {
return \PluginDynamic::model($table);
}
}
/**
* @see http://www.yiiframework.com/doc/api/1.1/CWebUser#checkAccess-detail
* @param string $operation
* @param array $params
* @param boolean $allowCaching
* @return boolean
*/
public function checkAccess($operation, $params = array(), $allowCaching = true)
{
return App()->user->checkAccess($operation, $params, $allowCaching);
}
/**
* Creates a new active record object instance.
* @param iPlugin $plugin
* @param string $sTableName
* @param string $scenario
* @param string $bPluginTable True if the table is plugin specific.
* @return PluginDynamic
*/
public function newModel(iPlugin $plugin, $sTableName, $scenario = 'insert', $bPluginTable = true)
{
if ($bPluginTable) {
$table = $this->getTableName($plugin, $sTableName);
} else {
$table = $sTableName;
}
if (isset($table)) {
return new \PluginDynamic($table, $scenario);
}
}
public function removeResponse($surveyId, $responseId)
{
return \Response::model($surveyId)->deleteByPk($responseId);
}
/**
* Check if a table does exist in the database
* @param iPlugin $plugin
* @param string $sTableName Table name to check for (without dbprefix!))
* @return boolean True or false if table exists or not
*/
public function tableExists(iPlugin $plugin, $sTableName)
{
$sTableName = $this->getTableName($plugin, $sTableName);
return isset($sTableName) && in_array($sTableName, App()->getDb()->getSchema()->getTableNames());
}
/**
* Evaluates an expression via Expression Manager
* Uses the current context.
* @param string $expression
* @return string
*/
public function EMevaluateExpression($expression)
{
$result = \LimeExpressionManager::ProcessString($expression);
return $result;
}
/**
* Get the current request object
*
* @return \LSHttpRequest
*/
public function getRequest()
{
return App()->getRequest();
}
/**
* Returns an array of all available template names - does a basic check if the template might be valid
* @return array
*/
public function getTemplateList()
{
return Template::getTemplateList();
}
/**
* Gets a survey response from the database.
*
* @param int $surveyId
* @param int $responseId
* @param bool $bMapQuestionCodes
* @return array
*/
public function getResponse($surveyId, $responseId, $bMapQuestionCodes = true)
{
$survey = \Survey::model()->findByPk($surveyId);
$response = \SurveyDynamic::model($surveyId)->findByPk($responseId);
if (!$bMapQuestionCodes) {
return $response;
}
if (isset($response)) {
// Now map the response to the question codes if possible, duplicate question codes will result in the
// old sidXgidXqid code for the second time the code is found
$fieldmap = createFieldMap($survey, 'full', null, false, $response->attributes['startlanguage']);
$output = array();
foreach ($response->attributes as $key => $value) {
$newKey = $key;
if (array_key_exists($key, $fieldmap)) {
if (array_key_exists('title', $fieldmap[$key])) {
$code = $fieldmap[$key]['title'];
// Add subquestion code if needed
if (array_key_exists('aid', $fieldmap[$key]) && isset($fieldmap[$key]['aid']) && $fieldmap[$key]['aid'] != '') {
$code .= '_'.$fieldmap[$key]['aid'];
}
// Only add if the code does not exist yet and is not empty
if (!empty($code) && !array_key_exists($code, $output)) {
$newKey = $code;
}
}
}
$output[$newKey] = $value;
}
// And return the mapped response, to further enhance we could add a method to the api that provides a
// simple sort of fieldmap that returns qcode index array with group, question, subquestion,
// possible answers, maybe even combined with relevance info so a plugin can handle display of the response
return $output;
}
}
public function getResponses($surveyId, $attributes = array(), $condition = '', $params = array())
{
return \Response::model($surveyId)->findAllByAttributes($attributes, $condition, $params);
}
public function getToken($surveyId, $token)
{
return \Token::model($surveyId)->findByAttributes(array('token' => $token));
}
/**
* Return a token object from a token id and a survey id
*
* @param integer $iSurveyId
* @param integer $iTokenId
* @return \Token Token
*/
public function getTokenById($iSurveyId, $iTokenId)
{
return \Token::model($iSurveyId)->findByAttributes(array('tid' => $iTokenId));
}
/**
* Gets a key value list using the group name as value and the group id
* as key.
* @param boolean $surveyId
* @return type
*/
public function getGroupList($surveyId)
{
$result = \QuestionGroup::model()->findListByAttributes(array('sid' => $surveyId), 'group_name');
return $result;
}
/**
* Retrieves user details for the currently logged in user
* Returns false if the user is not logged and returns null if the user does not exist anymore for some reason (should not really happen)
* @return User
*/
public function getCurrentUser()
{
if (\Yii::app()->user->id) {
return \User::model()->findByPk(\Yii::app()->user->id);
}
return false;
}
/**
* Gets the table name for responses for the specified survey id.
* @param int $surveyId
* @return string
*/
public function getResponseTable($surveyId)
{
return App()->getDb()->tablePrefix.'survey_'.$surveyId;
}
/**
* Gets an array of old response table names for a survey.
* @param int $surveyId
* @return string[]
*/
public function getOldResponseTables($surveyId)
{
$tables = array();
$base = App()->getDb()->tablePrefix.'old_survey_'.$surveyId;
$timingbase = App()->getDb()->tablePrefix.'old_survey_'.$surveyId.'_timings_';
foreach (App()->getDb()->getSchema()->getTableNames() as $table) {
if (strpos($table, $base) === 0 && strpos($table, $timingbase) === false) {
$tables[] = $table;
}
}
return $tables;
}
/**
* Retrieves user details for a user
* Returns null if the user does not exist anymore for some reason (should not really happen)
*
* @param int $iUserID The userid
* @return User
*/
public function getUser($iUserID)
{
return \User::model()->findByPk($iUserID);
}
/**
* Get the user object for a given username
*
* @param string $username
* @return User|null Returns the user, or null when not found
*/
public function getUserByName($username)
{
$user = \User::model()->findByAttributes(array('users_name' => $username));
return $user;
}
/**
* Get the user object for a given email
*
* @param string|null $email
* @return User|null Returns the user, or null when not found
*/
public function getUserByEmail($email)
{
$user = \User::model()->findByAttributes(array('email' => $email));
return $user;
}
/**
* Retrieves user permission details for a user
* @param $iUserID int The User ID
* @param $iSurveyID int The related survey IF for survey permissions - if 0 then global permissions will be retrieved
* Returns null if the user does not exist anymore for some reason (should not really happen)
* @return User
*/
public function getPermissionSet($iUserID, $iEntityID = null, $sEntityName = null)
{
return \Permission::model()->getPermissions($iUserID, $iEntityID, $sEntityName);
}
/**
* Retrieves Participant data
* @param $iParticipantID int The Participant ID
* Returns null if the user does not exist anymore for some reason (should not really happen)
* @return \Participant
*/
public function getParticipant($iParticipantID)
{
return \Participant::model()->findByPk($iParticipantID);
}
public function getQuestions($surveyId, $language = 'en', $conditions = array())
{
$conditions['sid'] = $surveyId;
$conditions['language'] = $language;
return \Question::model()->with('subquestions')->findAllByAttributes($conditions);
}
/**
* Gets the metadata for a table.
* For details on the object check: http://www.yiiframework.com/doc/api/1.1/CDbTableSchema
* @param string $table Table name.
* @param boolean $forceRefresh False if cached information is acceptable; setting this to true could affect performance.
* @return \CDbTableSchema Table schema object, NULL if the table does not exist.
*/
public function getTableSchema($table, $forceRefresh = false)
{
return App()->getDb()->getSchema()->getTable($table);
}
/**
* Returns true if a plugin exists with name $name (active or not)
*
* @param string $name Name of plugin
* @return boolean
* @throws InvalidArgumentException if $name is not a string
*/
public function pluginExists($name)
{
if (!is_string($name)) {
throw new InvalidArgumentException('$name must be a string');
}
$plugin = \Plugin::model()->findByAttributes(array('name' => $name));
return !empty($plugin);
}
/**
* Returns true if plugin with name $name is active; otherwise false
*
* @param string $name Name of plugin
* @return boolean
* @throws InvalidArgumentException if $name is not a string
* @throws Exception if no plugin with name $name is found
*/
public function pluginIsActive($name)
{
if (!is_string($name)) {
throw new InvalidArgumentException('$name must be a string');
}
$plugin = \Plugin::model()->findByAttributes(array('name' => $name));
if ($plugin) {
return $plugin->active == 1;
} else {
throw new Exception("Can't find a plugin with name ".$name);
}
}
/**
* @param string $file
* @param array $data
* @return string
*/
public function renderTwig($file, array $data)
{
return Yii::app()->twigRenderer->renderViewFromFile(
$file,
$data,
// Don't echo.
true,
// Don't append application dir.
false
);
}
/**
* Returns an array of all user groups
*
* @return array
*/
public function getUserGroups()
{
return \UserGroup::model()->findAllAsArray();
}
/**
* Returns a UserGroup object by ugid
* Returns null if the object does not exist
*
* @param int $ugid The user group ID
* @return \UserGroup|null
*/
public function getUserGroup($ugid)
{
return \UserGroup::model()->findByAttributes(array('ugid' => $ugid));
}
/**
* Returns a UserInGroup object
* Returns null if the object does not exist
*
* @param integer $ugid The user group ID
* @param integer $uid The user ID
* @return \UserInGroup|null
*/
public function getUserInGroup($ugid, $uid)
{
return \UserInGroup::model()->findByPk(array('ugid' => $ugid, 'uid' => $uid));
}
/**
* Adds a new user group
*
* @param string $groupName Name of user group to be created
* @param string $groupDescription Description of user group to be created
* @return boolean True or false if user group was added or not
* @throws InvalidArgumentException if user group name was not supplied
*/
public function addUserGroup($groupName, $groupDescription)
{
$db_group_name = flattenText($groupName, false, true, 'UTF-8', true);
$db_group_description = flattenText($groupDescription);
if (isset($db_group_name) && strlen($db_group_name) > 0) {
$newUserGroup = new \UserGroup();
$newUserGroup->owner_id = 1;
$newUserGroup->name = $db_group_name;
$newUserGroup->description = $db_group_description;
if ($newUserGroup->save()) {
\UserInGroup::model()->insertRecords(array('ugid' => $newUserGroup->getPrimaryKey(), 'uid' => 1));
return true;
}
else {
return false;
}
} else {
throw new InvalidArgumentException('must provide a user group name');
}
}
/**
* Adds a user to a user group
*
* @param integer $ugid The user group ID
* @param integer $uid The user ID
* @return boolean True if user was added to group or false if not
* @throws InvalidArgumentException if user or group does not exist or group owner was supplied
*/
public function addUserInGroup($ugid, $uid)
{
$group = $this->getUserGroup($ugid);
if (empty($group)) {
throw new InvalidArgumentException('group does not exist');
} else {
$user = $this->getUser($uid);
if ($uid > 0 && $user) {
if ($group->owner_id == $uid) {
throw new InvalidArgumentException('user must not be group owner');
} else {
$user_in_group = $this->getUserInGroup($ugid, $uid);
if (empty($user_in_group) && \UserInGroup::model()->insertRecords(array('ugid' => $ugid, 'uid' => $uid))) {
return true;
} else {
return false;
}
}
} else {
throw new InvalidArgumentException('user does not exist');
}
}
}
/**
* Removes a user from a user group
*
* @param integer $ugid The user group ID
* @param integer $uid The user ID
* @return boolean True if user was removed to group or false if not
* @throws InvalidArgumentException if user or group does not exist or group owner was supplied
*/
public function removeUserInGroup($ugid, $uid)
{
$group = $this->getUserGroup($ugid);
if (empty($group)) {
throw new InvalidArgumentException('group does not exist');
} else {
$user = $this->getUser($uid);
if ($uid > 0 && $user) {
if ($group->owner_id == $uid) {
throw new InvalidArgumentException('user must no be group owner');
} else {
$user_in_group = $this->getUserInGroup($ugid, $uid);
if (!empty($user_in_group) && \UserInGroup::model()->deleteByPk(array('ugid' => $ugid, 'uid' => $uid))) {
return true;
} else {
return false;
}
}
} else {
throw new InvalidArgumentException('user does not exist');
}
}
}
}