diff --git a/limesurvey/config/limesurvey.lime_survey.surveylist.yml b/limesurvey/config/limesurvey.lime_survey.surveylist.yml new file mode 100644 index 0000000..4a79797 --- /dev/null +++ b/limesurvey/config/limesurvey.lime_survey.surveylist.yml @@ -0,0 +1,7 @@ +surveydata: + : + surveytitle: 'Survey Title' + surveytype: nps +surveytypes: + nps: 'Customer Survey' + other: Other diff --git a/limesurvey/limesurvey.info.yml b/limesurvey/limesurvey.info.yml new file mode 100644 index 0000000..b91bd58 --- /dev/null +++ b/limesurvey/limesurvey.info.yml @@ -0,0 +1,5 @@ +name: 'Lime Survey API' +type: module +description: 'Provides a library to easily integrate with the Lime Survey API' +core: 8.x +package: 'Custom' diff --git a/limesurvey/limesurvey.links.menu.yml b/limesurvey/limesurvey.links.menu.yml new file mode 100644 index 0000000..fd0d15c --- /dev/null +++ b/limesurvey/limesurvey.links.menu.yml @@ -0,0 +1,5 @@ +limesurvey.settings: + route_name: limesurvey.settings + title: 'Survey Settings' + description: 'Interface to manage Lime Survey Settings.' + parent: system.admin_config_services diff --git a/limesurvey/limesurvey.links.task.yml b/limesurvey/limesurvey.links.task.yml new file mode 100644 index 0000000..25018d6 --- /dev/null +++ b/limesurvey/limesurvey.links.task.yml @@ -0,0 +1,8 @@ +limesurvey.settings: + title: ' Survey settings' + route_name: limesurvey.settings + base_route: limesurvey.settings +limesurvey.listsurvey: + title: 'Add/Configure Survey Ids' + route_name: limesurvey.listsurvey + base_route: limesurvey.settings diff --git a/limesurvey/limesurvey.module b/limesurvey/limesurvey.module new file mode 100644 index 0000000..c10e2fd --- /dev/null +++ b/limesurvey/limesurvey.module @@ -0,0 +1,37 @@ +' . t('About') . ''; + $output .= '

' . t('Provides a library to easily integrate with the Lime Survey API') . '

'; + return $output; + + default: + } +} + +/** + * Implements hook_theme(). + */ +function limesurvey_theme() { + return [ + 'limesurvey' => [ + 'render element' => 'children', + ], + ]; +} + diff --git a/limesurvey/limesurvey.permissions.yml b/limesurvey/limesurvey.permissions.yml new file mode 100644 index 0000000..16f92fe --- /dev/null +++ b/limesurvey/limesurvey.permissions.yml @@ -0,0 +1,3 @@ +survey configuration: + title: 'Access Lime Survey API' + description: 'Allows users to access the Lime Survey API' diff --git a/limesurvey/limesurvey.routing.yml b/limesurvey/limesurvey.routing.yml new file mode 100644 index 0000000..b13ea67 --- /dev/null +++ b/limesurvey/limesurvey.routing.yml @@ -0,0 +1,23 @@ +limesurvey.settings: + path: '/admin/config/services/limesurvey/settings' + defaults: + _form: 'Drupal\limesurvey\Form\SurveySettingsForm' + _title: ' Lime Survey Settings' + requirements: + _permission: ' survey configuration' + +limesurvey.listsurvey: + path: '/admin/config/services/limesurvey/surveylist' + defaults: + _controller: '\Drupal\limesurvey\Controller\SurveyController::ConfigureSurvey' + _title: 'Survey ID Configuration' + requirements: + _permission: ' survey configuration' + +limesurvey.delete: + path: '/admin/config/services/limesurvey/surveylist/delete/{surveyid}' + defaults: + _form: 'Drupal\limesurvey\Form\LimeSurveyDeleteForm' + title: 'Survey Delete' + requirements: + _permission: ' survey configuration' diff --git a/limesurvey/limesurvey.services.yml b/limesurvey/limesurvey.services.yml new file mode 100644 index 0000000..034ad66 --- /dev/null +++ b/limesurvey/limesurvey.services.yml @@ -0,0 +1,4 @@ +services: + limesurvey.client: + class: Drupal\limesurvey\LimeSurveyClient + arguments: ['@config.factory'] diff --git a/limesurvey/src/Controller/LimeSurveyController.php b/limesurvey/src/Controller/LimeSurveyController.php new file mode 100644 index 0000000..63b6f9e --- /dev/null +++ b/limesurvey/src/Controller/LimeSurveyController.php @@ -0,0 +1,107 @@ +formBuilder = $form_builder; + $this->configFactory = $config_factory; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('form_builder'), + $container->get('config.factory') + ); + } + + /** + * Constructs a list of locations. + */ + public function ConfigureSurvey() { + $rows = $build = []; + $surveyData = $this->configFactory->get('limesurvey.lime_survey.surveylist')->get('surveydata'); + $surveyTypes = $this->configFactory->getEditable('limesurvey.lime_survey.surveylist')->get('surveytypes'); + $form_arg = 'Drupal\limesurvey\Form\SurveyList'; + $build['limesurvey_form'] = $this->formBuilder->getForm($form_arg); + + $header = [ + $this->t('surveyid'), + $this->t('Survey Name'), + $this->t('Survey Type'), + [ + 'data' => $this->t('Operations'), + 'colspan' => 2, + ], + ]; + + if (!empty($surveyData)) { + + foreach ($surveyData as $key => $value) { + $operations = []; + $operations['delete'] = [ + 'title' => $this->t('Delete'), + 'url' => Url::fromRoute('limesurvey.delete', ['surveyid' => $key]), + ]; + + $data['surveyid'] = $key; + $data['surveyname'] = Html::escape($value['surveytitle']); + $data['surveytype'] = $surveyTypes[$value['surveytype']]; + + $data['operations'] = [ + 'data' => [ + '#type' => 'operations', + '#links' => $operations, + ], + ]; + + $rows[] = $data; + } + } + + $build['limesurvey_table'] = [ + '#type' => 'table', + '#header' => $header, + '#rows' => $rows, + '#empty' => $this->t('No survey available.'), + ]; + return $build; + } + +} diff --git a/limesurvey/src/Form/LimeSurveyDeleteForm.php b/limesurvey/src/Form/LimeSurveyDeleteForm.php new file mode 100644 index 0000000..8bf9f48 --- /dev/null +++ b/limesurvey/src/Form/LimeSurveyDeleteForm.php @@ -0,0 +1,96 @@ +configFactory = $config_factory; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('config.factory') + ); + } + + /** + * {@inheritdoc} + */ + public function getFormId() { + return 'lime_survey_delete_form'; + } + + /** + * {@inheritdoc} + */ + public function getQuestion() { + return t('Are you sure you want to delete this survey ID?'); + } + + /** + * {@inheritdoc} + */ + public function getCancelUrl() { + return new Url('limesurvey.listsurvey'); + } + + /** + * {@inheritdoc} + */ + public function buildForm(array $form, FormStateInterface $form_state, $surveyid = NULL) { + $this->surveyid = $surveyid; + return parent::buildForm($form, $form_state); + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + //@todo: Block cache needs to be invalidated + $SurveyData = $this->configFactory->get('limesurvey.lime_survey.surveylist')->get('surveydata'); + $survey_id = $this->surveyid; + if (array_key_exists($survey_id, $SurveyData)) { + unset($SurveyData[$survey_id]); + $this->configFactory->getEditable('limesurvey.lime_survey.surveylist')->set('surveydata', $SurveyData)->save(); + $form_state->setRedirect('limesurvey.listsurvey'); + $this->messenger()->addMessage($this->t('The Survey ID @survey_id has been removed.', ['@survey_id' => $survey_id])); + } + else { + $this->messenger()->addError($this->t('The Survey ID @survey_id is invalid.', ['@survey_id' => $survey_id])); + + } + //clear all video and article node cache + _limesurvey_clear_article_video_nodes_cache(); + } + +} diff --git a/limesurvey/src/Form/SurveyForm.php b/limesurvey/src/Form/SurveyForm.php new file mode 100644 index 0000000..b78dc83 --- /dev/null +++ b/limesurvey/src/Form/SurveyForm.php @@ -0,0 +1,135 @@ +configFactory = $config_factory; + $this->limesurvey = $lime_survey; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $cont) { + return new static( + $cont->get('config.factory'), + + $cont->get('limesurvey.client') + ); + } + + /** + * {@inheritdoc} + */ + public function getFormId() { + return 'nps_survey_form'; + } + + /** + * {@inheritdoc} + */ + public function buildForm(array $form, FormStateInterface $form_state, $arg = NULL) { + $data = []; + $service = \Drupal::service('limesurvey.client'); + $SurveyData = $this->configFactory->get('limesurvey.lime_survey.surveylist')->get('surveydata'); + foreach ($SurveyData as $SurveyId => $value) { + if( $arg ==$SurveyId ){ + $request = $service->requestData($SurveyId); + $data = $service->BuildSurveyForm($request); + } + } + $service->ReleaseSessionKey($service->sessionKey); + return($data); + } + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + //this form submit is not necessary due to ajax form submit + } + + /** + * Implements the submit handler for the modal dialog AJAX call. + * + * @param array $form + * Render array representing from. + * @param \Drupal\Core\Form\FormStateInterface $form_state + * Current form state. + * + * @return \Drupal\Core\Ajax\AjaxResponse + * Array of AJAX commands to execute on submit of the modal form. + */ + public function ajaxSubmitForm(array &$form, FormStateInterface $form_state) { + $ajax_response = new AjaxResponse(); + if ($form_state->getErrors()) { + $ajax_response->addCommand( + new HtmlCommand( + '.error_message', + $this->t('
Fields marked with * are required.
') + ) + ); + } + // If there are no errors, show the output dialog. + else { + $values = $form_state->getValues(); + $SurveyID = $values['survey_id']; + $groupID = $values['survey_gid']; + foreach ($values as $key => $value) { + if (strpos($key, 'question') !== FALSE) { + $quest = explode('_', $key); + $questionID = $quest[1]; + $answer = $value; + $sgqa = $SurveyID . 'X' . $groupID . 'X' . $questionID; + + $response[$sgqa] = $answer; + } + } + + $this->limesurvey->AddResponse($SurveyID, $response); + $ajax_response->addCommand( + new HtmlCommand( + '.success_message', + $this->t('

Thank you for your feedback.

') + + ) + ); + + } + return $ajax_response; + } + +} diff --git a/limesurvey/src/Form/SurveyList.php b/limesurvey/src/Form/SurveyList.php new file mode 100644 index 0000000..54abe5e --- /dev/null +++ b/limesurvey/src/Form/SurveyList.php @@ -0,0 +1,173 @@ +configFactory = $config_factory; + $this->limesurvey = $lime_survey; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container) { + return new static( + $container->get('config.factory'), + $container->get('limesurvey.client') + ); + } + + /** + * Implements \Drupal\Core\Form\FormInterface::getFormID(). + */ + public function getFormId() { + return 'limesurvey_form'; + } + + /** + * {@inheritdoc} + */ + protected function getEditableConfigNames() { + return [ + 'limesurvey.surveyid', + ]; + } + + /** + * Implements \Drupal\Core\Form\FormInterface::buildForm(). + */ + public function buildForm(array $form, FormStateInterface $form_state) { + $surveyTypes = ['nps' => 'NPS Survey', 'other' => 'Other']; + + $form['surveyid'] = [ + '#type' => 'textfield', + '#title' => 'Survey ID', + '#description' => t('Enter your Survey ID that you have created in the lime survey server'), + '#required' => TRUE, + ]; + + $form['surveytype'] = [ + '#type' => 'select', + '#title' => 'Survey Type', + '#options' => $surveyTypes, + '#description' => t('Select the survey type'), + '#required' => TRUE + ]; + + return parent::buildForm($form, $form_state); + + } + + /** + * @param array $form + * @param \Drupal\Core\Form\FormStateInterface $form_state + */ + public function validateForm(array &$form, FormStateInterface $form_state) { + $surveyData = $this->configFactory->get('limesurvey.lime_survey.surveylist')->get('surveydata'); + $SurveyID_value = $form_state->getValue('surveyid'); + $SurveyType_value = $form_state->getValue('surveytype'); + + //Check Survey ID + if (empty($SurveyID_value) || (!is_numeric($SurveyID_value))) { + $form_state->setErrorByName('surveyid', $this->t('Survey ID is invalid.')); + } + elseif (!empty($surveyData) && array_key_exists($SurveyID_value, $surveyData)) { + $form_state->setErrorByName('surveyid', $this->t('Survey ID already exists.')); + } + else { + $SurveyLists = $this->limesurvey->ListSurvey(); + $SurveyExists = false; + foreach ($SurveyLists as $Survey) { + if($SurveyID_value == $Survey->getID() && $Survey->isActive()) { + $SurveyExists = true; + } + if (!$Survey->isActive() && ($SurveyID_value == $Survey->getID())) { + $this->messenger()->addWarning($this->t('This survey with ID (@survey_id) is not active at this moment.', ['@survey_id' => $Survey->getID()])); + } + } + if(!$SurveyExists) { + $form_state->setErrorByName('surveyid', $this->t('A survey with that ID does not exist.')); + } + } + + //Check Survey Type + if (!empty($surveyData) && (array_search($SurveyType_value, array_column($surveyData, 'surveytype'))!==false && $SurveyType_value !== 'other')) { + $form_state->setErrorByName('surveyid', $this->t('A survey with that type already exists.')); + } + + } + + /** + * Submit handler. + * + * @param array $form + * @param \Drupal\Core\Form\FormStateInterface $form_state + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + //@todo: Block cache needs to be invalidated + $SurveyLists = $this->limesurvey->ListSurvey(); + $SurveyData = $this->configFactory->get('limesurvey.lime_survey.surveylist')->get('surveydata'); + $SurveyType = !empty($this->configFactory->getEditable('limesurvey.lime_survey.surveylist')->get('surveytypes')) ? $this->configFactory->getEditable('limesurvey.lime_survey.surveylist')->get('surveytypes') : []; + $SurveyID_value = $form_state->getValue('surveyid'); + $SurveyType_value = $form_state->getValue('surveytype'); + $SurveyTypes = ['nps' => 'NPS Survey', 'other' => 'Other']; + + if (!empty($SurveyID_value) && !empty($SurveyLists) && !empty($SurveyType_value)) { + foreach ($SurveyLists as $Survey) { + + if ($SurveyID_value == $Survey->getID()) { + $status = (!$Survey->isActive()) ? '(Inactive)' : ''; + $output = ['surveyid' => ['title' => $Survey->getTitle() . $status]]; + $SurveyData[$SurveyID_value] = [ + 'surveytitle' => $output['surveyid']['title'], + 'surveytype' => $SurveyType_value + ]; + } + } + $this->configFactory->getEditable('limesurvey.lime_survey.surveylist')->set('surveydata', $SurveyData)->save(); + + //Only save this the first time or if we make an update to the survey types + if(empty($this->configFactory->getEditable('limesurvey.lime_survey.surveylist')->get('surveytypes')) && count($SurveyTypes)!=count($SurveyType)) { + + $this->configFactory->getEditable('limesurvey.lime_survey.surveylist')->set('surveytypes', $SurveyTypes)->save(); + } + } + + //clear all video and article node cache + _limesurvey_clear_article_video_nodes_cache(); + parent::submitForm($form, $form_state); + } + +} diff --git a/limesurvey/src/Form/SurveySettingsForm.php b/limesurvey/src/Form/SurveySettingsForm.php new file mode 100644 index 0000000..4192628 --- /dev/null +++ b/limesurvey/src/Form/SurveySettingsForm.php @@ -0,0 +1,83 @@ +configFactory->get('limesurvey.settings')->get('settings'); + $yes_no_options = [ + FALSE => $this->t('No'), + TRUE => $this->t('Yes'), + ]; + + $form['#tree'] = TRUE; + $form['settings']['lime_survey_end_point'] = [ + '#type' => 'textfield', + '#title' => $this->t('Lime Survey Endpoint'), + '#required' => TRUE, + '#default_value' => empty($settings['lime_survey_end_point']) ? '' : $settings['lime_survey_end_point'], + '#description' => $this->t('Please enter your Lime Survey End Point'), + ]; + + $form['settings']['lime_survey_username'] = [ + '#type' => 'textfield', + '#title' => $this->t('Lime Survey User Name'), + '#required' => TRUE, + '#default_value' => empty($settings['lime_survey_username']) ? '' : $settings['lime_survey_username'], + '#description' => $this->t('Please enter your Lime Survey User Name.'), + ]; + + $form['settings']['lime_survey_password'] = [ + '#type' => 'textfield', + '#title' => $this->t('Lime Survey Secret Key'), + '#required' => TRUE, + '#default_value' => empty($settings['lime_survey_password']) ? '' : $settings['lime_survey_password'], + '#description' => $this->t('Please enter your lime_survey_password Secret Key.'), + ]; + + return parent::buildForm($form, $form_state); + } + + /** + * {@inheritdoc} + */ + public function validateForm(array &$form, FormStateInterface $form_state) {} + + /** + * {@inheritdoc} + */ + public function submitForm(array &$form, FormStateInterface $form_state) { + $form_value = $form_state->getValue('settings'); + $this->config('limesurvey.settings') + ->set('settings', $form_value) + ->save(); + parent::submitForm($form, $form_state); + } + +} diff --git a/limesurvey/src/LimeSurveyClient.php b/limesurvey/src/LimeSurveyClient.php new file mode 100644 index 0000000..d373789 --- /dev/null +++ b/limesurvey/src/LimeSurveyClient.php @@ -0,0 +1,426 @@ +configFactory = $config_factory; + $this->settings = $this->configFactory->get('limesurvey.settings')->get('settings'); + $this->connectionConfig = new ConnectionConfiguration($this->settings['lime_survey_end_point'], $this->settings['lime_survey_username'], $this->settings['lime_survey_password'], FALSE, FALSE); + $this->client = new Client($this->connectionConfig); + $this->rpcClientManager = new JsonRpcClientManager($this->connectionConfig); + if (!empty($this->settings['lime_survey_end_point'])) { + + try { + $resp = \Drupal::httpClient()->get($this->settings['lime_survey_end_point'], ['connect_timeout' => 3]); + if($resp) { + $this->sessionKey = $this->GetSessionKey($this->settings['lime_survey_username'], $this->settings['lime_survey_password']); + } + } + catch (RequestException $e) { + if ($e->getCode() > 499 || $e->getCode() < 199) { + \Drupal::logger(' Survey')->error($e->getMessage() . ' Code: ' . $e->getCode()); + } + } + } + + } + + + /** + * Make a request to the ww server and return it as an array. + * + * @param array $options + * Options build the request url. + * + * @return array + * An array containing survey data. + */ + public function requestData($SurveyID) { + $QuestionsProp = []; + if (!empty($this->settings['lime_survey_end_point']) && !empty($this->settings['lime_survey_username']) && !empty($this->settings['lime_survey_password'])) { + // List survey. + $SurveyList = $this->ListSurvey(); + + if (is_iterable($SurveyList)) { + foreach ($SurveyList as $Survey) { + + if (($Survey->isActive()) && ($SurveyID == $Survey->getID())) { + try { + $list_questions = $this->ListQuestions($SurveyID); + foreach ($list_questions as $question) { + $QuestionID = $question['qid']; + $QuestionsProp[] = $this->GetQuestionProperties($QuestionID); + } + } + catch (\Exception $exception) { + \Drupal::logger(' Survey')->error($exception->getMessage()); + } + } + } + } + return $QuestionsProp; + } + } + + /** + * Get the module settings. + * + * @return \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig + * The configuration object. + */ + public function GetSettings() { + return $this->configFactory->get('limesurvey.settings')->get('settings'); + } + + /** + * Create and return a session key. + * + * @param string $username + * @param string $password + * @param string $plugin + * to be used. + * + * @return string|array + */ + public function GetSessionKey($SurveyUname, $SurveyPass) { + $SessionKey = NULL; + try { + $SessionKey = $this->rpcClientManager->runMethod('get_session_key', [$SurveyUname, $SurveyPass]); + + } + catch (\Exception $exception) { + \Drupal::logger(' Survey')->error($exception->getMessage()); + + } + return $SessionKey; + } + + /** + * List the survey belonging to a user. + * + * If user is admin he can get surveys of every user (parameter sUser) or all surveys (sUser=null) + * Else only the surveys belonging to the user requesting will be shown. + * + * Returns array with + * * `sid` the ids of survey + * * `surveyls_title` the title of the survey + * * `startdate` start date + * * `expires` expiration date + * * `active` if survey is active (Y) or not (!Y) + * + * @param string $sSessionKey + * Auth credentials. + * @param string|null $sUsername + * (optional) username to get list of surveys. + * + * @return array In case of success the list of surveys + */ + public function ListSurvey() { + $SurveyList = NULL; + try { + $SurveyList = $this->client->run(MethodType::LIST_SURVEYS)->getData(); + + } + catch (\Exception $exception) { + \Drupal::logger(' Survey')->error($exception->getMessage()); + + } + return $SurveyList; + } + + /** + * Return the ids and info of (sub-)questions of a survey/group. + * Returns array of ids and info. + * + * @param string $sSessionKey + * Auth credentials. + * @param int $iSurveyID + * ID of the Survey to list questions. + * @param int $iGroupID + * Optional id of the group to list questions. + * @param string $sLanguage + * Optional parameter language for multilingual questions. + * + * @return array The list of questions + */ + public function ListQuestions($SurveyID) { + $QuestionList = NULL; + try { + $QuestionList = $this->rpcClientManager->runMethod('list_questions', [$this->sessionKey, $SurveyID]); + + } + catch (\Exception $exception) { + \Drupal::logger(' Survey')->error($exception->getMessage()); + + } + return $QuestionList; + } + + /** + * Get properties of a question in a survey. + * + * @see \Question for available properties. + * Some more properties are available_answers, subquestions, attributes, attributes_lang, answeroptions, defaultvalue + * @param string $sSessionKey + * Auth credentials. + * @param int $iQuestionID + * ID of the question to get properties. + * @param array $aQuestionSettings + * (optional) properties to get, default to all. + * @param string $sLanguage + * (optional) parameter language for multilingual questions, default are \Survey->language. + * + * @return array The requested values + */ + public function GetQuestionProperties($QuestionID) { + $QuestionProperties = NULL; + try { + $QuestionProperties = $this->rpcClientManager->runMethod('get_question_properties', [$this->sessionKey, $QuestionID]); + + } + catch (\Exception $exception) { + \Drupal::logger(' Survey')->error($exception->getMessage()); + + } + return $QuestionProperties; + } + + /** + * Add a response to the survey responses collection. + * Returns the id of the inserted survey response. + * + * @access public + * @param string $sSessionKey + * Auth credentials. + * @param int $iSurveyID + * ID of the Survey to insert responses. + * @param array $aResponseData + * The actual response. + * + * @return int|array The response ID or an array with status message (can include result_id) + */ + public function AddResponse($SurveyID, $ResponseData) { + $Response = NULL; + try { + $new_session_key = $this->GetSessionKey($this->settings['lime_survey_username'], $this->settings['lime_survey_password']); + $Response = $this->rpcClientManager->runMethod('add_response', [$new_session_key, $SurveyID, $ResponseData]); + $this->ReleaseSessionKey($new_session_key); + } + catch (\Exception $exception) { + \Drupal::logger(' Survey')->error($exception->getMessage()); + + } + return $Response; + } + + /** + * Close the RPC session. + * + * Using this function you can close a previously opened XML-RPC/JSON-RPC session. + * + * @access public + * @param string $sSessionKey + * the session key. + * + * @return string OK + */ + public function ReleaseSessionKey($SessionKey) { + $ReleaseSessionKey = NULL; + try { + $ReleaseSessionKey = $this->rpcClientManager->runMethod('release_session_key', [$SessionKey]); + } + catch (\Exception $exception) { + \Drupal::logger(' Survey')->error($exception->getMessage()); + + } + return $ReleaseSessionKey; + + } + + /** + * @param $request + * + * @return mixed + */ + public function BuildSurveyForm($request) { + $form = []; + $form['#attached']['library'][] = 'limesurvey/survey'; + $form['#attached']['library'][] = 'core/drupal.ajax'; + if (!empty($request)) { + foreach ($request as $surveyitem) { + $hidden = (isset($surveyitem['attributes']['hidden']) && $surveyitem['attributes']['hidden']) ? true : false; + + $inputType = $this->ProcessQuestionType($surveyitem['type']); + + $css_class = isset($surveyitem['attributes']['cssclass'])?$surveyitem['attributes']['cssclass']:''; + + $full_node_url = \Drupal::urlGenerator()->generateFromRoute('', [], ['absolute' => TRUE]); + + $referrer = ($surveyitem['title'] == 'referrer') ? ($full_node_url) : ''; + + $form['message'] = [ + '#type' => 'markup', + '#markup' => '
', + ]; + $form[$surveyitem['sid']]['question_' . $surveyitem['qid']] = [ + '#type' => $inputType['type'], + '#attributes' => ['class' => ['container-inline',$css_class]], + '#title' => ($surveyitem['question']), + '#required' => ($surveyitem['mandatory'] == 'Y') ? TRUE : FALSE, + '#weight' => $surveyitem['question_order'], + '#description' => $surveyitem['help'], + ]; + if (is_array($surveyitem['answeroptions'])) { + $options = $this->ProcessOptions($surveyitem['answeroptions']); + $form[$surveyitem['sid']]['question_' . $surveyitem['qid']]['#options'] = $options; + } + + if ($hidden) { + $form[$surveyitem['sid']]['question_' . $surveyitem['qid']] = [ + '#type' => 'hidden', + '#value' => $referrer, + ]; + } + + $form[$surveyitem['sid']]['survey_id'] = [ + '#type' => 'hidden', + '#value' => $surveyitem['sid'], + ]; + $form[$surveyitem['sid']]['survey_gid'] = [ + '#type' => 'hidden', + '#value' => $surveyitem['gid'], + ]; + $form['actions'] = [ + '#type' => 'actions', + ]; + + // Add a submit button that handles the submission of the form. + $form['actions']['submit'] = [ + '#type' => 'submit', + '#value' => 'Submit', + '#weight' => $surveyitem['question_order'] + 1, + '#ajax' => [ + 'callback' => '::ajaxSubmitForm', + 'event' => 'click', + ], + ]; + + } + $form['#cache']['contexts'][] = 'session'; + $form['#prefix'] = '
'; + $form['#suffix'] = '
'; + return $form; + + } + else { + $user = \Drupal::currentUser(); + $user_anonymous = $user->isAnonymous(); + //show the error only for loged in users + if (!$user_anonymous) { + $this->messenger()->addError($this->t('Survey not available!')); + } + } + + } + + /** + * @param $type + * The Input Field Type + * Translates the Field type code to html input type + * Please check your Lime Survey's folder /limesurvey/application/helpers/export_helper.php + * @return array with html input type and option (bool) + */ + public function ProcessQuestionType($type) { + switch ($type) { + // 5 point radio button. + case "5": + // LIST drop-down/radio-button list. + case "L": + // ARRAY (5 POINT CHOICE) radio-buttons. + case "A": + // ARRAY (10 POINT CHOICE) radio-buttons. + case "B": + // ARRAY (YES/UNCERTAIN/NO) radio-buttons. + case "C": + // ARRAY (Increase/Same/Decrease) radio-buttons. + case "E": + // YES/NO radio-buttons. + case "Y": + + $input = ['type' => 'radios', 'options' => TRUE]; + break; + + // LONG FREE TEXT. + case "T": + $input = ['type' => 'textarea']; + break; + + // HUGE FREE TEXT. + case "U": + $input = ['type' => 'text_format']; + break; + + // GENDER drop-down list. + case "G": + $input = ['type' => 'select', 'options' => TRUE]; + break; + + // Hidden field. + case "S": + $input = ['type' => 'hidden']; + break; + + } + return $input; + // End Switch. + } + + /** + * Process the given array's and convert them into radio oprions. + * + * @param $answeroptions + * + * @return array + */ + public function ProcessOptions($answeroptions) { + $choices = []; + foreach ($answeroptions as $key => $answeroption) { + $choices[$key] = $answeroption['answer']; + } + return $choices; + } + +} diff --git a/limesurvey/src/LimeSurveyClientinterface.php b/limesurvey/src/LimeSurveyClientinterface.php new file mode 100644 index 0000000..912c0ff --- /dev/null +++ b/limesurvey/src/LimeSurveyClientinterface.php @@ -0,0 +1,65 @@ +formBuilder = $formBuilder; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('form_builder') + ); + } + + /** + * {@inheritdoc} + */ + public function build() { + $block_id = $this->getDerivativeId(); + return [ + '#prefix' => '
', + '#suffix' => '
', + 'form' => \Drupal::formBuilder()->getForm('Drupal\limesurvey\Form\SurveyForm', $block_id), + '#cache' => [ + 'max-age' => 0, + ] + ]; + } + + /** + * {@inheritdoc} + */ + /* protected function blockAccess(AccountInterface $account) { + return AccessResult::allowedIfHasPermission($account, 'access content'); + }*/ +} diff --git a/limesurvey/src/Plugin/Derivative/LimeSurveyWidgetDeriver.php b/limesurvey/src/Plugin/Derivative/LimeSurveyWidgetDeriver.php new file mode 100644 index 0000000..555efd6 --- /dev/null +++ b/limesurvey/src/Plugin/Derivative/LimeSurveyWidgetDeriver.php @@ -0,0 +1,34 @@ +get('surveyid'); + if ($SurveyIds) { + foreach ($SurveyIds as $SurveyId => $value) { + $delta = $SurveyId; + $this->derivatives[$delta] = $base_plugin_definition; + $this->derivatives[$delta]['admin_label'] = $this->t('Survey Widget') . ': ' . $value; + } + } + return parent::getDerivativeDefinitions($base_plugin_definition); + } + +}