-
Notifications
You must be signed in to change notification settings - Fork 988
/
remotecontrol.php
629 lines (558 loc) · 21.7 KB
/
remotecontrol.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
<?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.
*
*/
class remotecontrol extends Survey_Common_Action
{
/**
* @var Zend_XmlRpc_Server
*/
protected $xmlrpc;
/**
* This is the XML-RPC server routine
*
* @access public
* @return void
*/
public function run()
{
$RPCType=Yii::app()->getConfig("RPCInterface");
if ($RPCType=='xml')
{
$cur_path = get_include_path();
set_include_path($cur_path . PATH_SEPARATOR . APPPATH . 'helpers');
// Yii::import was causing problems for some odd reason
require_once('Zend/XmlRpc/Server.php');
require_once('Zend/XmlRpc/Server/Exception.php');
require_once('Zend/XmlRpc/Value/Exception.php');
$this->xmlrpc = new Zend_XmlRpc_Server();
$this->xmlrpc->sendArgumentsToAllMethods(false);
$this->xmlrpc->setClass('remotecontrol_handle', '', $this->controller);
echo $this->xmlrpc->handle();
}
elseif($RPCType=='json')
{
Yii::app()->loadLibrary('jsonRPCServer');
$oHandler=new remotecontrol_handle($this->controller);
jsonRPCServer::handle($oHandler);
}
exit;
}
/**
* Simple procedure to test most RPC functions
*
*/
public function test()
{
$sFileToImport=dirname(Yii::app()->basePath).DIRECTORY_SEPARATOR.'docs'.DIRECTORY_SEPARATOR.'demosurveys'.DIRECTORY_SEPARATOR.'limesurvey2_sample_survey_english.lss';
// $sFileToImport=dirname(Yii::app()->basePath).DIRECTORY_SEPARATOR.'docs'.DIRECTORY_SEPARATOR.'demosurveys'.DIRECTORY_SEPARATOR.'survey_archive_example_feedback_survey.zip';
Yii::app()->loadLibrary('jsonRPCClient');
$myJSONRPCClient = new jsonRPCClient(Yii::app()->getBaseUrl(true).'/'.dirname(Yii::app()->request->getPathInfo()));
$sSessionKey= $myJSONRPCClient->get_session_key('admin','password');
if (is_array($sSessionKey)) {echo $sSessionKey['status']; die();}
else
{
echo 'Retrieved session key'.'<br>';
}
$sLSSData=base64_encode(file_get_contents($sFileToImport));
$iSurveyID=$myJSONRPCClient->import_survey($sSessionKey, $sLSSData, 'zip','Test import by JSON_RPC',1000);
echo 'Created new survey SID:'.$iSurveyID.'<br>';
/*
Very simple example to export responses as Excel file
$aResult=$myJSONRPCClient->export_reponses($sSessionKey,$iSurveyID,'xls');
file_put_contents('d:\test.xls',base64_decode(chunk_split($aResult)));
*/
$aResult=$myJSONRPCClient->activate_survey($sSessionKey, $iSurveyID);
if ($aResult['status']=='OK')
{
echo 'Survey '.$iSurveyID.' successfully activated.<br>';
}
$aResult=$myJSONRPCClient->activate_tokens($sSessionKey, $iSurveyID,array(1,2));
if ($aResult['status']=='OK')
{
echo 'Tokens for Survey ID '.$iSurveyID.' successfully activated.<br>';
}
$aResult=$myJSONRPCClient->modify_survey_settings($sSessionKey, $iSurveyID,array('faxto'=>'0800-LIMESURVEY'));
if ($aResult['status']=='OK')
{
echo 'Modified survey settings for survey '.$iSurveyID.'<br>';
}
$aResult=$myJSONRPCClient->add_survey_language($sSessionKey, $iSurveyID,'ar');
if ($aResult['status']=='OK')
{
echo 'Added Arabian as additional language'.'<br>';
}
$aResult=$myJSONRPCClient->modify_survey_locale_settings($sSessionKey, $iSurveyID,array('surveyls_welcometext'=>'An Arabian welcome text!'),'ar');
if ($aResult['status']=='OK')
{
echo 'Modified survey locale setting welcometext for Arabian in survey ID '.$iSurveyID.'<br>';
}
$aResult=$myJSONRPCClient->delete_survey_language($sSessionKey, $iSurveyID,'ar');
if ($aResult['status']=='OK')
{
echo 'Removed Arabian as additional language'.'<br>';
}
die();
$aResult=$myJSONRPCClient->delete_survey($sSessionKey, $iSurveyID);
echo 'Deleted survey SID:'.$iSurveyID.'-'.$aResult['status'].'<br>';
// Release the session key - close the session
$Result= $myJSONRPCClient->release_session_key($sSessionKey);
echo 'Closed the session'.'<br>';
}
}
/**
* This class handles all methods of the RPCs
*/
class remotecontrol_handle
{
/**
* @var AdminController
*/
protected $controller;
/**
* Constructor, stores the action instance into this handle class
*
* @access public
* @param AdminController $controller
* @return void
*/
public function __construct(AdminController $controller)
{
$this->controller = $controller;
}
/**
* RPC routine to create a session key
*
* @access public
* @param string $username
* @param string $password
* @return string
*/
public function get_session_key($username, $password)
{
if ($this->_doLogin($username, $password))
{
$this->_jumpStartSession($username);
$sSessionKey = randomChars(32);
$session = new Sessions;
$session->id = $sSessionKey;
$session->expire = time() + Yii::app()->getConfig('iSessionExpirationTime');
$session->data = $username;
$session->save();
return $sSessionKey;
}
else
return array('status' => 'Invalid user name or password');
}
/**
* Closes the RPC session
*
* @access public
* @param string $sSessionKey
* @return string
*/
public function release_session_key($sSessionKey)
{
Sessions::model()->deleteAllByAttributes(array('id' => $sSessionKey));
$criteria = new CDbCriteria;
$criteria->condition = 'expire < ' . time();
Sessions::model()->deleteAll($criteria);
return 'OK';
}
/**
* RPC routine to delete a survey
*
* @access public
* @param string $sSessionKey
* @param int $iSurveyID
* @return array
*/
public function delete_survey($sSessionKey, $iSurveyID)
{
if ($this->_checkSessionKey($sSessionKey))
{
if (hasSurveyPermission($iSurveyID, 'survey', 'delete'))
{
Survey::model()->deleteSurvey($iSurveyID,true);
return array('status' => 'OK');
}
else
return array('status' => 'No permission');
}
}
/**
* RPC routine to modify survey locale settings
*
* @access public
* @param string $sSessionKey
* @param integer $iSurveyID - ID of the survey
* @param array $aSurveyData - An array with the particular fieldnames as keys and their values to set on that particular survey
* @param string $aLanguage - Optional - Language to update - if not give the base language of the particular survey is used
* @return array status=>OK, when save successful otherwise error text.
*/
public function modify_survey_locale_settings($sSessionKey, $iSurveyID, $aSurveyLocaleData, $sLanguage=NULL)
{
if ($this->_checkSessionKey($sSessionKey))
{
$oSurvey=Survey::model()->findByPk($iSurveyID);
if (is_null($oSurvey))
{
return array('status' => 'Error: Invalid survey ID');
}
if (is_null($sLanguage))
{
$sLanguage=$oSurvey->language;
}
if (hasSurveyPermission($iSurveyID, 'surveylocale', 'update'))
{
// Remove fields that may not be modified
unset($aSurveyLocaleData['surveyls_language']);
unset($aSurveyLocaleData['surveyls_survey_id']);
// Remove invalid fields
$aDestinationFields=array_flip(Surveys_languagesettings::model()->tableSchema->columnNames);
$aSurveyLocaleData=array_intersect_key($aSurveyLocaleData,$aDestinationFields);
$oSurveyLocale = Surveys_languagesettings::model()->findByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $sLanguage));
foreach($aSurveyLocaleData as $sFieldName=>$sValue)
{
$oSurveyLocale->$sFieldName=$sValue;
}
try
{
$oSurveyLocale->save(); // save the change to database
return array('status' => 'OK');
}
catch(Exception $e)
{
return array('status' => 'Error');
}
}
else
return array('status' => 'No permission');
}
}
/**
* RPC routine to add a survey language
*
* @access public
* @param string $sSessionKey
* @param integer $iSurveyID ID of the survey where a token table will be created for
* @param string $sLanguage A valid language shortcut to add to the current survey. If the language already exists no error will be given.
* @return array Status=>OK when successfull, otherwise the error description
*/
public function add_survey_language($sSessionKey, $iSurveyID, $sLanguage)
{
if ($this->_checkSessionKey($sSessionKey))
{
$oSurvey=Survey::model()->findByPk($iSurveyID);
if (is_null($oSurvey))
{
return array('status' => 'Error: Invalid survey ID');
}
if (hasSurveyPermission($iSurveyID, 'surveysettings', 'update'))
{
Yii::app()->loadHelper('surveytranslator');
$aLanguages=getLanguageData();
if(!isset($aLanguages[$sLanguage]))
{
return array('status' => 'Invalid language');
}
$oSurvey=Survey::model()->findByPk($iSurveyID);
if ($sLanguage==$oSurvey->language)
{
return array('status' => 'OK');
}
$aLanguages=$oSurvey->getAdditionalLanguages();
$aLanguages[]=$sLanguage;
$aLanguages=array_unique($aLanguages);
$oSurvey->additional_languages=implode(' ',$aLanguages);
try
{
$oSurvey->save(); // save the change to database
$languagedetails=getLanguageDetails($sLanguage);
$insertdata = array(
'surveyls_survey_id' => $iSurveyID,
'surveyls_language' => $sLanguage,
'surveyls_title' => '',
'surveyls_dateformat' => $languagedetails['dateformat']
);
$setting= new Surveys_languagesettings;
foreach ($insertdata as $k => $v)
$setting->$k = $v;
$setting->save();
fixLanguageConsistency($iSurveyID,$sLanguage);
return array('status' => 'OK');
}
catch(Exception $e)
{
return array('status' => 'Error');
}
}
else
return array('status' => 'No permission');
}
}
/**
* RPC routine to delete a survey language
*
* @access public
* @param string $sSessionKey
* @param integer $iSurveyID ID of the survey where a token table will be created for
* @param string $sLanguage A valid language shortcut to delete from the current survey. If the language does not exist in that survey no error will be given.
* @return array Status=>OK when successfull, otherwise the error description
*/
public function delete_survey_language($sSessionKey, $iSurveyID, $sLanguage)
{
if ($this->_checkSessionKey($sSessionKey))
{
$oSurvey=Survey::model()->findByPk($iSurveyID);
if (is_null($oSurvey))
{
return array('status' => 'Error: Invalid survey ID');
}
if (hasSurveyPermission($iSurveyID, 'surveysettings', 'update'))
{
Yii::app()->loadHelper('surveytranslator');
$aLanguages=getLanguageData();
if(!isset($aLanguages[$sLanguage]))
{
return array('status' => 'Invalid language');
}
$oSurvey=Survey::model()->findByPk($iSurveyID);
if ($sLanguage==$oSurvey->language)
{
return array('status' => 'Cannot remove base language');
}
$aLanguages=$oSurvey->getAdditionalLanguages();
unset($aLanguages[$sLanguage]);
$oSurvey->additional_languages=implode(' ',$aLanguages);
try
{
$oSurvey->save(); // save the change to database
Surveys_languagesettings::model()->deleteByPk(array('surveyls_survey_id' => $iSurveyID, 'surveyls_language' => $sLanguage));
cleanLanguagesFromSurvey($iSurveyID,$oSurvey->additional_languages);
return array('status' => 'OK');
}
catch(Exception $e)
{
return array('status' => 'Error');
}
}
else
return array('status' => 'No permission');
}
}
/**
* RPC routine to activate tokens
*
* @access public
* @param string $sSessionKey
* @param integer $iSurveyID ID of the survey where a token table will be created for
* @param array $aAttributeFields An array of integer describing any additional attribute fields
* @return array Status=>OK when successfull, otherwise the error description
*/
public function activate_tokens($sSessionKey, $iSurveyID, $aAttributeFields=array())
{
if (!$this->_checkSessionKey($sSessionKey)) return array('status' => 'Invalid session key');
if (hasGlobalPermission('USER_RIGHT_CREATE_SURVEY'))
{
$oSurvey=Survey::model()->findByPk($iSurveyID);
if (is_null($oSurvey))
{
return array('status' => 'Error: Invalid survey ID');
}
if (is_array($aAttributeFields) && count($aAttributeFields)>0)
{
foreach ($aAttributeFields as &$sField)
{
$sField= intval($sField);
$sField='attribute_'.$sField;
}
$aAttributeFields=array_unique($aAttributeFields);
}
Yii::app()->loadHelper('admin/token');
if (createTokenTable($iSurveyID, $aAttributeFields))
{
return array('status' => 'OK');
}
else
{
return array('status' => 'Token table could not be created');
}
}
else
return array('status' => 'No permission');
}
/**
* RPC routine to add a response to the survey response table
* Returns the id of the inserted survey response
*
* @access public
* @param string $sSessionKey
* @param int $iSurveyID
* @param struct $aResponseData
* @return int The response ID
*/
public function add_response($sSessionKey, $iSurveyID, $aResponseData)
{
if (!$this->_checkSessionKey($sSessionKey)) return array('status' => 'Invalid session key');
$oSurvey=Survey::model()->findByPk($iSurveyID);
if (is_null($oSurvey))
{
return array('status' => 'Error: Invalid survey ID');
}
if (hasSurveyPermission($iSurveyID, 'responses', 'create'))
{
if (!Yii::app()->db->schema->getTable('{{survey_' . $iSurveyID . '}}'))
return array('status' => 'No survey response table');
//set required values if not set
// @todo: Some of this is part of the validation and should be done in the model instead
if (!isset($aResponseData['submitdate']))
$aResponseData['submitdate'] = date("Y-m-d H:i:s");
if (!isset($aResponseData['startlanguage']))
$aResponseData['startlanguage'] = getBaseLanguageFromSurveyID($iSurveyID);
if ($oSurvey->datestamp=='Y')
{
if (!isset($aResponseData['datestamp']))
$aResponseData['datestamp'] = date("Y-m-d H:i:s");
if (!isset($aResponseData['startdate']))
$aResponseData['startdate'] = date("Y-m-d H:i:s");
}
Survey_dynamic::sid($iSurveyID);
$survey_dynamic = new Survey_dynamic;
$result = $survey_dynamic->insert($aResponseData);
if ($result)
return $survey_dynamic->primaryKey;
else
return array('status' => 'Unable to add response');
}
else
return array('status' => 'No permission');
}
/**
* RPC routine to add a participant to a token table
* Returns the inserted data including additional new information like the Token entry ID and the token
*
* @access public
* @param string $sSessionKey
* @param int $iSurveyID
* @param struct $aParticipantData
* @param bool Optional - Defaults to true and determins if the access token automatically created
* @return array
* @throws Zend_XmlRpc_Server_Exception
*/
public function add_participants($sSessionKey, $iSurveyID, $aParticipantData, $bCreateToken=true)
{
if (!$this->_checkSessionKey($sSessionKey)) return array('status' => 'Invalid session key');
$oSurvey=Survey::model()->findByPk($iSurveyID);
if (is_null($oSurvey))
{
return array('status' => 'Error: Invalid survey ID');
}
if (hasSurveyPermission($iSurveyID, 'tokens', 'create'))
{
if (!Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}'))
return array('status' => 'No token table');
$aDestinationFields = Yii::app()->db->schema->getTable('{{tokens_' . $iSurveyID . '}}')->getColumnNames();
$aDestinationFields = array_flip($field_names);
foreach ($aParticipantData as &$aParticipant)
{
$aParticipant=array_intersect_key($aParticipant,$aDestinationFields);
Tokens_dynamic::sid($iSurveyID);
$token = new Tokens_dynamic;
if ($token->insert($aParticipant))
{
$new_token_id = $token->primaryKey;
if ($bCreateToken)
$token_string = Tokens_dynamic::model()->createToken($new_token_id);
else
$token_string = '';
$aParticipant = array_merge($aParticipant, array(
'tid' => $new_token_id,
'token' => $token_string,
));
}
}
return $aParticipantData;
}
else
return array('status' => 'No permission');
}
/**
* Tries to login with username and password
*
* @access protected
* @param string $sUsername
* @param mixed $sPassword
* @return bool
*/
protected function _doLogin($sUsername, $sPassword)
{
if (Failed_login_attempts::model()->isLockedOut())
return false;
$identity = new UserIdentity(sanitize_user($sUsername), $sPassword);
if (!$identity->authenticate())
{
Failed_login_attempts::model()->addAttempt();
return false;
}
else
return true;
}
/**
* Fills the session with necessary user info on the fly
*
* @access protected
* @param string $sUsername
* @return bool
*/
protected function _jumpStartSession($username)
{
$aUserData = User::model()->findByAttributes(array('users_name' => $username))->attributes;
$session = array(
'loginID' => intval($aUserData['uid']),
'user' => $aUserData['users_name'],
'full_name' => $aUserData['full_name'],
'htmleditormode' => $aUserData['htmleditormode'],
'templateeditormode' => $aUserData['templateeditormode'],
'questionselectormode' => $aUserData['questionselectormode'],
'dateformat' => $aUserData['dateformat'],
'adminlang' => 'en'
);
foreach ($session as $k => $v)
Yii::app()->session[$k] = $v;
Yii::app()->user->setId($aUserData['uid']);
$this->controller->_GetSessionUserRights($aUserData['uid']);
return true;
}
/**
* This function checks if the XML-RPC session key is valid. If yes returns true, otherwise false and sends an error message with error code 1
*
* @access protected
* @param string $sSessionKey
* @return bool
* @throws Zend_XmlRpc_Server_Exception
*/
protected function _checkSessionKey($sSessionKey)
{
$criteria = new CDbCriteria;
$criteria->condition = 'expire < ' . time();
Sessions::model()->deleteAll($criteria);
$oResult = Sessions::model()->findByPk($sSessionKey);
if (is_null($oResult))
return false;
else
{
$this->_jumpStartSession($oResult->data);
return true;
}
}
}